diff --git a/maven-resolver-api/pom.xml b/maven-resolver-api/pom.xml index df5263ea4..cf778ffaf 100644 --- a/maven-resolver-api/pom.xml +++ b/maven-resolver-api/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-api Maven Artifact Resolver API - - The application programming interface for the repository system. - + The application programming interface for the repository system. org.apache.maven.resolver diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/AbstractForwardingRepositorySystemSession.java b/maven-resolver-api/src/main/java/org/eclipse/aether/AbstractForwardingRepositorySystemSession.java index b1ace216a..a1a2083e1 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/AbstractForwardingRepositorySystemSession.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/AbstractForwardingRepositorySystemSession.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; import java.util.Map; @@ -42,16 +41,12 @@ * A special repository system session to enable decorating or proxying another session. To do so, clients have to * create a subclass and implement {@link #getSession()}, and optionally override other methods. */ -public abstract class AbstractForwardingRepositorySystemSession - implements RepositorySystemSession -{ +public abstract class AbstractForwardingRepositorySystemSession implements RepositorySystemSession { /** * Creates a new forwarding session. */ - protected AbstractForwardingRepositorySystemSession() - { - } + protected AbstractForwardingRepositorySystemSession() {} /** * Gets the repository system session to which this instance forwards calls. It's worth noting that this class does @@ -63,158 +58,132 @@ protected AbstractForwardingRepositorySystemSession() protected abstract RepositorySystemSession getSession(); @Override - public boolean isOffline() - { + public boolean isOffline() { return getSession().isOffline(); } @Override - public boolean isIgnoreArtifactDescriptorRepositories() - { + public boolean isIgnoreArtifactDescriptorRepositories() { return getSession().isIgnoreArtifactDescriptorRepositories(); } @Override - public ResolutionErrorPolicy getResolutionErrorPolicy() - { + public ResolutionErrorPolicy getResolutionErrorPolicy() { return getSession().getResolutionErrorPolicy(); } @Override - public ArtifactDescriptorPolicy getArtifactDescriptorPolicy() - { + public ArtifactDescriptorPolicy getArtifactDescriptorPolicy() { return getSession().getArtifactDescriptorPolicy(); } @Override - public String getChecksumPolicy() - { + public String getChecksumPolicy() { return getSession().getChecksumPolicy(); } @Override - public String getUpdatePolicy() - { + public String getUpdatePolicy() { return getSession().getUpdatePolicy(); } @Override - public LocalRepository getLocalRepository() - { + public LocalRepository getLocalRepository() { return getSession().getLocalRepository(); } @Override - public LocalRepositoryManager getLocalRepositoryManager() - { + public LocalRepositoryManager getLocalRepositoryManager() { return getSession().getLocalRepositoryManager(); } @Override - public WorkspaceReader getWorkspaceReader() - { + public WorkspaceReader getWorkspaceReader() { return getSession().getWorkspaceReader(); } @Override - public RepositoryListener getRepositoryListener() - { + public RepositoryListener getRepositoryListener() { return getSession().getRepositoryListener(); } @Override - public TransferListener getTransferListener() - { + public TransferListener getTransferListener() { return getSession().getTransferListener(); } @Override - public Map getSystemProperties() - { + public Map getSystemProperties() { return getSession().getSystemProperties(); } @Override - public Map getUserProperties() - { + public Map getUserProperties() { return getSession().getUserProperties(); } @Override - public Map getConfigProperties() - { + public Map getConfigProperties() { return getSession().getConfigProperties(); } @Override - public MirrorSelector getMirrorSelector() - { + public MirrorSelector getMirrorSelector() { return getSession().getMirrorSelector(); } @Override - public ProxySelector getProxySelector() - { + public ProxySelector getProxySelector() { return getSession().getProxySelector(); } @Override - public AuthenticationSelector getAuthenticationSelector() - { + public AuthenticationSelector getAuthenticationSelector() { return getSession().getAuthenticationSelector(); } @Override - public ArtifactTypeRegistry getArtifactTypeRegistry() - { + public ArtifactTypeRegistry getArtifactTypeRegistry() { return getSession().getArtifactTypeRegistry(); } @Override - public DependencyTraverser getDependencyTraverser() - { + public DependencyTraverser getDependencyTraverser() { return getSession().getDependencyTraverser(); } @Override - public DependencyManager getDependencyManager() - { + public DependencyManager getDependencyManager() { return getSession().getDependencyManager(); } @Override - public DependencySelector getDependencySelector() - { + public DependencySelector getDependencySelector() { return getSession().getDependencySelector(); } @Override - public VersionFilter getVersionFilter() - { + public VersionFilter getVersionFilter() { return getSession().getVersionFilter(); } @Override - public DependencyGraphTransformer getDependencyGraphTransformer() - { + public DependencyGraphTransformer getDependencyGraphTransformer() { return getSession().getDependencyGraphTransformer(); } @Override - public SessionData getData() - { + public SessionData getData() { return getSession().getData(); } @Override - public RepositoryCache getCache() - { + public RepositoryCache getCache() { return getSession().getCache(); } @Override - public FileTransformerManager getFileTransformerManager() - { + public FileTransformerManager getFileTransformerManager() { return getSession().getFileTransformerManager(); } } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/AbstractRepositoryListener.java b/maven-resolver-api/src/main/java/org/eclipse/aether/AbstractRepositoryListener.java index f42d15e3d..969bdfb96 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/AbstractRepositoryListener.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/AbstractRepositoryListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,95 +16,53 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; /** * A skeleton implementation for custom repository listeners. The callback methods in this class do nothing. */ -public abstract class AbstractRepositoryListener - implements RepositoryListener -{ +public abstract class AbstractRepositoryListener implements RepositoryListener { /** * Enables subclassing. */ - protected AbstractRepositoryListener() - { - } - - public void artifactDeployed( RepositoryEvent event ) - { - } + protected AbstractRepositoryListener() {} - public void artifactDeploying( RepositoryEvent event ) - { - } + public void artifactDeployed(RepositoryEvent event) {} - public void artifactDescriptorInvalid( RepositoryEvent event ) - { - } + public void artifactDeploying(RepositoryEvent event) {} - public void artifactDescriptorMissing( RepositoryEvent event ) - { - } + public void artifactDescriptorInvalid(RepositoryEvent event) {} - public void artifactDownloaded( RepositoryEvent event ) - { - } + public void artifactDescriptorMissing(RepositoryEvent event) {} - public void artifactDownloading( RepositoryEvent event ) - { - } + public void artifactDownloaded(RepositoryEvent event) {} - public void artifactInstalled( RepositoryEvent event ) - { - } + public void artifactDownloading(RepositoryEvent event) {} - public void artifactInstalling( RepositoryEvent event ) - { - } + public void artifactInstalled(RepositoryEvent event) {} - public void artifactResolved( RepositoryEvent event ) - { - } + public void artifactInstalling(RepositoryEvent event) {} - public void artifactResolving( RepositoryEvent event ) - { - } + public void artifactResolved(RepositoryEvent event) {} - public void metadataDeployed( RepositoryEvent event ) - { - } + public void artifactResolving(RepositoryEvent event) {} - public void metadataDeploying( RepositoryEvent event ) - { - } + public void metadataDeployed(RepositoryEvent event) {} - public void metadataDownloaded( RepositoryEvent event ) - { - } + public void metadataDeploying(RepositoryEvent event) {} - public void metadataDownloading( RepositoryEvent event ) - { - } + public void metadataDownloaded(RepositoryEvent event) {} - public void metadataInstalled( RepositoryEvent event ) - { - } + public void metadataDownloading(RepositoryEvent event) {} - public void metadataInstalling( RepositoryEvent event ) - { - } + public void metadataInstalled(RepositoryEvent event) {} - public void metadataInvalid( RepositoryEvent event ) - { - } + public void metadataInstalling(RepositoryEvent event) {} - public void metadataResolved( RepositoryEvent event ) - { - } + public void metadataInvalid(RepositoryEvent event) {} - public void metadataResolving( RepositoryEvent event ) - { - } + public void metadataResolved(RepositoryEvent event) {} + public void metadataResolving(RepositoryEvent event) {} } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/ConfigurationProperties.java b/maven-resolver-api/src/main/java/org/eclipse/aether/ConfigurationProperties.java index bc1738f31..fad69b026 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/ConfigurationProperties.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/ConfigurationProperties.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; /** * The keys and defaults for common configuration properties. - * + * * @see RepositorySystemSession#getConfigProperties() */ -public final class ConfigurationProperties -{ +public final class ConfigurationProperties { private static final String PREFIX_AETHER = "aether."; @@ -47,7 +45,7 @@ public final class ConfigurationProperties * corresponding {@code aether.priority.*} configuration properties are ignored when searching for a suitable * implementation among the available extensions. This priority mode is meant for cases where the application will * present/inject extensions in the desired search order. - * + * * @see #DEFAULT_IMPLICIT_PRIORITIES */ public static final String IMPLICIT_PRIORITIES = PREFIX_PRIORITY + "implicit"; @@ -59,7 +57,7 @@ public final class ConfigurationProperties /** * A flag indicating whether interaction with the user is allowed. - * + * * @see #DEFAULT_INTERACTIVE */ public static final String INTERACTIVE = PREFIX_AETHER + "interactive"; @@ -71,7 +69,7 @@ public final class ConfigurationProperties /** * The user agent that repository connectors should report to servers. - * + * * @see #DEFAULT_USER_AGENT */ public static final String USER_AGENT = PREFIX_CONNECTOR + "userAgent"; @@ -84,7 +82,7 @@ public final class ConfigurationProperties /** * The maximum amount of time (in milliseconds) to wait for a successful connection to a remote server. Non-positive * values indicate no timeout. - * + * * @see #DEFAULT_CONNECT_TIMEOUT */ public static final String CONNECT_TIMEOUT = PREFIX_CONNECTOR + "connectTimeout"; @@ -98,7 +96,7 @@ public final class ConfigurationProperties * The maximum amount of time (in milliseconds) to wait for remaining data to arrive from a remote server. Note that * this timeout does not restrict the overall duration of a request, it only restricts the duration of inactivity * between consecutive data packets. Non-positive values indicate no timeout. - * + * * @see #DEFAULT_REQUEST_TIMEOUT */ public static final String REQUEST_TIMEOUT = PREFIX_CONNECTOR + "requestTimeout"; @@ -121,7 +119,7 @@ public final class ConfigurationProperties * The encoding/charset to use when exchanging credentials with HTTP servers. Besides this general key, clients may * also specify the encoding for a specific remote repository by appending the suffix {@code .} to this key * when storing the charset name. - * + * * @see #DEFAULT_HTTP_CREDENTIAL_ENCODING */ public static final String HTTP_CREDENTIAL_ENCODING = PREFIX_CONNECTOR + "http.credentialEncoding"; @@ -134,7 +132,7 @@ public final class ConfigurationProperties /** * A flag indicating whether checksums which are retrieved during checksum validation should be persisted in the * local filesystem next to the file they provide the checksum for. - * + * * @see #DEFAULT_PERSISTED_CHECKSUMS */ public static final String PERSISTED_CHECKSUMS = PREFIX_CONNECTOR + "persistedChecksums"; @@ -144,9 +142,7 @@ public final class ConfigurationProperties */ public static final boolean DEFAULT_PERSISTED_CHECKSUMS = true; - private ConfigurationProperties() - { + private ConfigurationProperties() { // hide constructor } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultRepositoryCache.java b/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultRepositoryCache.java index 18e28f0a3..de8c4dc9a 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultRepositoryCache.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultRepositoryCache.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -26,27 +25,19 @@ * A simplistic repository cache backed by a thread-safe map. The simplistic nature of this cache makes it only suitable * for use with short-lived repository system sessions where pruning of cache data is not required. */ -public final class DefaultRepositoryCache - implements RepositoryCache -{ +public final class DefaultRepositoryCache implements RepositoryCache { - private final Map cache = new ConcurrentHashMap<>( 256 ); + private final Map cache = new ConcurrentHashMap<>(256); - public Object get( RepositorySystemSession session, Object key ) - { - return cache.get( key ); + public Object get(RepositorySystemSession session, Object key) { + return cache.get(key); } - public void put( RepositorySystemSession session, Object key, Object data ) - { - if ( data != null ) - { - cache.put( key, data ); - } - else - { - cache.remove( key ); + public void put(RepositorySystemSession session, Object key, Object data) { + if (data != null) { + cache.put(key, data); + } else { + cache.remove(key); } } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultRepositorySystemSession.java b/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultRepositorySystemSession.java index 4c0163e81..a6e24fd57 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultRepositorySystemSession.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultRepositorySystemSession.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; import java.util.Collection; import java.util.Collections; @@ -58,9 +57,7 @@ * system. It is recommended to call {@link #setReadOnly()} once the session has been fully initialized to prevent * accidental manipulation of it afterwards. */ -public final class DefaultRepositorySystemSession - implements RepositorySystemSession -{ +public final class DefaultRepositorySystemSession implements RepositorySystemSession { private boolean readOnly; @@ -125,14 +122,13 @@ public final class DefaultRepositorySystemSession * {@link #setLocalRepositoryManager(LocalRepositoryManager)} needs to be called but usually other settings also * need to be customized to achieve meaningful behavior. */ - public DefaultRepositorySystemSession() - { + public DefaultRepositorySystemSession() { systemProperties = new HashMap<>(); - systemPropertiesView = Collections.unmodifiableMap( systemProperties ); + systemPropertiesView = Collections.unmodifiableMap(systemProperties); userProperties = new HashMap<>(); - userPropertiesView = Collections.unmodifiableMap( userProperties ); + userPropertiesView = Collections.unmodifiableMap(userProperties); configProperties = new HashMap<>(); - configPropertiesView = Collections.unmodifiableMap( configProperties ); + configPropertiesView = Collections.unmodifiableMap(configProperties); mirrorSelector = NullMirrorSelector.INSTANCE; proxySelector = NullProxySelector.INSTANCE; authenticationSelector = NullAuthenticationSelector.INSTANCE; @@ -149,40 +145,38 @@ public DefaultRepositorySystemSession() * * @param session The session to copy, must not be {@code null}. */ - public DefaultRepositorySystemSession( RepositorySystemSession session ) - { - requireNonNull( session, "repository system session cannot be null" ); - - setOffline( session.isOffline() ); - setIgnoreArtifactDescriptorRepositories( session.isIgnoreArtifactDescriptorRepositories() ); - setResolutionErrorPolicy( session.getResolutionErrorPolicy() ); - setArtifactDescriptorPolicy( session.getArtifactDescriptorPolicy() ); - setChecksumPolicy( session.getChecksumPolicy() ); - setUpdatePolicy( session.getUpdatePolicy() ); - setLocalRepositoryManager( session.getLocalRepositoryManager() ); - setWorkspaceReader( session.getWorkspaceReader() ); - setRepositoryListener( session.getRepositoryListener() ); - setTransferListener( session.getTransferListener() ); - setSystemProperties( session.getSystemProperties() ); - setUserProperties( session.getUserProperties() ); - setConfigProperties( session.getConfigProperties() ); - setMirrorSelector( session.getMirrorSelector() ); - setProxySelector( session.getProxySelector() ); - setAuthenticationSelector( session.getAuthenticationSelector() ); - setArtifactTypeRegistry( session.getArtifactTypeRegistry() ); - setDependencyTraverser( session.getDependencyTraverser() ); - setDependencyManager( session.getDependencyManager() ); - setDependencySelector( session.getDependencySelector() ); - setVersionFilter( session.getVersionFilter() ); - setDependencyGraphTransformer( session.getDependencyGraphTransformer() ); - setFileTransformerManager( session.getFileTransformerManager() ); - setData( session.getData() ); - setCache( session.getCache() ); + public DefaultRepositorySystemSession(RepositorySystemSession session) { + requireNonNull(session, "repository system session cannot be null"); + + setOffline(session.isOffline()); + setIgnoreArtifactDescriptorRepositories(session.isIgnoreArtifactDescriptorRepositories()); + setResolutionErrorPolicy(session.getResolutionErrorPolicy()); + setArtifactDescriptorPolicy(session.getArtifactDescriptorPolicy()); + setChecksumPolicy(session.getChecksumPolicy()); + setUpdatePolicy(session.getUpdatePolicy()); + setLocalRepositoryManager(session.getLocalRepositoryManager()); + setWorkspaceReader(session.getWorkspaceReader()); + setRepositoryListener(session.getRepositoryListener()); + setTransferListener(session.getTransferListener()); + setSystemProperties(session.getSystemProperties()); + setUserProperties(session.getUserProperties()); + setConfigProperties(session.getConfigProperties()); + setMirrorSelector(session.getMirrorSelector()); + setProxySelector(session.getProxySelector()); + setAuthenticationSelector(session.getAuthenticationSelector()); + setArtifactTypeRegistry(session.getArtifactTypeRegistry()); + setDependencyTraverser(session.getDependencyTraverser()); + setDependencyManager(session.getDependencyManager()); + setDependencySelector(session.getDependencySelector()); + setVersionFilter(session.getVersionFilter()); + setDependencyGraphTransformer(session.getDependencyGraphTransformer()); + setFileTransformerManager(session.getFileTransformerManager()); + setData(session.getData()); + setCache(session.getCache()); } @Override - public boolean isOffline() - { + public boolean isOffline() { return offline; } @@ -193,16 +187,14 @@ public boolean isOffline() * @param offline {@code true} if the repository system is in offline mode, {@code false} otherwise. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setOffline( boolean offline ) - { + public DefaultRepositorySystemSession setOffline(boolean offline) { verifyStateForMutation(); this.offline = offline; return this; } @Override - public boolean isIgnoreArtifactDescriptorRepositories() - { + public boolean isIgnoreArtifactDescriptorRepositories() { return ignoreArtifactDescriptorRepositories; } @@ -216,16 +208,14 @@ public boolean isIgnoreArtifactDescriptorRepositories() * @return This session for chaining, never {@code null}. */ public DefaultRepositorySystemSession setIgnoreArtifactDescriptorRepositories( - boolean ignoreArtifactDescriptorRepositories ) - { + boolean ignoreArtifactDescriptorRepositories) { verifyStateForMutation(); this.ignoreArtifactDescriptorRepositories = ignoreArtifactDescriptorRepositories; return this; } @Override - public ResolutionErrorPolicy getResolutionErrorPolicy() - { + public ResolutionErrorPolicy getResolutionErrorPolicy() { return resolutionErrorPolicy; } @@ -236,16 +226,14 @@ public ResolutionErrorPolicy getResolutionErrorPolicy() * errors should generally not be cached. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setResolutionErrorPolicy( ResolutionErrorPolicy resolutionErrorPolicy ) - { + public DefaultRepositorySystemSession setResolutionErrorPolicy(ResolutionErrorPolicy resolutionErrorPolicy) { verifyStateForMutation(); this.resolutionErrorPolicy = resolutionErrorPolicy; return this; } @Override - public ArtifactDescriptorPolicy getArtifactDescriptorPolicy() - { + public ArtifactDescriptorPolicy getArtifactDescriptorPolicy() { return artifactDescriptorPolicy; } @@ -257,16 +245,14 @@ public ArtifactDescriptorPolicy getArtifactDescriptorPolicy() * @return This session for chaining, never {@code null}. */ public DefaultRepositorySystemSession setArtifactDescriptorPolicy( - ArtifactDescriptorPolicy artifactDescriptorPolicy ) - { + ArtifactDescriptorPolicy artifactDescriptorPolicy) { verifyStateForMutation(); this.artifactDescriptorPolicy = artifactDescriptorPolicy; return this; } @Override - public String getChecksumPolicy() - { + public String getChecksumPolicy() { return checksumPolicy; } @@ -280,16 +266,14 @@ public String getChecksumPolicy() * @see RepositoryPolicy#CHECKSUM_POLICY_IGNORE * @see RepositoryPolicy#CHECKSUM_POLICY_WARN */ - public DefaultRepositorySystemSession setChecksumPolicy( String checksumPolicy ) - { + public DefaultRepositorySystemSession setChecksumPolicy(String checksumPolicy) { verifyStateForMutation(); this.checksumPolicy = checksumPolicy; return this; } @Override - public String getUpdatePolicy() - { + public String getUpdatePolicy() { return updatePolicy; } @@ -303,22 +287,19 @@ public String getUpdatePolicy() * @see RepositoryPolicy#UPDATE_POLICY_DAILY * @see RepositoryPolicy#UPDATE_POLICY_NEVER */ - public DefaultRepositorySystemSession setUpdatePolicy( String updatePolicy ) - { + public DefaultRepositorySystemSession setUpdatePolicy(String updatePolicy) { verifyStateForMutation(); this.updatePolicy = updatePolicy; return this; } @Override - public LocalRepository getLocalRepository() - { + public LocalRepository getLocalRepository() { LocalRepositoryManager lrm = getLocalRepositoryManager(); - return ( lrm != null ) ? lrm.getRepository() : null; + return (lrm != null) ? lrm.getRepository() : null; } - public LocalRepositoryManager getLocalRepositoryManager() - { + public LocalRepositoryManager getLocalRepositoryManager() { return localRepositoryManager; } @@ -329,33 +310,28 @@ public LocalRepositoryManager getLocalRepositoryManager() * @param localRepositoryManager The local repository manager used during this session, may be {@code null}. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setLocalRepositoryManager( LocalRepositoryManager localRepositoryManager ) - { + public DefaultRepositorySystemSession setLocalRepositoryManager(LocalRepositoryManager localRepositoryManager) { verifyStateForMutation(); this.localRepositoryManager = localRepositoryManager; return this; } @Override - public FileTransformerManager getFileTransformerManager() - { + public FileTransformerManager getFileTransformerManager() { return fileTransformerManager; } - public DefaultRepositorySystemSession setFileTransformerManager( FileTransformerManager fileTransformerManager ) - { + public DefaultRepositorySystemSession setFileTransformerManager(FileTransformerManager fileTransformerManager) { verifyStateForMutation(); this.fileTransformerManager = fileTransformerManager; - if ( this.fileTransformerManager == null ) - { + if (this.fileTransformerManager == null) { this.fileTransformerManager = NullFileTransformerManager.INSTANCE; } return this; } @Override - public WorkspaceReader getWorkspaceReader() - { + public WorkspaceReader getWorkspaceReader() { return workspaceReader; } @@ -366,16 +342,14 @@ public WorkspaceReader getWorkspaceReader() * @param workspaceReader The workspace reader for this session, may be {@code null} if none. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setWorkspaceReader( WorkspaceReader workspaceReader ) - { + public DefaultRepositorySystemSession setWorkspaceReader(WorkspaceReader workspaceReader) { verifyStateForMutation(); this.workspaceReader = workspaceReader; return this; } @Override - public RepositoryListener getRepositoryListener() - { + public RepositoryListener getRepositoryListener() { return repositoryListener; } @@ -385,16 +359,14 @@ public RepositoryListener getRepositoryListener() * @param repositoryListener The repository listener, may be {@code null} if none. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setRepositoryListener( RepositoryListener repositoryListener ) - { + public DefaultRepositorySystemSession setRepositoryListener(RepositoryListener repositoryListener) { verifyStateForMutation(); this.repositoryListener = repositoryListener; return this; } @Override - public TransferListener getTransferListener() - { + public TransferListener getTransferListener() { return transferListener; } @@ -404,33 +376,25 @@ public TransferListener getTransferListener() * @param transferListener The transfer listener, may be {@code null} if none. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setTransferListener( TransferListener transferListener ) - { + public DefaultRepositorySystemSession setTransferListener(TransferListener transferListener) { verifyStateForMutation(); this.transferListener = transferListener; return this; } - @SuppressWarnings( "checkstyle:magicnumber" ) - private Map copySafe( Map table, Class valueType ) - { + @SuppressWarnings("checkstyle:magicnumber") + private Map copySafe(Map table, Class valueType) { Map map; - if ( table == null || table.isEmpty() ) - { + if (table == null || table.isEmpty()) { map = new HashMap<>(); - } - else - { - map = new HashMap<>( (int) ( table.size() / 0.75f ) + 1 ); - for ( Map.Entry entry : table.entrySet() ) - { + } else { + map = new HashMap<>((int) (table.size() / 0.75f) + 1); + for (Map.Entry entry : table.entrySet()) { Object key = entry.getKey(); - if ( key instanceof String ) - { + if (key instanceof String) { Object value = entry.getValue(); - if ( valueType.isInstance( value ) ) - { - map.put( key.toString(), valueType.cast( value ) ); + if (valueType.isInstance(value)) { + map.put(key.toString(), valueType.cast(value)); } } } @@ -439,8 +403,7 @@ private Map copySafe( Map table, Class valueType ) } @Override - public Map getSystemProperties() - { + public Map getSystemProperties() { return systemPropertiesView; } @@ -454,11 +417,10 @@ public Map getSystemProperties() * @param systemProperties The system properties, may be {@code null} or empty if none. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setSystemProperties( Map systemProperties ) - { + public DefaultRepositorySystemSession setSystemProperties(Map systemProperties) { verifyStateForMutation(); - this.systemProperties = copySafe( systemProperties, String.class ); - systemPropertiesView = Collections.unmodifiableMap( this.systemProperties ); + this.systemProperties = copySafe(systemProperties, String.class); + systemPropertiesView = Collections.unmodifiableMap(this.systemProperties); return this; } @@ -469,23 +431,18 @@ public DefaultRepositorySystemSession setSystemProperties( Map systemPrope * @param value The property value, may be {@code null} to remove/unset the property. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setSystemProperty( String key, String value ) - { + public DefaultRepositorySystemSession setSystemProperty(String key, String value) { verifyStateForMutation(); - if ( value != null ) - { - systemProperties.put( key, value ); - } - else - { - systemProperties.remove( key ); + if (value != null) { + systemProperties.put(key, value); + } else { + systemProperties.remove(key); } return this; } @Override - public Map getUserProperties() - { + public Map getUserProperties() { return userPropertiesView; } @@ -500,11 +457,10 @@ public Map getUserProperties() * @param userProperties The user properties, may be {@code null} or empty if none. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setUserProperties( Map userProperties ) - { + public DefaultRepositorySystemSession setUserProperties(Map userProperties) { verifyStateForMutation(); - this.userProperties = copySafe( userProperties, String.class ); - userPropertiesView = Collections.unmodifiableMap( this.userProperties ); + this.userProperties = copySafe(userProperties, String.class); + userPropertiesView = Collections.unmodifiableMap(this.userProperties); return this; } @@ -515,23 +471,18 @@ public DefaultRepositorySystemSession setUserProperties( Map userPropertie * @param value The property value, may be {@code null} to remove/unset the property. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setUserProperty( String key, String value ) - { + public DefaultRepositorySystemSession setUserProperty(String key, String value) { verifyStateForMutation(); - if ( value != null ) - { - userProperties.put( key, value ); - } - else - { - userProperties.remove( key ); + if (value != null) { + userProperties.put(key, value); + } else { + userProperties.remove(key); } return this; } @Override - public Map getConfigProperties() - { + public Map getConfigProperties() { return configPropertiesView; } @@ -545,11 +496,10 @@ public Map getConfigProperties() * @param configProperties The configuration properties, may be {@code null} or empty if none. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setConfigProperties( Map configProperties ) - { + public DefaultRepositorySystemSession setConfigProperties(Map configProperties) { verifyStateForMutation(); - this.configProperties = copySafe( configProperties, Object.class ); - configPropertiesView = Collections.unmodifiableMap( this.configProperties ); + this.configProperties = copySafe(configProperties, Object.class); + configPropertiesView = Collections.unmodifiableMap(this.configProperties); return this; } @@ -560,23 +510,18 @@ public DefaultRepositorySystemSession setConfigProperties( Map configPrope * @param value The property value, may be {@code null} to remove/unset the property. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setConfigProperty( String key, Object value ) - { + public DefaultRepositorySystemSession setConfigProperty(String key, Object value) { verifyStateForMutation(); - if ( value != null ) - { - configProperties.put( key, value ); - } - else - { - configProperties.remove( key ); + if (value != null) { + configProperties.put(key, value); + } else { + configProperties.remove(key); } return this; } @Override - public MirrorSelector getMirrorSelector() - { + public MirrorSelector getMirrorSelector() { return mirrorSelector; } @@ -588,20 +533,17 @@ public MirrorSelector getMirrorSelector() * @param mirrorSelector The mirror selector to use, may be {@code null}. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setMirrorSelector( MirrorSelector mirrorSelector ) - { + public DefaultRepositorySystemSession setMirrorSelector(MirrorSelector mirrorSelector) { verifyStateForMutation(); this.mirrorSelector = mirrorSelector; - if ( this.mirrorSelector == null ) - { + if (this.mirrorSelector == null) { this.mirrorSelector = NullMirrorSelector.INSTANCE; } return this; } @Override - public ProxySelector getProxySelector() - { + public ProxySelector getProxySelector() { return proxySelector; } @@ -614,20 +556,17 @@ public ProxySelector getProxySelector() * @return This session for chaining, never {@code null}. * @see org.eclipse.aether.repository.RemoteRepository#getProxy() */ - public DefaultRepositorySystemSession setProxySelector( ProxySelector proxySelector ) - { + public DefaultRepositorySystemSession setProxySelector(ProxySelector proxySelector) { verifyStateForMutation(); this.proxySelector = proxySelector; - if ( this.proxySelector == null ) - { + if (this.proxySelector == null) { this.proxySelector = NullProxySelector.INSTANCE; } return this; } @Override - public AuthenticationSelector getAuthenticationSelector() - { + public AuthenticationSelector getAuthenticationSelector() { return authenticationSelector; } @@ -640,20 +579,17 @@ public AuthenticationSelector getAuthenticationSelector() * @return This session for chaining, never {@code null}. * @see org.eclipse.aether.repository.RemoteRepository#getAuthentication() */ - public DefaultRepositorySystemSession setAuthenticationSelector( AuthenticationSelector authenticationSelector ) - { + public DefaultRepositorySystemSession setAuthenticationSelector(AuthenticationSelector authenticationSelector) { verifyStateForMutation(); this.authenticationSelector = authenticationSelector; - if ( this.authenticationSelector == null ) - { + if (this.authenticationSelector == null) { this.authenticationSelector = NullAuthenticationSelector.INSTANCE; } return this; } @Override - public ArtifactTypeRegistry getArtifactTypeRegistry() - { + public ArtifactTypeRegistry getArtifactTypeRegistry() { return artifactTypeRegistry; } @@ -663,20 +599,17 @@ public ArtifactTypeRegistry getArtifactTypeRegistry() * @param artifactTypeRegistry The artifact type registry, may be {@code null}. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setArtifactTypeRegistry( ArtifactTypeRegistry artifactTypeRegistry ) - { + public DefaultRepositorySystemSession setArtifactTypeRegistry(ArtifactTypeRegistry artifactTypeRegistry) { verifyStateForMutation(); this.artifactTypeRegistry = artifactTypeRegistry; - if ( this.artifactTypeRegistry == null ) - { + if (this.artifactTypeRegistry == null) { this.artifactTypeRegistry = NullArtifactTypeRegistry.INSTANCE; } return this; } @Override - public DependencyTraverser getDependencyTraverser() - { + public DependencyTraverser getDependencyTraverser() { return dependencyTraverser; } @@ -686,16 +619,14 @@ public DependencyTraverser getDependencyTraverser() * @param dependencyTraverser The dependency traverser to use for building dependency graphs, may be {@code null}. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setDependencyTraverser( DependencyTraverser dependencyTraverser ) - { + public DefaultRepositorySystemSession setDependencyTraverser(DependencyTraverser dependencyTraverser) { verifyStateForMutation(); this.dependencyTraverser = dependencyTraverser; return this; } @Override - public DependencyManager getDependencyManager() - { + public DependencyManager getDependencyManager() { return dependencyManager; } @@ -705,16 +636,14 @@ public DependencyManager getDependencyManager() * @param dependencyManager The dependency manager to use for building dependency graphs, may be {@code null}. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setDependencyManager( DependencyManager dependencyManager ) - { + public DefaultRepositorySystemSession setDependencyManager(DependencyManager dependencyManager) { verifyStateForMutation(); this.dependencyManager = dependencyManager; return this; } @Override - public DependencySelector getDependencySelector() - { + public DependencySelector getDependencySelector() { return dependencySelector; } @@ -724,16 +653,14 @@ public DependencySelector getDependencySelector() * @param dependencySelector The dependency selector to use for building dependency graphs, may be {@code null}. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setDependencySelector( DependencySelector dependencySelector ) - { + public DefaultRepositorySystemSession setDependencySelector(DependencySelector dependencySelector) { verifyStateForMutation(); this.dependencySelector = dependencySelector; return this; } @Override - public VersionFilter getVersionFilter() - { + public VersionFilter getVersionFilter() { return versionFilter; } @@ -744,16 +671,14 @@ public VersionFilter getVersionFilter() * versions. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setVersionFilter( VersionFilter versionFilter ) - { + public DefaultRepositorySystemSession setVersionFilter(VersionFilter versionFilter) { verifyStateForMutation(); this.versionFilter = versionFilter; return this; } @Override - public DependencyGraphTransformer getDependencyGraphTransformer() - { + public DependencyGraphTransformer getDependencyGraphTransformer() { return dependencyGraphTransformer; } @@ -765,16 +690,14 @@ public DependencyGraphTransformer getDependencyGraphTransformer() * @return This session for chaining, never {@code null}. */ public DefaultRepositorySystemSession setDependencyGraphTransformer( - DependencyGraphTransformer dependencyGraphTransformer ) - { + DependencyGraphTransformer dependencyGraphTransformer) { verifyStateForMutation(); this.dependencyGraphTransformer = dependencyGraphTransformer; return this; } @Override - public SessionData getData() - { + public SessionData getData() { return data; } @@ -784,20 +707,17 @@ public SessionData getData() * @param data The session data, may be {@code null}. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setData( SessionData data ) - { + public DefaultRepositorySystemSession setData(SessionData data) { verifyStateForMutation(); this.data = data; - if ( this.data == null ) - { + if (this.data == null) { this.data = new DefaultSessionData(); } return this; } @Override - public RepositoryCache getCache() - { + public RepositoryCache getCache() { return cache; } @@ -807,8 +727,7 @@ public RepositoryCache getCache() * @param cache The repository cache, may be {@code null} if none. * @return This session for chaining, never {@code null}. */ - public DefaultRepositorySystemSession setCache( RepositoryCache cache ) - { + public DefaultRepositorySystemSession setCache(RepositoryCache cache) { verifyStateForMutation(); this.cache = cache; return this; @@ -819,84 +738,63 @@ public DefaultRepositorySystemSession setCache( RepositoryCache cache ) * Marking an already read-only session as read-only has no effect. The session's data and cache remain writable * though. */ - public void setReadOnly() - { + public void setReadOnly() { readOnly = true; } /** * Verifies this instance state for mutation operations: mutated instance must not be read-only or closed. */ - private void verifyStateForMutation() - { - if ( readOnly ) - { - throw new IllegalStateException( "repository system session is read-only" ); + private void verifyStateForMutation() { + if (readOnly) { + throw new IllegalStateException("repository system session is read-only"); } } - static class NullProxySelector - implements ProxySelector - { + static class NullProxySelector implements ProxySelector { public static final ProxySelector INSTANCE = new NullProxySelector(); - public Proxy getProxy( RemoteRepository repository ) - { - requireNonNull( repository, "repository cannot be null" ); + public Proxy getProxy(RemoteRepository repository) { + requireNonNull(repository, "repository cannot be null"); return repository.getProxy(); } - } - static class NullMirrorSelector - implements MirrorSelector - { + static class NullMirrorSelector implements MirrorSelector { public static final MirrorSelector INSTANCE = new NullMirrorSelector(); - public RemoteRepository getMirror( RemoteRepository repository ) - { - requireNonNull( repository, "repository cannot be null" ); + public RemoteRepository getMirror(RemoteRepository repository) { + requireNonNull(repository, "repository cannot be null"); return null; } - } - static class NullAuthenticationSelector - implements AuthenticationSelector - { + static class NullAuthenticationSelector implements AuthenticationSelector { public static final AuthenticationSelector INSTANCE = new NullAuthenticationSelector(); - public Authentication getAuthentication( RemoteRepository repository ) - { - requireNonNull( repository, "repository cannot be null" ); + public Authentication getAuthentication(RemoteRepository repository) { + requireNonNull(repository, "repository cannot be null"); return repository.getAuthentication(); } - } - static final class NullArtifactTypeRegistry - implements ArtifactTypeRegistry - { + static final class NullArtifactTypeRegistry implements ArtifactTypeRegistry { public static final ArtifactTypeRegistry INSTANCE = new NullArtifactTypeRegistry(); - public ArtifactType get( String typeId ) - { + public ArtifactType get(String typeId) { return null; } - } - static final class NullFileTransformerManager implements FileTransformerManager - { + static final class NullFileTransformerManager implements FileTransformerManager { public static final FileTransformerManager INSTANCE = new NullFileTransformerManager(); @Override - public Collection getTransformersForArtifact( Artifact artifact ) - { + public Collection getTransformersForArtifact(Artifact artifact) { return Collections.emptyList(); } } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultSessionData.java b/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultSessionData.java index ea430a53c..284945e16 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultSessionData.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/DefaultSessionData.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,72 +16,58 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Objects.requireNonNull; +package org.eclipse.aether; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Supplier; +import static java.util.Objects.requireNonNull; + /** * A simple session data storage backed by a thread-safe map. */ -public final class DefaultSessionData - implements SessionData -{ +public final class DefaultSessionData implements SessionData { private final ConcurrentMap data; - public DefaultSessionData() - { + public DefaultSessionData() { data = new ConcurrentHashMap<>(); } - public void set( Object key, Object value ) - { - requireNonNull( key, "key cannot be null" ); + public void set(Object key, Object value) { + requireNonNull(key, "key cannot be null"); - if ( value != null ) - { - data.put( key, value ); - } - else - { - data.remove( key ); + if (value != null) { + data.put(key, value); + } else { + data.remove(key); } } - public boolean set( Object key, Object oldValue, Object newValue ) - { - requireNonNull( key, "key cannot be null" ); + public boolean set(Object key, Object oldValue, Object newValue) { + requireNonNull(key, "key cannot be null"); - if ( newValue != null ) - { - if ( oldValue == null ) - { - return data.putIfAbsent( key, newValue ) == null; + if (newValue != null) { + if (oldValue == null) { + return data.putIfAbsent(key, newValue) == null; } - return data.replace( key, oldValue, newValue ); - } - else - { - if ( oldValue == null ) - { - return !data.containsKey( key ); + return data.replace(key, oldValue, newValue); + } else { + if (oldValue == null) { + return !data.containsKey(key); } - return data.remove( key, oldValue ); + return data.remove(key, oldValue); } } - public Object get( Object key ) - { - requireNonNull( key, "key cannot be null" ); + public Object get(Object key) { + requireNonNull(key, "key cannot be null"); - return data.get( key ); + return data.get(key); } - public Object computeIfAbsent( Object key, Supplier supplier ) - { - return data.computeIfAbsent( key, k -> supplier.get() ); + public Object computeIfAbsent(Object key, Supplier supplier) { + return data.computeIfAbsent(key, k -> supplier.get()); } } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/MultiRuntimeException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/MultiRuntimeException.java index 94681666d..fd359bcee 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/MultiRuntimeException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/MultiRuntimeException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; import java.util.List; @@ -29,18 +28,14 @@ * * @since 1.9.0 */ -public final class MultiRuntimeException - extends RuntimeException -{ +public final class MultiRuntimeException extends RuntimeException { private final List throwables; - private MultiRuntimeException( String message, List throwables ) - { - super( message ); + private MultiRuntimeException(String message, List throwables) { + super(message); this.throwables = throwables; - for ( Throwable throwable : throwables ) - { - addSuppressed( throwable ); + for (Throwable throwable : throwables) { + addSuppressed(throwable); } } @@ -49,8 +44,7 @@ private MultiRuntimeException( String message, List throwab * * @return The list of throwables, never {@code null}. */ - public List getThrowables() - { + public List getThrowables() { return throwables; } @@ -61,14 +55,12 @@ public List getThrowables() *
  • if list not empty - {@link MultiRuntimeException} is thrown wrapping all elements
  • * */ - public static void mayThrow( String message, List throwables ) - { - requireNonNull( message ); - requireNonNull( throwables ); + public static void mayThrow(String message, List throwables) { + requireNonNull(message); + requireNonNull(throwables); - if ( !throwables.isEmpty() ) - { - throw new MultiRuntimeException( message, throwables ); + if (!throwables.isEmpty()) { + throw new MultiRuntimeException(message, throwables); } } } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryCache.java b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryCache.java index 6f9f1144f..9bf6268f0 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryCache.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryCache.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,16 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; /** * Caches auxiliary data used during repository access like already processed metadata. The data in the cache is meant * for exclusive consumption by the repository system and is opaque to the cache implementation. Note: * Actual cache implementations must be thread-safe. - * + * * @see RepositorySystemSession#getCache() */ -public interface RepositoryCache -{ +public interface RepositoryCache { /** * Puts the specified data into the cache. It is entirely up to the cache implementation how long this data will be @@ -36,12 +34,12 @@ public interface RepositoryCache * Warning: The cache will directly save the provided reference. If the cached data is mutable, i.e. could * be modified after being put into the cache, the caller is responsible for creating a copy of the original data * and store the copy in the cache. - * + * * @param session The repository session during which the cache is accessed, must not be {@code null}. * @param key The key to use for lookup of the data, must not be {@code null}. * @param data The data to store in the cache, may be {@code null}. */ - void put( RepositorySystemSession session, Object key, Object data ); + void put(RepositorySystemSession session, Object key, Object data); /** * Gets the specified data from the cache. @@ -49,11 +47,10 @@ public interface RepositoryCache * Warning: The cache will directly return the saved reference. If the cached data is to be modified after * its retrieval, the caller is responsible to create a copy of the returned data and use this instead of the cache * record. - * + * * @param session The repository session during which the cache is accessed, must not be {@code null}. * @param key The key to use for lookup of the data, must not be {@code null}. * @return The requested data or {@code null} if none was present in the cache. */ - Object get( RepositorySystemSession session, Object key ); - + Object get(RepositorySystemSession session, Object key); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryEvent.java b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryEvent.java index 8d1e6016f..a75bfa5e1 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryEvent.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryEvent.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,32 +16,32 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; import java.io.File; import java.util.Collections; import java.util.List; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.metadata.Metadata; import org.eclipse.aether.repository.ArtifactRepository; +import static java.util.Objects.requireNonNull; + /** * An event describing an action performed by the repository system. Note that events which indicate the end of an * action like {@link EventType#ARTIFACT_RESOLVED} are generally fired in both the success and the failure case. Use * {@link #getException()} to check whether an event denotes success or failure. - * + * * @see RepositoryListener * @see RepositoryEvent.Builder */ -public final class RepositoryEvent -{ +public final class RepositoryEvent { /** * The type of the repository event. */ - public enum EventType - { + public enum EventType { /** * @see RepositoryListener#artifactDescriptorInvalid(RepositoryEvent) @@ -139,7 +137,6 @@ public enum EventType * @see RepositoryListener#metadataDeployed(RepositoryEvent) */ METADATA_DEPLOYED - } private final EventType type; @@ -158,8 +155,7 @@ public enum EventType private final RequestTrace trace; - RepositoryEvent( Builder builder ) - { + RepositoryEvent(Builder builder) { type = builder.type; session = builder.session; artifact = builder.artifact; @@ -172,61 +168,55 @@ public enum EventType /** * Gets the type of the event. - * + * * @return The type of the event, never {@code null}. */ - public EventType getType() - { + public EventType getType() { return type; } /** * Gets the repository system session during which the event occurred. - * + * * @return The repository system session during which the event occurred, never {@code null}. */ - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } /** * Gets the artifact involved in the event (if any). - * + * * @return The involved artifact or {@code null} if none. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Gets the metadata involved in the event (if any). - * + * * @return The involved metadata or {@code null} if none. */ - public Metadata getMetadata() - { + public Metadata getMetadata() { return metadata; } /** * Gets the file involved in the event (if any). - * + * * @return The involved file or {@code null} if none. */ - public File getFile() - { + public File getFile() { return file; } /** * Gets the repository involved in the event (if any). - * + * * @return The involved repository or {@code null} if none. */ - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return repository; } @@ -234,55 +224,47 @@ public ArtifactRepository getRepository() * Gets the exception that caused the event (if any). As a rule of thumb, an event accompanied by an exception * indicates a failure of the corresponding action. If multiple exceptions occurred, this method returns the first * exception. - * + * * @return The exception or {@code null} if none. */ - public Exception getException() - { - return exceptions.isEmpty() ? null : exceptions.get( 0 ); + public Exception getException() { + return exceptions.isEmpty() ? null : exceptions.get(0); } /** * Gets the exceptions that caused the event (if any). As a rule of thumb, an event accompanied by exceptions * indicates a failure of the corresponding action. - * + * * @return The exceptions, never {@code null}. */ - public List getExceptions() - { + public List getExceptions() { return exceptions; } /** * Gets the trace information about the request during which the event occurred. - * + * * @return The trace information or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( getType() ); - if ( getArtifact() != null ) - { - buffer.append( " " ).append( getArtifact() ); + public String toString() { + StringBuilder buffer = new StringBuilder(256); + buffer.append(getType()); + if (getArtifact() != null) { + buffer.append(" ").append(getArtifact()); } - if ( getMetadata() != null ) - { - buffer.append( " " ).append( getMetadata() ); + if (getMetadata() != null) { + buffer.append(" ").append(getMetadata()); } - if ( getFile() != null ) - { - buffer.append( " (" ).append( getFile() ).append( ")" ); + if (getFile() != null) { + buffer.append(" (").append(getFile()).append(")"); } - if ( getRepository() != null ) - { - buffer.append( " @ " ).append( getRepository() ); + if (getRepository() != null) { + buffer.append(" @ ").append(getRepository()); } return buffer.toString(); } @@ -290,8 +272,7 @@ public String toString() /** * A builder to create events. */ - public static final class Builder - { + public static final class Builder { final EventType type; @@ -315,10 +296,9 @@ public static final class Builder * @param session The repository system session, must not be {@code null}. * @param type The type of the event, must not be {@code null}. */ - public Builder( RepositorySystemSession session, EventType type ) - { - this.session = requireNonNull( session, "session cannot be null" ); - this.type = requireNonNull( type, "event type cannot be null" ); + public Builder(RepositorySystemSession session, EventType type) { + this.session = requireNonNull(session, "session cannot be null"); + this.type = requireNonNull(type, "event type cannot be null"); } /** @@ -327,62 +307,54 @@ public Builder( RepositorySystemSession session, EventType type ) * @param artifact The involved artifact, may be {@code null}. * @return This event builder for chaining, never {@code null}. */ - public Builder setArtifact( Artifact artifact ) - { + public Builder setArtifact(Artifact artifact) { this.artifact = artifact; return this; } /** * Sets the metadata involved in the event. - * + * * @param metadata The involved metadata, may be {@code null}. * @return This event builder for chaining, never {@code null}. */ - public Builder setMetadata( Metadata metadata ) - { + public Builder setMetadata(Metadata metadata) { this.metadata = metadata; return this; } /** * Sets the repository involved in the event. - * + * * @param repository The involved repository, may be {@code null}. * @return This event builder for chaining, never {@code null}. */ - public Builder setRepository( ArtifactRepository repository ) - { + public Builder setRepository(ArtifactRepository repository) { this.repository = repository; return this; } /** * Sets the file involved in the event. - * + * * @param file The involved file, may be {@code null}. * @return This event builder for chaining, never {@code null}. */ - public Builder setFile( File file ) - { + public Builder setFile(File file) { this.file = file; return this; } /** * Sets the exception causing the event. - * + * * @param exception The exception causing the event, may be {@code null}. * @return This event builder for chaining, never {@code null}. */ - public Builder setException( Exception exception ) - { - if ( exception != null ) - { - this.exceptions = Collections.singletonList( exception ); - } - else - { + public Builder setException(Exception exception) { + if (exception != null) { + this.exceptions = Collections.singletonList(exception); + } else { this.exceptions = Collections.emptyList(); } return this; @@ -390,18 +362,14 @@ public Builder setException( Exception exception ) /** * Sets the exceptions causing the event. - * + * * @param exceptions The exceptions causing the event, may be {@code null}. * @return This event builder for chaining, never {@code null}. */ - public Builder setExceptions( List exceptions ) - { - if ( exceptions != null ) - { + public Builder setExceptions(List exceptions) { + if (exceptions != null) { this.exceptions = exceptions; - } - else - { + } else { this.exceptions = Collections.emptyList(); } return this; @@ -409,12 +377,11 @@ public Builder setExceptions( List exceptions ) /** * Sets the trace information about the request during which the event occurred. - * + * * @param trace The trace information, may be {@code null}. * @return This event builder for chaining, never {@code null}. */ - public Builder setTrace( RequestTrace trace ) - { + public Builder setTrace(RequestTrace trace) { this.trace = trace; return this; } @@ -422,14 +389,11 @@ public Builder setTrace( RequestTrace trace ) /** * Builds a new event from the current values of this builder. The state of the builder itself remains * unchanged. - * + * * @return The event, never {@code null}. */ - public RepositoryEvent build() - { - return new RepositoryEvent( this ); + public RepositoryEvent build() { + return new RepositoryEvent(this); } - } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryException.java index abf962eb8..d7f19a85e 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,34 +16,31 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; /** * The base class for exceptions thrown by the repository system. Note: Unless otherwise noted, instances of * this class and its subclasses will not persist fields carrying extended error information during serialization. */ -public class RepositoryException - extends Exception -{ +public class RepositoryException extends Exception { /** * Creates a new exception with the specified detail message. - * + * * @param message The detail message, may be {@code null}. */ - public RepositoryException( String message ) - { - super( message ); + public RepositoryException(String message) { + super(message); } /** * Creates a new exception with the specified detail message and cause. - * + * * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public RepositoryException( String message, Throwable cause ) - { - super( message, cause ); + public RepositoryException(String message, Throwable cause) { + super(message, cause); } /** @@ -54,19 +49,15 @@ public RepositoryException( String message, Throwable cause ) * @return The message. * @noreference This method is not intended to be used by clients. */ - protected static String getMessage( String prefix, Throwable cause ) - { + protected static String getMessage(String prefix, Throwable cause) { String msg = ""; - if ( cause != null ) - { + if (cause != null) { msg = cause.getMessage(); - if ( msg == null || msg.isEmpty() ) - { + if (msg == null || msg.isEmpty()) { msg = cause.getClass().getSimpleName(); } msg = prefix + msg; } return msg; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryListener.java b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryListener.java index d65463059..cca779b87 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryListener.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositoryListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; /** * A listener being notified of events from the repository system. In general, the system sends events upon termination @@ -25,14 +24,13 @@ * listeners need to inspect the event details carefully. Also, the listener may be called from an arbitrary thread. * Note: Implementors are strongly advised to inherit from {@link AbstractRepositoryListener} instead of * directly implementing this interface. - * + * * @see org.eclipse.aether.RepositorySystemSession#getRepositoryListener() * @see org.eclipse.aether.transfer.TransferListener * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface RepositoryListener -{ +public interface RepositoryListener { /** * Notifies the listener of a syntactically or semantically invalid artifact descriptor. @@ -40,39 +38,39 @@ public interface RepositoryListener * {@link RepositoryEvent#getExceptions()} carries the encountered errors. Depending on the session's * {@link org.eclipse.aether.resolution.ArtifactDescriptorPolicy}, the underlying repository operation might abort * with an exception or ignore the invalid descriptor. - * + * * @param event The event details, must not be {@code null}. */ - void artifactDescriptorInvalid( RepositoryEvent event ); + void artifactDescriptorInvalid(RepositoryEvent event); /** * Notifies the listener of a missing artifact descriptor. {@link RepositoryEvent#getArtifact()} indicates the * artifact whose descriptor is missing. Depending on the session's * {@link org.eclipse.aether.resolution.ArtifactDescriptorPolicy}, the underlying repository operation might abort * with an exception or ignore the missing descriptor. - * + * * @param event The event details, must not be {@code null}. */ - void artifactDescriptorMissing( RepositoryEvent event ); + void artifactDescriptorMissing(RepositoryEvent event); /** * Notifies the listener of syntactically or semantically invalid metadata. {@link RepositoryEvent#getMetadata()} * indicates the invalid metadata and {@link RepositoryEvent#getExceptions()} carries the encountered errors. The * underlying repository operation might still succeed, depending on whether the metadata in question is actually * needed to carry out the resolution process. - * + * * @param event The event details, must not be {@code null}. */ - void metadataInvalid( RepositoryEvent event ); + void metadataInvalid(RepositoryEvent event); /** * Notifies the listener of an artifact that is about to be resolved. {@link RepositoryEvent#getArtifact()} denotes * the artifact in question. Unlike the {@link #artifactDownloading(RepositoryEvent)} event, this event is fired * regardless whether the artifact already exists locally or not. - * + * * @param event The event details, must not be {@code null}. */ - void artifactResolving( RepositoryEvent event ); + void artifactResolving(RepositoryEvent event); /** * Notifies the listener of an artifact whose resolution has been completed, either successfully or not. @@ -80,19 +78,19 @@ public interface RepositoryListener * {@link RepositoryEvent#getExceptions()} indicates whether the resolution succeeded or failed. Unlike the * {@link #artifactDownloaded(RepositoryEvent)} event, this event is fired regardless whether the artifact already * exists locally or not. - * + * * @param event The event details, must not be {@code null}. */ - void artifactResolved( RepositoryEvent event ); + void artifactResolved(RepositoryEvent event); /** * Notifies the listener of some metadata that is about to be resolved. {@link RepositoryEvent#getMetadata()} * denotes the metadata in question. Unlike the {@link #metadataDownloading(RepositoryEvent)} event, this event is * fired regardless whether the metadata already exists locally or not. - * + * * @param event The event details, must not be {@code null}. */ - void metadataResolving( RepositoryEvent event ); + void metadataResolving(RepositoryEvent event); /** * Notifies the listener of some metadata whose resolution has been completed, either successfully or not. @@ -100,10 +98,10 @@ public interface RepositoryListener * {@link RepositoryEvent#getExceptions()} indicates whether the resolution succeeded or failed. Unlike the * {@link #metadataDownloaded(RepositoryEvent)} event, this event is fired regardless whether the metadata already * exists locally or not. - * + * * @param event The event details, must not be {@code null}. */ - void metadataResolved( RepositoryEvent event ); + void metadataResolved(RepositoryEvent event); /** * Notifies the listener of an artifact that is about to be downloaded from a remote repository. @@ -111,10 +109,10 @@ public interface RepositoryListener * {@link RepositoryEvent#getRepository()} the source repository. Unlike the * {@link #artifactResolving(RepositoryEvent)} event, this event is only fired when the artifact does not already * exist locally. - * + * * @param event The event details, must not be {@code null}. */ - void artifactDownloading( RepositoryEvent event ); + void artifactDownloading(RepositoryEvent event); /** * Notifies the listener of an artifact whose download has been completed, either successfully or not. @@ -122,10 +120,10 @@ public interface RepositoryListener * {@link RepositoryEvent#getExceptions()} indicates whether the download succeeded or failed. Unlike the * {@link #artifactResolved(RepositoryEvent)} event, this event is only fired when the artifact does not already * exist locally. - * + * * @param event The event details, must not be {@code null}. */ - void artifactDownloaded( RepositoryEvent event ); + void artifactDownloaded(RepositoryEvent event); /** * Notifies the listener of some metadata that is about to be downloaded from a remote repository. @@ -133,10 +131,10 @@ public interface RepositoryListener * {@link RepositoryEvent#getRepository()} the source repository. Unlike the * {@link #metadataResolving(RepositoryEvent)} event, this event is only fired when the metadata does not already * exist locally. - * + * * @param event The event details, must not be {@code null}. */ - void metadataDownloading( RepositoryEvent event ); + void metadataDownloading(RepositoryEvent event); /** * Notifies the listener of some metadata whose download has been completed, either successfully or not. @@ -144,79 +142,78 @@ public interface RepositoryListener * {@link RepositoryEvent#getExceptions()} indicates whether the download succeeded or failed. Unlike the * {@link #metadataResolved(RepositoryEvent)} event, this event is only fired when the metadata does not already * exist locally. - * + * * @param event The event details, must not be {@code null}. */ - void metadataDownloaded( RepositoryEvent event ); + void metadataDownloaded(RepositoryEvent event); /** * Notifies the listener of an artifact that is about to be installed to the local repository. * {@link RepositoryEvent#getArtifact()} denotes the artifact in question. - * + * * @param event The event details, must not be {@code null}. */ - void artifactInstalling( RepositoryEvent event ); + void artifactInstalling(RepositoryEvent event); /** * Notifies the listener of an artifact whose installation to the local repository has been completed, either * successfully or not. {@link RepositoryEvent#getArtifact()} denotes the artifact in question and * {@link RepositoryEvent#getExceptions()} indicates whether the installation succeeded or failed. - * + * * @param event The event details, must not be {@code null}. */ - void artifactInstalled( RepositoryEvent event ); + void artifactInstalled(RepositoryEvent event); /** * Notifies the listener of some metadata that is about to be installed to the local repository. * {@link RepositoryEvent#getMetadata()} denotes the metadata in question. - * + * * @param event The event details, must not be {@code null}. */ - void metadataInstalling( RepositoryEvent event ); + void metadataInstalling(RepositoryEvent event); /** * Notifies the listener of some metadata whose installation to the local repository has been completed, either * successfully or not. {@link RepositoryEvent#getMetadata()} denotes the metadata in question and * {@link RepositoryEvent#getExceptions()} indicates whether the installation succeeded or failed. - * + * * @param event The event details, must not be {@code null}. */ - void metadataInstalled( RepositoryEvent event ); + void metadataInstalled(RepositoryEvent event); /** * Notifies the listener of an artifact that is about to be uploaded to a remote repository. * {@link RepositoryEvent#getArtifact()} denotes the artifact in question and * {@link RepositoryEvent#getRepository()} the destination repository. - * + * * @param event The event details, must not be {@code null}. */ - void artifactDeploying( RepositoryEvent event ); + void artifactDeploying(RepositoryEvent event); /** * Notifies the listener of an artifact whose upload to a remote repository has been completed, either successfully * or not. {@link RepositoryEvent#getArtifact()} denotes the artifact in question and * {@link RepositoryEvent#getExceptions()} indicates whether the upload succeeded or failed. - * + * * @param event The event details, must not be {@code null}. */ - void artifactDeployed( RepositoryEvent event ); + void artifactDeployed(RepositoryEvent event); /** * Notifies the listener of some metadata that is about to be uploaded to a remote repository. * {@link RepositoryEvent#getMetadata()} denotes the metadata in question and * {@link RepositoryEvent#getRepository()} the destination repository. - * + * * @param event The event details, must not be {@code null}. */ - void metadataDeploying( RepositoryEvent event ); + void metadataDeploying(RepositoryEvent event); /** * Notifies the listener of some metadata whose upload to a remote repository has been completed, either * successfully or not. {@link RepositoryEvent#getMetadata()} denotes the metadata in question and * {@link RepositoryEvent#getExceptions()} indicates whether the upload succeeded or failed. - * + * * @param event The event details, must not be {@code null}. */ - void metadataDeployed( RepositoryEvent event ); - + void metadataDeployed(RepositoryEvent event); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositorySystem.java b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositorySystem.java index be186e875..61a612e21 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositorySystem.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositorySystem.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; import java.util.Collection; import java.util.List; @@ -65,8 +64,7 @@ * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface RepositorySystem -{ +public interface RepositorySystem { /** * Expands a version range to a list of matching versions, in ascending order. For example, resolves "[3.8,4.0)" to @@ -84,7 +82,7 @@ public interface RepositorySystem * not raise an exception. * @see #newResolutionRepositories(RepositorySystemSession, List) */ - VersionRangeResult resolveVersionRange( RepositorySystemSession session, VersionRangeRequest request ) + VersionRangeResult resolveVersionRange(RepositorySystemSession session, VersionRangeRequest request) throws VersionRangeResolutionException; /** @@ -97,7 +95,7 @@ VersionRangeResult resolveVersionRange( RepositorySystemSession session, Version * @throws VersionResolutionException If the metaversion could not be resolved. * @see #newResolutionRepositories(RepositorySystemSession, List) */ - VersionResult resolveVersion( RepositorySystemSession session, VersionRequest request ) + VersionResult resolveVersion(RepositorySystemSession session, VersionRequest request) throws VersionResolutionException; /** @@ -110,8 +108,7 @@ VersionResult resolveVersion( RepositorySystemSession session, VersionRequest re * @see RepositorySystemSession#getArtifactDescriptorPolicy() * @see #newResolutionRepositories(RepositorySystemSession, List) */ - ArtifactDescriptorResult readArtifactDescriptor( RepositorySystemSession session, - ArtifactDescriptorRequest request ) + ArtifactDescriptorResult readArtifactDescriptor(RepositorySystemSession session, ArtifactDescriptorRequest request) throws ArtifactDescriptorException; /** @@ -130,7 +127,7 @@ ArtifactDescriptorResult readArtifactDescriptor( RepositorySystemSession session * @see RepositorySystemSession#getDependencyGraphTransformer() * @see #newResolutionRepositories(RepositorySystemSession, List) */ - CollectResult collectDependencies( RepositorySystemSession session, CollectRequest request ) + CollectResult collectDependencies(RepositorySystemSession session, CollectRequest request) throws DependencyCollectionException; /** @@ -145,7 +142,7 @@ CollectResult collectDependencies( RepositorySystemSession session, CollectReque * not be resolved. * @see #newResolutionRepositories(RepositorySystemSession, List) */ - DependencyResult resolveDependencies( RepositorySystemSession session, DependencyRequest request ) + DependencyResult resolveDependencies(RepositorySystemSession session, DependencyRequest request) throws DependencyResolutionException; /** @@ -161,7 +158,7 @@ DependencyResult resolveDependencies( RepositorySystemSession session, Dependenc * @see Artifact#getFile() * @see #newResolutionRepositories(RepositorySystemSession, List) */ - ArtifactResult resolveArtifact( RepositorySystemSession session, ArtifactRequest request ) + ArtifactResult resolveArtifact(RepositorySystemSession session, ArtifactRequest request) throws ArtifactResolutionException; /** @@ -177,8 +174,8 @@ ArtifactResult resolveArtifact( RepositorySystemSession session, ArtifactRequest * @see Artifact#getFile() * @see #newResolutionRepositories(RepositorySystemSession, List) */ - List resolveArtifacts( RepositorySystemSession session, - Collection requests ) + List resolveArtifacts( + RepositorySystemSession session, Collection requests) throws ArtifactResolutionException; /** @@ -191,8 +188,8 @@ List resolveArtifacts( RepositorySystemSession session, * @see Metadata#getFile() * @see #newResolutionRepositories(RepositorySystemSession, List) */ - List resolveMetadata( RepositorySystemSession session, - Collection requests ); + List resolveMetadata( + RepositorySystemSession session, Collection requests); /** * Installs a collection of artifacts and their accompanying metadata to the local repository. @@ -202,8 +199,7 @@ List resolveMetadata( RepositorySystemSession session, * @return The installation result, never {@code null}. * @throws InstallationException If any artifact/metadata from the request could not be installed. */ - InstallResult install( RepositorySystemSession session, InstallRequest request ) - throws InstallationException; + InstallResult install(RepositorySystemSession session, InstallRequest request) throws InstallationException; /** * Uploads a collection of artifacts and their accompanying metadata to a remote repository. @@ -214,8 +210,7 @@ InstallResult install( RepositorySystemSession session, InstallRequest request ) * @throws DeploymentException If any artifact/metadata from the request could not be deployed. * @see #newDeploymentRepository(RepositorySystemSession, RemoteRepository) */ - DeployResult deploy( RepositorySystemSession session, DeployRequest request ) - throws DeploymentException; + DeployResult deploy(RepositorySystemSession session, DeployRequest request) throws DeploymentException; /** * Creates a new manager for the specified local repository. If the specified local repository has no type, the @@ -230,8 +225,7 @@ DeployResult deploy( RepositorySystemSession session, DeployRequest request ) * @throws IllegalArgumentException If the specified repository type is not recognized or no base directory is * given. */ - LocalRepositoryManager newLocalRepositoryManager( RepositorySystemSession session, - LocalRepository localRepository ); + LocalRepositoryManager newLocalRepositoryManager(RepositorySystemSession session, LocalRepository localRepository); /** * Creates a new synchronization context. @@ -241,7 +235,7 @@ LocalRepositoryManager newLocalRepositoryManager( RepositorySystemSession sessio * shared among concurrent readers or whether access needs to be exclusive to the calling thread. * @return The synchronization context, never {@code null}. */ - SyncContext newSyncContext( RepositorySystemSession session, boolean shared ); + SyncContext newSyncContext(RepositorySystemSession session, boolean shared); /** * Forms remote repositories suitable for artifact resolution by applying the session's authentication selector and @@ -261,8 +255,8 @@ LocalRepositoryManager newLocalRepositoryManager( RepositorySystemSession sessio * repositories. * @see #newDeploymentRepository(RepositorySystemSession, RemoteRepository) */ - List newResolutionRepositories( RepositorySystemSession session, - List repositories ); + List newResolutionRepositories( + RepositorySystemSession session, List repositories); /** * Forms a remote repository suitable for artifact deployment by applying the session's authentication selector and @@ -279,7 +273,7 @@ List newResolutionRepositories( RepositorySystemSession sessio * @return The deployment repository, never {@code null}. * @see #newResolutionRepositories(RepositorySystemSession, List) */ - RemoteRepository newDeploymentRepository( RepositorySystemSession session, RemoteRepository repository ); + RemoteRepository newDeploymentRepository(RepositorySystemSession session, RemoteRepository repository); /** * Registers an "on repository system end" handler, executed after repository system is shut down. @@ -287,7 +281,7 @@ List newResolutionRepositories( RepositorySystemSession sessio * @param handler The handler, must not be {@code null}. * @since 1.9.0 */ - void addOnSystemEndedHandler( Runnable handler ); + void addOnSystemEndedHandler(Runnable handler); /** * Signals to repository system to shut down. Shut down instance is not usable anymore. diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositorySystemSession.java b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositorySystemSession.java index df6b2fbfa..31e99cd70 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/RepositorySystemSession.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/RepositorySystemSession.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; import java.util.Map; @@ -48,13 +47,12 @@ * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface RepositorySystemSession -{ +public interface RepositorySystemSession { /** * Indicates whether the repository system operates in offline mode and avoids/refuses any access to remote * repositories. - * + * * @return {@code true} if the repository system is in offline mode, {@code false} otherwise. */ boolean isOffline(); @@ -62,7 +60,7 @@ public interface RepositorySystemSession /** * Indicates whether repositories declared in artifact descriptors should be ignored during transitive dependency * collection. If enabled, only the repositories originally provided with the collect request will be considered. - * + * * @return {@code true} if additional repositories from artifact descriptors are ignored, {@code false} to merge * those with the originally specified repositories. */ @@ -70,7 +68,7 @@ public interface RepositorySystemSession /** * Gets the policy which controls whether resolutions errors from remote repositories should be cached. - * + * * @return The resolution error policy for this session or {@code null} if resolution errors should generally not be * cached. */ @@ -78,7 +76,7 @@ public interface RepositorySystemSession /** * Gets the policy which controls how errors related to reading artifact descriptors should be handled. - * + * * @return The descriptor error policy for this session or {@code null} if descriptor errors should generally not be * tolerated. */ @@ -87,7 +85,7 @@ public interface RepositorySystemSession /** * Gets the global checksum policy. If set, the global checksum policy overrides the checksum policies of the remote * repositories being used for resolution. - * + * * @return The global checksum policy or {@code null}/empty if not set and the per-repository policies apply. * @see RepositoryPolicy#CHECKSUM_POLICY_FAIL * @see RepositoryPolicy#CHECKSUM_POLICY_IGNORE @@ -98,7 +96,7 @@ public interface RepositorySystemSession /** * Gets the global update policy. If set, the global update policy overrides the update policies of the remote * repositories being used for resolution. - * + * * @return The global update policy or {@code null}/empty if not set and the per-repository policies apply. * @see RepositoryPolicy#UPDATE_POLICY_ALWAYS * @see RepositoryPolicy#UPDATE_POLICY_DAILY @@ -109,14 +107,14 @@ public interface RepositorySystemSession /** * Gets the local repository used during this session. This is a convenience method for * {@link LocalRepositoryManager#getRepository()}. - * + * * @return The local repository being during this session, never {@code null}. */ LocalRepository getLocalRepository(); /** * Gets the local repository manager used during this session. - * + * * @return The local repository manager used during this session, never {@code null}. */ LocalRepositoryManager getLocalRepositoryManager(); @@ -124,21 +122,21 @@ public interface RepositorySystemSession /** * Gets the workspace reader used during this session. If set, the workspace reader will usually be consulted first * to resolve artifacts. - * + * * @return The workspace reader for this session or {@code null} if none. */ WorkspaceReader getWorkspaceReader(); /** * Gets the listener being notified of actions in the repository system. - * + * * @return The repository listener or {@code null} if none. */ RepositoryListener getRepositoryListener(); /** * Gets the listener being notified of uploads/downloads by the repository system. - * + * * @return The transfer listener or {@code null} if none. */ TransferListener getTransferListener(); @@ -146,7 +144,7 @@ public interface RepositorySystemSession /** * Gets the system properties to use, e.g. for processing of artifact descriptors. System properties are usually * collected from the runtime environment like {@link System#getProperties()} and environment variables. - * + * * @return The (read-only) system properties, never {@code null}. */ Map getSystemProperties(); @@ -155,7 +153,7 @@ public interface RepositorySystemSession * Gets the user properties to use, e.g. for processing of artifact descriptors. User properties are similar to * system properties but are set on the discretion of the user and hence are considered of higher priority than * system properties. - * + * * @return The (read-only) user properties, never {@code null}. */ Map getUserProperties(); @@ -163,7 +161,7 @@ public interface RepositorySystemSession /** * Gets the configuration properties used to tweak internal aspects of the repository system (e.g. thread pooling, * connector-specific behavior, etc.) - * + * * @return The (read-only) configuration properties, never {@code null}. * @see ConfigurationProperties */ @@ -173,7 +171,7 @@ public interface RepositorySystemSession * Gets the mirror selector to use for repositories discovered in artifact descriptors. Note that this selector is * not used for remote repositories which are passed as request parameters to the repository system, those * repositories are supposed to denote the effective repositories. - * + * * @return The mirror selector to use, never {@code null}. * @see RepositorySystem#newResolutionRepositories(RepositorySystemSession, java.util.List) */ @@ -183,7 +181,7 @@ public interface RepositorySystemSession * Gets the proxy selector to use for repositories discovered in artifact descriptors. Note that this selector is * not used for remote repositories which are passed as request parameters to the repository system, those * repositories are supposed to have their proxy (if any) already set. - * + * * @return The proxy selector to use, never {@code null}. * @see org.eclipse.aether.repository.RemoteRepository#getProxy() * @see RepositorySystem#newResolutionRepositories(RepositorySystemSession, java.util.List) @@ -194,7 +192,7 @@ public interface RepositorySystemSession * Gets the authentication selector to use for repositories discovered in artifact descriptors. Note that this * selector is not used for remote repositories which are passed as request parameters to the repository system, * those repositories are supposed to have their authentication (if any) already set. - * + * * @return The authentication selector to use, never {@code null}. * @see org.eclipse.aether.repository.RemoteRepository#getAuthentication() * @see RepositorySystem#newResolutionRepositories(RepositorySystemSession, java.util.List) @@ -204,14 +202,14 @@ public interface RepositorySystemSession /** * Gets the registry of artifact types recognized by this session, for instance when processing artifact * descriptors. - * + * * @return The artifact type registry, never {@code null}. */ ArtifactTypeRegistry getArtifactTypeRegistry(); /** * Gets the dependency traverser to use for building dependency graphs. - * + * * @return The dependency traverser to use for building dependency graphs or {@code null} if dependencies are * unconditionally traversed. */ @@ -219,7 +217,7 @@ public interface RepositorySystemSession /** * Gets the dependency manager to use for building dependency graphs. - * + * * @return The dependency manager to use for building dependency graphs or {@code null} if dependency management is * not performed. */ @@ -227,7 +225,7 @@ public interface RepositorySystemSession /** * Gets the dependency selector to use for building dependency graphs. - * + * * @return The dependency selector to use for building dependency graphs or {@code null} if dependencies are * unconditionally included. */ @@ -235,35 +233,35 @@ public interface RepositorySystemSession /** * Gets the version filter to use for building dependency graphs. - * + * * @return The version filter to use for building dependency graphs or {@code null} if versions aren't filtered. */ VersionFilter getVersionFilter(); /** * Gets the dependency graph transformer to use for building dependency graphs. - * + * * @return The dependency graph transformer to use for building dependency graphs or {@code null} if none. */ DependencyGraphTransformer getDependencyGraphTransformer(); /** * Gets the custom data associated with this session. - * + * * @return The session data, never {@code null}. */ SessionData getData(); /** * Gets the cache the repository system may use to save data for future reuse during the session. - * + * * @return The repository cache or {@code null} if none. */ RepositoryCache getCache(); /** * Get the file transformer manager - * + * * @return the manager, never {@code null} * @deprecated Without any direct replacement for now. This API is OOM-prone, and also lacks a lot of context about * transforming. diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/RequestTrace.java b/maven-resolver-api/src/main/java/org/eclipse/aether/RequestTrace.java index 86aaa78b1..fe2025224 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/RequestTrace.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/RequestTrace.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; /** * A trace of nested requests that are performed by the repository system. This trace information can be used to @@ -27,11 +26,10 @@ * object that is currently processed. When invoking methods on the repository system, client code may provide a request * trace that has been prepopulated with whatever data is useful for the application to indicate its state for later * evaluation when processing the repository events. - * + * * @see RepositoryEvent#getTrace() */ -public class RequestTrace -{ +public class RequestTrace { private final RequestTrace parent; @@ -41,77 +39,68 @@ public class RequestTrace * Creates a child of the specified request trace. This method is basically a convenience that will invoke * {@link RequestTrace#newChild(Object) parent.newChild()} when the specified parent trace is not {@code null} or * otherwise instantiante a new root trace. - * + * * @param parent The parent request trace, may be {@code null}. * @param data The data to associate with the child trace, may be {@code null}. * @return The child trace, never {@code null}. */ - public static RequestTrace newChild( RequestTrace parent, Object data ) - { - if ( parent == null ) - { - return new RequestTrace( data ); + public static RequestTrace newChild(RequestTrace parent, Object data) { + if (parent == null) { + return new RequestTrace(data); } - return parent.newChild( data ); + return parent.newChild(data); } /** * Creates a new root trace with the specified data. - * + * * @param data The data to associate with the trace, may be {@code null}. */ - public RequestTrace( Object data ) - { - this( null, data ); + public RequestTrace(Object data) { + this(null, data); } /** * Creates a new trace with the specified data and parent - * + * * @param parent The parent trace, may be {@code null} for a root trace. * @param data The data to associate with the trace, may be {@code null}. */ - protected RequestTrace( RequestTrace parent, Object data ) - { + protected RequestTrace(RequestTrace parent, Object data) { this.parent = parent; this.data = data; } /** * Gets the data associated with this trace. - * + * * @return The data associated with this trace or {@code null} if none. */ - public final Object getData() - { + public final Object getData() { return data; } /** * Gets the parent of this trace. - * + * * @return The parent of this trace or {@code null} if this is the root of the trace stack. */ - public final RequestTrace getParent() - { + public final RequestTrace getParent() { return parent; } /** * Creates a new child of this trace. - * + * * @param data The data to associate with the child, may be {@code null}. * @return The child trace, never {@code null}. */ - public RequestTrace newChild( Object data ) - { - return new RequestTrace( this, data ); + public RequestTrace newChild(Object data) { + return new RequestTrace(this, data); } @Override - public String toString() - { - return String.valueOf( getData() ); + public String toString() { + return String.valueOf(getData()); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/SessionData.java b/maven-resolver-api/src/main/java/org/eclipse/aether/SessionData.java index 330449e28..eeca945f8 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/SessionData.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/SessionData.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; import java.util.function.Supplier; @@ -29,41 +28,40 @@ * abused as a cache (i.e. for storing values that can be re-calculated) to avoid memory exhaustion. *

    * Note: Actual implementations must be thread-safe. - * + * * @see RepositorySystemSession#getData() * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface SessionData -{ +public interface SessionData { /** * Associates the specified session data with the given key. - * + * * @param key The key under which to store the session data, must not be {@code null}. * @param value The data to associate with the key, may be {@code null} to remove the mapping. */ - void set( Object key, Object value ); + void set(Object key, Object value); /** * Associates the specified session data with the given key if the key is currently mapped to the given value. This * method provides an atomic compare-and-update of some key's value. - * + * * @param key The key under which to store the session data, must not be {@code null}. * @param oldValue The expected data currently associated with the key, may be {@code null}. * @param newValue The data to associate with the key, may be {@code null} to remove the mapping. * @return {@code true} if the key mapping was successfully updated from the old value to the new value, * {@code false} if the current key mapping didn't match the expected value and was not updated. */ - boolean set( Object key, Object oldValue, Object newValue ); + boolean set(Object key, Object oldValue, Object newValue); /** * Gets the session data associated with the specified key. - * + * * @param key The key for which to retrieve the session data, must not be {@code null}. * @return The session data associated with the key or {@code null} if none. */ - Object get( Object key ); + Object get(Object key); /** * Retrieve of compute the data associated with the specified key. @@ -72,6 +70,5 @@ public interface SessionData * @param supplier The supplier will compute the new value. * @return The session data associated with the key. */ - Object computeIfAbsent( Object key, Supplier supplier ); - + Object computeIfAbsent(Object key, Supplier supplier); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/SyncContext.java b/maven-resolver-api/src/main/java/org/eclipse/aether/SyncContext.java index 2d751c047..63e8394bf 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/SyncContext.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/SyncContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; import java.io.Closeable; import java.util.Collection; @@ -28,7 +27,7 @@ /** * A synchronization context used to coordinate concurrent access to artifacts or metadatas. The typical usage of a * synchronization context looks like this: - * + * *
      * SyncContext syncContext = repositorySystem.newSyncContext( ... );
      * try {
    @@ -38,7 +37,7 @@
      *     syncContext.close();
      * }
      * 
    - * + * * Within one thread, synchronization contexts may be nested which can naturally happen in a hierarchy of method calls. * The nested synchronization contexts may also acquire overlapping sets of artifacts/metadatas as long as the following * conditions are met. If the outer-most context holding a particular resource is exclusive, that resource can be @@ -48,12 +47,10 @@ * A synchronization context is meant to be utilized by only one thread and as such is not thread-safe. *

    * Note that the level of actual synchronization is subject to the implementation and might range from OS-wide to none. - * + * * @see RepositorySystem#newSyncContext(RepositorySystemSession, boolean) */ -public interface SyncContext - extends Closeable -{ +public interface SyncContext extends Closeable { /** * Acquires synchronized access to the specified artifacts and metadatas. The invocation will potentially block @@ -61,16 +58,15 @@ public interface SyncContext * acquired by this synchronization context has no effect. Please also see the class-level documentation for * information regarding reentrancy. The method may be invoked multiple times on a synchronization context until all * desired resources have been acquired. - * + * * @param artifacts The artifacts to acquire, may be {@code null} or empty if none. * @param metadatas The metadatas to acquire, may be {@code null} or empty if none. */ - void acquire( Collection artifacts, Collection metadatas ); + void acquire(Collection artifacts, Collection metadatas); /** * Releases all previously acquired artifacts/metadatas. If no resources have been acquired before or if this * synchronization context has already been closed, this method does nothing. */ void close(); - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/AbstractArtifact.java b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/AbstractArtifact.java index f18b398c6..777a81e26 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/AbstractArtifact.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/AbstractArtifact.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.artifact; import java.io.File; import java.util.Collections; @@ -30,57 +29,40 @@ /** * A skeleton class for artifacts. */ -public abstract class AbstractArtifact - implements Artifact -{ +public abstract class AbstractArtifact implements Artifact { private static final String SNAPSHOT = "SNAPSHOT"; - private static final Pattern SNAPSHOT_TIMESTAMP = Pattern.compile( "^(.*-)?([0-9]{8}\\.[0-9]{6}-[0-9]+)$" ); + private static final Pattern SNAPSHOT_TIMESTAMP = Pattern.compile("^(.*-)?([0-9]{8}\\.[0-9]{6}-[0-9]+)$"); - public boolean isSnapshot() - { - return isSnapshot( getVersion() ); + public boolean isSnapshot() { + return isSnapshot(getVersion()); } - private static boolean isSnapshot( String version ) - { - return version.endsWith( SNAPSHOT ) || SNAPSHOT_TIMESTAMP.matcher( version ).matches(); + private static boolean isSnapshot(String version) { + return version.endsWith(SNAPSHOT) || SNAPSHOT_TIMESTAMP.matcher(version).matches(); } - public String getBaseVersion() - { - return toBaseVersion( getVersion() ); + public String getBaseVersion() { + return toBaseVersion(getVersion()); } - private static String toBaseVersion( String version ) - { + private static String toBaseVersion(String version) { String baseVersion; - if ( version == null ) - { + if (version == null) { baseVersion = null; - } - else if ( version.startsWith( "[" ) || version.startsWith( "(" ) ) - { + } else if (version.startsWith("[") || version.startsWith("(")) { baseVersion = version; - } - else - { - Matcher m = SNAPSHOT_TIMESTAMP.matcher( version ); - if ( m.matches() ) - { - if ( m.group( 1 ) != null ) - { - baseVersion = m.group( 1 ) + SNAPSHOT; - } - else - { + } else { + Matcher m = SNAPSHOT_TIMESTAMP.matcher(version); + if (m.matches()) { + if (m.group(1) != null) { + baseVersion = m.group(1) + SNAPSHOT; + } else { baseVersion = SNAPSHOT; } - } - else - { + } else { baseVersion = version; } } @@ -90,140 +72,119 @@ else if ( version.startsWith( "[" ) || version.startsWith( "(" ) ) /** * Creates a new artifact with the specified coordinates, properties and file. - * + * * @param version The version of the artifact, may be {@code null}. * @param properties The properties of the artifact, may be {@code null} if none. The method may assume immutability * of the supplied map, i.e. need not copy it. * @param file The resolved file of the artifact, may be {@code null}. * @return The new artifact instance, never {@code null}. */ - private Artifact newInstance( String version, Map properties, File file ) - { - return new DefaultArtifact( getGroupId(), getArtifactId(), getClassifier(), getExtension(), version, file, - properties ); + private Artifact newInstance(String version, Map properties, File file) { + return new DefaultArtifact( + getGroupId(), getArtifactId(), getClassifier(), getExtension(), version, file, properties); } - public Artifact setVersion( String version ) - { + public Artifact setVersion(String version) { String current = getVersion(); - if ( current.equals( version ) || ( version == null && current.isEmpty() ) ) - { + if (current.equals(version) || (version == null && current.isEmpty())) { return this; } - return newInstance( version, getProperties(), getFile() ); + return newInstance(version, getProperties(), getFile()); } - public Artifact setFile( File file ) - { + public Artifact setFile(File file) { File current = getFile(); - if ( Objects.equals( current, file ) ) - { + if (Objects.equals(current, file)) { return this; } - return newInstance( getVersion(), getProperties(), file ); + return newInstance(getVersion(), getProperties(), file); } - public Artifact setProperties( Map properties ) - { + public Artifact setProperties(Map properties) { Map current = getProperties(); - if ( current.equals( properties ) || ( properties == null && current.isEmpty() ) ) - { + if (current.equals(properties) || (properties == null && current.isEmpty())) { return this; } - return newInstance( getVersion(), copyProperties( properties ), getFile() ); + return newInstance(getVersion(), copyProperties(properties), getFile()); } - public String getProperty( String key, String defaultValue ) - { - String value = getProperties().get( key ); - return ( value != null ) ? value : defaultValue; + public String getProperty(String key, String defaultValue) { + String value = getProperties().get(key); + return (value != null) ? value : defaultValue; } /** * Copies the specified artifact properties. This utility method should be used when creating new artifact instances * with caller-supplied properties. - * + * * @param properties The properties to copy, may be {@code null}. * @return The copied and read-only properties, never {@code null}. */ - protected static Map copyProperties( Map properties ) - { - if ( properties != null && !properties.isEmpty() ) - { - return Collections.unmodifiableMap( new HashMap<>( properties ) ); - } - else - { + protected static Map copyProperties(Map properties) { + if (properties != null && !properties.isEmpty()) { + return Collections.unmodifiableMap(new HashMap<>(properties)); + } else { return Collections.emptyMap(); } } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 128 ); - buffer.append( getGroupId() ); - buffer.append( ':' ).append( getArtifactId() ); - buffer.append( ':' ).append( getExtension() ); - if ( getClassifier().length() > 0 ) - { - buffer.append( ':' ).append( getClassifier() ); + public String toString() { + StringBuilder buffer = new StringBuilder(128); + buffer.append(getGroupId()); + buffer.append(':').append(getArtifactId()); + buffer.append(':').append(getExtension()); + if (getClassifier().length() > 0) { + buffer.append(':').append(getClassifier()); } - buffer.append( ':' ).append( getVersion() ); + buffer.append(':').append(getVersion()); return buffer.toString(); } /** * Compares this artifact with the specified object. - * + * * @param obj The object to compare this artifact against, may be {@code null}. * @return {@code true} if and only if the specified object is another {@link Artifact} with equal coordinates, * properties and file, {@code false} otherwise. */ @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( !( obj instanceof Artifact ) ) - { + } else if (!(obj instanceof Artifact)) { return false; } Artifact that = (Artifact) obj; - return Objects.equals( getArtifactId(), that.getArtifactId() ) - && Objects.equals( getGroupId(), that.getGroupId() ) - && Objects.equals( getVersion(), that.getVersion() ) - && Objects.equals( getExtension(), that.getExtension() ) - && Objects.equals( getClassifier(), that.getClassifier() ) - && Objects.equals( getFile(), that.getFile() ) - && Objects.equals( getProperties(), that.getProperties() ); + return Objects.equals(getArtifactId(), that.getArtifactId()) + && Objects.equals(getGroupId(), that.getGroupId()) + && Objects.equals(getVersion(), that.getVersion()) + && Objects.equals(getExtension(), that.getExtension()) + && Objects.equals(getClassifier(), that.getClassifier()) + && Objects.equals(getFile(), that.getFile()) + && Objects.equals(getProperties(), that.getProperties()); } /** * Returns a hash code for this artifact. - * + * * @return A hash code for the artifact. */ @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + getGroupId().hashCode(); hash = hash * 31 + getArtifactId().hashCode(); hash = hash * 31 + getExtension().hashCode(); hash = hash * 31 + getClassifier().hashCode(); hash = hash * 31 + getVersion().hashCode(); - hash = hash * 31 + hash( getFile() ); + hash = hash * 31 + hash(getFile()); return hash; } - private static int hash( Object obj ) - { - return ( obj != null ) ? obj.hashCode() : 0; + private static int hash(Object obj) { + return (obj != null) ? obj.hashCode() : 0; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/Artifact.java b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/Artifact.java index 632324327..d9736c126 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/Artifact.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/Artifact.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.artifact; import java.io.File; import java.util.Map; @@ -27,23 +26,22 @@ * data. Note: Artifact instances are supposed to be immutable, e.g. any exposed mutator method returns a new * artifact instance and leaves the original instance unchanged. Note: Implementors are strongly advised to * inherit from {@link AbstractArtifact} instead of directly implementing this interface. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface Artifact -{ +public interface Artifact { /** * Gets the group identifier of this artifact, for example "org.apache.maven". - * + * * @return The group identifier, never {@code null}. */ String getGroupId(); /** * Gets the artifact identifier of this artifact, for example "maven-model". - * + * * @return The artifact identifier, never {@code null}. */ String getArtifactId(); @@ -52,44 +50,44 @@ public interface Artifact * Gets the version of this artifact, for example "1.0-20100529-1213". Note that in case of meta versions like * "1.0-SNAPSHOT", the artifact's version depends on the state of the artifact. Artifacts that have been resolved or * deployed will usually have the meta version expanded. - * + * * @return The version, never {@code null}. */ String getVersion(); /** * Sets the version of the artifact. - * + * * @param version The version of this artifact, may be {@code null} or empty. * @return The new artifact, never {@code null}. */ - Artifact setVersion( String version ); + Artifact setVersion(String version); /** * Gets the base version of this artifact, for example "1.0-SNAPSHOT". In contrast to the {@link #getVersion()}, the * base version will always refer to the unresolved meta version. - * + * * @return The base version, never {@code null}. */ String getBaseVersion(); /** * Determines whether this artifact uses a snapshot version. - * + * * @return {@code true} if the artifact is a snapshot, {@code false} otherwise. */ boolean isSnapshot(); /** * Gets the classifier of this artifact, for example "sources". - * + * * @return The classifier or an empty string if none, never {@code null}. */ String getClassifier(); /** * Gets the (file) extension of this artifact, for example "jar" or "tar.gz". - * + * * @return The file extension (without leading period), never {@code null}. */ String getExtension(); @@ -97,34 +95,34 @@ public interface Artifact /** * Gets the file of this artifact. Note that only resolved artifacts have a file associated with them. In general, * callers must not assume any relationship between an artifact's filename and its coordinates. - * + * * @return The file or {@code null} if the artifact isn't resolved. */ File getFile(); /** * Sets the file of the artifact. - * + * * @param file The file of the artifact, may be {@code null} * @return The new artifact, never {@code null}. */ - Artifact setFile( File file ); + Artifact setFile(File file); /** * Gets the specified property. - * + * * @param key The name of the property, must not be {@code null}. * @param defaultValue The default value to return in case the property is not set, may be {@code null}. * @return The requested property value or {@code null} if the property is not set and no default value was * provided. * @see ArtifactProperties */ - String getProperty( String key, String defaultValue ); + String getProperty(String key, String defaultValue); /** * Gets the properties of this artifact. Clients may use these properties to associate non-persistent values with an * artifact that help later processing when the artifact gets passed around within the application. - * + * * @return The (read-only) properties, never {@code null}. * @see ArtifactProperties */ @@ -133,11 +131,10 @@ public interface Artifact /** * Sets the properties for the artifact. Note that these properties exist merely in memory and are not persisted * when the artifact gets installed/deployed to a repository. - * + * * @param properties The properties for the artifact, may be {@code null}. * @return The new artifact, never {@code null}. * @see ArtifactProperties */ - Artifact setProperties( Map properties ); - + Artifact setProperties(Map properties); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactProperties.java b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactProperties.java index 11080868b..b900e2922 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactProperties.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactProperties.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,18 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.artifact; /** * The keys for common properties of artifacts. - * + * * @see Artifact#getProperties() */ -public final class ArtifactProperties -{ +public final class ArtifactProperties { /** * A high-level characterization of the artifact, e.g. "maven-plugin" or "test-jar". - * + * * @see ArtifactType#getId() */ public static final String TYPE = "type"; @@ -66,9 +64,7 @@ public final class ArtifactProperties */ public static final String DOWNLOAD_URL = "downloadUrl"; - private ArtifactProperties() - { + private ArtifactProperties() { // hide constructor } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactType.java b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactType.java index 5f8721743..589422130 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactType.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactType.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.artifact; import java.util.Map; @@ -25,18 +24,17 @@ * An artifact type describing artifact characteristics/properties that are common for certain artifacts. Artifact types * are a means to simplify the description of an artifact by referring to an artifact type instead of specifying the * various properties individually. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @see ArtifactTypeRegistry * @see DefaultArtifact#DefaultArtifact(String, String, String, String, String, ArtifactType) */ -public interface ArtifactType -{ +public interface ArtifactType { /** * Gets the identifier of this type, e.g. "maven-plugin" or "test-jar". - * + * * @return The identifier of this type, never {@code null}. * @see ArtifactProperties#TYPE */ @@ -44,24 +42,23 @@ public interface ArtifactType /** * Gets the file extension to use for artifacts of this type (unless explicitly overridden by the artifact). - * + * * @return The usual file extension, never {@code null}. */ String getExtension(); /** * Gets the classifier to use for artifacts of this type (unless explicitly overridden by the artifact). - * + * * @return The usual classifier or an empty string if none, never {@code null}. */ String getClassifier(); /** * Gets the properties to use for artifacts of this type (unless explicitly overridden by the artifact). - * + * * @return The (read-only) properties, never {@code null}. * @see ArtifactProperties */ Map getProperties(); - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactTypeRegistry.java b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactTypeRegistry.java index f3791733e..b07244eaf 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactTypeRegistry.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/ArtifactTypeRegistry.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,21 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.artifact; /** * A registry of known artifact types. - * + * * @see org.eclipse.aether.RepositorySystemSession#getArtifactTypeRegistry() */ -public interface ArtifactTypeRegistry -{ +public interface ArtifactTypeRegistry { /** * Gets the artifact type with the specified identifier. - * + * * @param typeId The identifier of the type, must not be {@code null}. * @return The artifact type or {@code null} if no type with the requested identifier exists. */ - ArtifactType get( String typeId ); - + ArtifactType get(String typeId); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/DefaultArtifact.java b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/DefaultArtifact.java index f385e2c8c..bf5827334 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/DefaultArtifact.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/DefaultArtifact.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.artifact; import java.io.File; import java.util.Collections; @@ -30,11 +29,9 @@ * A simple artifact. Note: Instances of this class are immutable and the exposed mutators return new objects * rather than changing the current instance. */ -public final class DefaultArtifact - extends AbstractArtifact -{ +public final class DefaultArtifact extends AbstractArtifact { private static final Pattern COORDINATE_PATTERN = - Pattern.compile( "([^: ]+):([^: ]+)(:([^: ]*)(:([^: ]+))?)?:([^: ]+)" ); + Pattern.compile("([^: ]+):([^: ]+)(:([^: ]*)(:([^: ]+))?)?:([^: ]+)"); private final String groupId; @@ -53,22 +50,21 @@ public final class DefaultArtifact /** * Creates a new artifact with the specified coordinates. If not specified in the artifact coordinates, the * artifact's extension defaults to {@code jar} and classifier to an empty string. - * + * * @param coords The artifact coordinates in the format * {@code :[:[:]]:}, must not be {@code null}. * * @throws IllegalArgumentException If the artifact coordinates found in {@code coords} do not match the expected * format. */ - public DefaultArtifact( String coords ) - { - this( coords, Collections.emptyMap() ); + public DefaultArtifact(String coords) { + this(coords, Collections.emptyMap()); } /** * Creates a new artifact with the specified coordinates and properties. If not specified in the artifact * coordinates, the artifact's extension defaults to {@code jar} and classifier to an empty string. - * + * * @param coords The artifact coordinates in the format * {@code :[:[:]]:}, must not be {@code null}. * @param properties The artifact properties, may be {@code null}. @@ -76,55 +72,50 @@ public DefaultArtifact( String coords ) * @throws IllegalArgumentException If the artifact coordinates found in {@code coords} do not match the expected * format. */ - public DefaultArtifact( String coords, Map properties ) - { - Matcher m = COORDINATE_PATTERN.matcher( coords ); - if ( !m.matches() ) - { - throw new IllegalArgumentException( "Bad artifact coordinates " + coords - + ", expected format is :[:[:]]:" ); + public DefaultArtifact(String coords, Map properties) { + Matcher m = COORDINATE_PATTERN.matcher(coords); + if (!m.matches()) { + throw new IllegalArgumentException("Bad artifact coordinates " + coords + + ", expected format is :[:[:]]:"); } - groupId = m.group( 1 ); - artifactId = m.group( 2 ); - extension = get( m.group( 4 ), "jar" ); - classifier = get( m.group( 6 ), "" ); - version = m.group( 7 ); + groupId = m.group(1); + artifactId = m.group(2); + extension = get(m.group(4), "jar"); + classifier = get(m.group(6), ""); + version = m.group(7); file = null; - this.properties = copyProperties( properties ); + this.properties = copyProperties(properties); } - private static String get( String value, String defaultValue ) - { - return ( value == null || value.isEmpty() ) ? defaultValue : value; + private static String get(String value, String defaultValue) { + return (value == null || value.isEmpty()) ? defaultValue : value; } /** * Creates a new artifact with the specified coordinates and no classifier. Passing {@code null} for any of the * coordinates is equivalent to specifying an empty string. - * + * * @param groupId The group identifier of the artifact, may be {@code null}. * @param artifactId The artifact identifier of the artifact, may be {@code null}. * @param extension The file extension of the artifact, may be {@code null}. * @param version The version of the artifact, may be {@code null}. */ - public DefaultArtifact( String groupId, String artifactId, String extension, String version ) - { - this( groupId, artifactId, "", extension, version ); + public DefaultArtifact(String groupId, String artifactId, String extension, String version) { + this(groupId, artifactId, "", extension, version); } /** * Creates a new artifact with the specified coordinates. Passing {@code null} for any of the coordinates is * equivalent to specifying an empty string. - * + * * @param groupId The group identifier of the artifact, may be {@code null}. * @param artifactId The artifact identifier of the artifact, may be {@code null}. * @param classifier The classifier of the artifact, may be {@code null}. * @param extension The file extension of the artifact, may be {@code null}. * @param version The version of the artifact, may be {@code null}. */ - public DefaultArtifact( String groupId, String artifactId, String classifier, String extension, String version ) - { - this( groupId, artifactId, classifier, extension, version, null, (File) null ); + public DefaultArtifact(String groupId, String artifactId, String classifier, String extension, String version) { + this(groupId, artifactId, classifier, extension, version, null, (File) null); } /** @@ -132,7 +123,7 @@ public DefaultArtifact( String groupId, String artifactId, String classifier, St * equivalent to specifying an empty string. The optional artifact type provided to this constructor will be used to * determine the artifact's classifier and file extension if the corresponding arguments for this constructor are * {@code null}. - * + * * @param groupId The group identifier of the artifact, may be {@code null}. * @param artifactId The artifact identifier of the artifact, may be {@code null}. * @param classifier The classifier of the artifact, may be {@code null}. @@ -140,10 +131,9 @@ public DefaultArtifact( String groupId, String artifactId, String classifier, St * @param version The version of the artifact, may be {@code null}. * @param type The artifact type from which to query classifier, file extension and properties, may be {@code null}. */ - public DefaultArtifact( String groupId, String artifactId, String classifier, String extension, String version, - ArtifactType type ) - { - this( groupId, artifactId, classifier, extension, version, null, type ); + public DefaultArtifact( + String groupId, String artifactId, String classifier, String extension, String version, ArtifactType type) { + this(groupId, artifactId, classifier, extension, version, null, type); } /** @@ -152,7 +142,7 @@ public DefaultArtifact( String groupId, String artifactId, String classifier, St * will be used to determine the artifact's classifier and file extension if the corresponding arguments for this * constructor are {@code null}. If the artifact type specifies properties, those will get merged with the * properties passed directly into the constructor, with the latter properties taking precedence. - * + * * @param groupId The group identifier of the artifact, may be {@code null}. * @param artifactId The artifact identifier of the artifact, may be {@code null}. * @param classifier The classifier of the artifact, may be {@code null}. @@ -161,52 +151,45 @@ public DefaultArtifact( String groupId, String artifactId, String classifier, St * @param properties The properties of the artifact, may be {@code null} if none. * @param type The artifact type from which to query classifier, file extension and properties, may be {@code null}. */ - public DefaultArtifact( String groupId, String artifactId, String classifier, String extension, String version, - Map properties, ArtifactType type ) - { - this.groupId = emptify( groupId ); - this.artifactId = emptify( artifactId ); - if ( classifier != null || type == null ) - { - this.classifier = emptify( classifier ); - } - else - { - this.classifier = emptify( type.getClassifier() ); - } - if ( extension != null || type == null ) - { - this.extension = emptify( extension ); + public DefaultArtifact( + String groupId, + String artifactId, + String classifier, + String extension, + String version, + Map properties, + ArtifactType type) { + this.groupId = emptify(groupId); + this.artifactId = emptify(artifactId); + if (classifier != null || type == null) { + this.classifier = emptify(classifier); + } else { + this.classifier = emptify(type.getClassifier()); } - else - { - this.extension = emptify( type.getExtension() ); + if (extension != null || type == null) { + this.extension = emptify(extension); + } else { + this.extension = emptify(type.getExtension()); } - this.version = emptify( version ); + this.version = emptify(version); this.file = null; - this.properties = merge( properties, ( type != null ) ? type.getProperties() : null ); + this.properties = merge(properties, (type != null) ? type.getProperties() : null); } - private static Map merge( Map dominant, Map recessive ) - { + private static Map merge(Map dominant, Map recessive) { Map properties; - if ( ( dominant == null || dominant.isEmpty() ) && ( recessive == null || recessive.isEmpty() ) ) - { + if ((dominant == null || dominant.isEmpty()) && (recessive == null || recessive.isEmpty())) { properties = Collections.emptyMap(); - } - else - { + } else { properties = new HashMap<>(); - if ( recessive != null ) - { - properties.putAll( recessive ); + if (recessive != null) { + properties.putAll(recessive); } - if ( dominant != null ) - { - properties.putAll( dominant ); + if (dominant != null) { + properties.putAll(dominant); } - properties = Collections.unmodifiableMap( properties ); + properties = Collections.unmodifiableMap(properties); } return properties; @@ -215,7 +198,7 @@ private static Map merge( Map dominant, Map merge( Map dominant, Map properties, File file ) - { - this.groupId = emptify( groupId ); - this.artifactId = emptify( artifactId ); - this.classifier = emptify( classifier ); - this.extension = emptify( extension ); - this.version = emptify( version ); + public DefaultArtifact( + String groupId, + String artifactId, + String classifier, + String extension, + String version, + Map properties, + File file) { + this.groupId = emptify(groupId); + this.artifactId = emptify(artifactId); + this.classifier = emptify(classifier); + this.extension = emptify(extension); + this.version = emptify(version); this.file = file; - this.properties = copyProperties( properties ); + this.properties = copyProperties(properties); } - DefaultArtifact( String groupId, String artifactId, String classifier, String extension, String version, File file, - Map properties ) - { + DefaultArtifact( + String groupId, + String artifactId, + String classifier, + String extension, + String version, + File file, + Map properties) { // NOTE: This constructor assumes immutability of the provided properties, for internal use only - this.groupId = emptify( groupId ); - this.artifactId = emptify( artifactId ); - this.classifier = emptify( classifier ); - this.extension = emptify( extension ); - this.version = emptify( version ); + this.groupId = emptify(groupId); + this.artifactId = emptify(artifactId); + this.classifier = emptify(classifier); + this.extension = emptify(extension); + this.version = emptify(version); this.file = file; this.properties = properties; } - private static String emptify( String str ) - { - return ( str == null ) ? "" : str; + private static String emptify(String str) { + return (str == null) ? "" : str; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public String getVersion() - { + public String getVersion() { return version; } - public String getClassifier() - { + public String getClassifier() { return classifier; } - public String getExtension() - { + public String getExtension() { return extension; } - public File getFile() - { + public File getFile() { return file; } - public Map getProperties() - { + public Map getProperties() { return properties; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/DefaultArtifactType.java b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/DefaultArtifactType.java index 5d23aa230..68d8963de 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/DefaultArtifactType.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/DefaultArtifactType.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,18 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.artifact; import java.util.Collections; import java.util.HashMap; import java.util.Map; + import static java.util.Objects.requireNonNull; /** * A simple artifact type. */ -public final class DefaultArtifactType - implements ArtifactType -{ +public final class DefaultArtifactType implements ArtifactType { private final String id; @@ -45,34 +43,32 @@ public final class DefaultArtifactType * {@link ArtifactProperties#LANGUAGE}, {@link ArtifactProperties#CONSTITUTES_BUILD_PATH} and * {@link ArtifactProperties#INCLUDES_DEPENDENCIES} will be set to {@code "none"}, {@code true} and {@code false}, * respectively. - * + * * @param id The identifier of the type which will also be used as the value for the {@link ArtifactProperties#TYPE} * property, must not be {@code null} or empty. */ - public DefaultArtifactType( String id ) - { - this( id, id, "", "none", false, false ); + public DefaultArtifactType(String id) { + this(id, id, "", "none", false, false); } /** * Creates a new artifact type with the specified properties. Additionally, the properties * {@link ArtifactProperties#CONSTITUTES_BUILD_PATH} and {@link ArtifactProperties#INCLUDES_DEPENDENCIES} will be * set to {@code true} and {@code false}, respectively. - * + * * @param id The identifier of the type which will also be used as the value for the {@link ArtifactProperties#TYPE} * property, must not be {@code null} or empty. * @param extension The usual file extension for artifacts of this type, may be {@code null}. * @param classifier The usual classifier for artifacts of this type, may be {@code null}. * @param language The value for the {@link ArtifactProperties#LANGUAGE} property, may be {@code null}. */ - public DefaultArtifactType( String id, String extension, String classifier, String language ) - { - this( id, extension, classifier, language, true, false ); + public DefaultArtifactType(String id, String extension, String classifier, String language) { + this(id, extension, classifier, language, true, false); } /** * Creates a new artifact type with the specified properties. - * + * * @param id The identifier of the type which will also be used as the value for the {@link ArtifactProperties#TYPE} * property, must not be {@code null} or empty. * @param extension The usual file extension for artifacts of this type, may be {@code null}. @@ -81,67 +77,62 @@ public DefaultArtifactType( String id, String extension, String classifier, Stri * @param constitutesBuildPath The value for the {@link ArtifactProperties#CONSTITUTES_BUILD_PATH} property. * @param includesDependencies The value for the {@link ArtifactProperties#INCLUDES_DEPENDENCIES} property. */ - public DefaultArtifactType( String id, String extension, String classifier, String language, - boolean constitutesBuildPath, boolean includesDependencies ) - { - this.id = requireNonNull( id, "type id cannot be null" ); - if ( id.length() == 0 ) - { - throw new IllegalArgumentException( "type id cannot be empty" ); + public DefaultArtifactType( + String id, + String extension, + String classifier, + String language, + boolean constitutesBuildPath, + boolean includesDependencies) { + this.id = requireNonNull(id, "type id cannot be null"); + if (id.length() == 0) { + throw new IllegalArgumentException("type id cannot be empty"); } - this.extension = emptify( extension ); - this.classifier = emptify( classifier ); + this.extension = emptify(extension); + this.classifier = emptify(classifier); Map props = new HashMap<>(); - props.put( ArtifactProperties.TYPE, id ); - props.put( ArtifactProperties.LANGUAGE, ( language != null && language.length() > 0 ) ? language : "none" ); - props.put( ArtifactProperties.INCLUDES_DEPENDENCIES, Boolean.toString( includesDependencies ) ); - props.put( ArtifactProperties.CONSTITUTES_BUILD_PATH, Boolean.toString( constitutesBuildPath ) ); - properties = Collections.unmodifiableMap( props ); + props.put(ArtifactProperties.TYPE, id); + props.put(ArtifactProperties.LANGUAGE, (language != null && language.length() > 0) ? language : "none"); + props.put(ArtifactProperties.INCLUDES_DEPENDENCIES, Boolean.toString(includesDependencies)); + props.put(ArtifactProperties.CONSTITUTES_BUILD_PATH, Boolean.toString(constitutesBuildPath)); + properties = Collections.unmodifiableMap(props); } /** * Creates a new artifact type with the specified properties. - * + * * @param id The identifier of the type, must not be {@code null} or empty. * @param extension The usual file extension for artifacts of this type, may be {@code null}. * @param classifier The usual classifier for artifacts of this type, may be {@code null}. * @param properties The properties for artifacts of this type, may be {@code null}. */ - public DefaultArtifactType( String id, String extension, String classifier, Map properties ) - { - this.id = requireNonNull( id, "type id cannot be null" ); - if ( id.length() == 0 ) - { - throw new IllegalArgumentException( "type id cannot be empty" ); + public DefaultArtifactType(String id, String extension, String classifier, Map properties) { + this.id = requireNonNull(id, "type id cannot be null"); + if (id.length() == 0) { + throw new IllegalArgumentException("type id cannot be empty"); } - this.extension = emptify( extension ); - this.classifier = emptify( classifier ); - this.properties = AbstractArtifact.copyProperties( properties ); + this.extension = emptify(extension); + this.classifier = emptify(classifier); + this.properties = AbstractArtifact.copyProperties(properties); } - private static String emptify( String str ) - { - return ( str == null ) ? "" : str; + private static String emptify(String str) { + return (str == null) ? "" : str; } - public String getId() - { + public String getId() { return id; } - public String getExtension() - { + public String getExtension() { return extension; } - public String getClassifier() - { + public String getClassifier() { return classifier; } - public Map getProperties() - { + public Map getProperties() { return properties; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/package-info.java b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/package-info.java index 9a4cc7950..373c1f700 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/package-info.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/artifact/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * The definition of an artifact, that is the primary entity managed by the repository system. */ package org.eclipse.aether.artifact; - diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectRequest.java index 59bc620e4..d524127e8 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import java.util.ArrayList; import java.util.Collections; @@ -35,11 +34,10 @@ * dependencies can be specified in which case the specified direct dependencies are merged with the direct dependencies * retrieved from the artifact descriptor of the root dependency. And last, only direct dependencies can be specified in * which case the root node of the resulting graph has no associated dependency. - * + * * @see RepositorySystem#collectDependencies(org.eclipse.aether.RepositorySystemSession, CollectRequest) */ -public final class CollectRequest -{ +public final class CollectRequest { private Artifact rootArtifact; @@ -58,61 +56,56 @@ public final class CollectRequest /** * Creates an uninitialized request. */ - public CollectRequest() - { + public CollectRequest() { // enables default constructor } /** * Creates a request with the specified properties. - * + * * @param root The root dependency whose transitive dependencies should be collected, may be {@code null}. * @param repositories The repositories to use for the collection, may be {@code null}. */ - public CollectRequest( Dependency root, List repositories ) - { - setRoot( root ); - setRepositories( repositories ); + public CollectRequest(Dependency root, List repositories) { + setRoot(root); + setRepositories(repositories); } /** * Creates a new request with the specified properties. - * + * * @param root The root dependency whose transitive dependencies should be collected, may be {@code null}. * @param dependencies The direct dependencies to merge with the direct dependencies from the root dependency's * artifact descriptor. * @param repositories The repositories to use for the collection, may be {@code null}. */ - public CollectRequest( Dependency root, List dependencies, List repositories ) - { - setRoot( root ); - setDependencies( dependencies ); - setRepositories( repositories ); + public CollectRequest(Dependency root, List dependencies, List repositories) { + setRoot(root); + setDependencies(dependencies); + setRepositories(repositories); } /** * Creates a new request with the specified properties. - * + * * @param dependencies The direct dependencies of some imaginary root, may be {@code null}. * @param managedDependencies The dependency management information to apply to the transitive dependencies, may be * {@code null}. * @param repositories The repositories to use for the collection, may be {@code null}. */ - public CollectRequest( List dependencies, List managedDependencies, - List repositories ) - { - setDependencies( dependencies ); - setManagedDependencies( managedDependencies ); - setRepositories( repositories ); + public CollectRequest( + List dependencies, List managedDependencies, List repositories) { + setDependencies(dependencies); + setManagedDependencies(managedDependencies); + setRepositories(repositories); } /** * Gets the root artifact for the dependency graph. - * + * * @return The root artifact for the dependency graph or {@code null} if none. */ - public Artifact getRootArtifact() - { + public Artifact getRootArtifact() { return rootArtifact; } @@ -123,45 +116,41 @@ public Artifact getRootArtifact() * artifact on the other hand is only used as a label for the root node of the graph in case no root * dependency was specified. As such, the configured root artifact is ignored if {@link #getRoot()} does not return * {@code null}. - * + * * @param rootArtifact The root artifact for the dependency graph, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public CollectRequest setRootArtifact( Artifact rootArtifact ) - { + public CollectRequest setRootArtifact(Artifact rootArtifact) { this.rootArtifact = rootArtifact; return this; } /** * Gets the root dependency of the graph. - * + * * @return The root dependency of the graph or {@code null} if none. */ - public Dependency getRoot() - { + public Dependency getRoot() { return root; } /** * Sets the root dependency of the graph. - * + * * @param root The root dependency of the graph, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public CollectRequest setRoot( Dependency root ) - { + public CollectRequest setRoot(Dependency root) { this.root = root; return this; } /** * Gets the direct dependencies. - * + * * @return The direct dependencies, never {@code null}. */ - public List getDependencies() - { + public List getDependencies() { return dependencies; } @@ -169,18 +158,14 @@ public List getDependencies() * Sets the direct dependencies. If both a root dependency and direct dependencies are given in the request, the * direct dependencies from the request will be merged with the direct dependencies from the root dependency's * artifact descriptor, giving higher priority to the dependencies from the request. - * + * * @param dependencies The direct dependencies, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public CollectRequest setDependencies( List dependencies ) - { - if ( dependencies == null ) - { + public CollectRequest setDependencies(List dependencies) { + if (dependencies == null) { this.dependencies = Collections.emptyList(); - } - else - { + } else { this.dependencies = dependencies; } return this; @@ -188,48 +173,40 @@ public CollectRequest setDependencies( List dependencies ) /** * Adds the specified direct dependency. - * + * * @param dependency The dependency to add, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public CollectRequest addDependency( Dependency dependency ) - { - if ( dependency != null ) - { - if ( this.dependencies.isEmpty() ) - { + public CollectRequest addDependency(Dependency dependency) { + if (dependency != null) { + if (this.dependencies.isEmpty()) { this.dependencies = new ArrayList<>(); } - this.dependencies.add( dependency ); + this.dependencies.add(dependency); } return this; } /** * Gets the dependency management to apply to transitive dependencies. - * + * * @return The dependency management to apply to transitive dependencies, never {@code null}. */ - public List getManagedDependencies() - { + public List getManagedDependencies() { return managedDependencies; } /** * Sets the dependency management to apply to transitive dependencies. To clarify, this management does not apply to * the direct dependencies of the root node. - * + * * @param managedDependencies The dependency management, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public CollectRequest setManagedDependencies( List managedDependencies ) - { - if ( managedDependencies == null ) - { + public CollectRequest setManagedDependencies(List managedDependencies) { + if (managedDependencies == null) { this.managedDependencies = Collections.emptyList(); - } - else - { + } else { this.managedDependencies = managedDependencies; } return this; @@ -237,47 +214,39 @@ public CollectRequest setManagedDependencies( List managedDependenci /** * Adds the specified managed dependency. - * + * * @param managedDependency The managed dependency to add, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public CollectRequest addManagedDependency( Dependency managedDependency ) - { - if ( managedDependency != null ) - { - if ( this.managedDependencies.isEmpty() ) - { + public CollectRequest addManagedDependency(Dependency managedDependency) { + if (managedDependency != null) { + if (this.managedDependencies.isEmpty()) { this.managedDependencies = new ArrayList<>(); } - this.managedDependencies.add( managedDependency ); + this.managedDependencies.add(managedDependency); } return this; } /** * Gets the repositories to use for the collection. - * + * * @return The repositories to use for the collection, never {@code null}. */ - public List getRepositories() - { + public List getRepositories() { return repositories; } /** * Sets the repositories to use for the collection. - * + * * @param repositories The repositories to use for the collection, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public CollectRequest setRepositories( List repositories ) - { - if ( repositories == null ) - { + public CollectRequest setRepositories(List repositories) { + if (repositories == null) { this.repositories = Collections.emptyList(); - } - else - { + } else { this.repositories = repositories; } return this; @@ -285,71 +254,62 @@ public CollectRequest setRepositories( List repositories ) /** * Adds the specified repository for collection. - * + * * @param repository The repository to collect dependency information from, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public CollectRequest addRepository( RemoteRepository repository ) - { - if ( repository != null ) - { - if ( this.repositories.isEmpty() ) - { + public CollectRequest addRepository(RemoteRepository repository) { + if (repository != null) { + if (this.repositories.isEmpty()) { this.repositories = new ArrayList<>(); } - this.repositories.add( repository ); + this.repositories.add(repository); } return this; } /** * Gets the context in which this request is made. - * + * * @return The context, never {@code null}. */ - public String getRequestContext() - { + public String getRequestContext() { return context; } /** * Sets the context in which this request is made. - * + * * @param context The context, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public CollectRequest setRequestContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public CollectRequest setRequestContext(String context) { + this.context = (context != null) ? context : ""; return this; } /** * Gets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @return The trace information about the higher level operation or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } /** * Sets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @param trace The trace information about the higher level operation, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public CollectRequest setTrace( RequestTrace trace ) - { + public CollectRequest setTrace(RequestTrace trace) { this.trace = trace; return this; } @Override - public String toString() - { + public String toString() { return getRoot() + " -> " + getDependencies() + " < " + getRepositories(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectResult.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectResult.java index 7944ad5c1..8bc234fd9 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectResult.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectResult.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,23 +16,24 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.graph.DependencyCycle; import org.eclipse.aether.graph.DependencyNode; +import static java.util.Objects.requireNonNull; + /** * The result of a dependency collection request. - * + * * @see RepositorySystem#collectDependencies(org.eclipse.aether.RepositorySystemSession, CollectRequest) */ -public final class CollectResult -{ +public final class CollectResult { private final CollectRequest request; @@ -49,9 +48,8 @@ public final class CollectResult * * @param request The resolution request, must not be {@code null}. */ - public CollectResult( CollectRequest request ) - { - this.request = requireNonNull( request, "dependency collection request cannot be null" ); + public CollectResult(CollectRequest request) { + this.request = requireNonNull(request, "dependency collection request cannot be null"); exceptions = Collections.emptyList(); cycles = Collections.emptyList(); } @@ -61,95 +59,82 @@ public CollectResult( CollectRequest request ) * * @return The collection request, never {@code null}. */ - public CollectRequest getRequest() - { + public CollectRequest getRequest() { return request; } /** * Gets the exceptions that occurred while building the dependency graph. - * + * * @return The exceptions that occurred, never {@code null}. */ - public List getExceptions() - { + public List getExceptions() { return exceptions; } /** * Records the specified exception while building the dependency graph. - * + * * @param exception The exception to record, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public CollectResult addException( Exception exception ) - { - if ( exception != null ) - { - if ( exceptions.isEmpty() ) - { + public CollectResult addException(Exception exception) { + if (exception != null) { + if (exceptions.isEmpty()) { exceptions = new ArrayList<>(); } - exceptions.add( exception ); + exceptions.add(exception); } return this; } /** * Gets the dependency cycles that were encountered while building the dependency graph. - * + * * @return The dependency cycles in the (raw) graph, never {@code null}. */ - public List getCycles() - { + public List getCycles() { return cycles; } /** * Records the specified dependency cycle. - * + * * @param cycle The dependency cycle to record, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public CollectResult addCycle( DependencyCycle cycle ) - { - if ( cycle != null ) - { - if ( cycles.isEmpty() ) - { + public CollectResult addCycle(DependencyCycle cycle) { + if (cycle != null) { + if (cycles.isEmpty()) { cycles = new ArrayList<>(); } - cycles.add( cycle ); + cycles.add(cycle); } return this; } /** * Gets the root node of the dependency graph. - * + * * @return The root node of the dependency graph or {@code null} if none. */ - public DependencyNode getRoot() - { + public DependencyNode getRoot() { return root; } /** * Sets the root node of the dependency graph. - * + * * @param root The root node of the dependency graph, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public CollectResult setRoot( DependencyNode root ) - { + public CollectResult setRoot(DependencyNode root) { this.root = root; return this; } @Override - public String toString() - { - return String.valueOf( getRoot() ); + public String toString() { + return String.valueOf(getRoot()); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectStepData.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectStepData.java index 632872dba..ae8d01f42 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectStepData.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/CollectStepData.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import java.util.List; @@ -32,8 +31,7 @@ * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface CollectStepData -{ +public interface CollectStepData { /** * Returns the context of collection. Never {@code null}. */ diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyCollectionContext.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyCollectionContext.java index 671bd2ac1..2c84e3dd7 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyCollectionContext.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyCollectionContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import java.util.List; @@ -27,7 +26,7 @@ /** * A context used during dependency collection to update the dependency manager, selector and traverser. - * + * * @see DependencyManager#deriveChildManager(DependencyCollectionContext) * @see DependencyTraverser#deriveChildTraverser(DependencyCollectionContext) * @see DependencySelector#deriveChildSelector(DependencyCollectionContext) @@ -35,12 +34,11 @@ * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface DependencyCollectionContext -{ +public interface DependencyCollectionContext { /** * Gets the repository system session during which the dependency collection happens. - * + * * @return The repository system session, never {@code null}. */ RepositorySystemSession getSession(); @@ -50,7 +48,7 @@ public interface DependencyCollectionContext * root, this is simply shorthand for {@code getDependency().getArtifact()}. In case of the root node however, * {@link #getDependency()} might be {@code null} while the node still has an artifact which serves as its label and * is not to be resolved. - * + * * @return The artifact whose children are going to be processed or {@code null} in case of the root node without * dependency and label. */ @@ -58,7 +56,7 @@ public interface DependencyCollectionContext /** * Gets the dependency whose children are to be processed next during dependency collection. - * + * * @return The dependency whose children are going to be processed or {@code null} in case of the root node without * dependency. */ @@ -67,9 +65,8 @@ public interface DependencyCollectionContext /** * Gets the dependency management information that was contributed by the artifact descriptor of the current * dependency. - * + * * @return The dependency management information, never {@code null}. */ List getManagedDependencies(); - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyCollectionException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyCollectionException.java index 8a04d7952..397219eec 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyCollectionException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyCollectionException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import org.eclipse.aether.RepositoryException; @@ -25,87 +24,74 @@ * Thrown in case of bad artifact descriptors, version ranges or other issues encountered during calculation of the * dependency graph. */ -public class DependencyCollectionException - extends RepositoryException -{ +public class DependencyCollectionException extends RepositoryException { private final transient CollectResult result; /** * Creates a new exception with the specified result. - * + * * @param result The collection result at the point the exception occurred, may be {@code null}. */ - public DependencyCollectionException( CollectResult result ) - { - super( "Failed to collect dependencies for " + getSource( result ), getCause( result ) ); + public DependencyCollectionException(CollectResult result) { + super("Failed to collect dependencies for " + getSource(result), getCause(result)); this.result = result; } /** * Creates a new exception with the specified result and detail message. - * + * * @param result The collection result at the point the exception occurred, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public DependencyCollectionException( CollectResult result, String message ) - { - super( message, getCause( result ) ); + public DependencyCollectionException(CollectResult result, String message) { + super(message, getCause(result)); this.result = result; } /** * Creates a new exception with the specified result, detail message and cause. - * + * * @param result The collection result at the point the exception occurred, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public DependencyCollectionException( CollectResult result, String message, Throwable cause ) - { - super( message, cause ); + public DependencyCollectionException(CollectResult result, String message, Throwable cause) { + super(message, cause); this.result = result; } /** * Gets the collection result at the point the exception occurred. Despite being incomplete, callers might want to * use this result to fail gracefully and continue their operation with whatever interim data has been gathered. - * + * * @return The collection result or {@code null} if unknown. */ - public CollectResult getResult() - { + public CollectResult getResult() { return result; } - private static String getSource( CollectResult result ) - { - if ( result == null ) - { + private static String getSource(CollectResult result) { + if (result == null) { return ""; } CollectRequest request = result.getRequest(); - if ( request.getRoot() != null ) - { + if (request.getRoot() != null) { return request.getRoot().toString(); } - if ( request.getRootArtifact() != null ) - { + if (request.getRootArtifact() != null) { return request.getRootArtifact().toString(); } return request.getDependencies().toString(); } - private static Throwable getCause( CollectResult result ) - { + private static Throwable getCause(CollectResult result) { Throwable cause = null; - if ( result != null && !result.getExceptions().isEmpty() ) - { - cause = result.getExceptions().get( 0 ); + if (result != null && !result.getExceptions().isEmpty()) { + cause = result.getExceptions().get(0); } return cause; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyGraphTransformationContext.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyGraphTransformationContext.java index ba6647472..3921a4fc3 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyGraphTransformationContext.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyGraphTransformationContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,41 +16,40 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import org.eclipse.aether.RepositorySystemSession; /** * A context used during dependency collection to exchange information within a chain of dependency graph transformers. - * + * * @see DependencyGraphTransformer * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface DependencyGraphTransformationContext -{ +public interface DependencyGraphTransformationContext { /** * Gets the repository system session during which the graph transformation happens. - * + * * @return The repository system session, never {@code null}. */ RepositorySystemSession getSession(); /** * Gets a keyed value from the context. - * + * * @param key The key used to query the value, must not be {@code null}. * @return The queried value or {@code null} if none. */ - Object get( Object key ); + Object get(Object key); /** * Puts a keyed value into the context. - * + * * @param key The key used to store the value, must not be {@code null}. * @param value The value to store, may be {@code null} to remove the mapping. * @return The previous value associated with the key or {@code null} if none. */ - Object put( Object key, Object value ); - + Object put(Object key, Object value); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyGraphTransformer.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyGraphTransformer.java index c47250087..3dc6979c8 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyGraphTransformer.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyGraphTransformer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.graph.DependencyNode; @@ -30,22 +29,20 @@ * Warning: Dependency graphs may generally contain cycles. As such a graph transformer that cannot assume for * sure that cycles have already been eliminated must gracefully handle cyclic graphs, e.g. guard against infinite * recursion. - * + * * @see org.eclipse.aether.RepositorySystemSession#getDependencyGraphTransformer() */ -public interface DependencyGraphTransformer -{ +public interface DependencyGraphTransformer { /** * Transforms the dependency graph denoted by the specified root node. The transformer may directly change the * provided input graph or create a new graph, the former is recommended for performance reasons. - * + * * @param node The root node of the (possibly cyclic!) graph to transform, must not be {@code null}. * @param context The graph transformation context, must not be {@code null}. * @return The result graph of the transformation, never {@code null}. * @throws RepositoryException If the transformation failed. */ - DependencyNode transformGraph( DependencyNode node, DependencyGraphTransformationContext context ) - throws RepositoryException; - + DependencyNode transformGraph(DependencyNode node, DependencyGraphTransformationContext context) + throws RepositoryException; } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyManagement.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyManagement.java index 618f237c4..71bfd5102 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyManagement.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyManagement.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import java.util.Collection; import java.util.Map; @@ -26,11 +25,10 @@ /** * The management updates to apply to a dependency. - * + * * @see DependencyManager#manageDependency(org.eclipse.aether.graph.Dependency) */ -public final class DependencyManagement -{ +public final class DependencyManagement { private String version; @@ -45,76 +43,69 @@ public final class DependencyManagement /** * Creates an empty management update. */ - public DependencyManagement() - { + public DependencyManagement() { // enables default constructor } /** * Gets the new version to apply to the dependency. - * + * * @return The new version or {@code null} if the version is not managed and the existing dependency version should * remain unchanged. */ - public String getVersion() - { + public String getVersion() { return version; } /** * Sets the new version to apply to the dependency. - * + * * @param version The new version, may be {@code null} if the version is not managed. * @return This management update for chaining, never {@code null}. */ - public DependencyManagement setVersion( String version ) - { + public DependencyManagement setVersion(String version) { this.version = version; return this; } /** * Gets the new scope to apply to the dependency. - * + * * @return The new scope or {@code null} if the scope is not managed and the existing dependency scope should remain * unchanged. */ - public String getScope() - { + public String getScope() { return scope; } /** * Sets the new scope to apply to the dependency. - * + * * @param scope The new scope, may be {@code null} if the scope is not managed. * @return This management update for chaining, never {@code null}. */ - public DependencyManagement setScope( String scope ) - { + public DependencyManagement setScope(String scope) { this.scope = scope; return this; } /** * Gets the new optional flag to apply to the dependency. - * + * * @return The new optional flag or {@code null} if the flag is not managed and the existing optional flag of the * dependency should remain unchanged. */ - public Boolean getOptional() - { + public Boolean getOptional() { return optional; } /** * Sets the new optional flag to apply to the dependency. - * + * * @param optional The optional flag, may be {@code null} if the flag is not managed. * @return This management update for chaining, never {@code null}. */ - public DependencyManagement setOptional( Boolean optional ) - { + public DependencyManagement setOptional(Boolean optional) { this.optional = optional; return this; } @@ -123,12 +114,11 @@ public DependencyManagement setOptional( Boolean optional ) * Gets the new exclusions to apply to the dependency. Note that this collection denotes the complete set of * exclusions for the dependency, i.e. the dependency manager controls whether any existing exclusions get merged * with information from dependency management or overridden by it. - * + * * @return The new exclusions or {@code null} if the exclusions are not managed and the existing dependency * exclusions should remain unchanged. */ - public Collection getExclusions() - { + public Collection getExclusions() { return exclusions; } @@ -136,12 +126,11 @@ public Collection getExclusions() * Sets the new exclusions to apply to the dependency. Note that this collection denotes the complete set of * exclusions for the dependency, i.e. the dependency manager controls whether any existing exclusions get merged * with information from dependency management or overridden by it. - * + * * @param exclusions The new exclusions, may be {@code null} if the exclusions are not managed. * @return This management update for chaining, never {@code null}. */ - public DependencyManagement setExclusions( Collection exclusions ) - { + public DependencyManagement setExclusions(Collection exclusions) { this.exclusions = exclusions; return this; } @@ -150,12 +139,11 @@ public DependencyManagement setExclusions( Collection exclusions ) * Gets the new properties to apply to the dependency. Note that this map denotes the complete set of properties, * i.e. the dependency manager controls whether any existing properties get merged with the information from * dependency management or overridden by it. - * + * * @return The new artifact properties or {@code null} if the properties are not managed and the existing properties * should remain unchanged. */ - public Map getProperties() - { + public Map getProperties() { return properties; } @@ -163,14 +151,12 @@ public Map getProperties() * Sets the new properties to apply to the dependency. Note that this map denotes the complete set of properties, * i.e. the dependency manager controls whether any existing properties get merged with the information from * dependency management or overridden by it. - * + * * @param properties The new artifact properties, may be {@code null} if the properties are not managed. * @return This management update for chaining, never {@code null}. */ - public DependencyManagement setProperties( Map properties ) - { + public DependencyManagement setProperties(Map properties) { this.properties = properties; return this; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyManager.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyManager.java index 993e388b1..d24f79c35 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyManager.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import org.eclipse.aether.graph.Dependency; @@ -28,30 +27,28 @@ *

    * Warning: This hook is called from a hot spot and therefore implementations should pay attention to * performance. Among others, implementations should provide a semantic {@link Object#equals(Object) equals()} method. - * + * * @see org.eclipse.aether.RepositorySystemSession#getDependencyManager() * @see org.eclipse.aether.RepositorySystem#collectDependencies(org.eclipse.aether.RepositorySystemSession, * CollectRequest) */ -public interface DependencyManager -{ +public interface DependencyManager { /** * Applies dependency management to the specified dependency. - * + * * @param dependency The dependency to manage, must not be {@code null}. * @return The management update to apply to the dependency or {@code null} if the dependency is not managed at all. */ - DependencyManagement manageDependency( Dependency dependency ); + DependencyManagement manageDependency(Dependency dependency); /** * Derives a dependency manager for the specified collection context. When calculating the child manager, * implementors are strongly advised to simply return the current instance if nothing changed to help save memory. - * + * * @param context The dependency collection context, must not be {@code null}. * @return The dependency manager for the dependencies of the target node or {@code null} if dependency management * should no longer be applied. */ - DependencyManager deriveChildManager( DependencyCollectionContext context ); - + DependencyManager deriveChildManager(DependencyCollectionContext context); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencySelector.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencySelector.java index b257ffa43..087a06a3a 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencySelector.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import org.eclipse.aether.graph.Dependency; @@ -28,31 +27,29 @@ *

    * Warning: This hook is called from a hot spot and therefore implementations should pay attention to * performance. Among others, implementations should provide a semantic {@link Object#equals(Object) equals()} method. - * + * * @see org.eclipse.aether.RepositorySystemSession#getDependencySelector() * @see org.eclipse.aether.RepositorySystem#collectDependencies(org.eclipse.aether.RepositorySystemSession, * CollectRequest) */ -public interface DependencySelector -{ +public interface DependencySelector { /** * Decides whether the specified dependency should be included in the dependency graph. - * + * * @param dependency The dependency to check, must not be {@code null}. * @return {@code false} if the dependency should be excluded from the children of the current node, {@code true} * otherwise. */ - boolean selectDependency( Dependency dependency ); + boolean selectDependency(Dependency dependency); /** * Derives a dependency selector for the specified collection context. When calculating the child selector, * implementors are strongly advised to simply return the current instance if nothing changed to help save memory. - * + * * @param context The dependency collection context, must not be {@code null}. * @return The dependency selector for the target node or {@code null} if dependencies should be unconditionally * included in the sub graph. */ - DependencySelector deriveChildSelector( DependencyCollectionContext context ); - + DependencySelector deriveChildSelector(DependencyCollectionContext context); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyTraverser.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyTraverser.java index be1887bfd..b70ec6352 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyTraverser.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/DependencyTraverser.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import org.eclipse.aether.graph.Dependency; @@ -28,32 +27,30 @@ *

    * Warning: This hook is called from a hot spot and therefore implementations should pay attention to * performance. Among others, implementations should provide a semantic {@link Object#equals(Object) equals()} method. - * + * * @see org.eclipse.aether.RepositorySystemSession#getDependencyTraverser() * @see org.eclipse.aether.RepositorySystem#collectDependencies(org.eclipse.aether.RepositorySystemSession, * CollectRequest) */ -public interface DependencyTraverser -{ +public interface DependencyTraverser { /** * Decides whether the dependencies of the specified dependency should be traversed. - * + * * @param dependency The dependency to check, must not be {@code null}. * @return {@code true} if the dependency graph builder should recurse into the specified dependency and process its * dependencies, {@code false} otherwise. */ - boolean traverseDependency( Dependency dependency ); + boolean traverseDependency(Dependency dependency); /** * Derives a dependency traverser that will be used to decide whether the transitive dependencies of the dependency * given in the collection context shall be traversed. When calculating the child traverser, implementors are * strongly advised to simply return the current instance if nothing changed to help save memory. - * + * * @param context The dependency collection context, must not be {@code null}. * @return The dependency traverser for the target node or {@code null} if dependencies should be unconditionally * traversed in the sub graph. */ - DependencyTraverser deriveChildTraverser( DependencyCollectionContext context ); - + DependencyTraverser deriveChildTraverser(DependencyCollectionContext context); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/UnsolvableVersionConflictException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/UnsolvableVersionConflictException.java index 81353ac2c..d2832e08d 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/UnsolvableVersionConflictException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/UnsolvableVersionConflictException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import java.util.Collection; import java.util.Collections; @@ -33,9 +32,7 @@ /** * Thrown in case of an unsolvable conflict between different version constraints for a dependency. */ -public class UnsolvableVersionConflictException - extends RepositoryException -{ +public class UnsolvableVersionConflictException extends RepositoryException { private final transient Collection versions; @@ -43,43 +40,34 @@ public class UnsolvableVersionConflictException /** * Creates a new exception with the specified paths to conflicting nodes in the dependency graph. - * + * * @param paths The paths to the dependency nodes that participate in the version conflict, may be {@code null}. */ - public UnsolvableVersionConflictException( Collection> paths ) - { - super( "Could not resolve version conflict among " + toPaths( paths ) ); - if ( paths == null ) - { + public UnsolvableVersionConflictException(Collection> paths) { + super("Could not resolve version conflict among " + toPaths(paths)); + if (paths == null) { this.paths = Collections.emptyList(); this.versions = Collections.emptyList(); - } - else - { + } else { this.paths = paths; this.versions = new LinkedHashSet<>(); - for ( List path : paths ) - { - VersionConstraint constraint = path.get( path.size() - 1 ).getVersionConstraint(); - if ( constraint != null && constraint.getRange() != null ) - { - versions.add( constraint.toString() ); + for (List path : paths) { + VersionConstraint constraint = path.get(path.size() - 1).getVersionConstraint(); + if (constraint != null && constraint.getRange() != null) { + versions.add(constraint.toString()); } } } } - private static String toPaths( Collection> paths ) - { + private static String toPaths(Collection> paths) { String result = ""; - if ( paths != null ) - { + if (paths != null) { Collection strings = new LinkedHashSet<>(); - for ( List path : paths ) - { - strings.add( toPath( path ) ); + for (List path : paths) { + strings.add(toPath(path)); } result = strings.toString(); @@ -88,31 +76,26 @@ private static String toPaths( Collection path ) - { - StringBuilder buffer = new StringBuilder( 256 ); + private static String toPath(List path) { + StringBuilder buffer = new StringBuilder(256); - for ( Iterator it = path.iterator(); it.hasNext(); ) - { + for (Iterator it = path.iterator(); it.hasNext(); ) { DependencyNode node = it.next(); - if ( node.getDependency() == null ) - { + if (node.getDependency() == null) { continue; } Artifact artifact = node.getDependency().getArtifact(); - buffer.append( artifact.getGroupId() ); - buffer.append( ':' ).append( artifact.getArtifactId() ); - buffer.append( ':' ).append( artifact.getExtension() ); - if ( artifact.getClassifier().length() > 0 ) - { - buffer.append( ':' ).append( artifact.getClassifier() ); + buffer.append(artifact.getGroupId()); + buffer.append(':').append(artifact.getArtifactId()); + buffer.append(':').append(artifact.getExtension()); + if (artifact.getClassifier().length() > 0) { + buffer.append(':').append(artifact.getClassifier()); } - buffer.append( ':' ).append( node.getVersionConstraint() ); + buffer.append(':').append(node.getVersionConstraint()); - if ( it.hasNext() ) - { - buffer.append( " -> " ); + if (it.hasNext()) { + buffer.append(" -> "); } } @@ -121,22 +104,19 @@ private static String toPath( List path ) /** * Gets the paths leading to the conflicting dependencies. - * + * * @return The (read-only) paths leading to the conflicting dependencies, never {@code null}. */ - public Collection> getPaths() - { + public Collection> getPaths() { return paths; } /** * Gets the conflicting version constraints of the dependency. - * + * * @return The (read-only) conflicting version constraints, never {@code null}. */ - public Collection getVersions() - { + public Collection getVersions() { return versions; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/VersionFilter.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/VersionFilter.java index fb36747f3..d9522d44b 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/VersionFilter.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/VersionFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.collection; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.collection; import java.util.Iterator; import java.util.List; @@ -38,41 +37,38 @@ *

    * Warning: This hook is called from a hot spot and therefore implementations should pay attention to * performance. Among others, implementations should provide a semantic {@link Object#equals(Object) equals()} method. - * + * * @see org.eclipse.aether.RepositorySystemSession#getVersionFilter() * @see org.eclipse.aether.RepositorySystem#collectDependencies(org.eclipse.aether.RepositorySystemSession, * CollectRequest) */ -public interface VersionFilter -{ +public interface VersionFilter { /** * A context used during version filtering to hold relevant data. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ - interface VersionFilterContext - extends Iterable - { + interface VersionFilterContext extends Iterable { /** * Gets the repository system session during which the version filtering happens. - * + * * @return The repository system session, never {@code null}. */ RepositorySystemSession getSession(); /** * Gets the dependency whose version range is being filtered. - * + * * @return The dependency, never {@code null}. */ Dependency getDependency(); /** * Gets the total number of available versions. This count reflects any removals made during version filtering. - * + * * @return The total number of available versions. */ int getCount(); @@ -80,33 +76,32 @@ interface VersionFilterContext /** * Gets an iterator over the available versions of the dependency. The iterator returns versions in ascending * order. Use {@link Iterator#remove()} to exclude a version from further consideration in the dependency graph. - * + * * @return The iterator of available versions, never {@code null}. */ Iterator iterator(); /** * Gets the version constraint that was parsed from the dependency's version string. - * + * * @return The parsed version constraint, never {@code null}. */ VersionConstraint getVersionConstraint(); /** * Gets the repository from which the specified version was resolved. - * + * * @param version The version whose source repository should be retrieved, must not be {@code null}. * @return The repository from which the version was resolved or {@code null} if unknown. */ - ArtifactRepository getRepository( Version version ); + ArtifactRepository getRepository(Version version); /** * Gets the remote repositories from which the versions were resolved. - * + * * @return The (read-only) list of repositories, never {@code null}. */ List getRepositories(); - } /** @@ -115,21 +110,19 @@ interface VersionFilterContext * {@link java.util.Iterator#remove()} to delete unacceptable versions. If no versions remain after all filtering * has been performed, the dependency collection process will automatically fail, i.e. implementations need not * handle this situation on their own. - * + * * @param context The version filter context, must not be {@code null}. * @throws RepositoryException If the filtering could not be performed. */ - void filterVersions( VersionFilterContext context ) - throws RepositoryException; + void filterVersions(VersionFilterContext context) throws RepositoryException; /** * Derives a version filter for the specified collection context. The derived filter will be used to handle version * ranges encountered in child dependencies of the current node. When calculating the child filter, implementors are * strongly advised to simply return the current instance if nothing changed to help save memory. - * + * * @param context The dependency collection context, must not be {@code null}. * @return The version filter for the target node or {@code null} if versions should not be filtered any more. */ - VersionFilter deriveChildFilter( DependencyCollectionContext context ); - + VersionFilter deriveChildFilter(DependencyCollectionContext context); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/package-info.java b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/package-info.java index 414629f62..4b7e55e23 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/collection/package-info.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/collection/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -22,4 +22,3 @@ * graph. */ package org.eclipse.aether.collection; - diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeployRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeployRequest.java index 44bc721af..c5b45c85b 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeployRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeployRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.deployment; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.deployment; import java.util.ArrayList; import java.util.Collection; @@ -30,11 +29,10 @@ /** * A request to deploy artifacts and their accompanying metadata into the a remote repository. - * + * * @see org.eclipse.aether.RepositorySystem#deploy(org.eclipse.aether.RepositorySystemSession, DeployRequest) */ -public final class DeployRequest -{ +public final class DeployRequest { private Collection artifacts = Collections.emptyList(); @@ -47,34 +45,27 @@ public final class DeployRequest /** * Creates an uninitialized request. */ - public DeployRequest() - { - } + public DeployRequest() {} /** * Gets the artifact to deploy. - * + * * @return The artifacts to deploy, never {@code null}. */ - public Collection getArtifacts() - { + public Collection getArtifacts() { return artifacts; } /** * Sets the artifacts to deploy. - * + * * @param artifacts The artifacts to deploy, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public DeployRequest setArtifacts( Collection artifacts ) - { - if ( artifacts == null ) - { + public DeployRequest setArtifacts(Collection artifacts) { + if (artifacts == null) { this.artifacts = Collections.emptyList(); - } - else - { + } else { this.artifacts = artifacts; } return this; @@ -82,47 +73,39 @@ public DeployRequest setArtifacts( Collection artifacts ) /** * Adds the specified artifacts for deployment. - * + * * @param artifact The artifact to add, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public DeployRequest addArtifact( Artifact artifact ) - { - if ( artifact != null ) - { - if ( artifacts.isEmpty() ) - { + public DeployRequest addArtifact(Artifact artifact) { + if (artifact != null) { + if (artifacts.isEmpty()) { artifacts = new ArrayList<>(); } - artifacts.add( artifact ); + artifacts.add(artifact); } return this; } /** * Gets the metadata to deploy. - * + * * @return The metadata to deploy, never {@code null}. */ - public Collection getMetadata() - { + public Collection getMetadata() { return metadata; } /** * Sets the metadata to deploy. - * + * * @param metadata The metadata to deploy, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public DeployRequest setMetadata( Collection metadata ) - { - if ( metadata == null ) - { + public DeployRequest setMetadata(Collection metadata) { + if (metadata == null) { this.metadata = Collections.emptyList(); - } - else - { + } else { this.metadata = metadata; } return this; @@ -130,71 +113,62 @@ public DeployRequest setMetadata( Collection metadata ) /** * Adds the specified metadata for deployment. - * + * * @param metadata The metadata to add, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public DeployRequest addMetadata( Metadata metadata ) - { - if ( metadata != null ) - { - if ( this.metadata.isEmpty() ) - { + public DeployRequest addMetadata(Metadata metadata) { + if (metadata != null) { + if (this.metadata.isEmpty()) { this.metadata = new ArrayList<>(); } - this.metadata.add( metadata ); + this.metadata.add(metadata); } return this; } /** * Gets the repository to deploy to. - * + * * @return The repository to deploy to or {@code null} if not set. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Sets the repository to deploy to. - * + * * @param repository The repository to deploy to, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public DeployRequest setRepository( RemoteRepository repository ) - { + public DeployRequest setRepository(RemoteRepository repository) { this.repository = repository; return this; } /** * Gets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @return The trace information about the higher level operation or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } /** * Sets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @param trace The trace information about the higher level operation, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public DeployRequest setTrace( RequestTrace trace ) - { + public DeployRequest setTrace(RequestTrace trace) { this.trace = trace; return this; } @Override - public String toString() - { + public String toString() { return getArtifacts() + ", " + getMetadata() + " > " + getRepository(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeployResult.java b/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeployResult.java index df37cb627..ed16035b0 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeployResult.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeployResult.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.deployment; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,23 +16,24 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.deployment; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.metadata.Metadata; +import static java.util.Objects.requireNonNull; + /** * The result of deploying artifacts and their accompanying metadata into the a remote repository. - * + * * @see RepositorySystem#deploy(org.eclipse.aether.RepositorySystemSession, DeployRequest) */ -public final class DeployResult -{ +public final class DeployResult { private final DeployRequest request; @@ -47,9 +46,8 @@ public final class DeployResult * * @param request The deployment request, must not be {@code null}. */ - public DeployResult( DeployRequest request ) - { - this.request = requireNonNull( request, "deploy request cannot be null" ); + public DeployResult(DeployRequest request) { + this.request = requireNonNull(request, "deploy request cannot be null"); artifacts = Collections.emptyList(); metadata = Collections.emptyList(); } @@ -59,35 +57,29 @@ public DeployResult( DeployRequest request ) * * @return The deploy request, never {@code null}. */ - public DeployRequest getRequest() - { + public DeployRequest getRequest() { return request; } /** * Gets the artifacts that got deployed. - * + * * @return The deployed artifacts, never {@code null}. */ - public Collection getArtifacts() - { + public Collection getArtifacts() { return artifacts; } /** * Sets the artifacts that got deployed. - * + * * @param artifacts The deployed artifacts, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public DeployResult setArtifacts( Collection artifacts ) - { - if ( artifacts == null ) - { + public DeployResult setArtifacts(Collection artifacts) { + if (artifacts == null) { this.artifacts = Collections.emptyList(); - } - else - { + } else { this.artifacts = artifacts; } return this; @@ -95,19 +87,16 @@ public DeployResult setArtifacts( Collection artifacts ) /** * Adds the specified artifacts to the result. - * + * * @param artifact The deployed artifact to add, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public DeployResult addArtifact( Artifact artifact ) - { - if ( artifact != null ) - { - if ( artifacts.isEmpty() ) - { + public DeployResult addArtifact(Artifact artifact) { + if (artifact != null) { + if (artifacts.isEmpty()) { artifacts = new ArrayList<>(); } - artifacts.add( artifact ); + artifacts.add(artifact); } return this; } @@ -115,28 +104,23 @@ public DeployResult addArtifact( Artifact artifact ) /** * Gets the metadata that got deployed. Note that due to automatically generated metadata, there might have been * more metadata deployed than originally specified in the deploy request. - * + * * @return The deployed metadata, never {@code null}. */ - public Collection getMetadata() - { + public Collection getMetadata() { return metadata; } /** * Sets the metadata that got deployed. - * + * * @param metadata The deployed metadata, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public DeployResult setMetadata( Collection metadata ) - { - if ( metadata == null ) - { + public DeployResult setMetadata(Collection metadata) { + if (metadata == null) { this.metadata = Collections.emptyList(); - } - else - { + } else { this.metadata = metadata; } return this; @@ -144,27 +128,22 @@ public DeployResult setMetadata( Collection metadata ) /** * Adds the specified metadata to this result. - * + * * @param metadata The deployed metadata to add, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public DeployResult addMetadata( Metadata metadata ) - { - if ( metadata != null ) - { - if ( this.metadata.isEmpty() ) - { + public DeployResult addMetadata(Metadata metadata) { + if (metadata != null) { + if (this.metadata.isEmpty()) { this.metadata = new ArrayList<>(); } - this.metadata.add( metadata ); + this.metadata.add(metadata); } return this; } @Override - public String toString() - { + public String toString() { return getArtifacts() + ", " + getMetadata(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeploymentException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeploymentException.java index 53252bafb..efdbe8cca 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeploymentException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/DeploymentException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.deployment; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,35 +16,31 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.deployment; import org.eclipse.aether.RepositoryException; /** * Thrown in case of a deployment error like authentication failure. */ -public class DeploymentException - extends RepositoryException -{ +public class DeploymentException extends RepositoryException { /** * Creates a new exception with the specified detail message. - * + * * @param message The detail message, may be {@code null}. */ - public DeploymentException( String message ) - { - super( message ); + public DeploymentException(String message) { + super(message); } /** * Creates a new exception with the specified detail message and cause. - * + * * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public DeploymentException( String message, Throwable cause ) - { - super( message, cause ); + public DeploymentException(String message, Throwable cause) { + super(message, cause); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/package-info.java b/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/package-info.java index dc50c2158..fc9192946 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/package-info.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/deployment/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * The types supporting the publishing of artifacts to a remote repository. */ package org.eclipse.aether.deployment; - diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DefaultDependencyNode.java b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DefaultDependencyNode.java index a2c1c8b0b..b746f7581 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DefaultDependencyNode.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DefaultDependencyNode.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.graph; import java.util.ArrayList; import java.util.Collection; @@ -25,19 +24,18 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.version.Version; import org.eclipse.aether.version.VersionConstraint; +import static java.util.Objects.requireNonNull; + /** * A node within a dependency graph. */ -public final class DefaultDependencyNode - implements DependencyNode -{ +public final class DefaultDependencyNode implements DependencyNode { private List children; @@ -63,14 +61,13 @@ public final class DefaultDependencyNode /** * Creates a new node with the specified dependency. - * + * * @param dependency The dependency associated with this node, may be {@code null} for a root node. */ - public DefaultDependencyNode( Dependency dependency ) - { + public DefaultDependencyNode(Dependency dependency) { this.dependency = dependency; - artifact = ( dependency != null ) ? dependency.getArtifact() : null; - children = new ArrayList<>( 0 ); + artifact = (dependency != null) ? dependency.getArtifact() : null; + children = new ArrayList<>(0); aliases = Collections.emptyList(); relocations = Collections.emptyList(); repositories = Collections.emptyList(); @@ -82,13 +79,12 @@ public DefaultDependencyNode( Dependency dependency ) * Creates a new root node with the specified artifact as its label. Note that the new node has no dependency, i.e. * {@link #getDependency()} will return {@code null}. Put differently, the specified artifact will not be subject to * dependency collection/resolution. - * + * * @param artifact The artifact to use as label for this node, may be {@code null}. */ - public DefaultDependencyNode( Artifact artifact ) - { + public DefaultDependencyNode(Artifact artifact) { this.artifact = artifact; - children = new ArrayList<>( 0 ); + children = new ArrayList<>(0); aliases = Collections.emptyList(); relocations = Collections.emptyList(); repositories = Collections.emptyList(); @@ -99,270 +95,214 @@ public DefaultDependencyNode( Artifact artifact ) /** * Creates a mostly shallow clone of the specified node. The new node has its own copy of any custom data and * initially no children. - * + * * @param node The node to copy, must not be {@code null}. */ - public DefaultDependencyNode( DependencyNode node ) - { + public DefaultDependencyNode(DependencyNode node) { dependency = node.getDependency(); artifact = node.getArtifact(); - children = new ArrayList<>( 0 ); - setAliases( node.getAliases() ); - setRequestContext( node.getRequestContext() ); - setManagedBits( node.getManagedBits() ); - setRelocations( node.getRelocations() ); - setRepositories( node.getRepositories() ); - setVersion( node.getVersion() ); - setVersionConstraint( node.getVersionConstraint() ); + children = new ArrayList<>(0); + setAliases(node.getAliases()); + setRequestContext(node.getRequestContext()); + setManagedBits(node.getManagedBits()); + setRelocations(node.getRelocations()); + setRepositories(node.getRepositories()); + setVersion(node.getVersion()); + setVersionConstraint(node.getVersionConstraint()); Map data = node.getData(); - setData( data.isEmpty() ? null : new HashMap<>( data ) ); + setData(data.isEmpty() ? null : new HashMap<>(data)); } - public List getChildren() - { + public List getChildren() { return children; } - public void setChildren( List children ) - { - if ( children == null ) - { - this.children = new ArrayList<>( 0 ); - } - else - { + public void setChildren(List children) { + if (children == null) { + this.children = new ArrayList<>(0); + } else { this.children = children; } } - public Dependency getDependency() - { + public Dependency getDependency() { return dependency; } - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } - public void setArtifact( Artifact artifact ) - { - if ( dependency == null ) - { - throw new IllegalStateException( "node does not have a dependency" ); + public void setArtifact(Artifact artifact) { + if (dependency == null) { + throw new IllegalStateException("node does not have a dependency"); } - dependency = dependency.setArtifact( artifact ); + dependency = dependency.setArtifact(artifact); this.artifact = dependency.getArtifact(); } - public List getRelocations() - { + public List getRelocations() { return relocations; } /** * Sets the sequence of relocations that was followed to resolve this dependency's artifact. - * + * * @param relocations The sequence of relocations, may be {@code null}. */ - public void setRelocations( List relocations ) - { - if ( relocations == null || relocations.isEmpty() ) - { + public void setRelocations(List relocations) { + if (relocations == null || relocations.isEmpty()) { this.relocations = Collections.emptyList(); - } - else - { + } else { this.relocations = relocations; } } - public Collection getAliases() - { + public Collection getAliases() { return aliases; } /** * Sets the known aliases for this dependency's artifact. - * + * * @param aliases The known aliases, may be {@code null}. */ - public void setAliases( Collection aliases ) - { - if ( aliases == null || aliases.isEmpty() ) - { + public void setAliases(Collection aliases) { + if (aliases == null || aliases.isEmpty()) { this.aliases = Collections.emptyList(); - } - else - { + } else { this.aliases = aliases; } } - public VersionConstraint getVersionConstraint() - { + public VersionConstraint getVersionConstraint() { return versionConstraint; } /** * Sets the version constraint that was parsed from the dependency's version declaration. - * + * * @param versionConstraint The version constraint for this node, may be {@code null}. */ - public void setVersionConstraint( VersionConstraint versionConstraint ) - { + public void setVersionConstraint(VersionConstraint versionConstraint) { this.versionConstraint = versionConstraint; } - public Version getVersion() - { + public Version getVersion() { return version; } /** * Sets the version that was selected for the dependency's target artifact. - * + * * @param version The parsed version, may be {@code null}. */ - public void setVersion( Version version ) - { + public void setVersion(Version version) { this.version = version; } - public void setScope( String scope ) - { - if ( dependency == null ) - { - throw new IllegalStateException( "node does not have a dependency" ); + public void setScope(String scope) { + if (dependency == null) { + throw new IllegalStateException("node does not have a dependency"); } - dependency = dependency.setScope( scope ); + dependency = dependency.setScope(scope); } - public void setOptional( Boolean optional ) - { - if ( dependency == null ) - { - throw new IllegalStateException( "node does not have a dependency" ); + public void setOptional(Boolean optional) { + if (dependency == null) { + throw new IllegalStateException("node does not have a dependency"); } - dependency = dependency.setOptional( optional ); + dependency = dependency.setOptional(optional); } - public int getManagedBits() - { + public int getManagedBits() { return managedBits; } /** * Sets a bit field indicating which attributes of this node were subject to dependency management. - * + * * @param managedBits The bit field indicating the managed attributes or {@code 0} if dependency management wasn't * applied. */ - public void setManagedBits( int managedBits ) - { - this.managedBits = (byte) ( managedBits & 0x1F ); + public void setManagedBits(int managedBits) { + this.managedBits = (byte) (managedBits & 0x1F); } - public List getRepositories() - { + public List getRepositories() { return repositories; } /** * Sets the remote repositories from which this node's artifact shall be resolved. - * + * * @param repositories The remote repositories to use for artifact resolution, may be {@code null}. */ - public void setRepositories( List repositories ) - { - if ( repositories == null || repositories.isEmpty() ) - { + public void setRepositories(List repositories) { + if (repositories == null || repositories.isEmpty()) { this.repositories = Collections.emptyList(); - } - else - { + } else { this.repositories = repositories; } } - public String getRequestContext() - { + public String getRequestContext() { return context; } - public void setRequestContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public void setRequestContext(String context) { + this.context = (context != null) ? context : ""; } - public Map getData() - { + public Map getData() { return data; } - public void setData( Map data ) - { - if ( data == null ) - { + public void setData(Map data) { + if (data == null) { this.data = Collections.emptyMap(); - } - else - { + } else { this.data = data; } } - public void setData( Object key, Object value ) - { - requireNonNull( key, "key cannot be null" ); + public void setData(Object key, Object value) { + requireNonNull(key, "key cannot be null"); - if ( value == null ) - { - if ( !data.isEmpty() ) - { - data.remove( key ); + if (value == null) { + if (!data.isEmpty()) { + data.remove(key); - if ( data.isEmpty() ) - { + if (data.isEmpty()) { data = Collections.emptyMap(); } } - } - else - { - if ( data.isEmpty() ) - { - data = new HashMap<>( 1, 2 ); // nodes can be numerous so let's be space conservative + } else { + if (data.isEmpty()) { + data = new HashMap<>(1, 2); // nodes can be numerous so let's be space conservative } - data.put( key, value ); + data.put(key, value); } } - public boolean accept( DependencyVisitor visitor ) - { - if ( visitor.visitEnter( this ) ) - { - for ( DependencyNode child : children ) - { - if ( !child.accept( visitor ) ) - { + public boolean accept(DependencyVisitor visitor) { + if (visitor.visitEnter(this)) { + for (DependencyNode child : children) { + if (!child.accept(visitor)) { break; } } } - return visitor.visitLeave( this ); + return visitor.visitLeave(this); } @Override - public String toString() - { + public String toString() { Dependency dep = getDependency(); - if ( dep == null ) - { - return String.valueOf( getArtifact() ); + if (dep == null) { + return String.valueOf(getArtifact()); } return dep.toString(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/Dependency.java b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/Dependency.java index db0efcb39..0dea94e49 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/Dependency.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/Dependency.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.graph; import java.util.AbstractSet; import java.util.Collection; @@ -25,19 +24,18 @@ import java.util.Iterator; import java.util.LinkedHashSet; import java.util.NoSuchElementException; -import static java.util.Objects.requireNonNull; - import java.util.Objects; import java.util.Set; import org.eclipse.aether.artifact.Artifact; +import static java.util.Objects.requireNonNull; + /** * A dependency to some artifact. Note: Instances of this class are immutable and the exposed mutators return * new objects rather than changing the current instance. */ -public final class Dependency -{ +public final class Dependency { private final Artifact artifact; @@ -49,276 +47,235 @@ public final class Dependency /** * Creates a mandatory dependency on the specified artifact with the given scope. - * + * * @param artifact The artifact being depended on, must not be {@code null}. * @param scope The scope of the dependency, may be {@code null}. */ - public Dependency( Artifact artifact, String scope ) - { - this( artifact, scope, false ); + public Dependency(Artifact artifact, String scope) { + this(artifact, scope, false); } /** * Creates a dependency on the specified artifact with the given scope. - * + * * @param artifact The artifact being depended on, must not be {@code null}. * @param scope The scope of the dependency, may be {@code null}. * @param optional A flag whether the dependency is optional or mandatory, may be {@code null}. */ - public Dependency( Artifact artifact, String scope, Boolean optional ) - { - this( artifact, scope, optional, null ); + public Dependency(Artifact artifact, String scope, Boolean optional) { + this(artifact, scope, optional, null); } /** * Creates a dependency on the specified artifact with the given scope and exclusions. - * + * * @param artifact The artifact being depended on, must not be {@code null}. * @param scope The scope of the dependency, may be {@code null}. * @param optional A flag whether the dependency is optional or mandatory, may be {@code null}. * @param exclusions The exclusions that apply to transitive dependencies, may be {@code null} if none. */ - public Dependency( Artifact artifact, String scope, Boolean optional, Collection exclusions ) - { - this( artifact, scope, Exclusions.copy( exclusions ), optional ); + public Dependency(Artifact artifact, String scope, Boolean optional, Collection exclusions) { + this(artifact, scope, Exclusions.copy(exclusions), optional); } - private Dependency( Artifact artifact, String scope, Set exclusions, Boolean optional ) - { + private Dependency(Artifact artifact, String scope, Set exclusions, Boolean optional) { // NOTE: This constructor assumes immutability of the provided exclusion collection, for internal use only - this.artifact = requireNonNull( artifact, "artifact cannot be null" ); - this.scope = ( scope != null ) ? scope : ""; + this.artifact = requireNonNull(artifact, "artifact cannot be null"); + this.scope = (scope != null) ? scope : ""; this.optional = optional; this.exclusions = exclusions; } /** * Gets the artifact being depended on. - * + * * @return The artifact, never {@code null}. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Sets the artifact being depended on. - * + * * @param artifact The artifact, must not be {@code null}. * @return The new dependency, never {@code null}. */ - public Dependency setArtifact( Artifact artifact ) - { - if ( this.artifact.equals( artifact ) ) - { + public Dependency setArtifact(Artifact artifact) { + if (this.artifact.equals(artifact)) { return this; } - return new Dependency( artifact, scope, exclusions, optional ); + return new Dependency(artifact, scope, exclusions, optional); } /** * Gets the scope of the dependency. The scope defines in which context this dependency is relevant. - * + * * @return The scope or an empty string if not set, never {@code null}. */ - public String getScope() - { + public String getScope() { return scope; } /** * Sets the scope of the dependency, e.g. "compile". - * + * * @param scope The scope of the dependency, may be {@code null}. * @return The new dependency, never {@code null}. */ - public Dependency setScope( String scope ) - { - if ( this.scope.equals( scope ) || ( scope == null && this.scope.isEmpty() ) ) - { + public Dependency setScope(String scope) { + if (this.scope.equals(scope) || (scope == null && this.scope.isEmpty())) { return this; } - return new Dependency( artifact, scope, exclusions, optional ); + return new Dependency(artifact, scope, exclusions, optional); } /** * Indicates whether this dependency is optional or not. Optional dependencies can be ignored in some contexts. - * + * * @return {@code true} if the dependency is (definitively) optional, {@code false} otherwise. */ - public boolean isOptional() - { - return Boolean.TRUE.equals( optional ); + public boolean isOptional() { + return Boolean.TRUE.equals(optional); } /** * Gets the optional flag for the dependency. Note: Most clients will usually call {@link #isOptional()} to * determine the optional flag, this method is for advanced use cases where three-valued logic is required. - * + * * @return The optional flag or {@code null} if unspecified. */ - public Boolean getOptional() - { + public Boolean getOptional() { return optional; } /** * Sets the optional flag for the dependency. - * + * * @param optional {@code true} if the dependency is optional, {@code false} if the dependency is mandatory, may be * {@code null} if unspecified. * @return The new dependency, never {@code null}. */ - public Dependency setOptional( Boolean optional ) - { - if ( Objects.equals( this.optional, optional ) ) - { + public Dependency setOptional(Boolean optional) { + if (Objects.equals(this.optional, optional)) { return this; } - return new Dependency( artifact, scope, exclusions, optional ); + return new Dependency(artifact, scope, exclusions, optional); } /** * Gets the exclusions for this dependency. Exclusions can be used to remove transitive dependencies during * resolution. - * + * * @return The (read-only) exclusions, never {@code null}. */ - public Collection getExclusions() - { + public Collection getExclusions() { return exclusions; } /** * Sets the exclusions for the dependency. - * + * * @param exclusions The exclusions, may be {@code null}. * @return The new dependency, never {@code null}. */ - public Dependency setExclusions( Collection exclusions ) - { - if ( hasEquivalentExclusions( exclusions ) ) - { + public Dependency setExclusions(Collection exclusions) { + if (hasEquivalentExclusions(exclusions)) { return this; } - return new Dependency( artifact, scope, optional, exclusions ); + return new Dependency(artifact, scope, optional, exclusions); } - private boolean hasEquivalentExclusions( Collection exclusions ) - { - if ( exclusions == null || exclusions.isEmpty() ) - { + private boolean hasEquivalentExclusions(Collection exclusions) { + if (exclusions == null || exclusions.isEmpty()) { return this.exclusions.isEmpty(); } - if ( exclusions instanceof Set ) - { - return this.exclusions.equals( exclusions ); + if (exclusions instanceof Set) { + return this.exclusions.equals(exclusions); } - return exclusions.size() >= this.exclusions.size() && this.exclusions.containsAll( exclusions ) - && exclusions.containsAll( this.exclusions ); + return exclusions.size() >= this.exclusions.size() + && this.exclusions.containsAll(exclusions) + && exclusions.containsAll(this.exclusions); } @Override - public String toString() - { - return getArtifact() + " (" + getScope() + ( isOptional() ? "?" : "" ) + ")"; + public String toString() { + return getArtifact() + " (" + getScope() + (isOptional() ? "?" : "") + ")"; } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + } else if (obj == null || !getClass().equals(obj.getClass())) { return false; } Dependency that = (Dependency) obj; - return Objects.equals( artifact, that.artifact ) && Objects.equals( scope, that.scope ) - && Objects.equals( optional, that.optional ) && Objects.equals( exclusions, that.exclusions ); + return Objects.equals(artifact, that.artifact) + && Objects.equals(scope, that.scope) + && Objects.equals(optional, that.optional) + && Objects.equals(exclusions, that.exclusions); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + artifact.hashCode(); hash = hash * 31 + scope.hashCode(); - hash = hash * 31 + ( optional != null ? optional.hashCode() : 0 ); + hash = hash * 31 + (optional != null ? optional.hashCode() : 0); hash = hash * 31 + exclusions.size(); return hash; } - private static class Exclusions - extends AbstractSet - { + private static class Exclusions extends AbstractSet { private final Exclusion[] exclusions; - public static Set copy( Collection exclusions ) - { - if ( exclusions == null || exclusions.isEmpty() ) - { + public static Set copy(Collection exclusions) { + if (exclusions == null || exclusions.isEmpty()) { return Collections.emptySet(); } - return new Exclusions( exclusions ); + return new Exclusions(exclusions); } - private Exclusions( Collection exclusions ) - { - if ( exclusions.size() > 1 && !( exclusions instanceof Set ) ) - { - exclusions = new LinkedHashSet<>( exclusions ); + private Exclusions(Collection exclusions) { + if (exclusions.size() > 1 && !(exclusions instanceof Set)) { + exclusions = new LinkedHashSet<>(exclusions); } - this.exclusions = exclusions.toArray( new Exclusion[0] ); + this.exclusions = exclusions.toArray(new Exclusion[0]); } @Override - public Iterator iterator() - { - return new Iterator() - { + public Iterator iterator() { + return new Iterator() { private int cursor = 0; - public boolean hasNext() - { + public boolean hasNext() { return cursor < exclusions.length; } - public Exclusion next() - { - try - { + public Exclusion next() { + try { Exclusion exclusion = exclusions[cursor]; cursor++; return exclusion; - } - catch ( IndexOutOfBoundsException e ) - { + } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } - }; } @Override - public int size() - { + public int size() { return exclusions.length; } - } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyCycle.java b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyCycle.java index 1076ab81b..3a552c864 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyCycle.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyCycle.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.graph; import java.util.List; @@ -25,17 +24,16 @@ * A cycle within a dependency graph, that is a sequence of dependencies d_1, d_2, ..., d_n where d_1 and d_n have the * same versionless coordinates. In more practical terms, a cycle occurs when a project directly or indirectly depends * on its own output artifact. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface DependencyCycle -{ +public interface DependencyCycle { /** * Gets the dependencies that lead to the first dependency on the cycle, starting from the root of the dependency * graph. - * + * * @return The (read-only) sequence of dependencies that precedes the cycle in the graph, potentially empty but * never {@code null}. */ @@ -45,9 +43,8 @@ public interface DependencyCycle * Gets the dependencies that actually form the cycle. For example, a -> b -> c -> a, i.e. the last * dependency in this sequence duplicates the first element and closes the cycle. Hence the length of the cycle is * the size of the returned sequence minus 1. - * + * * @return The (read-only) sequence of dependencies that forms the cycle, never {@code null}. */ List getCyclicDependencies(); - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyFilter.java b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyFilter.java index 41776ff98..585b1f1c9 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyFilter.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,18 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.graph; import java.util.List; /** * A filter to include/exclude dependency nodes during other operations. */ -public interface DependencyFilter -{ +public interface DependencyFilter { /** * Indicates whether the specified dependency node shall be included or excluded. - * + * * @param node The dependency node to filter, must not be {@code null}. * @param parents The (read-only) chain of parent nodes that leads to the node to be filtered, must not be * {@code null}. Iterating this (possibly empty) list walks up the dependency graph towards the root @@ -37,6 +35,5 @@ public interface DependencyFilter * denotes the zero-based depth of the filtered node. * @return {@code true} to include the dependency node, {@code false} to exclude it. */ - boolean accept( DependencyNode node, List parents ); - + boolean accept(DependencyNode node, List parents); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyNode.java b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyNode.java index 25510430d..da0baeb17 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyNode.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyNode.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.graph; import java.util.Collection; import java.util.List; @@ -34,44 +33,43 @@ * discover multiple paths leading to the same node instance unless the input graph is known to be a duplicate-free * tree. Note: Unless otherwise noted, implementation classes are not thread-safe and dependency nodes should * not be mutated by concurrent threads. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface DependencyNode -{ +public interface DependencyNode { /** * A bit flag indicating the dependency version was subject to dependency management - * + * * @see #getManagedBits() */ int MANAGED_VERSION = 0x01; /** * A bit flag indicating the dependency scope was subject to dependency management - * + * * @see #getManagedBits() */ int MANAGED_SCOPE = 0x02; /** * A bit flag indicating the optional flag was subject to dependency management - * + * * @see #getManagedBits() */ int MANAGED_OPTIONAL = 0x04; /** * A bit flag indicating the artifact properties were subject to dependency management - * + * * @see #getManagedBits() */ int MANAGED_PROPERTIES = 0x08; /** * A bit flag indicating the exclusions were subject to dependency management - * + * * @see #getManagedBits() */ int MANAGED_EXCLUSIONS = 0x10; @@ -81,23 +79,23 @@ public interface DependencyNode * same child list instance. Hence clients mutating the child list need to be aware that these changes might affect * more than this node. Where this is not desired, the child list should be copied before mutation if the client * cannot be sure whether it might be shared with other nodes in the graph. - * + * * @return The child nodes of this node, never {@code null}. */ List getChildren(); /** * Sets the child nodes of this node. - * + * * @param children The child nodes, may be {@code null} */ - void setChildren( List children ); + void setChildren(List children); /** * Gets the dependency associated with this node. Note: For dependency graphs that have been constructed * without a root dependency, this method will yield {@code null} when invoked on the graph's root node. The root * node of such graphs may however still have a label as returned by {@link #getArtifact()}. - * + * * @return The dependency or {@code null} if none. */ Dependency getDependency(); @@ -106,7 +104,7 @@ public interface DependencyNode * Gets the artifact associated with this node. If this node is associated with a dependency, this is equivalent to * {@code getDependency().getArtifact()}. Otherwise the artifact merely provides a label for this node in which case * the artifact must not be subjected to dependency collection/resolution. - * + * * @return The associated artifact or {@code null} if none. */ Artifact getArtifact(); @@ -115,14 +113,14 @@ public interface DependencyNode * Updates the artifact of the dependency after resolution. The new artifact must have the same coordinates as the * original artifact. This method may only be invoked if this node actually has a dependency, i.e. if * {@link #getDependency()} is not null. - * + * * @param artifact The artifact satisfying the dependency, must not be {@code null}. */ - void setArtifact( Artifact artifact ); + void setArtifact(Artifact artifact); /** * Gets the sequence of relocations that was followed to resolve the artifact referenced by the dependency. - * + * * @return The (read-only) sequence of relocations, never {@code null}. */ List getRelocations(); @@ -131,21 +129,21 @@ public interface DependencyNode * Gets the known aliases for this dependency's artifact. An alias can be used to mark a patched rebuild of some * other artifact as such, thereby allowing conflict resolution to consider the patched and the original artifact as * a conflict. - * + * * @return The (read-only) set of known aliases, never {@code null}. */ Collection getAliases(); /** * Gets the version constraint that was parsed from the dependency's version declaration. - * + * * @return The version constraint for this node or {@code null}. */ VersionConstraint getVersionConstraint(); /** * Gets the version that was selected for the dependency's target artifact. - * + * * @return The parsed version or {@code null}. */ Version getVersion(); @@ -153,22 +151,22 @@ public interface DependencyNode /** * Sets the scope of the dependency. This method may only be invoked if this node actually has a dependency, i.e. if * {@link #getDependency()} is not null. - * + * * @param scope The scope, may be {@code null}. */ - void setScope( String scope ); + void setScope(String scope); /** * Sets the optional flag of the dependency. This method may only be invoked if this node actually has a dependency, * i.e. if {@link #getDependency()} is not null. - * + * * @param optional The optional flag, may be {@code null}. */ - void setOptional( Boolean optional ); + void setOptional(Boolean optional); /** * Gets a bit field indicating which attributes of this node were subject to dependency management. - * + * * @return A bit field containing any of the bits {@link #MANAGED_VERSION}, {@link #MANAGED_SCOPE}, * {@link #MANAGED_OPTIONAL}, {@link #MANAGED_PROPERTIES} and {@link #MANAGED_EXCLUSIONS} if the * corresponding attribute was set via dependency management. @@ -177,56 +175,55 @@ public interface DependencyNode /** * Gets the remote repositories from which this node's artifact shall be resolved. - * + * * @return The (read-only) list of remote repositories to use for artifact resolution, never {@code null}. */ List getRepositories(); /** * Gets the request context in which this dependency node was created. - * + * * @return The request context, never {@code null}. */ String getRequestContext(); /** * Sets the request context in which this dependency node was created. - * + * * @param context The context, may be {@code null}. */ - void setRequestContext( String context ); + void setRequestContext(String context); /** * Gets the custom data associated with this dependency node. Clients of the repository system can use this data to * annotate dependency nodes with domain-specific information. Note that the returned map is read-only and * {@link #setData(Object, Object)} needs to be used to update the custom data. - * + * * @return The (read-only) key-value mappings, never {@code null}. */ Map getData(); /** * Sets the custom data associated with this dependency node. - * + * * @param data The new custom data, may be {@code null}. */ - void setData( Map data ); + void setData(Map data); /** * Associates the specified dependency node data with the given key. Note: This method must not be called * while {@link #getData()} is being iterated. - * + * * @param key The key under which to store the data, must not be {@code null}. * @param value The data to associate with the key, may be {@code null} to remove the mapping. */ - void setData( Object key, Object value ); + void setData(Object key, Object value); /** * Traverses this node and potentially its children using the specified visitor. - * + * * @param visitor The visitor to call back, must not be {@code null}. * @return {@code true} to visit siblings nodes of this node as well, {@code false} to skip siblings. */ - boolean accept( DependencyVisitor visitor ); - + boolean accept(DependencyVisitor visitor); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyVisitor.java b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyVisitor.java index 2a85f2d0f..cb611bc5b 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyVisitor.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/DependencyVisitor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,30 +16,29 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.graph; /** * A visitor for nodes of the dependency graph. - * + * * @see DependencyNode#accept(DependencyVisitor) */ -public interface DependencyVisitor -{ +public interface DependencyVisitor { /** * Notifies the visitor of a node visit before its children have been processed. - * + * * @param node The dependency node being visited, must not be {@code null}. * @return {@code true} to visit child nodes of the specified node as well, {@code false} to skip children. */ - boolean visitEnter( DependencyNode node ); + boolean visitEnter(DependencyNode node); /** * Notifies the visitor of a node visit after its children have been processed. Note that this method is always * invoked regardless whether any children have actually been visited. - * + * * @param node The dependency node being visited, must not be {@code null}. * @return {@code true} to visit siblings nodes of the specified node as well, {@code false} to skip siblings. */ - boolean visitLeave( DependencyNode node ); - + boolean visitLeave(DependencyNode node); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/Exclusion.java b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/Exclusion.java index 6d35b7109..ddf5d2523 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/Exclusion.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/Exclusion.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.graph; /** * An exclusion of one or more transitive dependencies. * * @see Dependency#getExclusions() */ -public final class Exclusion -{ +public final class Exclusion { private final String groupId; @@ -43,12 +41,11 @@ public final class Exclusion * @param classifier The classifier, may be {@code null}. * @param extension The file extension, may be {@code null}. */ - public Exclusion( String groupId, String artifactId, String classifier, String extension ) - { - this.groupId = ( groupId != null ) ? groupId : ""; - this.artifactId = ( artifactId != null ) ? artifactId : ""; - this.classifier = ( classifier != null ) ? classifier : ""; - this.extension = ( extension != null ) ? extension : ""; + public Exclusion(String groupId, String artifactId, String classifier, String extension) { + this.groupId = (groupId != null) ? groupId : ""; + this.artifactId = (artifactId != null) ? artifactId : ""; + this.classifier = (classifier != null) ? classifier : ""; + this.extension = (extension != null) ? extension : ""; } /** @@ -56,8 +53,7 @@ public Exclusion( String groupId, String artifactId, String classifier, String e * * @return The group identifier, never {@code null}. */ - public String getGroupId() - { + public String getGroupId() { return groupId; } @@ -66,8 +62,7 @@ public String getGroupId() * * @return The artifact identifier, never {@code null}. */ - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } @@ -76,8 +71,7 @@ public String getArtifactId() * * @return The classifier, never {@code null}. */ - public String getClassifier() - { + public String getClassifier() { return classifier; } @@ -86,39 +80,38 @@ public String getClassifier() * * @return The file extension of artifacts to exclude, never {@code null}. */ - public String getExtension() - { + public String getExtension() { return extension; } @Override - public String toString() - { - return getGroupId() + ':' + getArtifactId() + ':' + getExtension() - + ( getClassifier().length() > 0 ? ':' + getClassifier() : "" ); + public String toString() { + return getGroupId() + + ':' + + getArtifactId() + + ':' + + getExtension() + + (getClassifier().length() > 0 ? ':' + getClassifier() : ""); } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + } else if (obj == null || !getClass().equals(obj.getClass())) { return false; } Exclusion that = (Exclusion) obj; - return artifactId.equals( that.artifactId ) && groupId.equals( that.groupId ) - && extension.equals( that.extension ) && classifier.equals( that.classifier ); + return artifactId.equals(that.artifactId) + && groupId.equals(that.groupId) + && extension.equals(that.extension) + && classifier.equals(that.classifier); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + artifactId.hashCode(); hash = hash * 31 + groupId.hashCode(); @@ -126,5 +119,4 @@ public int hashCode() hash = hash * 31 + extension.hashCode(); return hash; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/package-info.java b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/package-info.java index c3ba9db1d..ac30e4b81 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/graph/package-info.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/graph/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * The representation of a dependency graph by means of connected dependency nodes. */ package org.eclipse.aether.graph; - diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallRequest.java index a7f00cf08..fd4567aa9 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.installation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.installation; import java.util.ArrayList; import java.util.Collection; @@ -30,11 +29,10 @@ /** * A request to install artifacts and their accompanying metadata into the local repository. - * + * * @see RepositorySystem#install(RepositorySystemSession, InstallRequest) */ -public final class InstallRequest -{ +public final class InstallRequest { private Collection artifacts = Collections.emptyList(); @@ -45,34 +43,27 @@ public final class InstallRequest /** * Creates an uninitialized request. */ - public InstallRequest() - { - } + public InstallRequest() {} /** * Gets the artifact to install. - * + * * @return The artifacts to install, never {@code null}. */ - public Collection getArtifacts() - { + public Collection getArtifacts() { return artifacts; } /** * Sets the artifacts to install. - * + * * @param artifacts The artifacts to install, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public InstallRequest setArtifacts( Collection artifacts ) - { - if ( artifacts == null ) - { + public InstallRequest setArtifacts(Collection artifacts) { + if (artifacts == null) { this.artifacts = Collections.emptyList(); - } - else - { + } else { this.artifacts = artifacts; } return this; @@ -80,47 +71,39 @@ public InstallRequest setArtifacts( Collection artifacts ) /** * Adds the specified artifacts for installation. - * + * * @param artifact The artifact to add, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public InstallRequest addArtifact( Artifact artifact ) - { - if ( artifact != null ) - { - if ( artifacts.isEmpty() ) - { + public InstallRequest addArtifact(Artifact artifact) { + if (artifact != null) { + if (artifacts.isEmpty()) { artifacts = new ArrayList<>(); } - artifacts.add( artifact ); + artifacts.add(artifact); } return this; } /** * Gets the metadata to install. - * + * * @return The metadata to install, never {@code null}. */ - public Collection getMetadata() - { + public Collection getMetadata() { return metadata; } /** * Sets the metadata to install. - * + * * @param metadata The metadata to install. * @return This request for chaining, never {@code null}. */ - public InstallRequest setMetadata( Collection metadata ) - { - if ( metadata == null ) - { + public InstallRequest setMetadata(Collection metadata) { + if (metadata == null) { this.metadata = Collections.emptyList(); - } - else - { + } else { this.metadata = metadata; } return this; @@ -128,49 +111,42 @@ public InstallRequest setMetadata( Collection metadata ) /** * Adds the specified metadata for installation. - * + * * @param metadata The metadata to add, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public InstallRequest addMetadata( Metadata metadata ) - { - if ( metadata != null ) - { - if ( this.metadata.isEmpty() ) - { + public InstallRequest addMetadata(Metadata metadata) { + if (metadata != null) { + if (this.metadata.isEmpty()) { this.metadata = new ArrayList<>(); } - this.metadata.add( metadata ); + this.metadata.add(metadata); } return this; } /** * Gets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @return The trace information about the higher level operation or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } /** * Sets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @param trace The trace information about the higher level operation, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public InstallRequest setTrace( RequestTrace trace ) - { + public InstallRequest setTrace(RequestTrace trace) { this.trace = trace; return this; } @Override - public String toString() - { + public String toString() { return getArtifacts() + ", " + getMetadata(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallResult.java b/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallResult.java index cfb9b6fcd..fcef5ce32 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallResult.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallResult.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.installation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,22 +16,23 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.installation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.metadata.Metadata; +import static java.util.Objects.requireNonNull; + /** * The result of installing artifacts and their accompanying metadata into the a remote repository. - * + * * @see org.eclipse.aether.RepositorySystem#install(org.eclipse.aether.RepositorySystemSession, InstallRequest) */ -public final class InstallResult -{ +public final class InstallResult { private final InstallRequest request; @@ -46,9 +45,8 @@ public final class InstallResult * * @param request The installation request, must not be {@code null}. */ - public InstallResult( InstallRequest request ) - { - this.request = requireNonNull( request, "install request cannot be null" ); + public InstallResult(InstallRequest request) { + this.request = requireNonNull(request, "install request cannot be null"); artifacts = Collections.emptyList(); metadata = Collections.emptyList(); } @@ -58,35 +56,29 @@ public InstallResult( InstallRequest request ) * * @return The install request, never {@code null}. */ - public InstallRequest getRequest() - { + public InstallRequest getRequest() { return request; } /** * Gets the artifacts that got installed. - * + * * @return The installed artifacts, never {@code null}. */ - public Collection getArtifacts() - { + public Collection getArtifacts() { return artifacts; } /** * Sets the artifacts that got installed. - * + * * @param artifacts The installed artifacts, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public InstallResult setArtifacts( Collection artifacts ) - { - if ( artifacts == null ) - { + public InstallResult setArtifacts(Collection artifacts) { + if (artifacts == null) { this.artifacts = Collections.emptyList(); - } - else - { + } else { this.artifacts = artifacts; } return this; @@ -94,19 +86,16 @@ public InstallResult setArtifacts( Collection artifacts ) /** * Adds the specified artifacts to the result. - * + * * @param artifact The installed artifact to add, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public InstallResult addArtifact( Artifact artifact ) - { - if ( artifact != null ) - { - if ( artifacts.isEmpty() ) - { + public InstallResult addArtifact(Artifact artifact) { + if (artifact != null) { + if (artifacts.isEmpty()) { artifacts = new ArrayList<>(); } - artifacts.add( artifact ); + artifacts.add(artifact); } return this; } @@ -114,28 +103,23 @@ public InstallResult addArtifact( Artifact artifact ) /** * Gets the metadata that got installed. Note that due to automatically generated metadata, there might have been * more metadata installed than originally specified in the install request. - * + * * @return The installed metadata, never {@code null}. */ - public Collection getMetadata() - { + public Collection getMetadata() { return metadata; } /** * Sets the metadata that got installed. - * + * * @param metadata The installed metadata, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public InstallResult setMetadata( Collection metadata ) - { - if ( metadata == null ) - { + public InstallResult setMetadata(Collection metadata) { + if (metadata == null) { this.metadata = Collections.emptyList(); - } - else - { + } else { this.metadata = metadata; } return this; @@ -143,27 +127,22 @@ public InstallResult setMetadata( Collection metadata ) /** * Adds the specified metadata to this result. - * + * * @param metadata The installed metadata to add, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public InstallResult addMetadata( Metadata metadata ) - { - if ( metadata != null ) - { - if ( this.metadata.isEmpty() ) - { + public InstallResult addMetadata(Metadata metadata) { + if (metadata != null) { + if (this.metadata.isEmpty()) { this.metadata = new ArrayList<>(); } - this.metadata.add( metadata ); + this.metadata.add(metadata); } return this; } @Override - public String toString() - { + public String toString() { return getArtifacts() + ", " + getMetadata(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallationException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallationException.java index 9a556bb62..9d003a932 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallationException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/installation/InstallationException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.installation; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,35 +16,31 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.installation; import org.eclipse.aether.RepositoryException; /** * Thrown in case of an installation error like an IO error. */ -public class InstallationException - extends RepositoryException -{ +public class InstallationException extends RepositoryException { /** * Creates a new exception with the specified detail message. - * + * * @param message The detail message, may be {@code null}. */ - public InstallationException( String message ) - { - super( message ); + public InstallationException(String message) { + super(message); } /** * Creates a new exception with the specified detail message and cause. - * + * * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public InstallationException( String message, Throwable cause ) - { - super( message, cause ); + public InstallationException(String message, Throwable cause) { + super(message, cause); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/installation/package-info.java b/maven-resolver-api/src/main/java/org/eclipse/aether/installation/package-info.java index d4ac07756..27c04eb70 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/installation/package-info.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/installation/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * The types supporting the publishing of artifacts to a local repository. */ package org.eclipse.aether.installation; - diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/AbstractMetadata.java b/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/AbstractMetadata.java index 3c0706a38..bbb07f9ea 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/AbstractMetadata.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/AbstractMetadata.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.metadata; import java.io.File; import java.util.Collections; @@ -28,132 +27,109 @@ /** * A skeleton class for metadata. */ -public abstract class AbstractMetadata - implements Metadata -{ +public abstract class AbstractMetadata implements Metadata { - private Metadata newInstance( Map properties, File file ) - { - return new DefaultMetadata( getGroupId(), getArtifactId(), getVersion(), getType(), getNature(), file, - properties ); + private Metadata newInstance(Map properties, File file) { + return new DefaultMetadata( + getGroupId(), getArtifactId(), getVersion(), getType(), getNature(), file, properties); } - public Metadata setFile( File file ) - { + public Metadata setFile(File file) { File current = getFile(); - if ( Objects.equals( current, file ) ) - { + if (Objects.equals(current, file)) { return this; } - return newInstance( getProperties(), file ); + return newInstance(getProperties(), file); } - public Metadata setProperties( Map properties ) - { + public Metadata setProperties(Map properties) { Map current = getProperties(); - if ( current.equals( properties ) || ( properties == null && current.isEmpty() ) ) - { + if (current.equals(properties) || (properties == null && current.isEmpty())) { return this; } - return newInstance( copyProperties( properties ), getFile() ); + return newInstance(copyProperties(properties), getFile()); } - public String getProperty( String key, String defaultValue ) - { - String value = getProperties().get( key ); - return ( value != null ) ? value : defaultValue; + public String getProperty(String key, String defaultValue) { + String value = getProperties().get(key); + return (value != null) ? value : defaultValue; } /** * Copies the specified metadata properties. This utility method should be used when creating new metadata instances * with caller-supplied properties. - * + * * @param properties The properties to copy, may be {@code null}. * @return The copied and read-only properties, never {@code null}. */ - protected static Map copyProperties( Map properties ) - { - if ( properties != null && !properties.isEmpty() ) - { - return Collections.unmodifiableMap( new HashMap<>( properties ) ); - } - else - { + protected static Map copyProperties(Map properties) { + if (properties != null && !properties.isEmpty()) { + return Collections.unmodifiableMap(new HashMap<>(properties)); + } else { return Collections.emptyMap(); } } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 128 ); - if ( getGroupId().length() > 0 ) - { - buffer.append( getGroupId() ); + public String toString() { + StringBuilder buffer = new StringBuilder(128); + if (getGroupId().length() > 0) { + buffer.append(getGroupId()); } - if ( getArtifactId().length() > 0 ) - { - buffer.append( ':' ).append( getArtifactId() ); + if (getArtifactId().length() > 0) { + buffer.append(':').append(getArtifactId()); } - if ( getVersion().length() > 0 ) - { - buffer.append( ':' ).append( getVersion() ); + if (getVersion().length() > 0) { + buffer.append(':').append(getVersion()); } - buffer.append( '/' ).append( getType() ); + buffer.append('/').append(getType()); return buffer.toString(); } /** * Compares this metadata with the specified object. - * + * * @param obj The object to compare this metadata against, may be {@code null}. * @return {@code true} if and only if the specified object is another {@link Metadata} with equal coordinates, * type, nature, properties and file, {@code false} otherwise. */ @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( !( obj instanceof Metadata ) ) - { + } else if (!(obj instanceof Metadata)) { return false; } Metadata that = (Metadata) obj; - return Objects.equals( getArtifactId(), that.getArtifactId() ) - && Objects.equals( getGroupId(), that.getGroupId() ) - && Objects.equals( getVersion(), that.getVersion() ) - && Objects.equals( getType(), that.getType() ) - && Objects.equals( getNature(), that.getNature() ) - && Objects.equals( getFile(), that.getFile() ) - && Objects.equals( getProperties(), that.getProperties() ); + return Objects.equals(getArtifactId(), that.getArtifactId()) + && Objects.equals(getGroupId(), that.getGroupId()) + && Objects.equals(getVersion(), that.getVersion()) + && Objects.equals(getType(), that.getType()) + && Objects.equals(getNature(), that.getNature()) + && Objects.equals(getFile(), that.getFile()) + && Objects.equals(getProperties(), that.getProperties()); } /** * Returns a hash code for this metadata. - * + * * @return A hash code for the metadata. */ @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + getGroupId().hashCode(); hash = hash * 31 + getArtifactId().hashCode(); hash = hash * 31 + getType().hashCode(); hash = hash * 31 + getNature().hashCode(); hash = hash * 31 + getVersion().hashCode(); - hash = hash * 31 + hash( getFile() ); + hash = hash * 31 + hash(getFile()); return hash; } - private static int hash( Object obj ) - { - return ( obj != null ) ? obj.hashCode() : 0; + private static int hash(Object obj) { + return (obj != null) ? obj.hashCode() : 0; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/DefaultMetadata.java b/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/DefaultMetadata.java index 16bcd6191..036ced33d 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/DefaultMetadata.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/DefaultMetadata.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,18 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.metadata; import java.io.File; import java.util.Map; + import static java.util.Objects.requireNonNull; /** * A basic metadata instance. Note: Instances of this class are immutable and the exposed mutators return new * objects rather than changing the current instance. */ -public final class DefaultMetadata - extends AbstractMetadata -{ +public final class DefaultMetadata extends AbstractMetadata { private final String groupId; @@ -47,57 +45,53 @@ public final class DefaultMetadata /** * Creates a new metadata for the repository root with the specific type and nature. - * + * * @param type The type of the metadata, e.g. "maven-metadata.xml", may be {@code null}. * @param nature The nature of the metadata, must not be {@code null}. */ - public DefaultMetadata( String type, Nature nature ) - { - this( "", "", "", type, nature, null, (File) null ); + public DefaultMetadata(String type, Nature nature) { + this("", "", "", type, nature, null, (File) null); } /** * Creates a new metadata for the groupId level with the specific type and nature. - * + * * @param groupId The group identifier to which this metadata applies, may be {@code null}. * @param type The type of the metadata, e.g. "maven-metadata.xml", may be {@code null}. * @param nature The nature of the metadata, must not be {@code null}. */ - public DefaultMetadata( String groupId, String type, Nature nature ) - { - this( groupId, "", "", type, nature, null, (File) null ); + public DefaultMetadata(String groupId, String type, Nature nature) { + this(groupId, "", "", type, nature, null, (File) null); } /** * Creates a new metadata for the groupId:artifactId level with the specific type and nature. - * + * * @param groupId The group identifier to which this metadata applies, may be {@code null}. * @param artifactId The artifact identifier to which this metadata applies, may be {@code null}. * @param type The type of the metadata, e.g. "maven-metadata.xml", may be {@code null}. * @param nature The nature of the metadata, must not be {@code null}. */ - public DefaultMetadata( String groupId, String artifactId, String type, Nature nature ) - { - this( groupId, artifactId, "", type, nature, null, (File) null ); + public DefaultMetadata(String groupId, String artifactId, String type, Nature nature) { + this(groupId, artifactId, "", type, nature, null, (File) null); } /** * Creates a new metadata for the groupId:artifactId:version level with the specific type and nature. - * + * * @param groupId The group identifier to which this metadata applies, may be {@code null}. * @param artifactId The artifact identifier to which this metadata applies, may be {@code null}. * @param version The version to which this metadata applies, may be {@code null}. * @param type The type of the metadata, e.g. "maven-metadata.xml", may be {@code null}. * @param nature The nature of the metadata, must not be {@code null}. */ - public DefaultMetadata( String groupId, String artifactId, String version, String type, Nature nature ) - { - this( groupId, artifactId, version, type, nature, null, (File) null ); + public DefaultMetadata(String groupId, String artifactId, String version, String type, Nature nature) { + this(groupId, artifactId, version, type, nature, null, (File) null); } /** * Creates a new metadata for the groupId:artifactId:version level with the specific type and nature. - * + * * @param groupId The group identifier to which this metadata applies, may be {@code null}. * @param artifactId The artifact identifier to which this metadata applies, may be {@code null}. * @param version The version to which this metadata applies, may be {@code null}. @@ -105,14 +99,13 @@ public DefaultMetadata( String groupId, String artifactId, String version, Strin * @param nature The nature of the metadata, must not be {@code null}. * @param file The resolved file of the metadata, may be {@code null}. */ - public DefaultMetadata( String groupId, String artifactId, String version, String type, Nature nature, File file ) - { - this( groupId, artifactId, version, type, nature, null, file ); + public DefaultMetadata(String groupId, String artifactId, String version, String type, Nature nature, File file) { + this(groupId, artifactId, version, type, nature, null, file); } /** * Creates a new metadata for the groupId:artifactId:version level with the specific type and nature. - * + * * @param groupId The group identifier to which this metadata applies, may be {@code null}. * @param artifactId The artifact identifier to which this metadata applies, may be {@code null}. * @param version The version to which this metadata applies, may be {@code null}. @@ -121,69 +114,70 @@ public DefaultMetadata( String groupId, String artifactId, String version, Strin * @param properties The properties of the metadata, may be {@code null} if none. * @param file The resolved file of the metadata, may be {@code null}. */ - public DefaultMetadata( String groupId, String artifactId, String version, String type, Nature nature, - Map properties, File file ) - { - this.groupId = emptify( groupId ); - this.artifactId = emptify( artifactId ); - this.version = emptify( version ); - this.type = emptify( type ); - this.nature = requireNonNull( nature, "metadata nature cannot be null" ); + public DefaultMetadata( + String groupId, + String artifactId, + String version, + String type, + Nature nature, + Map properties, + File file) { + this.groupId = emptify(groupId); + this.artifactId = emptify(artifactId); + this.version = emptify(version); + this.type = emptify(type); + this.nature = requireNonNull(nature, "metadata nature cannot be null"); this.file = file; - this.properties = copyProperties( properties ); + this.properties = copyProperties(properties); } - DefaultMetadata( String groupId, String artifactId, String version, String type, Nature nature, File file, - Map properties ) - { + DefaultMetadata( + String groupId, + String artifactId, + String version, + String type, + Nature nature, + File file, + Map properties) { // NOTE: This constructor assumes immutability of the provided properties, for internal use only - this.groupId = emptify( groupId ); - this.artifactId = emptify( artifactId ); - this.version = emptify( version ); - this.type = emptify( type ); + this.groupId = emptify(groupId); + this.artifactId = emptify(artifactId); + this.version = emptify(version); + this.type = emptify(type); this.nature = nature; this.file = file; this.properties = properties; } - private static String emptify( String str ) - { - return ( str == null ) ? "" : str; + private static String emptify(String str) { + return (str == null) ? "" : str; } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public String getVersion() - { + public String getVersion() { return version; } - public String getType() - { + public String getType() { return type; } - public Nature getNature() - { + public Nature getNature() { return nature; } - public File getFile() - { + public File getFile() { return file; } - public Map getProperties() - { + public Map getProperties() { return properties; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/MergeableMetadata.java b/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/MergeableMetadata.java index deaff701b..96ab2ee9c 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/MergeableMetadata.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/MergeableMetadata.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.metadata; import java.io.File; @@ -26,26 +25,22 @@ /** * A piece of metadata that needs to be merged with any current metadata before installation/deployment. */ -public interface MergeableMetadata - extends Metadata -{ +public interface MergeableMetadata extends Metadata { /** * Merges this metadata into the current metadata (if any). Note that this method will be invoked regardless whether * metadata currently exists or not. - * + * * @param current The path to the current metadata file, may not exist but must not be {@code null}. * @param result The path to the result file where the merged metadata should be stored, must not be {@code null}. * @throws RepositoryException If the metadata could not be merged. */ - void merge( File current, File result ) - throws RepositoryException; + void merge(File current, File result) throws RepositoryException; /** * Indicates whether this metadata has been merged. - * + * * @return {@code true} if the metadata has been merged, {@code false} otherwise. */ boolean isMerged(); - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/Metadata.java b/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/Metadata.java index 84e921231..e957919a1 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/Metadata.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/Metadata.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.metadata; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.metadata; import java.io.File; import java.util.Map; @@ -29,18 +28,16 @@ * returns a new metadata instance and leaves the original instance unchanged. Implementors are strongly advised to obey * this contract. Note: Implementors are strongly advised to inherit from {@link AbstractMetadata} instead of * directly implementing this interface. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface Metadata -{ +public interface Metadata { /** * The nature of the metadata. */ - enum Nature - { + enum Nature { /** * The metadata refers to release artifacts only. */ @@ -59,7 +56,7 @@ enum Nature /** * Gets the group identifier of this metadata. - * + * * @return The group identifier or an empty string if the metadata applies to the entire repository, never * {@code null}. */ @@ -67,7 +64,7 @@ enum Nature /** * Gets the artifact identifier of this metadata. - * + * * @return The artifact identifier or an empty string if the metadata applies to the groupId level only, never * {@code null}. */ @@ -75,7 +72,7 @@ enum Nature /** * Gets the version of this metadata. - * + * * @return The version or an empty string if the metadata applies to the groupId:artifactId level only, never * {@code null}. */ @@ -83,56 +80,55 @@ enum Nature /** * Gets the type of the metadata, e.g. "maven-metadata.xml". - * + * * @return The type of the metadata, never {@code null}. */ String getType(); /** * Gets the nature of this metadata. The nature indicates to what artifact versions the metadata refers. - * + * * @return The nature, never {@code null}. */ Nature getNature(); /** * Gets the file of this metadata. Note that only resolved metadata has a file associated with it. - * + * * @return The file or {@code null} if none. */ File getFile(); /** * Sets the file of the metadata. - * + * * @param file The file of the metadata, may be {@code null} * @return The new metadata, never {@code null}. */ - Metadata setFile( File file ); + Metadata setFile(File file); /** * Gets the specified property. - * + * * @param key The name of the property, must not be {@code null}. * @param defaultValue The default value to return in case the property is not set, may be {@code null}. * @return The requested property value or {@code null} if the property is not set and no default value was * provided. */ - String getProperty( String key, String defaultValue ); + String getProperty(String key, String defaultValue); /** * Gets the properties of this metadata. - * + * * @return The (read-only) properties, never {@code null}. */ Map getProperties(); /** * Sets the properties for the metadata. - * + * * @param properties The properties for the metadata, may be {@code null}. * @return The new metadata, never {@code null}. */ - Metadata setProperties( Map properties ); - + Metadata setProperties(Map properties); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/package-info.java b/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/package-info.java index e41f98e99..beff9b6a1 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/package-info.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/metadata/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * The definition of metadata, that is an auxiliary entity managed by the repository system to locate artifacts. */ package org.eclipse.aether.metadata; - diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/package-info.java b/maven-resolver-api/src/main/java/org/eclipse/aether/package-info.java index 8d11fa8ad..a0c8d7c40 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/package-info.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * The primary API of the {@link org.eclipse.aether.RepositorySystem} and its functionality. */ package org.eclipse.aether; - diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/ArtifactRepository.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/ArtifactRepository.java index c62bf8793..2a041fb3a 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/ArtifactRepository.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/ArtifactRepository.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,28 +16,27 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; /** * A repository hosting artifacts. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface ArtifactRepository -{ +public interface ArtifactRepository { /** * Gets the type of the repository, for example "default". - * + * * @return The (case-sensitive) type of the repository, never {@code null}. */ String getContentType(); /** * Gets the identifier of this repository. - * + * * @return The (case-sensitive) identifier, never {@code null}. */ String getId(); - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/Authentication.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/Authentication.java index d85c2a26e..e5da70581 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/Authentication.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/Authentication.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.util.Map; @@ -25,8 +24,7 @@ * The authentication to use for accessing a protected resource. This acts basically as an extensible callback mechanism * from which network operations can request authentication data like username and password when needed. */ -public interface Authentication -{ +public interface Authentication { /** * Fills the given authentication context with the data from this authentication callback. To do so, implementors @@ -35,21 +33,20 @@ public interface Authentication * The {@code key} parameter supplied to this method acts merely as a hint for interactive callbacks that want to * prompt the user for only that authentication data which is required. Implementations are free to ignore this * parameter and put all the data they have into the authentication context at once. - * + * * @param context The authentication context to populate, must not be {@code null}. * @param key The key denoting a specific piece of authentication data that is being requested for a network * operation, may be {@code null}. * @param data Any (read-only) extra data in form of key value pairs that might be useful when getting the * authentication data, may be {@code null}. */ - void fill( AuthenticationContext context, String key, Map data ); + void fill(AuthenticationContext context, String key, Map data); /** * Updates the given digest with data from this authentication callback. To do so, implementors have to call the * {@code update()} methods in {@link AuthenticationDigest}. - * + * * @param digest The digest to update, must not be {@code null}. */ - void digest( AuthenticationDigest digest ); - + void digest(AuthenticationDigest digest); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationContext.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationContext.java index 88e13bd9a..9d266a61b 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationContext.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,23 +16,25 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.io.Closeable; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositorySystemSession; +import static java.util.Objects.requireNonNull; + /** * A glorified map of key value pairs holding (cleartext) authentication data. Authentication contexts are used * internally when network operations need to access secured repositories or proxies. Each authentication context * manages the credentials required to access a single host. Unlike {@link Authentication} callbacks which exist for a * potentially long time like the duration of a repository system session, an authentication context has a supposedly * short lifetime and should be {@link #close() closed} as soon as the corresponding network operation has finished: - * + * *

      * AuthenticationContext context = AuthenticationContext.forRepository( session, repository );
      * try {
    @@ -47,7 +47,7 @@
      *     AuthenticationContext.close( context );
      * }
      * 
    - * + * * The same authentication data can often be presented using different data types, e.g. a password can be presented * using a character array or (less securely) using a string. For ease of use, an authentication context treats the * following groups of data types as equivalent and converts values automatically during retrieval: @@ -57,9 +57,7 @@ * * An authentication context is thread-safe. */ -public final class AuthenticationContext - implements Closeable -{ +public final class AuthenticationContext implements Closeable { /** * The key used to store the username. The corresponding authentication data should be of type {@link String}. @@ -143,44 +141,39 @@ public final class AuthenticationContext /** * Gets an authentication context for the specified repository. - * + * * @param session The repository system session during which the repository is accessed, must not be {@code null}. * @param repository The repository for which to create an authentication context, must not be {@code null}. * @return An authentication context for the repository or {@code null} if no authentication is configured for it. */ - public static AuthenticationContext forRepository( RepositorySystemSession session, RemoteRepository repository ) - { - return newInstance( session, repository, null, repository.getAuthentication() ); + public static AuthenticationContext forRepository(RepositorySystemSession session, RemoteRepository repository) { + return newInstance(session, repository, null, repository.getAuthentication()); } /** * Gets an authentication context for the proxy of the specified repository. - * + * * @param session The repository system session during which the repository is accessed, must not be {@code null}. * @param repository The repository for whose proxy to create an authentication context, must not be {@code null}. * @return An authentication context for the proxy or {@code null} if no proxy is set or no authentication is * configured for it. */ - public static AuthenticationContext forProxy( RepositorySystemSession session, RemoteRepository repository ) - { + public static AuthenticationContext forProxy(RepositorySystemSession session, RemoteRepository repository) { Proxy proxy = repository.getProxy(); - return newInstance( session, repository, proxy, ( proxy != null ) ? proxy.getAuthentication() : null ); + return newInstance(session, repository, proxy, (proxy != null) ? proxy.getAuthentication() : null); } - private static AuthenticationContext newInstance( RepositorySystemSession session, RemoteRepository repository, - Proxy proxy, Authentication auth ) - { - if ( auth == null ) - { + private static AuthenticationContext newInstance( + RepositorySystemSession session, RemoteRepository repository, Proxy proxy, Authentication auth) { + if (auth == null) { return null; } - return new AuthenticationContext( session, repository, proxy, auth ); + return new AuthenticationContext(session, repository, proxy, auth); } - private AuthenticationContext( RepositorySystemSession session, RemoteRepository repository, Proxy proxy, - Authentication auth ) - { - this.session = requireNonNull( session, "repository system session cannot be null" ); + private AuthenticationContext( + RepositorySystemSession session, RemoteRepository repository, Proxy proxy, Authentication auth) { + this.session = requireNonNull(session, "repository system session cannot be null"); this.repository = repository; this.proxy = proxy; this.auth = auth; @@ -189,62 +182,57 @@ private AuthenticationContext( RepositorySystemSession session, RemoteRepository /** * Gets the repository system session during which the authentication happens. - * + * * @return The repository system session, never {@code null}. */ - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } /** * Gets the repository requiring authentication. If {@link #getProxy()} is not {@code null}, the data gathered by * this authentication context does not apply to the repository's host but rather the proxy. - * + * * @return The repository to be contacted, never {@code null}. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Gets the proxy (if any) to be authenticated with. - * + * * @return The proxy or {@code null} if authenticating directly with the repository's host. */ - public Proxy getProxy() - { + public Proxy getProxy() { return proxy; } /** * Gets the authentication data for the specified key. - * + * * @param key The key whose authentication data should be retrieved, must not be {@code null}. * @return The requested authentication data or {@code null} if none. */ - public String get( String key ) - { - return get( key, null, String.class ); + public String get(String key) { + return get(key, null, String.class); } /** * Gets the authentication data for the specified key. - * + * * @param The data type of the authentication data. * @param key The key whose authentication data should be retrieved, must not be {@code null}. * @param type The expected type of the authentication data, must not be {@code null}. * @return The requested authentication data or {@code null} if none or if the data doesn't match the expected type. */ - public T get( String key, Class type ) - { - return get( key, null, type ); + public T get(String key, Class type) { + return get(key, null, type); } /** * Gets the authentication data for the specified key. - * + * * @param The data type of the authentication data. * @param key The key whose authentication data should be retrieved, must not be {@code null}. * @param data Any (read-only) extra data in form of key value pairs that might be useful when getting the @@ -252,77 +240,55 @@ public T get( String key, Class type ) * @param type The expected type of the authentication data, must not be {@code null}. * @return The requested authentication data or {@code null} if none or if the data doesn't match the expected type. */ - public T get( String key, Map data, Class type ) - { - requireNonNull( key, "authentication key cannot be null" ); - if ( key.length() == 0 ) - { - throw new IllegalArgumentException( "authentication key cannot be empty" ); + public T get(String key, Map data, Class type) { + requireNonNull(key, "authentication key cannot be null"); + if (key.length() == 0) { + throw new IllegalArgumentException("authentication key cannot be empty"); } Object value; - synchronized ( authData ) - { - value = authData.get( key ); - if ( value == null && !authData.containsKey( key ) && !fillingAuthData ) - { - if ( auth != null ) - { - try - { + synchronized (authData) { + value = authData.get(key); + if (value == null && !authData.containsKey(key) && !fillingAuthData) { + if (auth != null) { + try { fillingAuthData = true; - auth.fill( this, key, data ); - } - finally - { + auth.fill(this, key, data); + } finally { fillingAuthData = false; } - value = authData.get( key ); + value = authData.get(key); } - if ( value == null ) - { - authData.put( key, null ); + if (value == null) { + authData.put(key, null); } } } - return convert( value, type ); + return convert(value, type); } - private T convert( Object value, Class type ) - { - if ( !type.isInstance( value ) ) - { - if ( String.class.equals( type ) ) - { - if ( value instanceof File ) - { - value = ( (File) value ).getPath(); + private T convert(Object value, Class type) { + if (!type.isInstance(value)) { + if (String.class.equals(type)) { + if (value instanceof File) { + value = ((File) value).getPath(); + } else if (value instanceof char[]) { + value = new String((char[]) value); } - else if ( value instanceof char[] ) - { - value = new String( (char[]) value ); + } else if (File.class.equals(type)) { + if (value instanceof String) { + value = new File((String) value); } - } - else if ( File.class.equals( type ) ) - { - if ( value instanceof String ) - { - value = new File( (String) value ); - } - } - else if ( char[].class.equals( type ) ) - { - if ( value instanceof String ) - { - value = ( (String) value ).toCharArray(); + } else if (char[].class.equals(type)) { + if (value instanceof String) { + value = ((String) value).toCharArray(); } } } - if ( type.isInstance( value ) ) - { - return type.cast( value ); + if (type.isInstance(value)) { + return type.cast(value); } return null; @@ -336,20 +302,16 @@ else if ( char[].class.equals( type ) ) * @param key The key to associate the authentication data with, must not be {@code null}. * @param value The (cleartext) authentication data to store, may be {@code null}. */ - public void put( String key, Object value ) - { - requireNonNull( key, "authentication key cannot be null" ); - if ( key.length() == 0 ) - { - throw new IllegalArgumentException( "authentication key cannot be empty" ); + public void put(String key, Object value) { + requireNonNull(key, "authentication key cannot be null"); + if (key.length() == 0) { + throw new IllegalArgumentException("authentication key cannot be empty"); } - synchronized ( authData ) - { - Object oldValue = authData.put( key, value ); - if ( oldValue instanceof char[] ) - { - Arrays.fill( (char[]) oldValue, '\0' ); + synchronized (authData) { + Object oldValue = authData.put(key, value); + if (oldValue instanceof char[]) { + Arrays.fill((char[]) oldValue, '\0'); } } } @@ -358,15 +320,11 @@ public void put( String key, Object value ) * Closes this authentication context and erases sensitive authentication data from heap memory. Closing an already * closed context has no effect. */ - public void close() - { - synchronized ( authData ) - { - for ( Object value : authData.values() ) - { - if ( value instanceof char[] ) - { - Arrays.fill( (char[]) value, '\0' ); + public void close() { + synchronized (authData) { + for (Object value : authData.values()) { + if (value instanceof char[]) { + Arrays.fill((char[]) value, '\0'); } } authData.clear(); @@ -376,15 +334,12 @@ public void close() /** * Closes the specified authentication context. This is a convenience method doing a {@code null} check before * calling {@link #close()} on the given context. - * + * * @param context The authentication context to close, may be {@code null}. */ - public static void close( AuthenticationContext context ) - { - if ( context != null ) - { + public static void close(AuthenticationContext context) { + if (context != null) { context.close(); } } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationDigest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationDigest.java index 27b88c021..ec95fcbaf 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationDigest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationDigest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -29,8 +28,7 @@ * A helper to calculate a fingerprint/digest for the authentication data of a repository/proxy. Such a fingerprint can * be used to detect changes in the authentication data across JVM restarts without exposing sensitive information. */ -public final class AuthenticationDigest -{ +public final class AuthenticationDigest { private final MessageDigest digest; @@ -42,20 +40,18 @@ public final class AuthenticationDigest /** * Gets the fingerprint for the authentication of the specified repository. - * + * * @param session The repository system session during which the fingerprint is requested, must not be {@code null}. * @param repository The repository whose authentication is to be fingerprinted, must not be {@code null}. * @return The fingerprint of the repository authentication or an empty string if no authentication is configured, * never {@code null}. */ - public static String forRepository( RepositorySystemSession session, RemoteRepository repository ) - { + public static String forRepository(RepositorySystemSession session, RemoteRepository repository) { String digest = ""; Authentication auth = repository.getAuthentication(); - if ( auth != null ) - { - AuthenticationDigest authDigest = new AuthenticationDigest( session, repository, null ); - auth.digest( authDigest ); + if (auth != null) { + AuthenticationDigest authDigest = new AuthenticationDigest(session, repository, null); + auth.digest(authDigest); digest = authDigest.digest(); } return digest; @@ -63,101 +59,83 @@ public static String forRepository( RepositorySystemSession session, RemoteRepos /** * Gets the fingerprint for the authentication of the specified repository's proxy. - * + * * @param session The repository system session during which the fingerprint is requested, must not be {@code null}. * @param repository The repository whose proxy authentication is to be fingerprinted, must not be {@code null}. * @return The fingerprint of the proxy authentication or an empty string if no proxy is present or if no proxy * authentication is configured, never {@code null}. */ - public static String forProxy( RepositorySystemSession session, RemoteRepository repository ) - { + public static String forProxy(RepositorySystemSession session, RemoteRepository repository) { String digest = ""; Proxy proxy = repository.getProxy(); - if ( proxy != null ) - { + if (proxy != null) { Authentication auth = proxy.getAuthentication(); - if ( auth != null ) - { - AuthenticationDigest authDigest = new AuthenticationDigest( session, repository, proxy ); - auth.digest( authDigest ); + if (auth != null) { + AuthenticationDigest authDigest = new AuthenticationDigest(session, repository, proxy); + auth.digest(authDigest); digest = authDigest.digest(); } } return digest; } - private AuthenticationDigest( RepositorySystemSession session, RemoteRepository repository, Proxy proxy ) - { + private AuthenticationDigest(RepositorySystemSession session, RemoteRepository repository, Proxy proxy) { this.session = session; this.repository = repository; this.proxy = proxy; digest = newDigest(); } - private static MessageDigest newDigest() - { - try - { - return MessageDigest.getInstance( "SHA-1" ); - } - catch ( NoSuchAlgorithmException e ) - { - try - { - return MessageDigest.getInstance( "MD5" ); - } - catch ( NoSuchAlgorithmException ne ) - { - throw new IllegalStateException( ne ); + private static MessageDigest newDigest() { + try { + return MessageDigest.getInstance("SHA-1"); + } catch (NoSuchAlgorithmException e) { + try { + return MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException ne) { + throw new IllegalStateException(ne); } } } /** * Gets the repository system session during which the authentication fingerprint is calculated. - * + * * @return The repository system session, never {@code null}. */ - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } /** * Gets the repository requiring authentication. If {@link #getProxy()} is not {@code null}, the data gathered by * this authentication digest does not apply to the repository's host but rather the proxy. - * + * * @return The repository to be contacted, never {@code null}. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Gets the proxy (if any) to be authenticated with. - * + * * @return The proxy or {@code null} if authenticating directly with the repository's host. */ - public Proxy getProxy() - { + public Proxy getProxy() { return proxy; } /** * Updates the digest with the specified strings. - * + * * @param strings The strings to update the digest with, may be {@code null} or contain {@code null} elements. */ - public void update( String... strings ) - { - if ( strings != null ) - { - for ( String string : strings ) - { - if ( string != null ) - { - digest.update( string.getBytes( StandardCharsets.UTF_8 ) ); + public void update(String... strings) { + if (strings != null) { + for (String string : strings) { + if (string != null) { + digest.update(string.getBytes(StandardCharsets.UTF_8)); } } } @@ -165,50 +143,41 @@ public void update( String... strings ) /** * Updates the digest with the specified characters. - * + * * @param chars The characters to update the digest with, may be {@code null}. */ - @SuppressWarnings( "checkstyle:magicnumber" ) - public void update( char... chars ) - { - if ( chars != null ) - { - for ( char c : chars ) - { - digest.update( (byte) ( c >> 8 ) ); - digest.update( (byte) ( c & 0xFF ) ); + @SuppressWarnings("checkstyle:magicnumber") + public void update(char... chars) { + if (chars != null) { + for (char c : chars) { + digest.update((byte) (c >> 8)); + digest.update((byte) (c & 0xFF)); } } } /** * Updates the digest with the specified bytes. - * + * * @param bytes The bytes to update the digest with, may be {@code null}. */ - public void update( byte... bytes ) - { - if ( bytes != null ) - { - digest.update( bytes ); + public void update(byte... bytes) { + if (bytes != null) { + digest.update(bytes); } } - @SuppressWarnings( "checkstyle:magicnumber" ) - private String digest() - { + @SuppressWarnings("checkstyle:magicnumber") + private String digest() { byte[] bytes = digest.digest(); - StringBuilder buffer = new StringBuilder( bytes.length * 2 ); - for ( byte aByte : bytes ) - { + StringBuilder buffer = new StringBuilder(bytes.length * 2); + for (byte aByte : bytes) { int b = aByte & 0xFF; - if ( b < 0x10 ) - { - buffer.append( '0' ); + if (b < 0x10) { + buffer.append('0'); } - buffer.append( Integer.toHexString( b ) ); + buffer.append(Integer.toHexString(b)); } return buffer.toString(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationSelector.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationSelector.java index 0637d1c28..815fb35dc 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationSelector.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/AuthenticationSelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,21 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; /** * Selects authentication for a given remote repository. - * + * * @see org.eclipse.aether.RepositorySystemSession#getAuthenticationSelector() */ -public interface AuthenticationSelector -{ +public interface AuthenticationSelector { /** * Selects authentication for the specified remote repository. - * + * * @param repository The repository for which to select authentication, must not be {@code null}. * @return The selected authentication or {@code null} if none. */ - Authentication getAuthentication( RemoteRepository repository ); - + Authentication getAuthentication(RemoteRepository repository); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactRegistration.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactRegistration.java index 770cb1133..c7d4f162f 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactRegistration.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactRegistration.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.util.Collection; import java.util.Collections; @@ -27,11 +26,10 @@ /** * A request to register an artifact within the local repository. Certain local repository implementations can refuse to * serve physically present artifacts if those haven't been previously registered to them. - * + * * @see LocalRepositoryManager#add(org.eclipse.aether.RepositorySystemSession, LocalArtifactRegistration) */ -public final class LocalArtifactRegistration -{ +public final class LocalArtifactRegistration { private Artifact artifact; @@ -42,107 +40,94 @@ public final class LocalArtifactRegistration /** * Creates an uninitialized registration. */ - public LocalArtifactRegistration() - { + public LocalArtifactRegistration() { // enables default constructor } /** * Creates a registration request for the specified (locally installed) artifact. - * + * * @param artifact The artifact to register, may be {@code null}. */ - public LocalArtifactRegistration( Artifact artifact ) - { - setArtifact( artifact ); + public LocalArtifactRegistration(Artifact artifact) { + setArtifact(artifact); } /** * Creates a registration request for the specified artifact. - * + * * @param artifact The artifact to register, may be {@code null}. * @param repository The remote repository from which the artifact was resolved or {@code null} if the artifact was * locally installed. * @param contexts The resolution contexts, may be {@code null}. */ - public LocalArtifactRegistration( Artifact artifact, RemoteRepository repository, Collection contexts ) - { - setArtifact( artifact ); - setRepository( repository ); - setContexts( contexts ); + public LocalArtifactRegistration(Artifact artifact, RemoteRepository repository, Collection contexts) { + setArtifact(artifact); + setRepository(repository); + setContexts(contexts); } /** * Gets the artifact to register. - * + * * @return The artifact or {@code null} if not set. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Sets the artifact to register. - * + * * @param artifact The artifact, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public LocalArtifactRegistration setArtifact( Artifact artifact ) - { + public LocalArtifactRegistration setArtifact(Artifact artifact) { this.artifact = artifact; return this; } /** * Gets the remote repository from which the artifact was resolved. - * + * * @return The remote repository or {@code null} if the artifact was locally installed. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Sets the remote repository from which the artifact was resolved. - * + * * @param repository The remote repository or {@code null} if the artifact was locally installed. * @return This request for chaining, never {@code null}. */ - public LocalArtifactRegistration setRepository( RemoteRepository repository ) - { + public LocalArtifactRegistration setRepository(RemoteRepository repository) { this.repository = repository; return this; } /** * Gets the resolution contexts in which the artifact is available. - * + * * @return The resolution contexts in which the artifact is available, never {@code null}. */ - public Collection getContexts() - { + public Collection getContexts() { return contexts; } /** * Sets the resolution contexts in which the artifact is available. - * + * * @param contexts The resolution contexts, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public LocalArtifactRegistration setContexts( Collection contexts ) - { - if ( contexts != null ) - { + public LocalArtifactRegistration setContexts(Collection contexts) { + if (contexts != null) { this.contexts = contexts; - } - else - { + } else { this.contexts = Collections.emptyList(); } return this; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactRequest.java index 790dbfdac..8dc3790f7 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.util.Collections; import java.util.List; @@ -26,11 +25,10 @@ /** * A query to the local repository for the existence of an artifact. - * + * * @see LocalRepositoryManager#find(org.eclipse.aether.RepositorySystemSession, LocalArtifactRequest) */ -public final class LocalArtifactRequest -{ +public final class LocalArtifactRequest { private Artifact artifact; @@ -41,104 +39,91 @@ public final class LocalArtifactRequest /** * Creates an uninitialized query. */ - public LocalArtifactRequest() - { + public LocalArtifactRequest() { // enables default constructor } /** * Creates a query with the specified properties. - * + * * @param artifact The artifact to query for, may be {@code null}. * @param repositories The remote repositories that should be considered as potential sources for the artifact, may * be {@code null} or empty to only consider locally installed artifacts. * @param context The resolution context for the artifact, may be {@code null}. */ - public LocalArtifactRequest( Artifact artifact, List repositories, String context ) - { - setArtifact( artifact ); - setRepositories( repositories ); - setContext( context ); + public LocalArtifactRequest(Artifact artifact, List repositories, String context) { + setArtifact(artifact); + setRepositories(repositories); + setContext(context); } /** * Gets the artifact to query for. - * + * * @return The artifact or {@code null} if not set. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Sets the artifact to query for. - * + * * @param artifact The artifact, may be {@code null}. * @return This query for chaining, never {@code null}. */ - public LocalArtifactRequest setArtifact( Artifact artifact ) - { + public LocalArtifactRequest setArtifact(Artifact artifact) { this.artifact = artifact; return this; } /** * Gets the resolution context. - * + * * @return The resolution context, never {@code null}. */ - public String getContext() - { + public String getContext() { return context; } /** * Sets the resolution context. - * + * * @param context The resolution context, may be {@code null}. * @return This query for chaining, never {@code null}. */ - public LocalArtifactRequest setContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public LocalArtifactRequest setContext(String context) { + this.context = (context != null) ? context : ""; return this; } /** * Gets the remote repositories to consider as sources of the artifact. - * + * * @return The remote repositories, never {@code null}. */ - public List getRepositories() - { + public List getRepositories() { return repositories; } /** * Sets the remote repositories to consider as sources of the artifact. - * + * * @param repositories The remote repositories, may be {@code null} or empty to only consider locally installed * artifacts. * @return This query for chaining, never {@code null}. */ - public LocalArtifactRequest setRepositories( List repositories ) - { - if ( repositories != null ) - { + public LocalArtifactRequest setRepositories(List repositories) { + if (repositories != null) { this.repositories = repositories; - } - else - { + } else { this.repositories = Collections.emptyList(); } return this; } @Override - public String toString() - { + public String toString() { return getArtifact() + " @ " + getRepositories(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactResult.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactResult.java index a18c1b2e6..aa1636b3c 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactResult.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalArtifactResult.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.io.File; + import static java.util.Objects.requireNonNull; /** @@ -27,8 +27,7 @@ * * @see LocalRepositoryManager#find(org.eclipse.aether.RepositorySystemSession, LocalArtifactRequest) */ -public final class LocalArtifactResult -{ +public final class LocalArtifactResult { private final LocalArtifactRequest request; @@ -43,9 +42,8 @@ public final class LocalArtifactResult * * @param request The local artifact request, must not be {@code null}. */ - public LocalArtifactResult( LocalArtifactRequest request ) - { - this.request = requireNonNull( request, "local artifact request cannot be null" ); + public LocalArtifactResult(LocalArtifactRequest request) { + this.request = requireNonNull(request, "local artifact request cannot be null"); } /** @@ -53,8 +51,7 @@ public LocalArtifactResult( LocalArtifactRequest request ) * * @return The corresponding request, never {@code null}. */ - public LocalArtifactRequest getRequest() - { + public LocalArtifactRequest getRequest() { return request; } @@ -62,22 +59,20 @@ public LocalArtifactRequest getRequest() * Gets the file to the requested artifact. Note that this file must not be used unless {@link #isAvailable()} * returns {@code true}. An artifact file can be found but considered unavailable if the artifact was cached from a * remote repository that is not part of the list of remote repositories used for the query. - * + * * @return The file to the requested artifact or {@code null} if the artifact does not exist locally. */ - public File getFile() - { + public File getFile() { return file; } /** * Sets the file to requested artifact. - * + * * @param file The artifact file, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public LocalArtifactResult setFile( File file ) - { + public LocalArtifactResult setFile(File file) { this.file = file; return this; } @@ -87,56 +82,50 @@ public LocalArtifactResult setFile( File file ) * existent in the local repository to be available. Additionally, a local repository manager can consider the list * of supplied remote repositories to determine whether the artifact is logically available and mark an artifact * unavailable (despite its physical existence) if it is not known to be hosted by any of the provided repositories. - * + * * @return {@code true} if the artifact is available, {@code false} otherwise. * @see LocalArtifactRequest#getRepositories() */ - public boolean isAvailable() - { + public boolean isAvailable() { return available; } /** * Sets whether the artifact is available. - * + * * @param available {@code true} if the artifact is available, {@code false} otherwise. * @return This result for chaining, never {@code null}. */ - public LocalArtifactResult setAvailable( boolean available ) - { + public LocalArtifactResult setAvailable(boolean available) { this.available = available; return this; } /** * Gets the (first) remote repository from which the artifact was cached (if any). - * + * * @return The remote repository from which the artifact was originally retrieved or {@code null} if unknown or if * the artifact has been locally installed. * @see LocalArtifactRequest#getRepositories() */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Sets the (first) remote repository from which the artifact was cached. - * + * * @param repository The remote repository from which the artifact was originally retrieved, may be {@code null} if * unknown or if the artifact has been locally installed. * @return This result for chaining, never {@code null}. */ - public LocalArtifactResult setRepository( RemoteRepository repository ) - { + public LocalArtifactResult setRepository(RemoteRepository repository) { this.repository = repository; return this; } @Override - public String toString() - { - return getFile() + " (" + ( isAvailable() ? "available" : "unavailable" ) + ")"; + public String toString() { + return getFile() + " (" + (isAvailable() ? "available" : "unavailable") + ")"; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataRegistration.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataRegistration.java index c2fe647ba..816d902d7 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataRegistration.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataRegistration.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.util.Collection; import java.util.Collections; @@ -26,11 +25,10 @@ /** * A request to register metadata within the local repository. - * + * * @see LocalRepositoryManager#add(org.eclipse.aether.RepositorySystemSession, LocalMetadataRegistration) */ -public final class LocalMetadataRegistration -{ +public final class LocalMetadataRegistration { private Metadata metadata; @@ -41,107 +39,94 @@ public final class LocalMetadataRegistration /** * Creates an uninitialized registration. */ - public LocalMetadataRegistration() - { + public LocalMetadataRegistration() { // enables default constructor } /** * Creates a registration request for the specified metadata accompanying a locally installed artifact. - * + * * @param metadata The metadata to register, may be {@code null}. */ - public LocalMetadataRegistration( Metadata metadata ) - { - setMetadata( metadata ); + public LocalMetadataRegistration(Metadata metadata) { + setMetadata(metadata); } /** * Creates a registration request for the specified metadata. - * + * * @param metadata The metadata to register, may be {@code null}. * @param repository The remote repository from which the metadata was resolved or {@code null} if the metadata * accompanies a locally installed artifact. * @param contexts The resolution contexts, may be {@code null}. */ - public LocalMetadataRegistration( Metadata metadata, RemoteRepository repository, Collection contexts ) - { - setMetadata( metadata ); - setRepository( repository ); - setContexts( contexts ); + public LocalMetadataRegistration(Metadata metadata, RemoteRepository repository, Collection contexts) { + setMetadata(metadata); + setRepository(repository); + setContexts(contexts); } /** * Gets the metadata to register. - * + * * @return The metadata or {@code null} if not set. */ - public Metadata getMetadata() - { + public Metadata getMetadata() { return metadata; } /** * Sets the metadata to register. - * + * * @param metadata The metadata, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public LocalMetadataRegistration setMetadata( Metadata metadata ) - { + public LocalMetadataRegistration setMetadata(Metadata metadata) { this.metadata = metadata; return this; } /** * Gets the remote repository from which the metadata was resolved. - * + * * @return The remote repository or {@code null} if the metadata was locally installed. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Sets the remote repository from which the metadata was resolved. - * + * * @param repository The remote repository or {@code null} if the metadata accompanies a locally installed artifact. * @return This request for chaining, never {@code null}. */ - public LocalMetadataRegistration setRepository( RemoteRepository repository ) - { + public LocalMetadataRegistration setRepository(RemoteRepository repository) { this.repository = repository; return this; } /** * Gets the resolution contexts in which the metadata is available. - * + * * @return The resolution contexts in which the metadata is available, never {@code null}. */ - public Collection getContexts() - { + public Collection getContexts() { return contexts; } /** * Sets the resolution contexts in which the metadata is available. - * + * * @param contexts The resolution contexts, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public LocalMetadataRegistration setContexts( Collection contexts ) - { - if ( contexts != null ) - { + public LocalMetadataRegistration setContexts(Collection contexts) { + if (contexts != null) { this.contexts = contexts; - } - else - { + } else { this.contexts = Collections.emptyList(); } return this; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataRequest.java index deb34c690..65f2adea5 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,16 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import org.eclipse.aether.metadata.Metadata; /** * A query to the local repository for the existence of metadata. - * + * * @see LocalRepositoryManager#find(org.eclipse.aether.RepositorySystemSession, LocalMetadataRequest) */ -public final class LocalMetadataRequest -{ +public final class LocalMetadataRequest { private Metadata metadata; @@ -38,95 +36,85 @@ public final class LocalMetadataRequest /** * Creates an uninitialized query. */ - public LocalMetadataRequest() - { + public LocalMetadataRequest() { // enables default constructor } /** * Creates a query with the specified properties. - * + * * @param metadata The metadata to query for, may be {@code null}. * @param repository The source remote repository for the metadata, may be {@code null} for local metadata. * @param context The resolution context for the metadata, may be {@code null}. */ - public LocalMetadataRequest( Metadata metadata, RemoteRepository repository, String context ) - { - setMetadata( metadata ); - setRepository( repository ); - setContext( context ); + public LocalMetadataRequest(Metadata metadata, RemoteRepository repository, String context) { + setMetadata(metadata); + setRepository(repository); + setContext(context); } /** * Gets the metadata to query for. - * + * * @return The metadata or {@code null} if not set. */ - public Metadata getMetadata() - { + public Metadata getMetadata() { return metadata; } /** * Sets the metadata to query for. - * + * * @param metadata The metadata, may be {@code null}. * @return This query for chaining, never {@code null}. */ - public LocalMetadataRequest setMetadata( Metadata metadata ) - { + public LocalMetadataRequest setMetadata(Metadata metadata) { this.metadata = metadata; return this; } /** * Gets the resolution context. - * + * * @return The resolution context, never {@code null}. */ - public String getContext() - { + public String getContext() { return context; } /** * Sets the resolution context. - * + * * @param context The resolution context, may be {@code null}. * @return This query for chaining, never {@code null}. */ - public LocalMetadataRequest setContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public LocalMetadataRequest setContext(String context) { + this.context = (context != null) ? context : ""; return this; } /** * Gets the remote repository to use as source of the metadata. - * + * * @return The remote repositories, may be {@code null} for local metadata. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Sets the remote repository to use as sources of the metadata. - * + * * @param repository The remote repository, may be {@code null}. * @return This query for chaining, may be {@code null} for local metadata. */ - public LocalMetadataRequest setRepository( RemoteRepository repository ) - { + public LocalMetadataRequest setRepository(RemoteRepository repository) { this.repository = repository; return this; } @Override - public String toString() - { + public String toString() { return getMetadata() + " @ " + getRepository(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataResult.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataResult.java index 5fcfdf45b..a3ad6f473 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataResult.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalMetadataResult.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.io.File; + import static java.util.Objects.requireNonNull; /** @@ -27,8 +27,7 @@ * * @see LocalRepositoryManager#find(org.eclipse.aether.RepositorySystemSession, LocalMetadataRequest) */ -public final class LocalMetadataResult -{ +public final class LocalMetadataResult { private final LocalMetadataRequest request; @@ -41,9 +40,8 @@ public final class LocalMetadataResult * * @param request The local metadata request, must not be {@code null}. */ - public LocalMetadataResult( LocalMetadataRequest request ) - { - this.request = requireNonNull( request, "local metadata request cannot be null" ); + public LocalMetadataResult(LocalMetadataRequest request) { + this.request = requireNonNull(request, "local metadata request cannot be null"); } /** @@ -51,59 +49,52 @@ public LocalMetadataResult( LocalMetadataRequest request ) * * @return The corresponding request, never {@code null}. */ - public LocalMetadataRequest getRequest() - { + public LocalMetadataRequest getRequest() { return request; } /** * Gets the file to the requested metadata if the metadata is available in the local repository. - * + * * @return The file to the requested metadata or {@code null}. */ - public File getFile() - { + public File getFile() { return file; } /** * Sets the file to requested metadata. - * + * * @param file The metadata file, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public LocalMetadataResult setFile( File file ) - { + public LocalMetadataResult setFile(File file) { this.file = file; return this; } /** * This value indicates whether the metadata is stale and should be updated. - * + * * @return {@code true} if the metadata is stale and should be updated, {@code false} otherwise. */ - public boolean isStale() - { + public boolean isStale() { return stale; } /** * Sets whether the metadata is stale. - * + * * @param stale {@code true} if the metadata is stale and should be updated, {@code false} otherwise. * @return This result for chaining, never {@code null}. */ - public LocalMetadataResult setStale( boolean stale ) - { + public LocalMetadataResult setStale(boolean stale) { this.stale = stale; return this; } @Override - public String toString() - { + public String toString() { return request.toString() + "(" + getFile() + ")"; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalRepository.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalRepository.java index 0ef9ccd49..04ec5ad8e 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalRepository.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalRepository.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.io.File; import java.util.Objects; @@ -28,9 +27,7 @@ * handled by a {@link LocalRepositoryManager} which is usually determined from the {@link #getContentType() type} of * the repository. */ -public final class LocalRepository - implements ArtifactRepository -{ +public final class LocalRepository implements ArtifactRepository { private final File basedir; @@ -38,91 +35,78 @@ public final class LocalRepository /** * Creates a new local repository with the specified base directory and unknown type. - * + * * @param basedir The base directory of the repository, may be {@code null}. */ - public LocalRepository( String basedir ) - { - this( ( basedir != null ) ? new File( basedir ) : null, "" ); + public LocalRepository(String basedir) { + this((basedir != null) ? new File(basedir) : null, ""); } /** * Creates a new local repository with the specified base directory and unknown type. - * + * * @param basedir The base directory of the repository, may be {@code null}. */ - public LocalRepository( File basedir ) - { - this( basedir, "" ); + public LocalRepository(File basedir) { + this(basedir, ""); } /** * Creates a new local repository with the specified properties. - * + * * @param basedir The base directory of the repository, may be {@code null}. * @param type The type of the repository, may be {@code null}. */ - public LocalRepository( File basedir, String type ) - { + public LocalRepository(File basedir, String type) { this.basedir = basedir; - this.type = ( type != null ) ? type : ""; + this.type = (type != null) ? type : ""; } - public String getContentType() - { + public String getContentType() { return type; } - public String getId() - { + public String getId() { return "local"; } /** * Gets the base directory of the repository. - * + * * @return The base directory or {@code null} if none. */ - public File getBasedir() - { + public File getBasedir() { return basedir; } @Override - public String toString() - { + public String toString() { return getBasedir() + " (" + getContentType() + ")"; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } LocalRepository that = (LocalRepository) obj; - return Objects.equals( basedir, that.basedir ) && Objects.equals( type, that.type ); + return Objects.equals(basedir, that.basedir) && Objects.equals(type, that.type); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + hash( basedir ); - hash = hash * 31 + hash( type ); + hash = hash * 31 + hash(basedir); + hash = hash * 31 + hash(type); return hash; } - private static int hash( Object obj ) - { + private static int hash(Object obj) { return obj != null ? obj.hashCode() : 0; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalRepositoryManager.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalRepositoryManager.java index 649707ce9..14651cb0d 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalRepositoryManager.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/LocalRepositoryManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -25,16 +24,15 @@ /** * Manages access to a local repository. - * + * * @see RepositorySystemSession#getLocalRepositoryManager() * @see org.eclipse.aether.RepositorySystem#newLocalRepositoryManager(RepositorySystemSession, LocalRepository) */ -public interface LocalRepositoryManager -{ +public interface LocalRepositoryManager { /** * Gets the description of the local repository being managed. - * + * * @return The description of the local repository, never {@code null}. */ LocalRepository getRepository(); @@ -43,85 +41,84 @@ public interface LocalRepositoryManager * Gets the relative path for a locally installed artifact. Note that the artifact need not actually exist yet at * the returned location, the path merely indicates where the artifact would eventually be stored. The path uses the * forward slash as directory separator regardless of the underlying file system. - * + * * @param artifact The artifact for which to determine the path, must not be {@code null}. * @return The path, relative to the local repository's base directory. */ - String getPathForLocalArtifact( Artifact artifact ); + String getPathForLocalArtifact(Artifact artifact); /** * Gets the relative path for an artifact cached from a remote repository. Note that the artifact need not actually * exist yet at the returned location, the path merely indicates where the artifact would eventually be stored. The * path uses the forward slash as directory separator regardless of the underlying file system. - * + * * @param artifact The artifact for which to determine the path, must not be {@code null}. * @param repository The source repository of the artifact, must not be {@code null}. * @param context The resolution context in which the artifact is being requested, may be {@code null}. * @return The path, relative to the local repository's base directory. */ - String getPathForRemoteArtifact( Artifact artifact, RemoteRepository repository, String context ); + String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context); /** * Gets the relative path for locally installed metadata. Note that the metadata need not actually exist yet at the * returned location, the path merely indicates where the metadata would eventually be stored. The path uses the * forward slash as directory separator regardless of the underlying file system. - * + * * @param metadata The metadata for which to determine the path, must not be {@code null}. * @return The path, relative to the local repository's base directory. */ - String getPathForLocalMetadata( Metadata metadata ); + String getPathForLocalMetadata(Metadata metadata); /** * Gets the relative path for metadata cached from a remote repository. Note that the metadata need not actually * exist yet at the returned location, the path merely indicates where the metadata would eventually be stored. The * path uses the forward slash as directory separator regardless of the underlying file system. - * + * * @param metadata The metadata for which to determine the path, must not be {@code null}. * @param repository The source repository of the metadata, must not be {@code null}. * @param context The resolution context in which the metadata is being requested, may be {@code null}. * @return The path, relative to the local repository's base directory. */ - String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repository, String context ); + String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context); /** * Queries for the existence of an artifact in the local repository. The request could be satisfied by a locally * installed artifact or a previously downloaded artifact. - * + * * @param session The repository system session during which the request is made, must not be {@code null}. * @param request The artifact request, must not be {@code null}. * @return The result of the request, never {@code null}. */ - LocalArtifactResult find( RepositorySystemSession session, LocalArtifactRequest request ); + LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request); /** * Registers an installed or resolved artifact with the local repository. Note that artifact registration is merely * concerned about updating the local repository's internal state, not about actually installing the artifact or its * accompanying metadata. - * + * * @param session The repository system session during which the registration is made, must not be {@code null}. * @param request The registration request, must not be {@code null}. */ - void add( RepositorySystemSession session, LocalArtifactRegistration request ); + void add(RepositorySystemSession session, LocalArtifactRegistration request); /** * Queries for the existence of metadata in the local repository. The request could be satisfied by locally * installed or previously downloaded metadata. - * + * * @param session The repository system session during which the request is made, must not be {@code null}. * @param request The metadata request, must not be {@code null}. * @return The result of the request, never {@code null}. */ - LocalMetadataResult find( RepositorySystemSession session, LocalMetadataRequest request ); + LocalMetadataResult find(RepositorySystemSession session, LocalMetadataRequest request); /** * Registers installed or resolved metadata with the local repository. Note that metadata registration is merely * concerned about updating the local repository's internal state, not about actually installing the metadata. * However, this method MUST be called after the actual install to give the repository manager the opportunity to * inspect the added metadata. - * + * * @param session The repository system session during which the registration is made, must not be {@code null}. * @param request The registration request, must not be {@code null}. */ - void add( RepositorySystemSession session, LocalMetadataRegistration request ); - + void add(RepositorySystemSession session, LocalMetadataRegistration request); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/MirrorSelector.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/MirrorSelector.java index d50262c08..2ade6025a 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/MirrorSelector.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/MirrorSelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,22 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; /** * Selects a mirror for a given remote repository. - * + * * @see org.eclipse.aether.RepositorySystemSession#getMirrorSelector() */ -public interface MirrorSelector -{ +public interface MirrorSelector { /** * Selects a mirror for the specified repository. - * + * * @param repository The repository to select a mirror for, must not be {@code null}. * @return The selected mirror or {@code null} if none. * @see RemoteRepository#getMirroredRepositories() */ - RemoteRepository getMirror( RemoteRepository repository ); - + RemoteRepository getMirror(RemoteRepository repository); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/NoLocalRepositoryManagerException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/NoLocalRepositoryManagerException.java index c8048216a..66c348730 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/NoLocalRepositoryManagerException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/NoLocalRepositoryManagerException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,85 +16,74 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import org.eclipse.aether.RepositoryException; /** * Thrown in case of an unsupported local repository type. */ -public class NoLocalRepositoryManagerException - extends RepositoryException -{ +public class NoLocalRepositoryManagerException extends RepositoryException { private final transient LocalRepository repository; /** * Creates a new exception with the specified repository. - * + * * @param repository The local repository for which no support is available, may be {@code null}. */ - public NoLocalRepositoryManagerException( LocalRepository repository ) - { - this( repository, toMessage( repository ) ); + public NoLocalRepositoryManagerException(LocalRepository repository) { + this(repository, toMessage(repository)); } /** * Creates a new exception with the specified repository and detail message. - * + * * @param repository The local repository for which no support is available, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public NoLocalRepositoryManagerException( LocalRepository repository, String message ) - { - super( message ); + public NoLocalRepositoryManagerException(LocalRepository repository, String message) { + super(message); this.repository = repository; } /** * Creates a new exception with the specified repository and cause. - * + * * @param repository The local repository for which no support is available, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public NoLocalRepositoryManagerException( LocalRepository repository, Throwable cause ) - { - this( repository, toMessage( repository ), cause ); + public NoLocalRepositoryManagerException(LocalRepository repository, Throwable cause) { + this(repository, toMessage(repository), cause); } /** * Creates a new exception with the specified repository, detail message and cause. - * + * * @param repository The local repository for which no support is available, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public NoLocalRepositoryManagerException( LocalRepository repository, String message, Throwable cause ) - { - super( message, cause ); + public NoLocalRepositoryManagerException(LocalRepository repository, String message, Throwable cause) { + super(message, cause); this.repository = repository; } - private static String toMessage( LocalRepository repository ) - { - if ( repository != null ) - { - return "No manager available for local repository (" + repository.getBasedir().getAbsolutePath() - + ") of type " + repository.getContentType(); - } - else - { + private static String toMessage(LocalRepository repository) { + if (repository != null) { + return "No manager available for local repository (" + + repository.getBasedir().getAbsolutePath() + ") of type " + repository.getContentType(); + } else { return "No manager available for local repository"; } } /** * Gets the local repository whose content type is not supported. - * + * * @return The unsupported local repository or {@code null} if unknown. */ - public LocalRepository getRepository() - { + public LocalRepository getRepository() { return repository; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/Proxy.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/Proxy.java index 25807a856..a0190744f 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/Proxy.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/Proxy.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.util.Objects; /** * A proxy to use for connections to a repository. */ -public final class Proxy -{ +public final class Proxy { /** * Type denoting a proxy for HTTP transfers. @@ -47,111 +45,99 @@ public final class Proxy /** * Creates a new proxy with the specified properties and no authentication. - * + * * @param type The type of the proxy, e.g. "http", may be {@code null}. * @param host The host of the proxy, may be {@code null}. * @param port The port of the proxy. */ - public Proxy( String type, String host, int port ) - { - this( type, host, port, null ); + public Proxy(String type, String host, int port) { + this(type, host, port, null); } /** * Creates a new proxy with the specified properties. - * + * * @param type The type of the proxy, e.g. "http", may be {@code null}. * @param host The host of the proxy, may be {@code null}. * @param port The port of the proxy. * @param auth The authentication to use for the proxy connection, may be {@code null}. */ - public Proxy( String type, String host, int port, Authentication auth ) - { - this.type = ( type != null ) ? type : ""; - this.host = ( host != null ) ? host : ""; + public Proxy(String type, String host, int port, Authentication auth) { + this.type = (type != null) ? type : ""; + this.host = (host != null) ? host : ""; this.port = port; this.auth = auth; } /** * Gets the type of this proxy. - * + * * @return The type of this proxy, never {@code null}. */ - public String getType() - { + public String getType() { return type; } /** * Gets the host for this proxy. - * + * * @return The host for this proxy, never {@code null}. */ - public String getHost() - { + public String getHost() { return host; } /** * Gets the port number for this proxy. - * + * * @return The port number for this proxy. */ - public int getPort() - { + public int getPort() { return port; } /** * Gets the authentication to use for the proxy connection. - * + * * @return The authentication to use or {@code null} if none. */ - public Authentication getAuthentication() - { + public Authentication getAuthentication() { return auth; } @Override - public String toString() - { + public String toString() { return getHost() + ':' + getPort(); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } Proxy that = (Proxy) obj; - return Objects.equals( type, that.type ) - && Objects.equals( host, that.host ) && port == that.port - && Objects.equals( auth, that.auth ); + return Objects.equals(type, that.type) + && Objects.equals(host, that.host) + && port == that.port + && Objects.equals(auth, that.auth); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + hash( host ); - hash = hash * 31 + hash( type ); + hash = hash * 31 + hash(host); + hash = hash * 31 + hash(type); hash = hash * 31 + port; - hash = hash * 31 + hash( auth ); + hash = hash * 31 + hash(auth); return hash; } - private static int hash( Object obj ) - { + private static int hash(Object obj) { return obj != null ? obj.hashCode() : 0; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/ProxySelector.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/ProxySelector.java index 29b9e4eea..1e41aed58 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/ProxySelector.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/ProxySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,21 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; /** * Selects a proxy for a given remote repository. - * + * * @see org.eclipse.aether.RepositorySystemSession#getProxySelector() */ -public interface ProxySelector -{ +public interface ProxySelector { /** * Selects a proxy for the specified remote repository. - * + * * @param repository The repository for which to select a proxy, must not be {@code null}. * @return The selected proxy or {@code null} if none. */ - Proxy getProxy( RemoteRepository repository ); - + Proxy getProxy(RemoteRepository repository); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/RemoteRepository.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/RemoteRepository.java index 3092fc123..99cec7d2e 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/RemoteRepository.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/RemoteRepository.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,26 +16,25 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import static java.util.Objects.requireNonNull; - import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static java.util.Objects.requireNonNull; + /** * A repository on a remote server. */ -public final class RemoteRepository - implements ArtifactRepository -{ +public final class RemoteRepository implements ArtifactRepository { private static final Pattern URL_PATTERN = - Pattern.compile( "([^:/]+(:[^:/]{2,}+(?=://))?):(//([^@/]*@)?([^/:]+))?.*" ); + Pattern.compile("([^:/]+(:[^:/]{2,}+(?=://))?):(//([^@/]*@)?([^/:]+))?.*"); private final String id; @@ -63,30 +60,27 @@ public final class RemoteRepository private final boolean blocked; - RemoteRepository( Builder builder ) - { - if ( builder.prototype != null ) - { - id = ( builder.delta & Builder.ID ) != 0 ? builder.id : builder.prototype.id; - type = ( builder.delta & Builder.TYPE ) != 0 ? builder.type : builder.prototype.type; - url = ( builder.delta & Builder.URL ) != 0 ? builder.url : builder.prototype.url; + RemoteRepository(Builder builder) { + if (builder.prototype != null) { + id = (builder.delta & Builder.ID) != 0 ? builder.id : builder.prototype.id; + type = (builder.delta & Builder.TYPE) != 0 ? builder.type : builder.prototype.type; + url = (builder.delta & Builder.URL) != 0 ? builder.url : builder.prototype.url; releasePolicy = - ( builder.delta & Builder.RELEASES ) != 0 ? builder.releasePolicy : builder.prototype.releasePolicy; - snapshotPolicy = - ( builder.delta & Builder.SNAPSHOTS ) != 0 ? builder.snapshotPolicy : builder.prototype.snapshotPolicy; - proxy = ( builder.delta & Builder.PROXY ) != 0 ? builder.proxy : builder.prototype.proxy; + (builder.delta & Builder.RELEASES) != 0 ? builder.releasePolicy : builder.prototype.releasePolicy; + snapshotPolicy = (builder.delta & Builder.SNAPSHOTS) != 0 + ? builder.snapshotPolicy + : builder.prototype.snapshotPolicy; + proxy = (builder.delta & Builder.PROXY) != 0 ? builder.proxy : builder.prototype.proxy; authentication = - ( builder.delta & Builder.AUTH ) != 0 ? builder.authentication : builder.prototype.authentication; - repositoryManager = - ( builder.delta & Builder.REPOMAN ) != 0 ? builder.repositoryManager - : builder.prototype.repositoryManager; - blocked = ( builder.delta & Builder.BLOCKED ) != 0 ? builder.blocked : builder.prototype.blocked; - mirroredRepositories = - ( builder.delta & Builder.MIRRORED ) != 0 ? copy( builder.mirroredRepositories ) - : builder.prototype.mirroredRepositories; - } - else - { + (builder.delta & Builder.AUTH) != 0 ? builder.authentication : builder.prototype.authentication; + repositoryManager = (builder.delta & Builder.REPOMAN) != 0 + ? builder.repositoryManager + : builder.prototype.repositoryManager; + blocked = (builder.delta & Builder.BLOCKED) != 0 ? builder.blocked : builder.prototype.blocked; + mirroredRepositories = (builder.delta & Builder.MIRRORED) != 0 + ? copy(builder.mirroredRepositories) + : builder.prototype.mirroredRepositories; + } else { id = builder.id; type = builder.type; url = builder.url; @@ -96,224 +90,203 @@ public final class RemoteRepository authentication = builder.authentication; repositoryManager = builder.repositoryManager; blocked = builder.blocked; - mirroredRepositories = copy( builder.mirroredRepositories ); + mirroredRepositories = copy(builder.mirroredRepositories); } - Matcher m = URL_PATTERN.matcher( url ); - if ( m.matches() ) - { - protocol = m.group( 1 ); - String host = m.group( 5 ); - this.host = ( host != null ) ? host : ""; - } - else - { + Matcher m = URL_PATTERN.matcher(url); + if (m.matches()) { + protocol = m.group(1); + String host = m.group(5); + this.host = (host != null) ? host : ""; + } else { protocol = ""; host = ""; } } - private static List copy( List repos ) - { - if ( repos == null || repos.isEmpty() ) - { + private static List copy(List repos) { + if (repos == null || repos.isEmpty()) { return Collections.emptyList(); } - return Collections.unmodifiableList( Arrays.asList( repos.toArray( new RemoteRepository[0] ) ) ); + return Collections.unmodifiableList(Arrays.asList(repos.toArray(new RemoteRepository[0]))); } - public String getId() - { + public String getId() { return id; } - public String getContentType() - { + public String getContentType() { return type; } /** * Gets the (base) URL of this repository. - * + * * @return The (base) URL of this repository, never {@code null}. */ - public String getUrl() - { + public String getUrl() { return url; } /** * Gets the protocol part from the repository's URL, for example {@code file} or {@code http}. As suggested by RFC * 2396, section 3.1 "Scheme Component", the protocol name should be treated case-insensitively. - * + * * @return The protocol or an empty string if none, never {@code null}. */ - public String getProtocol() - { + public String getProtocol() { return protocol; } /** * Gets the host part from the repository's URL. - * + * * @return The host or an empty string if none, never {@code null}. */ - public String getHost() - { + public String getHost() { return host; } /** * Gets the policy to apply for snapshot/release artifacts. - * + * * @param snapshot {@code true} to retrieve the snapshot policy, {@code false} to retrieve the release policy. * @return The requested repository policy, never {@code null}. */ - public RepositoryPolicy getPolicy( boolean snapshot ) - { + public RepositoryPolicy getPolicy(boolean snapshot) { return snapshot ? snapshotPolicy : releasePolicy; } /** * Gets the proxy that has been selected for this repository. - * + * * @return The selected proxy or {@code null} if none. */ - public Proxy getProxy() - { + public Proxy getProxy() { return proxy; } /** * Gets the authentication that has been selected for this repository. - * + * * @return The selected authentication or {@code null} if none. */ - public Authentication getAuthentication() - { + public Authentication getAuthentication() { return authentication; } /** * Gets the repositories that this repository serves as a mirror for. - * + * * @return The (read-only) repositories being mirrored by this repository, never {@code null}. */ - public List getMirroredRepositories() - { + public List getMirroredRepositories() { return mirroredRepositories; } /** * Indicates whether this repository refers to a repository manager or not. - * + * * @return {@code true} if this repository is a repository manager, {@code false} otherwise. */ - public boolean isRepositoryManager() - { + public boolean isRepositoryManager() { return repositoryManager; } /** * Indicates whether this repository is blocked from performing any download requests. - * + * * @return {@code true} if this repository is blocked from performing any download requests, * {@code false} otherwise. */ - public boolean isBlocked() - { + public boolean isBlocked() { return blocked; } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( getId() ); - buffer.append( " (" ).append( getUrl() ); - buffer.append( ", " ).append( getContentType() ); - boolean r = getPolicy( false ).isEnabled(), s = getPolicy( true ).isEnabled(); - if ( r && s ) - { - buffer.append( ", releases+snapshots" ); - } - else if ( r ) - { - buffer.append( ", releases" ); - } - else if ( s ) - { - buffer.append( ", snapshots" ); - } - else - { - buffer.append( ", disabled" ); + public String toString() { + StringBuilder buffer = new StringBuilder(256); + buffer.append(getId()); + buffer.append(" (").append(getUrl()); + buffer.append(", ").append(getContentType()); + boolean r = getPolicy(false).isEnabled(), s = getPolicy(true).isEnabled(); + if (r && s) { + buffer.append(", releases+snapshots"); + } else if (r) { + buffer.append(", releases"); + } else if (s) { + buffer.append(", snapshots"); + } else { + buffer.append(", disabled"); } - if ( isRepositoryManager() ) - { - buffer.append( ", managed" ); + if (isRepositoryManager()) { + buffer.append(", managed"); } - if ( isBlocked() ) - { - buffer.append( ", blocked" ); + if (isBlocked()) { + buffer.append(", blocked"); } - buffer.append( ")" ); + buffer.append(")"); return buffer.toString(); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } RemoteRepository that = (RemoteRepository) obj; - return Objects.equals( url, that.url ) && Objects.equals( type, that.type ) - && Objects.equals( id, that.id ) && Objects.equals( releasePolicy, that.releasePolicy ) - && Objects.equals( snapshotPolicy, that.snapshotPolicy ) && Objects.equals( proxy, that.proxy ) - && Objects.equals( authentication, that.authentication ) - && Objects.equals( mirroredRepositories, that.mirroredRepositories ) + return Objects.equals(url, that.url) + && Objects.equals(type, that.type) + && Objects.equals(id, that.id) + && Objects.equals(releasePolicy, that.releasePolicy) + && Objects.equals(snapshotPolicy, that.snapshotPolicy) + && Objects.equals(proxy, that.proxy) + && Objects.equals(authentication, that.authentication) + && Objects.equals(mirroredRepositories, that.mirroredRepositories) && repositoryManager == that.repositoryManager; } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + hash( url ); - hash = hash * 31 + hash( type ); - hash = hash * 31 + hash( id ); - hash = hash * 31 + hash( releasePolicy ); - hash = hash * 31 + hash( snapshotPolicy ); - hash = hash * 31 + hash( proxy ); - hash = hash * 31 + hash( authentication ); - hash = hash * 31 + hash( mirroredRepositories ); - hash = hash * 31 + ( repositoryManager ? 1 : 0 ); + hash = hash * 31 + hash(url); + hash = hash * 31 + hash(type); + hash = hash * 31 + hash(id); + hash = hash * 31 + hash(releasePolicy); + hash = hash * 31 + hash(snapshotPolicy); + hash = hash * 31 + hash(proxy); + hash = hash * 31 + hash(authentication); + hash = hash * 31 + hash(mirroredRepositories); + hash = hash * 31 + (repositoryManager ? 1 : 0); return hash; } - private static int hash( Object obj ) - { + private static int hash(Object obj) { return obj != null ? obj.hashCode() : 0; } /** * A builder to create remote repositories. */ - public static final class Builder - { + public static final class Builder { private static final RepositoryPolicy DEFAULT_POLICY = new RepositoryPolicy(); - static final int ID = 0x0001, TYPE = 0x0002, URL = 0x0004, RELEASES = 0x0008, SNAPSHOTS = 0x0010, - PROXY = 0x0020, AUTH = 0x0040, MIRRORED = 0x0080, REPOMAN = 0x0100, BLOCKED = 0x0200; + static final int ID = 0x0001, + TYPE = 0x0002, + URL = 0x0004, + RELEASES = 0x0008, + SNAPSHOTS = 0x0010, + PROXY = 0x0020, + AUTH = 0x0040, + MIRRORED = 0x0080, + REPOMAN = 0x0100, + BLOCKED = 0x0200; int delta; @@ -341,16 +314,15 @@ public static final class Builder /** * Creates a new repository builder. - * + * * @param id The identifier of the repository, may be {@code null}. * @param type The type of the repository, may be {@code null}. * @param url The (base) URL of the repository, may be {@code null}. */ - public Builder( String id, String type, String url ) - { - this.id = ( id != null ) ? id : ""; - this.type = ( type != null ) ? type : ""; - this.url = ( url != null ) ? url : ""; + public Builder(String id, String type, String url) { + this.id = (id != null) ? id : ""; + this.type = (type != null) ? type : ""; + this.url = (url != null) ? url : ""; } /** @@ -360,9 +332,8 @@ public Builder( String id, String type, String url ) * * @param prototype The remote repository to use as prototype, must not be {@code null}. */ - public Builder( RemoteRepository prototype ) - { - this.prototype = requireNonNull( prototype, "remote repository prototype cannot be null" ); + public Builder(RemoteRepository prototype) { + this.prototype = requireNonNull(prototype, "remote repository prototype cannot be null"); } /** @@ -371,181 +342,153 @@ public Builder( RemoteRepository prototype ) * * @return The remote repository, never {@code null}. */ - public RemoteRepository build() - { - if ( prototype != null && delta == 0 ) - { + public RemoteRepository build() { + if (prototype != null && delta == 0) { return prototype; } - return new RemoteRepository( this ); + return new RemoteRepository(this); } - private void delta( int flag, T builder, T prototype ) - { - boolean equal = Objects.equals( builder, prototype ); - if ( equal ) - { + private void delta(int flag, T builder, T prototype) { + boolean equal = Objects.equals(builder, prototype); + if (equal) { delta &= ~flag; - } - else - { + } else { delta |= flag; } } /** * Sets the identifier of the repository. - * + * * @param id The identifier of the repository, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public Builder setId( String id ) - { - this.id = ( id != null ) ? id : ""; - if ( prototype != null ) - { - delta( ID, this.id, prototype.getId() ); + public Builder setId(String id) { + this.id = (id != null) ? id : ""; + if (prototype != null) { + delta(ID, this.id, prototype.getId()); } return this; } /** * Sets the type of the repository, e.g. "default". - * + * * @param type The type of the repository, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public Builder setContentType( String type ) - { - this.type = ( type != null ) ? type : ""; - if ( prototype != null ) - { - delta( TYPE, this.type, prototype.getContentType() ); + public Builder setContentType(String type) { + this.type = (type != null) ? type : ""; + if (prototype != null) { + delta(TYPE, this.type, prototype.getContentType()); } return this; } /** * Sets the (base) URL of the repository. - * + * * @param url The URL of the repository, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public Builder setUrl( String url ) - { - this.url = ( url != null ) ? url : ""; - if ( prototype != null ) - { - delta( URL, this.url, prototype.getUrl() ); + public Builder setUrl(String url) { + this.url = (url != null) ? url : ""; + if (prototype != null) { + delta(URL, this.url, prototype.getUrl()); } return this; } /** * Sets the policy to apply for snapshot and release artifacts. - * + * * @param policy The repository policy to set, may be {@code null} to use a default policy. * @return This builder for chaining, never {@code null}. */ - public Builder setPolicy( RepositoryPolicy policy ) - { - this.releasePolicy = ( policy != null ) ? policy : DEFAULT_POLICY; - this.snapshotPolicy = ( policy != null ) ? policy : DEFAULT_POLICY; - if ( prototype != null ) - { - delta( RELEASES, this.releasePolicy, prototype.getPolicy( false ) ); - delta( SNAPSHOTS, this.snapshotPolicy, prototype.getPolicy( true ) ); + public Builder setPolicy(RepositoryPolicy policy) { + this.releasePolicy = (policy != null) ? policy : DEFAULT_POLICY; + this.snapshotPolicy = (policy != null) ? policy : DEFAULT_POLICY; + if (prototype != null) { + delta(RELEASES, this.releasePolicy, prototype.getPolicy(false)); + delta(SNAPSHOTS, this.snapshotPolicy, prototype.getPolicy(true)); } return this; } /** * Sets the policy to apply for release artifacts. - * + * * @param releasePolicy The repository policy to set, may be {@code null} to use a default policy. * @return This builder for chaining, never {@code null}. */ - public Builder setReleasePolicy( RepositoryPolicy releasePolicy ) - { - this.releasePolicy = ( releasePolicy != null ) ? releasePolicy : DEFAULT_POLICY; - if ( prototype != null ) - { - delta( RELEASES, this.releasePolicy, prototype.getPolicy( false ) ); + public Builder setReleasePolicy(RepositoryPolicy releasePolicy) { + this.releasePolicy = (releasePolicy != null) ? releasePolicy : DEFAULT_POLICY; + if (prototype != null) { + delta(RELEASES, this.releasePolicy, prototype.getPolicy(false)); } return this; } /** * Sets the policy to apply for snapshot artifacts. - * + * * @param snapshotPolicy The repository policy to set, may be {@code null} to use a default policy. * @return This builder for chaining, never {@code null}. */ - public Builder setSnapshotPolicy( RepositoryPolicy snapshotPolicy ) - { - this.snapshotPolicy = ( snapshotPolicy != null ) ? snapshotPolicy : DEFAULT_POLICY; - if ( prototype != null ) - { - delta( SNAPSHOTS, this.snapshotPolicy, prototype.getPolicy( true ) ); + public Builder setSnapshotPolicy(RepositoryPolicy snapshotPolicy) { + this.snapshotPolicy = (snapshotPolicy != null) ? snapshotPolicy : DEFAULT_POLICY; + if (prototype != null) { + delta(SNAPSHOTS, this.snapshotPolicy, prototype.getPolicy(true)); } return this; } /** * Sets the proxy to use in order to access the repository. - * + * * @param proxy The proxy to use, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public Builder setProxy( Proxy proxy ) - { + public Builder setProxy(Proxy proxy) { this.proxy = proxy; - if ( prototype != null ) - { - delta( PROXY, this.proxy, prototype.getProxy() ); + if (prototype != null) { + delta(PROXY, this.proxy, prototype.getProxy()); } return this; } /** * Sets the authentication to use in order to access the repository. - * + * * @param authentication The authentication to use, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public Builder setAuthentication( Authentication authentication ) - { + public Builder setAuthentication(Authentication authentication) { this.authentication = authentication; - if ( prototype != null ) - { - delta( AUTH, this.authentication, prototype.getAuthentication() ); + if (prototype != null) { + delta(AUTH, this.authentication, prototype.getAuthentication()); } return this; } /** * Sets the repositories being mirrored by the repository. - * + * * @param mirroredRepositories The repositories being mirrored by the repository, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public Builder setMirroredRepositories( List mirroredRepositories ) - { - if ( this.mirroredRepositories == null ) - { + public Builder setMirroredRepositories(List mirroredRepositories) { + if (this.mirroredRepositories == null) { this.mirroredRepositories = new ArrayList<>(); - } - else - { + } else { this.mirroredRepositories.clear(); } - if ( mirroredRepositories != null ) - { - this.mirroredRepositories.addAll( mirroredRepositories ); + if (mirroredRepositories != null) { + this.mirroredRepositories.addAll(mirroredRepositories); } - if ( prototype != null ) - { - delta( MIRRORED, this.mirroredRepositories, prototype.getMirroredRepositories() ); + if (prototype != null) { + delta(MIRRORED, this.mirroredRepositories, prototype.getMirroredRepositories()); } return this; } @@ -554,25 +497,20 @@ public Builder setMirroredRepositories( List mirroredRepositor * Adds the specified repository to the list of repositories being mirrored by the repository. If this builder * was {@link Builder constructed from a prototype}, the given repository * will be added to the list of mirrored repositories from the prototype. - * + * * @param mirroredRepository The repository being mirrored by the repository, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public Builder addMirroredRepository( RemoteRepository mirroredRepository ) - { - if ( mirroredRepository != null ) - { - if ( this.mirroredRepositories == null ) - { + public Builder addMirroredRepository(RemoteRepository mirroredRepository) { + if (mirroredRepository != null) { + if (this.mirroredRepositories == null) { this.mirroredRepositories = new ArrayList<>(); - if ( prototype != null ) - { - mirroredRepositories.addAll( prototype.getMirroredRepositories() ); + if (prototype != null) { + mirroredRepositories.addAll(prototype.getMirroredRepositories()); } } - mirroredRepositories.add( mirroredRepository ); - if ( prototype != null ) - { + mirroredRepositories.add(mirroredRepository); + if (prototype != null) { delta |= MIRRORED; } } @@ -581,37 +519,31 @@ public Builder addMirroredRepository( RemoteRepository mirroredRepository ) /** * Marks the repository as a repository manager or not. - * + * * @param repositoryManager {@code true} if the repository points at a repository manager, {@code false} if the * repository is just serving static contents. * @return This builder for chaining, never {@code null}. */ - public Builder setRepositoryManager( boolean repositoryManager ) - { + public Builder setRepositoryManager(boolean repositoryManager) { this.repositoryManager = repositoryManager; - if ( prototype != null ) - { - delta( REPOMAN, this.repositoryManager, prototype.isRepositoryManager() ); + if (prototype != null) { + delta(REPOMAN, this.repositoryManager, prototype.isRepositoryManager()); } return this; } - /** * Marks the repository as blocked or not. - * + * * @param blocked {@code true} if the repository should not be allowed to perform any requests. * @return This builder for chaining, never {@code null}. */ - public Builder setBlocked( boolean blocked ) - { + public Builder setBlocked(boolean blocked) { this.blocked = blocked; - if ( prototype != null ) - { - delta( BLOCKED, this.blocked, prototype.isBlocked() ); + if (prototype != null) { + delta(BLOCKED, this.blocked, prototype.isBlocked()); } return this; } } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/RepositoryPolicy.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/RepositoryPolicy.java index 18fb850ce..14f44d44d 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/RepositoryPolicy.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/RepositoryPolicy.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; /** * A policy controlling access to a repository. */ -public final class RepositoryPolicy -{ +public final class RepositoryPolicy { /** * Never update locally cached data. @@ -69,93 +67,83 @@ public final class RepositoryPolicy /** * Creates a new policy with checksum warnings and daily update checks. */ - public RepositoryPolicy() - { - this( true, UPDATE_POLICY_DAILY, CHECKSUM_POLICY_WARN ); + public RepositoryPolicy() { + this(true, UPDATE_POLICY_DAILY, CHECKSUM_POLICY_WARN); } /** * Creates a new policy with the specified settings. - * + * * @param enabled A flag whether the associated repository should be accessed or not. * @param updatePolicy The update interval after which locally cached data from the repository is considered stale * and should be refetched, may be {@code null}. * @param checksumPolicy The way checksum verification should be handled, may be {@code null}. */ - public RepositoryPolicy( boolean enabled, String updatePolicy, String checksumPolicy ) - { + public RepositoryPolicy(boolean enabled, String updatePolicy, String checksumPolicy) { this.enabled = enabled; - this.updatePolicy = ( updatePolicy != null ) ? updatePolicy : ""; - this.checksumPolicy = ( checksumPolicy != null ) ? checksumPolicy : ""; + this.updatePolicy = (updatePolicy != null) ? updatePolicy : ""; + this.checksumPolicy = (checksumPolicy != null) ? checksumPolicy : ""; } /** * Indicates whether the associated repository should be contacted or not. - * + * * @return {@code true} if the repository should be contacted, {@code false} otherwise. */ - public boolean isEnabled() - { + public boolean isEnabled() { return enabled; } /** * Gets the update policy for locally cached data from the repository. - * + * * @return The update policy, never {@code null}. */ - public String getUpdatePolicy() - { + public String getUpdatePolicy() { return updatePolicy; } /** * Gets the policy for checksum validation. - * + * * @return The checksum policy, never {@code null}. */ - public String getChecksumPolicy() - { + public String getChecksumPolicy() { return checksumPolicy; } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( "enabled=" ).append( isEnabled() ); - buffer.append( ", checksums=" ).append( getChecksumPolicy() ); - buffer.append( ", updates=" ).append( getUpdatePolicy() ); + public String toString() { + StringBuilder buffer = new StringBuilder(256); + buffer.append("enabled=").append(isEnabled()); + buffer.append(", checksums=").append(getChecksumPolicy()); + buffer.append(", updates=").append(getUpdatePolicy()); return buffer.toString(); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } RepositoryPolicy that = (RepositoryPolicy) obj; - return enabled == that.enabled && updatePolicy.equals( that.updatePolicy ) - && checksumPolicy.equals( that.checksumPolicy ); + return enabled == that.enabled + && updatePolicy.equals(that.updatePolicy) + && checksumPolicy.equals(that.checksumPolicy); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + ( enabled ? 1 : 0 ); + hash = hash * 31 + (enabled ? 1 : 0); hash = hash * 31 + updatePolicy.hashCode(); hash = hash * 31 + checksumPolicy.hashCode(); return hash; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/WorkspaceReader.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/WorkspaceReader.java index d1140f3ff..92127bbe9 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/WorkspaceReader.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/WorkspaceReader.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.io.File; import java.util.List; @@ -26,33 +25,31 @@ /** * Manages a repository backed by the IDE workspace, a build session or a similar ad-hoc collection of artifacts. - * + * * @see org.eclipse.aether.RepositorySystemSession#getWorkspaceReader() */ -public interface WorkspaceReader -{ +public interface WorkspaceReader { /** * Gets a description of the workspace repository. - * + * * @return The repository description, never {@code null}. */ WorkspaceRepository getRepository(); /** * Locates the specified artifact. - * + * * @param artifact The artifact to locate, must not be {@code null}. * @return The path to the artifact or {@code null} if the artifact is not available. */ - File findArtifact( Artifact artifact ); + File findArtifact(Artifact artifact); /** * Determines all available versions of the specified artifact. - * + * * @param artifact The artifact whose versions should be listed, must not be {@code null}. * @return The available versions of the artifact, must not be {@code null}. */ - List findVersions( Artifact artifact ); - + List findVersions(Artifact artifact); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/WorkspaceRepository.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/WorkspaceRepository.java index 38dc5c52a..e128af209 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/WorkspaceRepository.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/WorkspaceRepository.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; import java.util.UUID; @@ -27,9 +26,7 @@ * resolution but not installation/deployment. Note that this class merely describes such a repository, actual access to * the contained artifacts is handled by a {@link WorkspaceReader}. */ -public final class WorkspaceRepository - implements ArtifactRepository -{ +public final class WorkspaceRepository implements ArtifactRepository { private final String type; @@ -38,85 +35,73 @@ public final class WorkspaceRepository /** * Creates a new workspace repository of type {@code "workspace"} and a random key. */ - public WorkspaceRepository() - { - this( "workspace" ); + public WorkspaceRepository() { + this("workspace"); } /** * Creates a new workspace repository with the specified type and a random key. - * + * * @param type The type of the repository, may be {@code null}. */ - public WorkspaceRepository( String type ) - { - this( type, null ); + public WorkspaceRepository(String type) { + this(type, null); } /** * Creates a new workspace repository with the specified type and key. The key is used to distinguish one workspace * from another and should be sensitive to the artifacts that are (potentially) available in the workspace. - * + * * @param type The type of the repository, may be {@code null}. * @param key The (comparison) key for the repository, may be {@code null} to generate a unique random key. */ - public WorkspaceRepository( String type, Object key ) - { - this.type = ( type != null ) ? type : ""; - this.key = ( key != null ) ? key : UUID.randomUUID().toString().replace( "-", "" ); + public WorkspaceRepository(String type, Object key) { + this.type = (type != null) ? type : ""; + this.key = (key != null) ? key : UUID.randomUUID().toString().replace("-", ""); } - public String getContentType() - { + public String getContentType() { return type; } - public String getId() - { + public String getId() { return "workspace"; } /** * Gets the key of this workspace repository. The key is used to distinguish one workspace from another and should * be sensitive to the artifacts that are (potentially) available in the workspace. - * + * * @return The (comparison) key for this workspace repository, never {@code null}. */ - public Object getKey() - { + public Object getKey() { return key; } @Override - public String toString() - { + public String toString() { return "(" + getContentType() + ")"; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } WorkspaceRepository that = (WorkspaceRepository) obj; - return getContentType().equals( that.getContentType() ) && getKey().equals( that.getKey() ); + return getContentType().equals(that.getContentType()) && getKey().equals(that.getKey()); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + getKey().hashCode(); hash = hash * 31 + getContentType().hashCode(); return hash; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/package-info.java b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/package-info.java index 538e7f17b..f280cee51 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/repository/package-info.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/repository/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * The definition of various kinds of repositories that host artifacts. */ package org.eclipse.aether.repository; - diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorException.java index d645a82c9..bda7ac590 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,74 +16,68 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import org.eclipse.aether.RepositoryException; /** * Thrown in case of an unreadable or unresolvable artifact descriptor. */ -public class ArtifactDescriptorException - extends RepositoryException -{ +public class ArtifactDescriptorException extends RepositoryException { private final transient ArtifactDescriptorResult result; /** * Creates a new exception with the specified result. - * + * * @param result The descriptor result at the point the exception occurred, may be {@code null}. */ - public ArtifactDescriptorException( ArtifactDescriptorResult result ) - { - super( "Failed to read artifact descriptor" - + ( result != null ? " for " + result.getRequest().getArtifact() : "" ), getCause( result ) ); + public ArtifactDescriptorException(ArtifactDescriptorResult result) { + super( + "Failed to read artifact descriptor" + + (result != null ? " for " + result.getRequest().getArtifact() : ""), + getCause(result)); this.result = result; } /** * Creates a new exception with the specified result and detail message. - * + * * @param result The descriptor result at the point the exception occurred, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public ArtifactDescriptorException( ArtifactDescriptorResult result, String message ) - { - super( message, getCause( result ) ); + public ArtifactDescriptorException(ArtifactDescriptorResult result, String message) { + super(message, getCause(result)); this.result = result; } /** * Creates a new exception with the specified result, detail message and cause. - * + * * @param result The descriptor result at the point the exception occurred, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public ArtifactDescriptorException( ArtifactDescriptorResult result, String message, Throwable cause ) - { - super( message, cause ); + public ArtifactDescriptorException(ArtifactDescriptorResult result, String message, Throwable cause) { + super(message, cause); this.result = result; } /** * Gets the descriptor result at the point the exception occurred. Despite being incomplete, callers might want to * use this result to fail gracefully and continue their operation with whatever interim data has been gathered. - * + * * @return The descriptor result or {@code null} if unknown. */ - public ArtifactDescriptorResult getResult() - { + public ArtifactDescriptorResult getResult() { return result; } - private static Throwable getCause( ArtifactDescriptorResult result ) - { + private static Throwable getCause(ArtifactDescriptorResult result) { Throwable cause = null; - if ( result != null && !result.getExceptions().isEmpty() ) - { - cause = result.getExceptions().get( 0 ); + if (result != null && !result.getExceptions().isEmpty()) { + cause = result.getExceptions().get(0); } return cause; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorPolicy.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorPolicy.java index c4de9b224..b4cbdc933 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorPolicy.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorPolicy.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,16 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import org.eclipse.aether.RepositorySystemSession; /** * Controls the handling of errors related to reading an artifact descriptor. - * + * * @see RepositorySystemSession#getArtifactDescriptorPolicy() */ -public interface ArtifactDescriptorPolicy -{ +public interface ArtifactDescriptorPolicy { /** * Bit mask indicating that errors while reading the artifact descriptor should not be tolerated. @@ -51,11 +49,10 @@ public interface ArtifactDescriptorPolicy /** * Gets the error policy for an artifact's descriptor. - * + * * @param session The repository session during which the policy is determined, must not be {@code null}. * @param request The policy request holding further details, must not be {@code null}. * @return The bit mask describing the desired error policy. */ - int getPolicy( RepositorySystemSession session, ArtifactDescriptorPolicyRequest request ); - + int getPolicy(RepositorySystemSession session, ArtifactDescriptorPolicyRequest request); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorPolicyRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorPolicyRequest.java index ffaac16c5..9a7cdcf4f 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorPolicyRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorPolicyRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,16 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import org.eclipse.aether.artifact.Artifact; /** * A query for the error policy for a given artifact's descriptor. - * + * * @see ArtifactDescriptorPolicy */ -public final class ArtifactDescriptorPolicyRequest -{ +public final class ArtifactDescriptorPolicyRequest { private Artifact artifact; @@ -36,71 +34,63 @@ public final class ArtifactDescriptorPolicyRequest /** * Creates an uninitialized request. */ - public ArtifactDescriptorPolicyRequest() - { + public ArtifactDescriptorPolicyRequest() { // enables default constructor } /** * Creates a request for the specified artifact. - * + * * @param artifact The artifact for whose descriptor to determine the error policy, may be {@code null}. * @param context The context in which this request is made, may be {@code null}. */ - public ArtifactDescriptorPolicyRequest( Artifact artifact, String context ) - { - setArtifact( artifact ); - setRequestContext( context ); + public ArtifactDescriptorPolicyRequest(Artifact artifact, String context) { + setArtifact(artifact); + setRequestContext(context); } /** * Gets the artifact for whose descriptor to determine the error policy. - * + * * @return The artifact for whose descriptor to determine the error policy or {@code null} if not set. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Sets the artifact for whose descriptor to determine the error policy. - * + * * @param artifact The artifact for whose descriptor to determine the error policy, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactDescriptorPolicyRequest setArtifact( Artifact artifact ) - { + public ArtifactDescriptorPolicyRequest setArtifact(Artifact artifact) { this.artifact = artifact; return this; } /** * Gets the context in which this request is made. - * + * * @return The context, never {@code null}. */ - public String getRequestContext() - { + public String getRequestContext() { return context; } /** * Sets the context in which this request is made. - * + * * @param context The context, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactDescriptorPolicyRequest setRequestContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public ArtifactDescriptorPolicyRequest setRequestContext(String context) { + this.context = (context != null) ? context : ""; return this; } @Override - public String toString() - { - return String.valueOf( getArtifact() ); + public String toString() { + return String.valueOf(getArtifact()); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorRequest.java index 193e27449..962e0b017 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import java.util.ArrayList; import java.util.Collections; @@ -30,11 +29,10 @@ /** * A request to read an artifact descriptor. - * + * * @see RepositorySystem#readArtifactDescriptor(org.eclipse.aether.RepositorySystemSession, ArtifactDescriptorRequest) */ -public final class ArtifactDescriptorRequest -{ +public final class ArtifactDescriptorRequest { private Artifact artifact; @@ -47,71 +45,62 @@ public final class ArtifactDescriptorRequest /** * Creates an uninitialized request. */ - public ArtifactDescriptorRequest() - { + public ArtifactDescriptorRequest() { // enables default constructor } /** * Creates a request with the specified properties. - * + * * @param artifact The artifact whose descriptor should be read, may be {@code null}. * @param repositories The repositories to resolve the descriptor from, may be {@code null}. * @param context The context in which this request is made, may be {@code null}. */ - public ArtifactDescriptorRequest( Artifact artifact, List repositories, String context ) - { - setArtifact( artifact ); - setRepositories( repositories ); - setRequestContext( context ); + public ArtifactDescriptorRequest(Artifact artifact, List repositories, String context) { + setArtifact(artifact); + setRepositories(repositories); + setRequestContext(context); } /** * Gets the artifact whose descriptor shall be read. - * + * * @return The artifact or {@code null} if not set. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Sets the artifact whose descriptor shall be read. Eventually, a valid request must have an artifact set. - * + * * @param artifact The artifact, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactDescriptorRequest setArtifact( Artifact artifact ) - { + public ArtifactDescriptorRequest setArtifact(Artifact artifact) { this.artifact = artifact; return this; } /** * Gets the repositories to resolve the descriptor from. - * + * * @return The repositories, never {@code null}. */ - public List getRepositories() - { + public List getRepositories() { return repositories; } /** * Sets the repositories to resolve the descriptor from. - * + * * @param repositories The repositories, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactDescriptorRequest setRepositories( List repositories ) - { - if ( repositories == null ) - { + public ArtifactDescriptorRequest setRepositories(List repositories) { + if (repositories == null) { this.repositories = Collections.emptyList(); - } - else - { + } else { this.repositories = repositories; } return this; @@ -119,71 +108,62 @@ public ArtifactDescriptorRequest setRepositories( List reposit /** * Adds the specified repository for the resolution of the artifact descriptor. - * + * * @param repository The repository to add, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactDescriptorRequest addRepository( RemoteRepository repository ) - { - if ( repository != null ) - { - if ( this.repositories.isEmpty() ) - { + public ArtifactDescriptorRequest addRepository(RemoteRepository repository) { + if (repository != null) { + if (this.repositories.isEmpty()) { this.repositories = new ArrayList<>(); } - this.repositories.add( repository ); + this.repositories.add(repository); } return this; } /** * Gets the context in which this request is made. - * + * * @return The context, never {@code null}. */ - public String getRequestContext() - { + public String getRequestContext() { return context; } /** * Sets the context in which this request is made. - * + * * @param context The context, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactDescriptorRequest setRequestContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public ArtifactDescriptorRequest setRequestContext(String context) { + this.context = (context != null) ? context : ""; return this; } /** * Gets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @return The trace information about the higher level operation or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } /** * Sets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @param trace The trace information about the higher level operation, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactDescriptorRequest setTrace( RequestTrace trace ) - { + public ArtifactDescriptorRequest setTrace(RequestTrace trace) { this.trace = trace; return this; } @Override - public String toString() - { + public String toString() { return getArtifact() + " < " + getRepositories(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorResult.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorResult.java index 4e97aab62..1464873d2 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorResult.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactDescriptorResult.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.artifact.Artifact; @@ -32,13 +30,14 @@ import org.eclipse.aether.repository.ArtifactRepository; import org.eclipse.aether.repository.RemoteRepository; +import static java.util.Objects.requireNonNull; + /** * The result from reading an artifact descriptor. - * + * * @see RepositorySystem#readArtifactDescriptor(org.eclipse.aether.RepositorySystemSession, ArtifactDescriptorRequest) */ -public final class ArtifactDescriptorResult -{ +public final class ArtifactDescriptorResult { private final ArtifactDescriptorRequest request; @@ -65,9 +64,8 @@ public final class ArtifactDescriptorResult * * @param request The descriptor request, must not be {@code null}. */ - public ArtifactDescriptorResult( ArtifactDescriptorRequest request ) - { - this.request = requireNonNull( request, "artifact descriptor request cannot be null" ); + public ArtifactDescriptorResult(ArtifactDescriptorRequest request) { + this.request = requireNonNull(request, "artifact descriptor request cannot be null"); artifact = request.getArtifact(); exceptions = Collections.emptyList(); relocations = Collections.emptyList(); @@ -80,38 +78,32 @@ public ArtifactDescriptorResult( ArtifactDescriptorRequest request ) /** * Gets the descriptor request that was made. - * + * * @return The descriptor request, never {@code null}. */ - public ArtifactDescriptorRequest getRequest() - { + public ArtifactDescriptorRequest getRequest() { return request; } /** * Gets the exceptions that occurred while reading the artifact descriptor. - * + * * @return The exceptions that occurred, never {@code null}. */ - public List getExceptions() - { + public List getExceptions() { return exceptions; } /** * Sets the exceptions that occurred while reading the artifact descriptor. - * + * * @param exceptions The exceptions that occurred, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult setExceptions( List exceptions ) - { - if ( exceptions == null ) - { + public ArtifactDescriptorResult setExceptions(List exceptions) { + if (exceptions == null) { this.exceptions = Collections.emptyList(); - } - else - { + } else { this.exceptions = exceptions; } return this; @@ -119,19 +111,16 @@ public ArtifactDescriptorResult setExceptions( List exceptions ) /** * Records the specified exception while reading the artifact descriptor. - * + * * @param exception The exception to record, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult addException( Exception exception ) - { - if ( exception != null ) - { - if ( exceptions.isEmpty() ) - { + public ArtifactDescriptorResult addException(Exception exception) { + if (exception != null) { + if (exceptions.isEmpty()) { exceptions = new ArrayList<>(); } - exceptions.add( exception ); + exceptions.add(exception); } return this; } @@ -139,28 +128,23 @@ public ArtifactDescriptorResult addException( Exception exception ) /** * Gets the relocations that were processed to read the artifact descriptor. The returned list denotes the hops that * lead to the final artifact coordinates as given by {@link #getArtifact()}. - * + * * @return The relocations that were processed, never {@code null}. */ - public List getRelocations() - { + public List getRelocations() { return relocations; } /** * Sets the relocations that were processed to read the artifact descriptor. - * + * * @param relocations The relocations that were processed, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult setRelocations( List relocations ) - { - if ( relocations == null ) - { + public ArtifactDescriptorResult setRelocations(List relocations) { + if (relocations == null) { this.relocations = Collections.emptyList(); - } - else - { + } else { this.relocations = relocations; } return this; @@ -168,19 +152,16 @@ public ArtifactDescriptorResult setRelocations( List relocations ) /** * Records the specified relocation hop while locating the artifact descriptor. - * + * * @param artifact The artifact that got relocated, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult addRelocation( Artifact artifact ) - { - if ( artifact != null ) - { - if ( relocations.isEmpty() ) - { + public ArtifactDescriptorResult addRelocation(Artifact artifact) { + if (artifact != null) { + if (relocations.isEmpty()) { relocations = new ArrayList<>(); } - relocations.add( artifact ); + relocations.add(artifact); } return this; } @@ -189,28 +170,23 @@ public ArtifactDescriptorResult addRelocation( Artifact artifact ) * Gets the known aliases for this artifact. An alias denotes a different artifact with (almost) the same contents * and can be used to mark a patched rebuild of some other artifact as such, thereby allowing conflict resolution to * consider the patched and the original artifact as a conflict. - * + * * @return The aliases of the artifact, never {@code null}. */ - public Collection getAliases() - { + public Collection getAliases() { return aliases; } /** * Sets the aliases of the artifact. - * + * * @param aliases The aliases of the artifact, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult setAliases( Collection aliases ) - { - if ( aliases == null ) - { + public ArtifactDescriptorResult setAliases(Collection aliases) { + if (aliases == null) { this.aliases = Collections.emptyList(); - } - else - { + } else { this.aliases = aliases; } return this; @@ -218,19 +194,16 @@ public ArtifactDescriptorResult setAliases( Collection aliases ) /** * Records the specified alias. - * + * * @param alias The alias for the artifact, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult addAlias( Artifact alias ) - { - if ( alias != null ) - { - if ( aliases.isEmpty() ) - { + public ArtifactDescriptorResult addAlias(Artifact alias) { + if (alias != null) { + if (aliases.isEmpty()) { aliases = new ArrayList<>(); } - aliases.add( alias ); + aliases.add(alias); } return this; } @@ -238,72 +211,63 @@ public ArtifactDescriptorResult addAlias( Artifact alias ) /** * Gets the artifact whose descriptor was read. This can be a different artifact than originally requested in case * relocations were encountered. - * + * * @return The artifact after following any relocations, never {@code null}. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Sets the artifact whose descriptor was read. - * + * * @param artifact The artifact whose descriptor was read, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult setArtifact( Artifact artifact ) - { + public ArtifactDescriptorResult setArtifact(Artifact artifact) { this.artifact = artifact; return this; } /** * Gets the repository from which the descriptor was eventually resolved. - * + * * @return The repository from which the descriptor was resolved or {@code null} if unknown. */ - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return repository; } /** * Sets the repository from which the descriptor was resolved. - * + * * @param repository The repository from which the descriptor was resolved, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult setRepository( ArtifactRepository repository ) - { + public ArtifactDescriptorResult setRepository(ArtifactRepository repository) { this.repository = repository; return this; } /** * Gets the list of direct dependencies of the artifact. - * + * * @return The list of direct dependencies, never {@code null} */ - public List getDependencies() - { + public List getDependencies() { return dependencies; } /** * Sets the list of direct dependencies of the artifact. - * + * * @param dependencies The list of direct dependencies, may be {@code null} * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult setDependencies( List dependencies ) - { - if ( dependencies == null ) - { + public ArtifactDescriptorResult setDependencies(List dependencies) { + if (dependencies == null) { this.dependencies = Collections.emptyList(); - } - else - { + } else { this.dependencies = dependencies; } return this; @@ -311,47 +275,39 @@ public ArtifactDescriptorResult setDependencies( List dependencies ) /** * Adds the specified direct dependency. - * + * * @param dependency The direct dependency to add, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult addDependency( Dependency dependency ) - { - if ( dependency != null ) - { - if ( dependencies.isEmpty() ) - { + public ArtifactDescriptorResult addDependency(Dependency dependency) { + if (dependency != null) { + if (dependencies.isEmpty()) { dependencies = new ArrayList<>(); } - dependencies.add( dependency ); + dependencies.add(dependency); } return this; } /** * Gets the dependency management information. - * + * * @return The dependency management information. */ - public List getManagedDependencies() - { + public List getManagedDependencies() { return managedDependencies; } /** * Sets the dependency management information. - * + * * @param dependencies The dependency management information, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult setManagedDependencies( List dependencies ) - { - if ( dependencies == null ) - { + public ArtifactDescriptorResult setManagedDependencies(List dependencies) { + if (dependencies == null) { this.managedDependencies = Collections.emptyList(); - } - else - { + } else { this.managedDependencies = dependencies; } return this; @@ -359,47 +315,39 @@ public ArtifactDescriptorResult setManagedDependencies( List depende /** * Adds the specified managed dependency. - * + * * @param dependency The managed dependency to add, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult addManagedDependency( Dependency dependency ) - { - if ( dependency != null ) - { - if ( managedDependencies.isEmpty() ) - { + public ArtifactDescriptorResult addManagedDependency(Dependency dependency) { + if (dependency != null) { + if (managedDependencies.isEmpty()) { managedDependencies = new ArrayList<>(); } - managedDependencies.add( dependency ); + managedDependencies.add(dependency); } return this; } /** * Gets the remote repositories listed in the artifact descriptor. - * + * * @return The remote repositories listed in the artifact descriptor, never {@code null}. */ - public List getRepositories() - { + public List getRepositories() { return repositories; } /** * Sets the remote repositories listed in the artifact descriptor. - * + * * @param repositories The remote repositories listed in the artifact descriptor, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult setRepositories( List repositories ) - { - if ( repositories == null ) - { + public ArtifactDescriptorResult setRepositories(List repositories) { + if (repositories == null) { this.repositories = Collections.emptyList(); - } - else - { + } else { this.repositories = repositories; } return this; @@ -407,19 +355,16 @@ public ArtifactDescriptorResult setRepositories( List reposito /** * Adds the specified remote repository. - * + * * @param repository The remote repository to add, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult addRepository( RemoteRepository repository ) - { - if ( repository != null ) - { - if ( repositories.isEmpty() ) - { + public ArtifactDescriptorResult addRepository(RemoteRepository repository) { + if (repository != null) { + if (repositories.isEmpty()) { repositories = new ArrayList<>(); } - repositories.add( repository ); + repositories.add(repository); } return this; } @@ -427,37 +372,30 @@ public ArtifactDescriptorResult addRepository( RemoteRepository repository ) /** * Gets any additional information about the artifact in form of key-value pairs. Note: Regardless of their * actual type, all property values must be treated as being read-only. - * + * * @return The additional information about the artifact, never {@code null}. */ - public Map getProperties() - { + public Map getProperties() { return properties; } /** * Sets any additional information about the artifact in form of key-value pairs. - * + * * @param properties The additional information about the artifact, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactDescriptorResult setProperties( Map properties ) - { - if ( properties == null ) - { + public ArtifactDescriptorResult setProperties(Map properties) { + if (properties == null) { this.properties = Collections.emptyMap(); - } - else - { + } else { this.properties = properties; } return this; } @Override - public String toString() - { + public String toString() { return getArtifact() + " -> " + getDependencies(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactRequest.java index fec1affb7..ba83940f7 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import java.util.ArrayList; import java.util.Collections; @@ -31,12 +30,11 @@ /** * A request to resolve an artifact. - * + * * @see RepositorySystem#resolveArtifacts(org.eclipse.aether.RepositorySystemSession, java.util.Collection) * @see Artifact#getFile() */ -public final class ArtifactRequest -{ +public final class ArtifactRequest { private Artifact artifact; @@ -51,109 +49,96 @@ public final class ArtifactRequest /** * Creates an uninitialized request. */ - public ArtifactRequest() - { + public ArtifactRequest() { // enables default constructor } /** * Creates a request with the specified properties. - * + * * @param artifact The artifact to resolve, may be {@code null}. * @param repositories The repositories to resolve the artifact from, may be {@code null}. * @param context The context in which this request is made, may be {@code null}. */ - public ArtifactRequest( Artifact artifact, List repositories, String context ) - { - setArtifact( artifact ); - setRepositories( repositories ); - setRequestContext( context ); + public ArtifactRequest(Artifact artifact, List repositories, String context) { + setArtifact(artifact); + setRepositories(repositories); + setRequestContext(context); } /** * Creates a request from the specified dependency node. - * + * * @param node The dependency node to resolve, may be {@code null}. */ - public ArtifactRequest( DependencyNode node ) - { - setDependencyNode( node ); - setRepositories( node.getRepositories() ); - setRequestContext( node.getRequestContext() ); + public ArtifactRequest(DependencyNode node) { + setDependencyNode(node); + setRepositories(node.getRepositories()); + setRequestContext(node.getRequestContext()); } /** * Gets the artifact to resolve. - * + * * @return The artifact to resolve or {@code null}. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Sets the artifact to resolve. - * + * * @param artifact The artifact to resolve, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactRequest setArtifact( Artifact artifact ) - { + public ArtifactRequest setArtifact(Artifact artifact) { this.artifact = artifact; return this; } /** * Gets the dependency node (if any) for which to resolve the artifact. - * + * * @return The dependency node to resolve or {@code null} if unknown. */ - public DependencyNode getDependencyNode() - { + public DependencyNode getDependencyNode() { return node; } /** * Sets the dependency node to resolve. - * + * * @param node The dependency node to resolve, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactRequest setDependencyNode( DependencyNode node ) - { + public ArtifactRequest setDependencyNode(DependencyNode node) { this.node = node; - if ( node != null ) - { - setArtifact( node.getDependency().getArtifact() ); + if (node != null) { + setArtifact(node.getDependency().getArtifact()); } return this; } /** * Gets the repositories to resolve the artifact from. - * + * * @return The repositories, never {@code null}. */ - public List getRepositories() - { + public List getRepositories() { return repositories; } /** * Sets the repositories to resolve the artifact from. - * + * * @param repositories The repositories, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactRequest setRepositories( List repositories ) - { - if ( repositories == null ) - { + public ArtifactRequest setRepositories(List repositories) { + if (repositories == null) { this.repositories = Collections.emptyList(); - } - else - { + } else { this.repositories = repositories; } return this; @@ -161,71 +146,62 @@ public ArtifactRequest setRepositories( List repositories ) /** * Adds the specified repository for the resolution. - * + * * @param repository The repository to add, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactRequest addRepository( RemoteRepository repository ) - { - if ( repository != null ) - { - if ( this.repositories.isEmpty() ) - { + public ArtifactRequest addRepository(RemoteRepository repository) { + if (repository != null) { + if (this.repositories.isEmpty()) { this.repositories = new ArrayList<>(); } - this.repositories.add( repository ); + this.repositories.add(repository); } return this; } /** * Gets the context in which this request is made. - * + * * @return The context, never {@code null}. */ - public String getRequestContext() - { + public String getRequestContext() { return context; } /** * Sets the context in which this request is made. - * + * * @param context The context, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactRequest setRequestContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public ArtifactRequest setRequestContext(String context) { + this.context = (context != null) ? context : ""; return this; } /** * Gets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @return The trace information about the higher level operation or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } /** * Sets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @param trace The trace information about the higher level operation, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ArtifactRequest setTrace( RequestTrace trace ) - { + public ArtifactRequest setTrace(RequestTrace trace) { this.trace = trace; return this; } @Override - public String toString() - { + public String toString() { return getArtifact() + " < " + getRepositories(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactResolutionException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactResolutionException.java index bfae4a0bb..2d829e18f 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactResolutionException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactResolutionException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import java.util.Collections; import java.util.List; @@ -29,145 +28,118 @@ /** * Thrown in case of a unresolvable artifacts. */ -public class ArtifactResolutionException - extends RepositoryException -{ +public class ArtifactResolutionException extends RepositoryException { private final transient List results; /** * Creates a new exception with the specified results. - * + * * @param results The resolution results at the point the exception occurred, may be {@code null}. */ - public ArtifactResolutionException( List results ) - { - super( getMessage( results ), getCause( results ) ); - this.results = ( results != null ) ? results : Collections.emptyList(); + public ArtifactResolutionException(List results) { + super(getMessage(results), getCause(results)); + this.results = (results != null) ? results : Collections.emptyList(); } /** * Creates a new exception with the specified results and detail message. - * + * * @param results The resolution results at the point the exception occurred, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public ArtifactResolutionException( List results, String message ) - { - super( message, getCause( results ) ); - this.results = ( results != null ) ? results : Collections.emptyList(); + public ArtifactResolutionException(List results, String message) { + super(message, getCause(results)); + this.results = (results != null) ? results : Collections.emptyList(); } /** * Creates a new exception with the specified results, detail message and cause. - * + * * @param results The resolution results at the point the exception occurred, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public ArtifactResolutionException( List results, String message, Throwable cause ) - { - super( message, cause ); - this.results = ( results != null ) ? results : Collections.emptyList(); + public ArtifactResolutionException(List results, String message, Throwable cause) { + super(message, cause); + this.results = (results != null) ? results : Collections.emptyList(); } /** * Gets the resolution results at the point the exception occurred. Despite being incomplete, callers might want to * use these results to fail gracefully and continue their operation with whatever interim data has been gathered. - * + * * @return The resolution results or {@code null} if unknown. */ - public List getResults() - { + public List getResults() { return results; } /** * Gets the first result from {@link #getResults()}. This is a convenience method for cases where callers know only * a single result/request is involved. - * + * * @return The (first) resolution result or {@code null} if none. */ - public ArtifactResult getResult() - { - return ( results != null && !results.isEmpty() ) ? results.get( 0 ) : null; + public ArtifactResult getResult() { + return (results != null && !results.isEmpty()) ? results.get(0) : null; } - private static String getMessage( List results ) - { - StringBuilder buffer = new StringBuilder( 256 ); + private static String getMessage(List results) { + StringBuilder buffer = new StringBuilder(256); - buffer.append( "The following artifacts could not be resolved: " ); + buffer.append("The following artifacts could not be resolved: "); int unresolved = 0; String sep = ""; - for ( ArtifactResult result : results ) - { - if ( !result.isResolved() ) - { + for (ArtifactResult result : results) { + if (!result.isResolved()) { unresolved++; - buffer.append( sep ); - buffer.append( result.getRequest().getArtifact() ); + buffer.append(sep); + buffer.append(result.getRequest().getArtifact()); sep = ", "; } } - Throwable cause = getCause( results ); - if ( cause != null ) - { - if ( unresolved == 1 ) - { - buffer.setLength( 0 ); - buffer.append( cause.getMessage() ); - } - else - { - buffer.append( ": " ).append( cause.getMessage() ); + Throwable cause = getCause(results); + if (cause != null) { + if (unresolved == 1) { + buffer.setLength(0); + buffer.append(cause.getMessage()); + } else { + buffer.append(": ").append(cause.getMessage()); } } return buffer.toString(); } - private static Throwable getCause( List results ) - { - for ( ArtifactResult result : results ) - { - if ( !result.isResolved() ) - { + private static Throwable getCause(List results) { + for (ArtifactResult result : results) { + if (!result.isResolved()) { Throwable notFound = null, offline = null; - for ( Throwable t : result.getExceptions() ) - { - if ( t instanceof ArtifactNotFoundException ) - { - if ( notFound == null ) - { + for (Throwable t : result.getExceptions()) { + if (t instanceof ArtifactNotFoundException) { + if (notFound == null) { notFound = t; } - if ( offline == null && t.getCause() instanceof RepositoryOfflineException ) - { + if (offline == null && t.getCause() instanceof RepositoryOfflineException) { offline = t; } - } - else - { + } else { return t; } - } - if ( offline != null ) - { + if (offline != null) { return offline; } - if ( notFound != null ) - { + if (notFound != null) { return notFound; } } } return null; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactResult.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactResult.java index 0c98dac1d..f69dfb7ec 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactResult.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ArtifactResult.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,25 +16,26 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.repository.ArtifactRepository; import org.eclipse.aether.transfer.ArtifactNotFoundException; +import static java.util.Objects.requireNonNull; + /** * The result of an artifact resolution request. - * + * * @see RepositorySystem#resolveArtifacts(org.eclipse.aether.RepositorySystemSession, java.util.Collection) * @see Artifact#getFile() */ -public final class ArtifactResult -{ +public final class ArtifactResult { private final ArtifactRequest request; @@ -51,9 +50,8 @@ public final class ArtifactResult * * @param request The resolution request, must not be {@code null}. */ - public ArtifactResult( ArtifactRequest request ) - { - this.request = requireNonNull( request, "artifact request cannot be null" ); + public ArtifactResult(ArtifactRequest request) { + this.request = requireNonNull(request, "artifact request cannot be null"); exceptions = Collections.emptyList(); } @@ -62,30 +60,27 @@ public ArtifactResult( ArtifactRequest request ) * * @return The resolution request, never {@code null}. */ - public ArtifactRequest getRequest() - { + public ArtifactRequest getRequest() { return request; } /** * Gets the resolved artifact (if any). Use {@link #getExceptions()} to query the errors that occurred while trying * to resolve the artifact. - * + * * @return The resolved artifact or {@code null} if the resolution failed. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Sets the resolved artifact. - * + * * @param artifact The resolved artifact, may be {@code null} if the resolution failed. * @return This result for chaining, never {@code null}. */ - public ArtifactResult setArtifact( Artifact artifact ) - { + public ArtifactResult setArtifact(Artifact artifact) { this.artifact = artifact; return this; } @@ -94,30 +89,26 @@ public ArtifactResult setArtifact( Artifact artifact ) * Gets the exceptions that occurred while resolving the artifact. Note that this list can be non-empty even if the * artifact was successfully resolved, e.g. when one of the contacted remote repositories didn't contain the * artifact but a later repository eventually contained it. - * + * * @return The exceptions that occurred, never {@code null}. * @see #isResolved() */ - public List getExceptions() - { + public List getExceptions() { return exceptions; } /** * Records the specified exception while resolving the artifact. - * + * * @param exception The exception to record, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactResult addException( Exception exception ) - { - if ( exception != null ) - { - if ( exceptions.isEmpty() ) - { + public ArtifactResult addException(Exception exception) { + if (exception != null) { + if (exceptions.isEmpty()) { exceptions = new ArrayList<>(); } - exceptions.add( exception ); + exceptions.add(exception); } return this; } @@ -125,22 +116,20 @@ public ArtifactResult addException( Exception exception ) /** * Gets the repository from which the artifact was eventually resolved. Note that successive resolutions of the same * artifact might yield different results if the employed local repository does not track the origin of an artifact. - * + * * @return The repository from which the artifact was resolved or {@code null} if unknown. */ - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return repository; } /** * Sets the repository from which the artifact was resolved. - * + * * @param repository The repository from which the artifact was resolved, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public ArtifactResult setRepository( ArtifactRepository repository ) - { + public ArtifactResult setRepository(ArtifactRepository repository) { this.repository = repository; return this; } @@ -149,26 +138,22 @@ public ArtifactResult setRepository( ArtifactRepository repository ) * Indicates whether the requested artifact was resolved. Note that the artifact might have been successfully * resolved despite {@link #getExceptions()} indicating transfer errors while trying to fetch the artifact from some * of the specified remote repositories. - * + * * @return {@code true} if the artifact was resolved, {@code false} otherwise. * @see Artifact#getFile() */ - public boolean isResolved() - { + public boolean isResolved() { return getArtifact() != null && getArtifact().getFile() != null; } /** * Indicates whether the requested artifact is not present in any of the specified repositories. - * + * * @return {@code true} if the artifact is not present in any repository, {@code false} otherwise. */ - public boolean isMissing() - { - for ( Exception e : getExceptions() ) - { - if ( !( e instanceof ArtifactNotFoundException ) ) - { + public boolean isMissing() { + for (Exception e : getExceptions()) { + if (!(e instanceof ArtifactNotFoundException)) { return false; } } @@ -176,9 +161,7 @@ public boolean isMissing() } @Override - public String toString() - { + public String toString() { return getArtifact() + " < " + getRepository(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyRequest.java index 426540eda..8310afc01 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RequestTrace; @@ -29,12 +28,11 @@ /** * A request to resolve transitive dependencies. This request can either be supplied with a {@link CollectRequest} to * calculate the transitive dependencies or with an already resolved dependency graph. - * + * * @see RepositorySystem#resolveDependencies(org.eclipse.aether.RepositorySystemSession, DependencyRequest) * @see Artifact#getFile() */ -public final class DependencyRequest -{ +public final class DependencyRequest { private DependencyNode root; @@ -48,43 +46,39 @@ public final class DependencyRequest * Creates an uninitialized request. Note that either {@link #setRoot(DependencyNode)} or * {@link #setCollectRequest(CollectRequest)} must eventually be called to create a valid request. */ - public DependencyRequest() - { + public DependencyRequest() { // enables default constructor } /** * Creates a request for the specified dependency graph and with the given resolution filter. - * + * * @param node The root node of the dependency graph whose artifacts should be resolved, may be {@code null}. * @param filter The resolution filter to use, may be {@code null}. */ - public DependencyRequest( DependencyNode node, DependencyFilter filter ) - { - setRoot( node ); - setFilter( filter ); + public DependencyRequest(DependencyNode node, DependencyFilter filter) { + setRoot(node); + setFilter(filter); } /** * Creates a request for the specified collect request and with the given resolution filter. - * + * * @param request The collect request used to calculate the dependency graph whose artifacts should be resolved, may * be {@code null}. * @param filter The resolution filter to use, may be {@code null}. */ - public DependencyRequest( CollectRequest request, DependencyFilter filter ) - { - setCollectRequest( request ); - setFilter( filter ); + public DependencyRequest(CollectRequest request, DependencyFilter filter) { + setCollectRequest(request); + setFilter(filter); } /** * Gets the root node of the dependency graph whose artifacts should be resolved. - * + * * @return The root node of the dependency graph or {@code null} if none. */ - public DependencyNode getRoot() - { + public DependencyNode getRoot() { return root; } @@ -93,23 +87,21 @@ public DependencyNode getRoot() * the nodes of the given dependency graph will be updated to refer to the resolved artifacts. Eventually, either * {@link #setRoot(DependencyNode)} or {@link #setCollectRequest(CollectRequest)} must be called to create a valid * request. - * + * * @param root The root node of the dependency graph, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public DependencyRequest setRoot( DependencyNode root ) - { + public DependencyRequest setRoot(DependencyNode root) { this.root = root; return this; } /** * Gets the collect request used to calculate the dependency graph whose artifacts should be resolved. - * + * * @return The collect request or {@code null} if none. */ - public CollectRequest getCollectRequest() - { + public CollectRequest getCollectRequest() { return collectRequest; } @@ -118,69 +110,61 @@ public CollectRequest getCollectRequest() * either {@link #setRoot(DependencyNode)} or {@link #setCollectRequest(CollectRequest)} must be called to create a * valid request. If this request is supplied with a dependency node via {@link #setRoot(DependencyNode)}, the * collect request is ignored. - * + * * @param collectRequest The collect request, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public DependencyRequest setCollectRequest( CollectRequest collectRequest ) - { + public DependencyRequest setCollectRequest(CollectRequest collectRequest) { this.collectRequest = collectRequest; return this; } /** * Gets the resolution filter used to select which artifacts of the dependency graph should be resolved. - * + * * @return The resolution filter or {@code null} to resolve all artifacts of the dependency graph. */ - public DependencyFilter getFilter() - { + public DependencyFilter getFilter() { return filter; } /** * Sets the resolution filter used to select which artifacts of the dependency graph should be resolved. For * example, use this filter to restrict resolution to dependencies of a certain scope. - * + * * @param filter The resolution filter, may be {@code null} to resolve all artifacts of the dependency graph. * @return This request for chaining, never {@code null}. */ - public DependencyRequest setFilter( DependencyFilter filter ) - { + public DependencyRequest setFilter(DependencyFilter filter) { this.filter = filter; return this; } /** * Gets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @return The trace information about the higher level operation or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } /** * Sets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @param trace The trace information about the higher level operation, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public DependencyRequest setTrace( RequestTrace trace ) - { + public DependencyRequest setTrace(RequestTrace trace) { this.trace = trace; return this; } @Override - public String toString() - { - if ( root != null ) - { - return String.valueOf( root ); + public String toString() { + if (root != null) { + return String.valueOf(root); } - return String.valueOf( collectRequest ); + return String.valueOf(collectRequest); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyResolutionException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyResolutionException.java index 658a11405..af721b317 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyResolutionException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyResolutionException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,52 +16,46 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import org.eclipse.aether.RepositoryException; /** * Thrown in case of a unresolvable dependencies. */ -public class DependencyResolutionException - extends RepositoryException -{ +public class DependencyResolutionException extends RepositoryException { private final transient DependencyResult result; /** * Creates a new exception with the specified result and cause. - * + * * @param result The dependency result at the point the exception occurred, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public DependencyResolutionException( DependencyResult result, Throwable cause ) - { - super( getMessage( cause ), cause ); + public DependencyResolutionException(DependencyResult result, Throwable cause) { + super(getMessage(cause), cause); this.result = result; } /** * Creates a new exception with the specified result, detail message and cause. - * + * * @param result The dependency result at the point the exception occurred, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public DependencyResolutionException( DependencyResult result, String message, Throwable cause ) - { - super( message, cause ); + public DependencyResolutionException(DependencyResult result, String message, Throwable cause) { + super(message, cause); this.result = result; } - private static String getMessage( Throwable cause ) - { + private static String getMessage(Throwable cause) { String msg = null; - if ( cause != null ) - { + if (cause != null) { msg = cause.getMessage(); } - if ( msg == null || msg.isEmpty() ) - { + if (msg == null || msg.isEmpty()) { msg = "Could not resolve transitive dependencies"; } return msg; @@ -72,12 +64,10 @@ private static String getMessage( Throwable cause ) /** * Gets the dependency result at the point the exception occurred. Despite being incomplete, callers might want to * use this result to fail gracefully and continue their operation with whatever interim data has been gathered. - * + * * @return The dependency result or {@code null} if unknown. */ - public DependencyResult getResult() - { + public DependencyResult getResult() { return result; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyResult.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyResult.java index 6aea55253..500c5b5e9 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyResult.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/DependencyResult.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,22 +16,23 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import java.util.Collections; import java.util.List; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.graph.DependencyCycle; import org.eclipse.aether.graph.DependencyNode; +import static java.util.Objects.requireNonNull; + /** * The result of a dependency resolution request. - * + * * @see RepositorySystem#resolveDependencies(org.eclipse.aether.RepositorySystemSession, DependencyRequest) */ -public final class DependencyResult -{ +public final class DependencyResult { private final DependencyRequest request; @@ -50,9 +49,8 @@ public final class DependencyResult * * @param request The resolution request, must not be {@code null}. */ - public DependencyResult( DependencyRequest request ) - { - this.request = requireNonNull( request, "dependency request cannot be null" ); + public DependencyResult(DependencyRequest request) { + this.request = requireNonNull(request, "dependency request cannot be null"); root = request.getRoot(); cycles = Collections.emptyList(); collectExceptions = Collections.emptyList(); @@ -61,33 +59,30 @@ public DependencyResult( DependencyRequest request ) /** * Gets the resolution request that was made. - * + * * @return The resolution request, never {@code null}. */ - public DependencyRequest getRequest() - { + public DependencyRequest getRequest() { return request; } /** * Gets the root node of the resolved dependency graph. Note that this dependency graph might be * incomplete/unfinished in case of {@link #getCollectExceptions()} indicating errors during its calculation. - * + * * @return The root node of the resolved dependency graph or {@code null} if none. */ - public DependencyNode getRoot() - { + public DependencyNode getRoot() { return root; } /** * Sets the root node of the resolved dependency graph. - * + * * @param root The root node of the resolved dependency graph, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public DependencyResult setRoot( DependencyNode root ) - { + public DependencyResult setRoot(DependencyNode root) { this.root = root; return this; } @@ -97,28 +92,23 @@ public DependencyResult setRoot( DependencyNode root ) * will only be reported here if the underlying request was created from a * {@link org.eclipse.aether.collection.CollectRequest CollectRequest}. If the underlying {@link DependencyRequest} * was created from an existing dependency graph, information about cycles will not be available in this result. - * + * * @return The dependency cycles in the (raw) graph, never {@code null}. */ - public List getCycles() - { + public List getCycles() { return cycles; } /** * Records the specified dependency cycles while building the dependency graph. - * + * * @param cycles The dependency cycles to record, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public DependencyResult setCycles( List cycles ) - { - if ( cycles == null ) - { + public DependencyResult setCycles(List cycles) { + if (cycles == null) { this.cycles = Collections.emptyList(); - } - else - { + } else { this.cycles = cycles; } return this; @@ -126,28 +116,23 @@ public DependencyResult setCycles( List cycles ) /** * Gets the exceptions that occurred while building the dependency graph. - * + * * @return The exceptions that occurred, never {@code null}. */ - public List getCollectExceptions() - { + public List getCollectExceptions() { return collectExceptions; } /** * Records the specified exceptions while building the dependency graph. - * + * * @param exceptions The exceptions to record, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public DependencyResult setCollectExceptions( List exceptions ) - { - if ( exceptions == null ) - { + public DependencyResult setCollectExceptions(List exceptions) { + if (exceptions == null) { this.collectExceptions = Collections.emptyList(); - } - else - { + } else { this.collectExceptions = exceptions; } return this; @@ -155,37 +140,30 @@ public DependencyResult setCollectExceptions( List exceptions ) /** * Gets the resolution results for the dependency artifacts that matched {@link DependencyRequest#getFilter()}. - * + * * @return The resolution results for the dependency artifacts, never {@code null}. */ - public List getArtifactResults() - { + public List getArtifactResults() { return artifactResults; } /** * Sets the resolution results for the artifacts that matched {@link DependencyRequest#getFilter()}. - * + * * @param results The resolution results for the artifacts, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public DependencyResult setArtifactResults( List results ) - { - if ( results == null ) - { + public DependencyResult setArtifactResults(List results) { + if (results == null) { this.artifactResults = Collections.emptyList(); - } - else - { + } else { this.artifactResults = results; } return this; } @Override - public String toString() - { - return String.valueOf( artifactResults ); + public String toString() { + return String.valueOf(artifactResults); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/MetadataRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/MetadataRequest.java index 6b55d92b6..3279513fb 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/MetadataRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/MetadataRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RequestTrace; @@ -26,12 +25,11 @@ /** * A request to resolve metadata from either a remote repository or the local repository. - * + * * @see RepositorySystem#resolveMetadata(org.eclipse.aether.RepositorySystemSession, java.util.Collection) * @see Metadata#getFile() */ -public final class MetadataRequest -{ +public final class MetadataRequest { private Metadata metadata; @@ -48,124 +46,113 @@ public final class MetadataRequest /** * Creates an uninitialized request. */ - public MetadataRequest() - { + public MetadataRequest() { // enables default constructor } /** * Creates a request to resolve the specified metadata from the local repository. - * + * * @param metadata The metadata to resolve, may be {@code null}. */ - public MetadataRequest( Metadata metadata ) - { - setMetadata( metadata ); + public MetadataRequest(Metadata metadata) { + setMetadata(metadata); } /** * Creates a request with the specified properties. - * + * * @param metadata The metadata to resolve, may be {@code null}. * @param repository The repository to resolve the metadata from, may be {@code null} to resolve from the local * repository. * @param context The context in which this request is made, may be {@code null}. */ - public MetadataRequest( Metadata metadata, RemoteRepository repository, String context ) - { - setMetadata( metadata ); - setRepository( repository ); - setRequestContext( context ); + public MetadataRequest(Metadata metadata, RemoteRepository repository, String context) { + setMetadata(metadata); + setRepository(repository); + setRequestContext(context); } /** * Gets the metadata to resolve. - * + * * @return The metadata or {@code null} if not set. */ - public Metadata getMetadata() - { + public Metadata getMetadata() { return metadata; } /** * Sets the metadata to resolve. - * + * * @param metadata The metadata, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public MetadataRequest setMetadata( Metadata metadata ) - { + public MetadataRequest setMetadata(Metadata metadata) { this.metadata = metadata; return this; } /** * Gets the repository from which the metadata should be resolved. - * + * * @return The repository or {@code null} to resolve from the local repository. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Sets the repository from which the metadata should be resolved. - * + * * @param repository The repository, may be {@code null} to resolve from the local repository. * @return This request for chaining, never {@code null}. */ - public MetadataRequest setRepository( RemoteRepository repository ) - { + public MetadataRequest setRepository(RemoteRepository repository) { this.repository = repository; return this; } /** * Gets the context in which this request is made. - * + * * @return The context, never {@code null}. */ - public String getRequestContext() - { + public String getRequestContext() { return context; } /** * Sets the context in which this request is made. - * + * * @param context The context, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public MetadataRequest setRequestContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public MetadataRequest setRequestContext(String context) { + this.context = (context != null) ? context : ""; return this; } /** * Indicates whether the locally cached copy of the metadata should be removed if the corresponding file does not * exist (any more) in the remote repository. - * + * * @return {@code true} if locally cached metadata should be deleted if no corresponding remote file exists, * {@code false} to keep the local copy. */ - public boolean isDeleteLocalCopyIfMissing() - { + public boolean isDeleteLocalCopyIfMissing() { return deleteLocalCopyIfMissing; } /** * Controls whether the locally cached copy of the metadata should be removed if the corresponding file does not * exist (any more) in the remote repository. - * + * * @param deleteLocalCopyIfMissing {@code true} if locally cached metadata should be deleted if no corresponding * remote file exists, {@code false} to keep the local copy. * @return This request for chaining, never {@code null}. */ - public MetadataRequest setDeleteLocalCopyIfMissing( boolean deleteLocalCopyIfMissing ) - { + public MetadataRequest setDeleteLocalCopyIfMissing(boolean deleteLocalCopyIfMissing) { this.deleteLocalCopyIfMissing = deleteLocalCopyIfMissing; return this; } @@ -174,13 +161,12 @@ public MetadataRequest setDeleteLocalCopyIfMissing( boolean deleteLocalCopyIfMis * Indicates whether the metadata resolution should be suppressed if the corresponding metadata of the local * repository is up-to-date according to the update policy of the remote repository. In this case, the metadata * resolution will even be suppressed if no local copy of the remote metadata exists yet. - * + * * @return {@code true} to suppress resolution of remote metadata if the corresponding metadata of the local * repository is up-to-date, {@code false} to resolve the remote metadata normally according to the update * policy. */ - public boolean isFavorLocalRepository() - { + public boolean isFavorLocalRepository() { return favorLocalRepository; } @@ -188,44 +174,39 @@ public boolean isFavorLocalRepository() * Controls resolution of remote metadata when already corresponding metadata of the local repository exists. In * cases where the local repository's metadata is sufficient and going to be preferred, resolution of the remote * metadata can be suppressed to avoid unnecessary network access. - * + * * @param favorLocalRepository {@code true} to suppress resolution of remote metadata if the corresponding metadata * of the local repository is up-to-date, {@code false} to resolve the remote metadata normally according * to the update policy. * @return This request for chaining, never {@code null}. */ - public MetadataRequest setFavorLocalRepository( boolean favorLocalRepository ) - { + public MetadataRequest setFavorLocalRepository(boolean favorLocalRepository) { this.favorLocalRepository = favorLocalRepository; return this; } /** * Gets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @return The trace information about the higher level operation or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } /** * Sets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @param trace The trace information about the higher level operation, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public MetadataRequest setTrace( RequestTrace trace ) - { + public MetadataRequest setTrace(RequestTrace trace) { this.trace = trace; return this; } @Override - public String toString() - { + public String toString() { return getMetadata() + " < " + getRepository(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/MetadataResult.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/MetadataResult.java index 2bfd24df8..ddb648c39 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/MetadataResult.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/MetadataResult.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,20 +16,20 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Objects.requireNonNull; +package org.eclipse.aether.resolution; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.metadata.Metadata; import org.eclipse.aether.transfer.MetadataNotFoundException; +import static java.util.Objects.requireNonNull; + /** * The result of a metadata resolution request. - * + * * @see RepositorySystem#resolveMetadata(org.eclipse.aether.RepositorySystemSession, java.util.Collection) */ -public final class MetadataResult -{ +public final class MetadataResult { private final MetadataRequest request; @@ -46,9 +44,8 @@ public final class MetadataResult * * @param request The resolution request, must not be {@code null}. */ - public MetadataResult( MetadataRequest request ) - { - this.request = requireNonNull( request, "metadata request cannot be null" ); + public MetadataResult(MetadataRequest request) { + this.request = requireNonNull(request, "metadata request cannot be null"); } /** @@ -56,64 +53,58 @@ public MetadataResult( MetadataRequest request ) * * @return The resolution request, never {@code null}. */ - public MetadataRequest getRequest() - { + public MetadataRequest getRequest() { return request; } /** * Gets the resolved metadata (if any). - * + * * @return The resolved metadata or {@code null} if the resolution failed. */ - public Metadata getMetadata() - { + public Metadata getMetadata() { return metadata; } /** * Sets the resolved metadata. - * + * * @param metadata The resolved metadata, may be {@code null} if the resolution failed. * @return This result for chaining, never {@code null}. */ - public MetadataResult setMetadata( Metadata metadata ) - { + public MetadataResult setMetadata(Metadata metadata) { this.metadata = metadata; return this; } /** * Records the specified exception while resolving the metadata. - * + * * @param exception The exception to record, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public MetadataResult setException( Exception exception ) - { + public MetadataResult setException(Exception exception) { this.exception = exception; return this; } /** * Gets the exception that occurred while resolving the metadata. - * + * * @return The exception that occurred or {@code null} if none. */ - public Exception getException() - { + public Exception getException() { return exception; } /** * Sets the updated flag for the metadata. - * + * * @param updated {@code true} if the metadata was actually fetched from the remote repository during the * resolution, {@code false} if the metadata was resolved from a locally cached copy. * @return This result for chaining, never {@code null}. */ - public MetadataResult setUpdated( boolean updated ) - { + public MetadataResult setUpdated(boolean updated) { this.updated = updated; return this; } @@ -122,12 +113,11 @@ public MetadataResult setUpdated( boolean updated ) * Indicates whether the metadata was actually fetched from the remote repository or resolved from the local cache. * If metadata has been locally cached during a previous resolution request and this local copy is still up-to-date * according to the remote repository's update policy, no remote access is made. - * + * * @return {@code true} if the metadata was actually fetched from the remote repository during the resolution, * {@code false} if the metadata was resolved from a locally cached copy. */ - public boolean isUpdated() - { + public boolean isUpdated() { return updated; } @@ -135,29 +125,25 @@ public boolean isUpdated() * Indicates whether the requested metadata was resolved. Note that the metadata might have been successfully * resolved (from the local cache) despite {@link #getException()} indicating a transfer error while trying to * refetch the metadata from the remote repository. - * + * * @return {@code true} if the metadata was resolved, {@code false} otherwise. * @see Metadata#getFile() */ - public boolean isResolved() - { + public boolean isResolved() { return getMetadata() != null && getMetadata().getFile() != null; } /** * Indicates whether the requested metadata is not present in the remote repository. - * + * * @return {@code true} if the metadata is not present in the remote repository, {@code false} otherwise. */ - public boolean isMissing() - { + public boolean isMissing() { return getException() instanceof MetadataNotFoundException; } @Override - public String toString() - { - return getMetadata() + ( isUpdated() ? " (updated)" : " (cached)" ); + public String toString() { + return getMetadata() + (isUpdated() ? " (updated)" : " (cached)"); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ResolutionErrorPolicy.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ResolutionErrorPolicy.java index 5158fa030..872b81281 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ResolutionErrorPolicy.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ResolutionErrorPolicy.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -31,11 +30,10 @@ * Error caching considers the current network settings such that fixes to the configuration like authentication or * proxy automatically trigger revalidation with the remote side regardless of the time elapsed since the previous * resolution error. - * + * * @see RepositorySystemSession#getResolutionErrorPolicy() */ -public interface ResolutionErrorPolicy -{ +public interface ResolutionErrorPolicy { /** * Bit mask indicating that resolution errors should not be cached in the local repository. This forces the system @@ -63,20 +61,19 @@ public interface ResolutionErrorPolicy /** * Gets the error policy for an artifact. - * + * * @param session The repository session during which the policy is determined, must not be {@code null}. * @param request The policy request holding further details, must not be {@code null}. * @return The bit mask describing the desired error policy. */ - int getArtifactPolicy( RepositorySystemSession session, ResolutionErrorPolicyRequest request ); + int getArtifactPolicy(RepositorySystemSession session, ResolutionErrorPolicyRequest request); /** * Gets the error policy for some metadata. - * + * * @param session The repository session during which the policy is determined, must not be {@code null}. * @param request The policy request holding further details, must not be {@code null}. * @return The bit mask describing the desired error policy. */ - int getMetadataPolicy( RepositorySystemSession session, ResolutionErrorPolicyRequest request ); - + int getMetadataPolicy(RepositorySystemSession session, ResolutionErrorPolicyRequest request); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ResolutionErrorPolicyRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ResolutionErrorPolicyRequest.java index 912691471..1a244300f 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ResolutionErrorPolicyRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/ResolutionErrorPolicyRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,17 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import org.eclipse.aether.repository.RemoteRepository; /** * A query for the resolution error policy for a given artifact/metadata. - * + * * @param The type of the affected repository item (artifact or metadata). * @see ResolutionErrorPolicy */ -public final class ResolutionErrorPolicyRequest -{ +public final class ResolutionErrorPolicyRequest { private T item; @@ -37,71 +35,63 @@ public final class ResolutionErrorPolicyRequest /** * Creates an uninitialized request. */ - public ResolutionErrorPolicyRequest() - { + public ResolutionErrorPolicyRequest() { // enables default constructor } /** * Creates a request for the specified artifact/metadata and remote repository. - * + * * @param item The artifact/metadata for which to determine the error policy, may be {@code null}. * @param repository The repository from which the resolution is attempted, may be {@code null}. */ - public ResolutionErrorPolicyRequest( T item, RemoteRepository repository ) - { - setItem( item ); - setRepository( repository ); + public ResolutionErrorPolicyRequest(T item, RemoteRepository repository) { + setItem(item); + setRepository(repository); } /** * Gets the artifact/metadata for which to determine the error policy. - * + * * @return The artifact/metadata for which to determine the error policy or {@code null} if not set. */ - public T getItem() - { + public T getItem() { return item; } /** * Sets the artifact/metadata for which to determine the error policy. - * + * * @param item The artifact/metadata for which to determine the error policy, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ResolutionErrorPolicyRequest setItem( T item ) - { + public ResolutionErrorPolicyRequest setItem(T item) { this.item = item; return this; } /** * Gets the remote repository from which the resolution of the artifact/metadata is attempted. - * + * * @return The involved remote repository or {@code null} if not set. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Sets the remote repository from which the resolution of the artifact/metadata is attempted. - * + * * @param repository The repository from which the resolution is attempted, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public ResolutionErrorPolicyRequest setRepository( RemoteRepository repository ) - { + public ResolutionErrorPolicyRequest setRepository(RemoteRepository repository) { this.repository = repository; return this; } @Override - public String toString() - { + public String toString() { return getItem() + " < " + getRepository(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeRequest.java index 64803dca4..75c82cf49 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import java.util.ArrayList; import java.util.Collections; @@ -29,12 +28,11 @@ /** * A request to resolve a version range. - * + * * @see org.eclipse.aether.RepositorySystem#resolveVersionRange(org.eclipse.aether.RepositorySystemSession, * VersionRangeRequest) */ -public final class VersionRangeRequest -{ +public final class VersionRangeRequest { private Artifact artifact; @@ -47,71 +45,62 @@ public final class VersionRangeRequest /** * Creates an uninitialized request. */ - public VersionRangeRequest() - { + public VersionRangeRequest() { // enables default constructor } /** * Creates a request with the specified properties. - * + * * @param artifact The artifact whose version range should be resolved, may be {@code null}. * @param repositories The repositories to resolve the version from, may be {@code null}. * @param context The context in which this request is made, may be {@code null}. */ - public VersionRangeRequest( Artifact artifact, List repositories, String context ) - { - setArtifact( artifact ); - setRepositories( repositories ); - setRequestContext( context ); + public VersionRangeRequest(Artifact artifact, List repositories, String context) { + setArtifact(artifact); + setRepositories(repositories); + setRequestContext(context); } /** * Gets the artifact whose version range shall be resolved. - * + * * @return The artifact or {@code null} if not set. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Sets the artifact whose version range shall be resolved. - * + * * @param artifact The artifact, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public VersionRangeRequest setArtifact( Artifact artifact ) - { + public VersionRangeRequest setArtifact(Artifact artifact) { this.artifact = artifact; return this; } /** * Gets the repositories to resolve the version range from. - * + * * @return The repositories, never {@code null}. */ - public List getRepositories() - { + public List getRepositories() { return repositories; } /** * Sets the repositories to resolve the version range from. - * + * * @param repositories The repositories, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public VersionRangeRequest setRepositories( List repositories ) - { - if ( repositories == null ) - { + public VersionRangeRequest setRepositories(List repositories) { + if (repositories == null) { this.repositories = Collections.emptyList(); - } - else - { + } else { this.repositories = repositories; } return this; @@ -119,71 +108,62 @@ public VersionRangeRequest setRepositories( List repositories /** * Adds the specified repository for the resolution. - * + * * @param repository The repository to add, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public VersionRangeRequest addRepository( RemoteRepository repository ) - { - if ( repository != null ) - { - if ( this.repositories.isEmpty() ) - { + public VersionRangeRequest addRepository(RemoteRepository repository) { + if (repository != null) { + if (this.repositories.isEmpty()) { this.repositories = new ArrayList<>(); } - this.repositories.add( repository ); + this.repositories.add(repository); } return this; } /** * Gets the context in which this request is made. - * + * * @return The context, never {@code null}. */ - public String getRequestContext() - { + public String getRequestContext() { return context; } /** * Sets the context in which this request is made. - * + * * @param context The context, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public VersionRangeRequest setRequestContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public VersionRangeRequest setRequestContext(String context) { + this.context = (context != null) ? context : ""; return this; } /** * Gets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @return The trace information about the higher level operation or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } /** * Sets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @param trace The trace information about the higher level operation, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public VersionRangeRequest setTrace( RequestTrace trace ) - { + public VersionRangeRequest setTrace(RequestTrace trace) { this.trace = trace; return this; } @Override - public String toString() - { + public String toString() { return getArtifact() + " < " + getRepositories(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeResolutionException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeResolutionException.java index deb0e5293..821b66349 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeResolutionException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeResolutionException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,88 +16,78 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import org.eclipse.aether.RepositoryException; /** * Thrown in case of an unparseable or unresolvable version range. */ -public class VersionRangeResolutionException - extends RepositoryException -{ +public class VersionRangeResolutionException extends RepositoryException { private final transient VersionRangeResult result; /** * Creates a new exception with the specified result. - * + * * @param result The version range result at the point the exception occurred, may be {@code null}. */ - public VersionRangeResolutionException( VersionRangeResult result ) - { - super( getMessage( result ), getCause( result ) ); + public VersionRangeResolutionException(VersionRangeResult result) { + super(getMessage(result), getCause(result)); this.result = result; } - private static String getMessage( VersionRangeResult result ) - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( "Failed to resolve version range" ); - if ( result != null ) - { - buffer.append( " for " ).append( result.getRequest().getArtifact() ); - if ( !result.getExceptions().isEmpty() ) - { - buffer.append( ": " ).append( result.getExceptions().iterator().next().getMessage() ); + private static String getMessage(VersionRangeResult result) { + StringBuilder buffer = new StringBuilder(256); + buffer.append("Failed to resolve version range"); + if (result != null) { + buffer.append(" for ").append(result.getRequest().getArtifact()); + if (!result.getExceptions().isEmpty()) { + buffer.append(": ") + .append(result.getExceptions().iterator().next().getMessage()); } } return buffer.toString(); } - private static Throwable getCause( VersionRangeResult result ) - { + private static Throwable getCause(VersionRangeResult result) { Throwable cause = null; - if ( result != null && !result.getExceptions().isEmpty() ) - { - cause = result.getExceptions().get( 0 ); + if (result != null && !result.getExceptions().isEmpty()) { + cause = result.getExceptions().get(0); } return cause; } /** * Creates a new exception with the specified result and detail message. - * + * * @param result The version range result at the point the exception occurred, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public VersionRangeResolutionException( VersionRangeResult result, String message ) - { - super( message ); + public VersionRangeResolutionException(VersionRangeResult result, String message) { + super(message); this.result = result; } /** * Creates a new exception with the specified result, detail message and cause. - * + * * @param result The version range result at the point the exception occurred, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public VersionRangeResolutionException( VersionRangeResult result, String message, Throwable cause ) - { - super( message, cause ); + public VersionRangeResolutionException(VersionRangeResult result, String message, Throwable cause) { + super(message, cause); this.result = result; } /** * Gets the version range result at the point the exception occurred. Despite being incomplete, callers might want * to use this result to fail gracefully and continue their operation with whatever interim data has been gathered. - * + * * @return The version range result or {@code null} if unknown. */ - public VersionRangeResult getResult() - { + public VersionRangeResult getResult() { return result; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeResult.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeResult.java index 78a279acb..1600fd093 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeResult.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRangeResult.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,26 +16,27 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.repository.ArtifactRepository; import org.eclipse.aether.version.Version; import org.eclipse.aether.version.VersionConstraint; +import static java.util.Objects.requireNonNull; + /** * The result of a version range resolution request. - * + * * @see org.eclipse.aether.RepositorySystem#resolveVersionRange(org.eclipse.aether.RepositorySystemSession, * VersionRangeRequest) */ -public final class VersionRangeResult -{ +public final class VersionRangeResult { private final VersionRangeRequest request; @@ -54,9 +53,8 @@ public final class VersionRangeResult * * @param request The resolution request, must not be {@code null}. */ - public VersionRangeResult( VersionRangeRequest request ) - { - this.request = requireNonNull( request, "version range request cannot be null" ); + public VersionRangeResult(VersionRangeRequest request) { + this.request = requireNonNull(request, "version range request cannot be null"); exceptions = Collections.emptyList(); versions = Collections.emptyList(); repositories = Collections.emptyMap(); @@ -64,83 +62,71 @@ public VersionRangeResult( VersionRangeRequest request ) /** * Gets the resolution request that was made. - * + * * @return The resolution request, never {@code null}. */ - public VersionRangeRequest getRequest() - { + public VersionRangeRequest getRequest() { return request; } /** * Gets the exceptions that occurred while resolving the version range. - * + * * @return The exceptions that occurred, never {@code null}. */ - public List getExceptions() - { + public List getExceptions() { return exceptions; } /** * Records the specified exception while resolving the version range. - * + * * @param exception The exception to record, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public VersionRangeResult addException( Exception exception ) - { - if ( exception != null ) - { - if ( exceptions.isEmpty() ) - { + public VersionRangeResult addException(Exception exception) { + if (exception != null) { + if (exceptions.isEmpty()) { exceptions = new ArrayList<>(); } - exceptions.add( exception ); + exceptions.add(exception); } return this; } /** * Gets the versions (in ascending order) that matched the requested range. - * + * * @return The matching versions (if any), never {@code null}. */ - public List getVersions() - { + public List getVersions() { return versions; } /** * Adds the specified version to the result. Note that versions must be added in ascending order. - * + * * @param version The version to add, must not be {@code null}. * @return This result for chaining, never {@code null}. */ - public VersionRangeResult addVersion( Version version ) - { - if ( versions.isEmpty() ) - { + public VersionRangeResult addVersion(Version version) { + if (versions.isEmpty()) { versions = new ArrayList<>(); } - versions.add( version ); + versions.add(version); return this; } /** * Sets the versions (in ascending order) matching the requested range. - * + * * @param versions The matching versions, may be empty or {@code null} if none. * @return This result for chaining, never {@code null}. */ - public VersionRangeResult setVersions( List versions ) - { - if ( versions == null ) - { + public VersionRangeResult setVersions(List versions) { + if (versions == null) { this.versions = Collections.emptyList(); - } - else - { + } else { this.versions = versions; } return this; @@ -148,89 +134,77 @@ public VersionRangeResult setVersions( List versions ) /** * Gets the lowest version matching the requested range. - * + * * @return The lowest matching version or {@code null} if no versions matched the requested range. */ - public Version getLowestVersion() - { - if ( versions.isEmpty() ) - { + public Version getLowestVersion() { + if (versions.isEmpty()) { return null; } - return versions.get( 0 ); + return versions.get(0); } /** * Gets the highest version matching the requested range. - * + * * @return The highest matching version or {@code null} if no versions matched the requested range. */ - public Version getHighestVersion() - { - if ( versions.isEmpty() ) - { + public Version getHighestVersion() { + if (versions.isEmpty()) { return null; } - return versions.get( versions.size() - 1 ); + return versions.get(versions.size() - 1); } /** * Gets the repository from which the specified version was resolved. - * + * * @param version The version whose source repository should be retrieved, must not be {@code null}. * @return The repository from which the version was resolved or {@code null} if unknown. */ - public ArtifactRepository getRepository( Version version ) - { - return repositories.get( version ); + public ArtifactRepository getRepository(Version version) { + return repositories.get(version); } /** * Records the repository from which the specified version was resolved - * + * * @param version The version whose source repository is to be recorded, must not be {@code null}. * @param repository The repository from which the version was resolved, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public VersionRangeResult setRepository( Version version, ArtifactRepository repository ) - { - if ( repository != null ) - { - if ( repositories.isEmpty() ) - { + public VersionRangeResult setRepository(Version version, ArtifactRepository repository) { + if (repository != null) { + if (repositories.isEmpty()) { repositories = new HashMap<>(); } - repositories.put( version, repository ); + repositories.put(version, repository); } return this; } /** * Gets the version constraint that was parsed from the artifact's version string. - * + * * @return The parsed version constraint or {@code null}. */ - public VersionConstraint getVersionConstraint() - { + public VersionConstraint getVersionConstraint() { return versionConstraint; } /** * Sets the version constraint that was parsed from the artifact's version string. - * + * * @param versionConstraint The parsed version constraint, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public VersionRangeResult setVersionConstraint( VersionConstraint versionConstraint ) - { + public VersionRangeResult setVersionConstraint(VersionConstraint versionConstraint) { this.versionConstraint = versionConstraint; return this; } @Override - public String toString() - { - return String.valueOf( repositories ); + public String toString() { + return String.valueOf(repositories); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRequest.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRequest.java index c36b9910c..b6d0ed51c 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRequest.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionRequest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import java.util.ArrayList; import java.util.Collections; @@ -30,11 +29,10 @@ /** * A request to resolve a metaversion. - * + * * @see RepositorySystem#resolveVersion(org.eclipse.aether.RepositorySystemSession, VersionRequest) */ -public final class VersionRequest -{ +public final class VersionRequest { private Artifact artifact; @@ -47,71 +45,62 @@ public final class VersionRequest /** * Creates an uninitialized request. */ - public VersionRequest() - { + public VersionRequest() { // enables default constructor } /** * Creates a request with the specified properties. - * + * * @param artifact The artifact whose (meta-)version should be resolved, may be {@code null}. * @param repositories The repositories to resolve the version from, may be {@code null}. * @param context The context in which this request is made, may be {@code null}. */ - public VersionRequest( Artifact artifact, List repositories, String context ) - { - setArtifact( artifact ); - setRepositories( repositories ); - setRequestContext( context ); + public VersionRequest(Artifact artifact, List repositories, String context) { + setArtifact(artifact); + setRepositories(repositories); + setRequestContext(context); } /** * Gets the artifact whose (meta-)version shall be resolved. - * + * * @return The artifact or {@code null} if not set. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Sets the artifact whose (meta-)version shall be resolved. - * + * * @param artifact The artifact, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public VersionRequest setArtifact( Artifact artifact ) - { + public VersionRequest setArtifact(Artifact artifact) { this.artifact = artifact; return this; } /** * Gets the repositories to resolve the version from. - * + * * @return The repositories, never {@code null}. */ - public List getRepositories() - { + public List getRepositories() { return repositories; } /** * Sets the repositories to resolve the version from. - * + * * @param repositories The repositories, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public VersionRequest setRepositories( List repositories ) - { - if ( repositories == null ) - { + public VersionRequest setRepositories(List repositories) { + if (repositories == null) { this.repositories = Collections.emptyList(); - } - else - { + } else { this.repositories = repositories; } return this; @@ -119,71 +108,62 @@ public VersionRequest setRepositories( List repositories ) /** * Adds the specified repository for the resolution. - * + * * @param repository The repository to add, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public VersionRequest addRepository( RemoteRepository repository ) - { - if ( repository != null ) - { - if ( this.repositories.isEmpty() ) - { + public VersionRequest addRepository(RemoteRepository repository) { + if (repository != null) { + if (this.repositories.isEmpty()) { this.repositories = new ArrayList<>(); } - this.repositories.add( repository ); + this.repositories.add(repository); } return this; } /** * Gets the context in which this request is made. - * + * * @return The context, never {@code null}. */ - public String getRequestContext() - { + public String getRequestContext() { return context; } /** * Sets the context in which this request is made. - * + * * @param context The context, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public VersionRequest setRequestContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public VersionRequest setRequestContext(String context) { + this.context = (context != null) ? context : ""; return this; } /** * Gets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @return The trace information about the higher level operation or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } /** * Sets the trace information that describes the higher level request/operation in which this request is issued. - * + * * @param trace The trace information about the higher level operation, may be {@code null}. * @return This request for chaining, never {@code null}. */ - public VersionRequest setTrace( RequestTrace trace ) - { + public VersionRequest setTrace(RequestTrace trace) { this.trace = trace; return this; } @Override - public String toString() - { + public String toString() { return getArtifact() + " < " + getRepositories(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionResolutionException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionResolutionException.java index 1aca861e0..538c8c364 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionResolutionException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionResolutionException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,88 +16,78 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import org.eclipse.aether.RepositoryException; /** * Thrown in case of an unresolvable metaversion. */ -public class VersionResolutionException - extends RepositoryException -{ +public class VersionResolutionException extends RepositoryException { private final transient VersionResult result; /** * Creates a new exception with the specified result. - * + * * @param result The version result at the point the exception occurred, may be {@code null}. */ - public VersionResolutionException( VersionResult result ) - { - super( getMessage( result ), getCause( result ) ); + public VersionResolutionException(VersionResult result) { + super(getMessage(result), getCause(result)); this.result = result; } - private static String getMessage( VersionResult result ) - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( "Failed to resolve version" ); - if ( result != null ) - { - buffer.append( " for " ).append( result.getRequest().getArtifact() ); - if ( !result.getExceptions().isEmpty() ) - { - buffer.append( ": " ).append( result.getExceptions().iterator().next().getMessage() ); + private static String getMessage(VersionResult result) { + StringBuilder buffer = new StringBuilder(256); + buffer.append("Failed to resolve version"); + if (result != null) { + buffer.append(" for ").append(result.getRequest().getArtifact()); + if (!result.getExceptions().isEmpty()) { + buffer.append(": ") + .append(result.getExceptions().iterator().next().getMessage()); } } return buffer.toString(); } - private static Throwable getCause( VersionResult result ) - { + private static Throwable getCause(VersionResult result) { Throwable cause = null; - if ( result != null && !result.getExceptions().isEmpty() ) - { - cause = result.getExceptions().get( 0 ); + if (result != null && !result.getExceptions().isEmpty()) { + cause = result.getExceptions().get(0); } return cause; } /** * Creates a new exception with the specified result and detail message. - * + * * @param result The version result at the point the exception occurred, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public VersionResolutionException( VersionResult result, String message ) - { - super( message, getCause( result ) ); + public VersionResolutionException(VersionResult result, String message) { + super(message, getCause(result)); this.result = result; } /** * Creates a new exception with the specified result, detail message and cause. - * + * * @param result The version result at the point the exception occurred, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public VersionResolutionException( VersionResult result, String message, Throwable cause ) - { - super( message, cause ); + public VersionResolutionException(VersionResult result, String message, Throwable cause) { + super(message, cause); this.result = result; } /** * Gets the version result at the point the exception occurred. Despite being incomplete, callers might want to use * this result to fail gracefully and continue their operation with whatever interim data has been gathered. - * + * * @return The version result or {@code null} if unknown. */ - public VersionResult getResult() - { + public VersionResult getResult() { return result; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionResult.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionResult.java index 40797a2b6..6a56ebd84 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionResult.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/VersionResult.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,22 +16,23 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.resolution; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.repository.ArtifactRepository; +import static java.util.Objects.requireNonNull; + /** * The result of a version resolution request. - * + * * @see RepositorySystem#resolveVersion(org.eclipse.aether.RepositorySystemSession, VersionRequest) */ -public final class VersionResult -{ +public final class VersionResult { private final VersionRequest request; @@ -48,9 +47,8 @@ public final class VersionResult * * @param request The resolution request, must not be {@code null}. */ - public VersionResult( VersionRequest request ) - { - this.request = requireNonNull( request, "version request cannot be null" ); + public VersionResult(VersionRequest request) { + this.request = requireNonNull(request, "version request cannot be null"); exceptions = Collections.emptyList(); } @@ -59,88 +57,77 @@ public VersionResult( VersionRequest request ) * * @return The resolution request, never {@code null}. */ - public VersionRequest getRequest() - { + public VersionRequest getRequest() { return request; } /** * Gets the exceptions that occurred while resolving the version. - * + * * @return The exceptions that occurred, never {@code null}. */ - public List getExceptions() - { + public List getExceptions() { return exceptions; } /** * Records the specified exception while resolving the version. - * + * * @param exception The exception to record, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public VersionResult addException( Exception exception ) - { - if ( exception != null ) - { - if ( exceptions.isEmpty() ) - { + public VersionResult addException(Exception exception) { + if (exception != null) { + if (exceptions.isEmpty()) { exceptions = new ArrayList<>(); } - exceptions.add( exception ); + exceptions.add(exception); } return this; } /** * Gets the resolved version. - * + * * @return The resolved version or {@code null} if the resolution failed. */ - public String getVersion() - { + public String getVersion() { return version; } /** * Sets the resolved version. - * + * * @param version The resolved version, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public VersionResult setVersion( String version ) - { + public VersionResult setVersion(String version) { this.version = version; return this; } /** * Gets the repository from which the version was eventually resolved. - * + * * @return The repository from which the version was resolved or {@code null} if unknown. */ - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return repository; } /** * Sets the repository from which the version was resolved. - * + * * @param repository The repository from which the version was resolved, may be {@code null}. * @return This result for chaining, never {@code null}. */ - public VersionResult setRepository( ArtifactRepository repository ) - { + public VersionResult setRepository(ArtifactRepository repository) { this.repository = repository; return this; } @Override - public String toString() - { + public String toString() { return getVersion() + " @ " + getRepository(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/package-info.java b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/package-info.java index 33f9ef892..1ca7df3de 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/package-info.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/resolution/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * The types supporting the resolution of artifacts and metadata from repositories. */ package org.eclipse.aether.resolution; - diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/AbstractTransferListener.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/AbstractTransferListener.java index 5691e31db..f3e229746 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/AbstractTransferListener.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/AbstractTransferListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,47 +16,27 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; /** * A skeleton implementation for custom transfer listeners. The callback methods in this class do nothing. */ -public abstract class AbstractTransferListener - implements TransferListener -{ +public abstract class AbstractTransferListener implements TransferListener { /** * Enables subclassing. */ - protected AbstractTransferListener() - { - } - - public void transferInitiated( TransferEvent event ) - throws TransferCancelledException - { - } + protected AbstractTransferListener() {} - public void transferStarted( TransferEvent event ) - throws TransferCancelledException - { - } + public void transferInitiated(TransferEvent event) throws TransferCancelledException {} - public void transferProgressed( TransferEvent event ) - throws TransferCancelledException - { - } + public void transferStarted(TransferEvent event) throws TransferCancelledException {} - public void transferCorrupted( TransferEvent event ) - throws TransferCancelledException - { - } + public void transferProgressed(TransferEvent event) throws TransferCancelledException {} - public void transferSucceeded( TransferEvent event ) - { - } + public void transferCorrupted(TransferEvent event) throws TransferCancelledException {} - public void transferFailed( TransferEvent event ) - { - } + public void transferSucceeded(TransferEvent event) {} + public void transferFailed(TransferEvent event) {} } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ArtifactNotFoundException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ArtifactNotFoundException.java index 88f62aa7f..4f10aed1d 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ArtifactNotFoundException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ArtifactNotFoundException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.ArtifactProperties; @@ -26,37 +25,30 @@ /** * Thrown when an artifact was not found in a particular repository. */ -public class ArtifactNotFoundException - extends ArtifactTransferException -{ +public class ArtifactNotFoundException extends ArtifactTransferException { /** * Creates a new exception with the specified artifact and repository. - * + * * @param artifact The missing artifact, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. */ - public ArtifactNotFoundException( Artifact artifact, RemoteRepository repository ) - { - super( artifact, repository, getMessage( artifact, repository ) ); + public ArtifactNotFoundException(Artifact artifact, RemoteRepository repository) { + super(artifact, repository, getMessage(artifact, repository)); } - private static String getMessage( Artifact artifact, RemoteRepository repository ) - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( "Could not find artifact " ).append( artifact ); - buffer.append( getString( " in ", repository ) ); - if ( artifact != null ) - { - String localPath = artifact.getProperty( ArtifactProperties.LOCAL_PATH, null ); - if ( localPath != null && repository == null ) - { - buffer.append( " at specified path " ).append( localPath ); + private static String getMessage(Artifact artifact, RemoteRepository repository) { + StringBuilder buffer = new StringBuilder(256); + buffer.append("Could not find artifact ").append(artifact); + buffer.append(getString(" in ", repository)); + if (artifact != null) { + String localPath = artifact.getProperty(ArtifactProperties.LOCAL_PATH, null); + if (localPath != null && repository == null) { + buffer.append(" at specified path ").append(localPath); } - String downloadUrl = artifact.getProperty( ArtifactProperties.DOWNLOAD_URL, null ); - if ( downloadUrl != null ) - { - buffer.append( ", try downloading from " ).append( downloadUrl ); + String downloadUrl = artifact.getProperty(ArtifactProperties.DOWNLOAD_URL, null); + if (downloadUrl != null) { + buffer.append(", try downloading from ").append(downloadUrl); } } return buffer.toString(); @@ -64,42 +56,38 @@ private static String getMessage( Artifact artifact, RemoteRepository repository /** * Creates a new exception with the specified artifact, repository and detail message. - * + * * @param artifact The missing artifact, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public ArtifactNotFoundException( Artifact artifact, RemoteRepository repository, String message ) - { - super( artifact, repository, message ); + public ArtifactNotFoundException(Artifact artifact, RemoteRepository repository, String message) { + super(artifact, repository, message); } /** * Creates a new exception with the specified artifact, repository and detail message. - * + * * @param artifact The missing artifact, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. * @param fromCache {@code true} if the exception was played back from the error cache, {@code false} if the * exception actually just occurred. */ - public ArtifactNotFoundException( Artifact artifact, RemoteRepository repository, String message, - boolean fromCache ) - { - super( artifact, repository, message, fromCache ); + public ArtifactNotFoundException( + Artifact artifact, RemoteRepository repository, String message, boolean fromCache) { + super(artifact, repository, message, fromCache); } /** * Creates a new exception with the specified artifact, repository, detail message and cause. - * + * * @param artifact The missing artifact, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public ArtifactNotFoundException( Artifact artifact, RemoteRepository repository, String message, Throwable cause ) - { - super( artifact, repository, message, cause ); + public ArtifactNotFoundException(Artifact artifact, RemoteRepository repository, String message, Throwable cause) { + super(artifact, repository, message, cause); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ArtifactTransferException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ArtifactTransferException.java index c79f12539..fb11a9f62 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ArtifactTransferException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ArtifactTransferException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.artifact.Artifact; @@ -26,9 +25,7 @@ /** * Thrown when an artifact could not be uploaded/downloaded to/from a particular remote repository. */ -public class ArtifactTransferException - extends RepositoryException -{ +public class ArtifactTransferException extends RepositoryException { private final transient Artifact artifact; @@ -36,43 +33,37 @@ public class ArtifactTransferException private final boolean fromCache; - static String getString( String prefix, RemoteRepository repository ) - { - if ( repository == null ) - { + static String getString(String prefix, RemoteRepository repository) { + if (repository == null) { return ""; - } - else - { + } else { return prefix + repository.getId() + " (" + repository.getUrl() + ")"; } } /** * Creates a new exception with the specified artifact, repository and detail message. - * + * * @param artifact The untransferable artifact, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public ArtifactTransferException( Artifact artifact, RemoteRepository repository, String message ) - { - this( artifact, repository, message, false ); + public ArtifactTransferException(Artifact artifact, RemoteRepository repository, String message) { + this(artifact, repository, message, false); } /** * Creates a new exception with the specified artifact, repository and detail message. - * + * * @param artifact The untransferable artifact, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. * @param fromCache {@code true} if the exception was played back from the error cache, {@code false} if the * exception actually just occurred. */ - public ArtifactTransferException( Artifact artifact, RemoteRepository repository, String message, - boolean fromCache ) - { - super( message ); + public ArtifactTransferException( + Artifact artifact, RemoteRepository repository, String message, boolean fromCache) { + super(message); this.artifact = artifact; this.repository = repository; this.fromCache = fromCache; @@ -80,28 +71,30 @@ public ArtifactTransferException( Artifact artifact, RemoteRepository repository /** * Creates a new exception with the specified artifact, repository and cause. - * + * * @param artifact The untransferable artifact, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public ArtifactTransferException( Artifact artifact, RemoteRepository repository, Throwable cause ) - { - this( artifact, repository, "Could not transfer artifact " + artifact + getString( " from/to ", repository ) - + getMessage( ": ", cause ), cause ); + public ArtifactTransferException(Artifact artifact, RemoteRepository repository, Throwable cause) { + this( + artifact, + repository, + "Could not transfer artifact " + artifact + getString(" from/to ", repository) + + getMessage(": ", cause), + cause); } /** * Creates a new exception with the specified artifact, repository, detail message and cause. - * + * * @param artifact The untransferable artifact, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public ArtifactTransferException( Artifact artifact, RemoteRepository repository, String message, Throwable cause ) - { - super( message, cause ); + public ArtifactTransferException(Artifact artifact, RemoteRepository repository, String message, Throwable cause) { + super(message, cause); this.artifact = artifact; this.repository = repository; this.fromCache = false; @@ -109,33 +102,29 @@ public ArtifactTransferException( Artifact artifact, RemoteRepository repository /** * Gets the artifact that could not be transferred. - * + * * @return The troublesome artifact or {@code null} if unknown. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Gets the remote repository involved in the transfer. - * + * * @return The involved remote repository or {@code null} if unknown. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Indicates whether this exception actually just occurred or was played back from the error cache. - * + * * @return {@code true} if the exception was played back from the error cache, {@code false} if the exception * actually occurred just now. */ - public boolean isFromCache() - { + public boolean isFromCache() { return fromCache; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ChecksumFailureException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ChecksumFailureException.java index 88df9703a..0d42eeb14 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ChecksumFailureException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/ChecksumFailureException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,15 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import org.eclipse.aether.RepositoryException; /** * Thrown in case of a checksum failure during an artifact/metadata download. */ -public class ChecksumFailureException - extends RepositoryException -{ +public class ChecksumFailureException extends RepositoryException { private final String expected; @@ -39,15 +36,14 @@ public class ChecksumFailureException /** * Creates a new exception with the specified expected and actual checksum. The resulting exception is * {@link #isRetryWorthy() retry-worthy}. - * + * * @param expected The expected checksum as declared by the hosting repository, may be {@code null}. * @param actual The actual checksum as computed from the local bytes, may be {@code null}. * @deprecated Does not reveal expected checksum kind, use other constructor that provide that information as well. */ @Deprecated - public ChecksumFailureException( String expected, String actual ) - { - this( expected, null, actual ); + public ChecksumFailureException(String expected, String actual) { + this(expected, null, actual); } /** @@ -59,11 +55,10 @@ public ChecksumFailureException( String expected, String actual ) * @param actual The actual checksum as computed from the local bytes, may be {@code null}. * @since 1.8.0 */ - public ChecksumFailureException( String expected, String expectedKind, String actual ) - { - super( "Checksum validation failed, expected '" - + expected + "'" + ( expectedKind == null ? "" : " (" + expectedKind + ")" ) - + " but is actually '" + actual + "'" ); + public ChecksumFailureException(String expected, String expectedKind, String actual) { + super("Checksum validation failed, expected '" + + expected + "'" + (expectedKind == null ? "" : " (" + expectedKind + ")") + + " but is actually '" + actual + "'"); this.expected = expected; this.expectedKind = expectedKind; this.actual = actual; @@ -73,47 +68,43 @@ public ChecksumFailureException( String expected, String expectedKind, String ac /** * Creates a new exception with the specified detail message. The resulting exception is not * {@link #isRetryWorthy() retry-worthy}. - * + * * @param message The detail message, may be {@code null}. */ - public ChecksumFailureException( String message ) - { - this( false, message, null ); + public ChecksumFailureException(String message) { + this(false, message, null); } /** * Creates a new exception with the specified cause. The resulting exception is not {@link #isRetryWorthy() * retry-worthy}. - * + * * @param cause The exception that caused this one, may be {@code null}. */ - public ChecksumFailureException( Throwable cause ) - { - this( "Checksum validation failed" + getMessage( ": ", cause ), cause ); + public ChecksumFailureException(Throwable cause) { + this("Checksum validation failed" + getMessage(": ", cause), cause); } /** * Creates a new exception with the specified detail message and cause. The resulting exception is not * {@link #isRetryWorthy() retry-worthy}. - * + * * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public ChecksumFailureException( String message, Throwable cause ) - { - this( false, message, cause ); + public ChecksumFailureException(String message, Throwable cause) { + this(false, message, cause); } /** * Creates a new exception with the specified retry flag, detail message and cause. - * + * * @param retryWorthy {@code true} if the exception is retry-worthy, {@code false} otherwise. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public ChecksumFailureException( boolean retryWorthy, String message, Throwable cause ) - { - super( message, cause ); + public ChecksumFailureException(boolean retryWorthy, String message, Throwable cause) { + super(message, cause); this.expected = ""; this.expectedKind = ""; this.actual = ""; @@ -122,11 +113,10 @@ public ChecksumFailureException( boolean retryWorthy, String message, Throwable /** * Gets the expected checksum for the downloaded artifact/metadata. - * + * * @return The expected checksum as declared by the hosting repository or {@code null} if unknown. */ - public String getExpected() - { + public String getExpected() { return expected; } @@ -136,30 +126,26 @@ public String getExpected() * @return The expected checksum kind or {@code null} if unknown. * @since 1.8.0 */ - public String getExpectedKind() - { + public String getExpectedKind() { return expectedKind; } /** * Gets the actual checksum for the downloaded artifact/metadata. - * + * * @return The actual checksum as computed from the local bytes or {@code null} if unknown. */ - public String getActual() - { + public String getActual() { return actual; } /** * Indicates whether the corresponding download is retry-worthy. - * + * * @return {@code true} if retrying the download might solve the checksum failure, {@code false} if the checksum * failure is non-recoverable. */ - public boolean isRetryWorthy() - { + public boolean isRetryWorthy() { return retryWorthy; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/MetadataNotFoundException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/MetadataNotFoundException.java index 28d78bdf9..f7f9c2d94 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/MetadataNotFoundException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/MetadataNotFoundException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import org.eclipse.aether.metadata.Metadata; import org.eclipse.aether.repository.LocalRepository; @@ -26,82 +25,70 @@ /** * Thrown when metadata was not found in a particular repository. */ -public class MetadataNotFoundException - extends MetadataTransferException -{ +public class MetadataNotFoundException extends MetadataTransferException { /** * Creates a new exception with the specified metadata and local repository. - * + * * @param metadata The missing metadata, may be {@code null}. * @param repository The involved local repository, may be {@code null}. */ - public MetadataNotFoundException( Metadata metadata, LocalRepository repository ) - { - super( metadata, null, "Could not find metadata " + metadata + getString( " in ", repository ) ); + public MetadataNotFoundException(Metadata metadata, LocalRepository repository) { + super(metadata, null, "Could not find metadata " + metadata + getString(" in ", repository)); } - private static String getString( String prefix, LocalRepository repository ) - { - if ( repository == null ) - { + private static String getString(String prefix, LocalRepository repository) { + if (repository == null) { return ""; - } - else - { + } else { return prefix + repository.getId() + " (" + repository.getBasedir() + ")"; } } /** * Creates a new exception with the specified metadata and repository. - * + * * @param metadata The missing metadata, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. */ - public MetadataNotFoundException( Metadata metadata, RemoteRepository repository ) - { - super( metadata, repository, "Could not find metadata " + metadata + getString( " in ", repository ) ); + public MetadataNotFoundException(Metadata metadata, RemoteRepository repository) { + super(metadata, repository, "Could not find metadata " + metadata + getString(" in ", repository)); } /** * Creates a new exception with the specified metadata, repository and detail message. - * + * * @param metadata The missing metadata, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public MetadataNotFoundException( Metadata metadata, RemoteRepository repository, String message ) - { - super( metadata, repository, message ); + public MetadataNotFoundException(Metadata metadata, RemoteRepository repository, String message) { + super(metadata, repository, message); } /** * Creates a new exception with the specified metadata, repository and detail message. - * + * * @param metadata The missing metadata, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. * @param fromCache {@code true} if the exception was played back from the error cache, {@code false} if the * exception actually just occurred. */ - public MetadataNotFoundException( Metadata metadata, RemoteRepository repository, String message, - boolean fromCache ) - { - super( metadata, repository, message, fromCache ); + public MetadataNotFoundException( + Metadata metadata, RemoteRepository repository, String message, boolean fromCache) { + super(metadata, repository, message, fromCache); } /** * Creates a new exception with the specified metadata, repository, detail message and cause. - * + * * @param metadata The missing metadata, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public MetadataNotFoundException( Metadata metadata, RemoteRepository repository, String message, Throwable cause ) - { - super( metadata, repository, message, cause ); + public MetadataNotFoundException(Metadata metadata, RemoteRepository repository, String message, Throwable cause) { + super(metadata, repository, message, cause); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/MetadataTransferException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/MetadataTransferException.java index ff363a332..3ba261a9a 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/MetadataTransferException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/MetadataTransferException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.metadata.Metadata; @@ -26,9 +25,7 @@ /** * Thrown when metadata could not be uploaded/downloaded to/from a particular remote repository. */ -public class MetadataTransferException - extends RepositoryException -{ +public class MetadataTransferException extends RepositoryException { private final transient Metadata metadata; @@ -36,43 +33,37 @@ public class MetadataTransferException private final boolean fromCache; - static String getString( String prefix, RemoteRepository repository ) - { - if ( repository == null ) - { + static String getString(String prefix, RemoteRepository repository) { + if (repository == null) { return ""; - } - else - { + } else { return prefix + repository.getId() + " (" + repository.getUrl() + ")"; } } /** * Creates a new exception with the specified metadata, repository and detail message. - * + * * @param metadata The untransferable metadata, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public MetadataTransferException( Metadata metadata, RemoteRepository repository, String message ) - { - this( metadata, repository, message, false ); + public MetadataTransferException(Metadata metadata, RemoteRepository repository, String message) { + this(metadata, repository, message, false); } /** * Creates a new exception with the specified metadata, repository and detail message. - * + * * @param metadata The untransferable metadata, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. * @param fromCache {@code true} if the exception was played back from the error cache, {@code false} if the * exception actually just occurred. */ - public MetadataTransferException( Metadata metadata, RemoteRepository repository, String message, - boolean fromCache ) - { - super( message ); + public MetadataTransferException( + Metadata metadata, RemoteRepository repository, String message, boolean fromCache) { + super(message); this.metadata = metadata; this.repository = repository; this.fromCache = fromCache; @@ -80,28 +71,30 @@ public MetadataTransferException( Metadata metadata, RemoteRepository repository /** * Creates a new exception with the specified metadata, repository and cause. - * + * * @param metadata The untransferable metadata, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public MetadataTransferException( Metadata metadata, RemoteRepository repository, Throwable cause ) - { - this( metadata, repository, "Could not transfer metadata " + metadata + getString( " from/to ", repository ) - + getMessage( ": ", cause ), cause ); + public MetadataTransferException(Metadata metadata, RemoteRepository repository, Throwable cause) { + this( + metadata, + repository, + "Could not transfer metadata " + metadata + getString(" from/to ", repository) + + getMessage(": ", cause), + cause); } /** * Creates a new exception with the specified metadata, repository, detail message and cause. - * + * * @param metadata The untransferable metadata, may be {@code null}. * @param repository The involved remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public MetadataTransferException( Metadata metadata, RemoteRepository repository, String message, Throwable cause ) - { - super( message, cause ); + public MetadataTransferException(Metadata metadata, RemoteRepository repository, String message, Throwable cause) { + super(message, cause); this.metadata = metadata; this.repository = repository; this.fromCache = false; @@ -109,33 +102,29 @@ public MetadataTransferException( Metadata metadata, RemoteRepository repository /** * Gets the metadata that could not be transferred. - * + * * @return The troublesome metadata or {@code null} if unknown. */ - public Metadata getMetadata() - { + public Metadata getMetadata() { return metadata; } /** * Gets the remote repository involved in the transfer. - * + * * @return The involved remote repository or {@code null} if unknown. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Indicates whether this exception actually just occurred or was played back from the error cache. - * + * * @return {@code true} if the exception was played back from the error cache, {@code false} if the exception * actually occurred just now. */ - public boolean isFromCache() - { + public boolean isFromCache() { return fromCache; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoRepositoryConnectorException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoRepositoryConnectorException.java index 314056998..116795742 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoRepositoryConnectorException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoRepositoryConnectorException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.repository.RemoteRepository; @@ -25,79 +24,67 @@ /** * Thrown in case of an unsupported remote repository type. */ -public class NoRepositoryConnectorException - extends RepositoryException -{ +public class NoRepositoryConnectorException extends RepositoryException { private final transient RemoteRepository repository; /** * Creates a new exception with the specified repository. - * + * * @param repository The remote repository whose content type is not supported, may be {@code null}. */ - public NoRepositoryConnectorException( RemoteRepository repository ) - { - this( repository, toMessage( repository ) ); + public NoRepositoryConnectorException(RemoteRepository repository) { + this(repository, toMessage(repository)); } /** * Creates a new exception with the specified repository and detail message. - * + * * @param repository The remote repository whose content type is not supported, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public NoRepositoryConnectorException( RemoteRepository repository, String message ) - { - super( message ); + public NoRepositoryConnectorException(RemoteRepository repository, String message) { + super(message); this.repository = repository; } /** * Creates a new exception with the specified repository and cause. - * + * * @param repository The remote repository whose content type is not supported, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public NoRepositoryConnectorException( RemoteRepository repository, Throwable cause ) - { - this( repository, toMessage( repository ), cause ); + public NoRepositoryConnectorException(RemoteRepository repository, Throwable cause) { + this(repository, toMessage(repository), cause); } /** * Creates a new exception with the specified repository, detail message and cause. - * + * * @param repository The remote repository whose content type is not supported, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public NoRepositoryConnectorException( RemoteRepository repository, String message, Throwable cause ) - { - super( message, cause ); + public NoRepositoryConnectorException(RemoteRepository repository, String message, Throwable cause) { + super(message, cause); this.repository = repository; } - private static String toMessage( RemoteRepository repository ) - { - if ( repository != null ) - { + private static String toMessage(RemoteRepository repository) { + if (repository != null) { return "No connector available to access repository " + repository.getId() + " (" + repository.getUrl() - + ") of type " + repository.getContentType(); - } - else - { + + ") of type " + repository.getContentType(); + } else { return "No connector available to access repository"; } } /** * Gets the remote repository whose content type is not supported. - * + * * @return The unsupported remote repository or {@code null} if unknown. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoRepositoryLayoutException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoRepositoryLayoutException.java index 3fc05bb70..4d59b9eb6 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoRepositoryLayoutException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoRepositoryLayoutException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.repository.RemoteRepository; @@ -25,78 +24,66 @@ /** * Thrown in case of an unsupported repository layout. */ -public class NoRepositoryLayoutException - extends RepositoryException -{ +public class NoRepositoryLayoutException extends RepositoryException { private final transient RemoteRepository repository; /** * Creates a new exception with the specified repository. - * + * * @param repository The remote repository whose layout is not supported, may be {@code null}. */ - public NoRepositoryLayoutException( RemoteRepository repository ) - { - this( repository, toMessage( repository ) ); + public NoRepositoryLayoutException(RemoteRepository repository) { + this(repository, toMessage(repository)); } /** * Creates a new exception with the specified repository and detail message. - * + * * @param repository The remote repository whose layout is not supported, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public NoRepositoryLayoutException( RemoteRepository repository, String message ) - { - super( message ); + public NoRepositoryLayoutException(RemoteRepository repository, String message) { + super(message); this.repository = repository; } /** * Creates a new exception with the specified repository and cause. - * + * * @param repository The remote repository whose layout is not supported, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public NoRepositoryLayoutException( RemoteRepository repository, Throwable cause ) - { - this( repository, toMessage( repository ), cause ); + public NoRepositoryLayoutException(RemoteRepository repository, Throwable cause) { + this(repository, toMessage(repository), cause); } /** * Creates a new exception with the specified repository, detail message and cause. - * + * * @param repository The remote repository whose layout is not supported, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public NoRepositoryLayoutException( RemoteRepository repository, String message, Throwable cause ) - { - super( message, cause ); + public NoRepositoryLayoutException(RemoteRepository repository, String message, Throwable cause) { + super(message, cause); this.repository = repository; } - private static String toMessage( RemoteRepository repository ) - { - if ( repository != null ) - { + private static String toMessage(RemoteRepository repository) { + if (repository != null) { return "Unsupported repository layout " + repository.getContentType(); - } - else - { + } else { return "Unsupported repository layout"; } } /** * Gets the remote repository whose layout is not supported. - * + * * @return The unsupported remote repository or {@code null} if unknown. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoTransporterException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoTransporterException.java index 5d985588d..ad5d8711d 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoTransporterException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/NoTransporterException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.repository.RemoteRepository; @@ -25,78 +24,66 @@ /** * Thrown in case of an unsupported transport protocol. */ -public class NoTransporterException - extends RepositoryException -{ +public class NoTransporterException extends RepositoryException { private final transient RemoteRepository repository; /** * Creates a new exception with the specified repository. - * + * * @param repository The remote repository whose transport layout is not supported, may be {@code null}. */ - public NoTransporterException( RemoteRepository repository ) - { - this( repository, toMessage( repository ) ); + public NoTransporterException(RemoteRepository repository) { + this(repository, toMessage(repository)); } /** * Creates a new exception with the specified repository and detail message. - * + * * @param repository The remote repository whose transport layout is not supported, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public NoTransporterException( RemoteRepository repository, String message ) - { - super( message ); + public NoTransporterException(RemoteRepository repository, String message) { + super(message); this.repository = repository; } /** * Creates a new exception with the specified repository and cause. - * + * * @param repository The remote repository whose transport layout is not supported, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public NoTransporterException( RemoteRepository repository, Throwable cause ) - { - this( repository, toMessage( repository ), cause ); + public NoTransporterException(RemoteRepository repository, Throwable cause) { + this(repository, toMessage(repository), cause); } /** * Creates a new exception with the specified repository, detail message and cause. - * + * * @param repository The remote repository whose transport layout is not supported, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public NoTransporterException( RemoteRepository repository, String message, Throwable cause ) - { - super( message, cause ); + public NoTransporterException(RemoteRepository repository, String message, Throwable cause) { + super(message, cause); this.repository = repository; } - private static String toMessage( RemoteRepository repository ) - { - if ( repository != null ) - { + private static String toMessage(RemoteRepository repository) { + if (repository != null) { return "Unsupported transport protocol " + repository.getProtocol(); - } - else - { + } else { return "Unsupported transport protocol"; } } /** * Gets the remote repository whose transport protocol is not supported. - * + * * @return The unsupported remote repository or {@code null} if unknown. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/RepositoryOfflineException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/RepositoryOfflineException.java index 02d468080..39da554ba 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/RepositoryOfflineException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/RepositoryOfflineException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.repository.RemoteRepository; @@ -25,55 +24,45 @@ /** * Thrown when a transfer could not be performed because a remote repository is not accessible in offline mode. */ -public class RepositoryOfflineException - extends RepositoryException -{ +public class RepositoryOfflineException extends RepositoryException { private final transient RemoteRepository repository; - private static String getMessage( RemoteRepository repository ) - { - if ( repository == null ) - { + private static String getMessage(RemoteRepository repository) { + if (repository == null) { return "Cannot access remote repositories in offline mode"; - } - else - { + } else { return "Cannot access " + repository.getId() + " (" + repository.getUrl() + ") in offline mode"; } } /** * Creates a new exception with the specified repository. - * + * * @param repository The inaccessible remote repository, may be {@code null}. */ - public RepositoryOfflineException( RemoteRepository repository ) - { - super( getMessage( repository ) ); + public RepositoryOfflineException(RemoteRepository repository) { + super(getMessage(repository)); this.repository = repository; } /** * Creates a new exception with the specified repository and detail message. - * + * * @param repository The inaccessible remote repository, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public RepositoryOfflineException( RemoteRepository repository, String message ) - { - super( message ); + public RepositoryOfflineException(RemoteRepository repository, String message) { + super(message); this.repository = repository; } /** * Gets the remote repository that could not be accessed due to offline mode. - * + * * @return The inaccessible remote repository or {@code null} if unknown. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferCancelledException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferCancelledException.java index 88caa13dc..663187eb1 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferCancelledException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferCancelledException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,43 +16,38 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import org.eclipse.aether.RepositoryException; /** * Thrown in case an upload/download was cancelled (e.g. due to user request). */ -public class TransferCancelledException - extends RepositoryException -{ +public class TransferCancelledException extends RepositoryException { /** * Creates a new exception with a stock detail message. */ - public TransferCancelledException() - { - super( "The operation was cancelled." ); + public TransferCancelledException() { + super("The operation was cancelled."); } /** * Creates a new exception with the specified detail message. - * + * * @param message The detail message, may be {@code null}. */ - public TransferCancelledException( String message ) - { - super( message ); + public TransferCancelledException(String message) { + super(message); } /** * Creates a new exception with the specified detail message and cause. - * + * * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public TransferCancelledException( String message, Throwable cause ) - { - super( message, cause ); + public TransferCancelledException(String message, Throwable cause) { + super(message, cause); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferEvent.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferEvent.java index b73543985..409770864 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferEvent.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferEvent.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,26 +16,26 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import java.nio.ByteBuffer; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositorySystemSession; +import static java.util.Objects.requireNonNull; + /** * An event fired to a transfer listener during an artifact/metadata transfer. * * @see TransferListener * @see TransferEvent.Builder */ -public final class TransferEvent -{ +public final class TransferEvent { /** * The type of the event. */ - public enum EventType - { + public enum EventType { /** * @see TransferListener#transferInitiated(TransferEvent) @@ -68,14 +66,12 @@ public enum EventType * @see TransferListener#transferFailed(TransferEvent) */ FAILED - } /** * The type of the request/transfer being performed. */ - public enum RequestType - { + public enum RequestType { /** * Download artifact/metadata. @@ -91,7 +87,6 @@ public enum RequestType * Upload artifact/metadata. */ PUT, - } private final EventType type; @@ -108,8 +103,7 @@ public enum RequestType private final Exception exception; - TransferEvent( Builder builder ) - { + TransferEvent(Builder builder) { type = builder.type; requestType = builder.requestType; session = builder.session; @@ -121,41 +115,37 @@ public enum RequestType /** * Gets the type of the event. - * + * * @return The type of the event, never {@code null}. */ - public EventType getType() - { + public EventType getType() { return type; } /** * Gets the type of the request/transfer. - * + * * @return The type of the request/transfer, never {@code null}. */ - public RequestType getRequestType() - { + public RequestType getRequestType() { return requestType; } /** * Gets the repository system session during which the event occurred. - * + * * @return The repository system session during which the event occurred, never {@code null}. */ - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } /** * Gets the resource that is being transferred. - * + * * @return The resource being transferred, never {@code null}. */ - public TransferResource getResource() - { + public TransferResource getResource() { return resource; } @@ -164,13 +154,12 @@ public TransferResource getResource() * If a download has been resumed, the returned count includes the bytes that were already downloaded during the * previous attempt. In other words, the ratio of transferred bytes to the content length of the resource indicates * the percentage of transfer completion. - * + * * @return The total number of bytes that have been transferred since the transfer started, never negative. * @see #getDataLength() * @see TransferResource#getResumeOffset() */ - public long getTransferredBytes() - { + public long getTransferredBytes() { return transferredBytes; } @@ -180,47 +169,42 @@ public long getTransferredBytes() * duration of the event callback, i.e. the next event might reuse the same buffer (with updated contents). * Therefore, if the actual event processing is deferred, the byte buffer would have to be cloned to create an * immutable snapshot of its contents. - * + * * @return The (read-only) byte buffer or {@code null} if not applicable to the event, i.e. if the event type is not * {@link EventType#PROGRESSED}. */ - public ByteBuffer getDataBuffer() - { - return ( dataBuffer != null ) ? dataBuffer.asReadOnlyBuffer() : null; + public ByteBuffer getDataBuffer() { + return (dataBuffer != null) ? dataBuffer.asReadOnlyBuffer() : null; } /** * Gets the number of bytes that have been transferred since the last event. - * + * * @return The number of bytes that have been transferred since the last event, possibly zero but never negative. * @see #getTransferredBytes() */ - public int getDataLength() - { - return ( dataBuffer != null ) ? dataBuffer.remaining() : 0; + public int getDataLength() { + return (dataBuffer != null) ? dataBuffer.remaining() : 0; } /** * Gets the error that occurred during the transfer. - * + * * @return The error that occurred or {@code null} if none. */ - public Exception getException() - { + public Exception getException() { return exception; } @Override - public String toString() - { + public String toString() { return getRequestType() + " " + getType() + " " + getResource(); } /** * A builder to create transfer events. */ - public static final class Builder - { + public static final class Builder { EventType type; @@ -242,16 +226,14 @@ public static final class Builder * @param session The repository system session, must not be {@code null}. * @param resource The resource being transferred, must not be {@code null}. */ - public Builder( RepositorySystemSession session, TransferResource resource ) - { - this.session = requireNonNull( session, "repository system session cannot be null" ); - this.resource = requireNonNull( resource, "transfer resource cannot be null" ); + public Builder(RepositorySystemSession session, TransferResource resource) { + this.session = requireNonNull(session, "repository system session cannot be null"); + this.resource = requireNonNull(resource, "transfer resource cannot be null"); type = EventType.INITIATED; requestType = RequestType.GET; } - private Builder( Builder prototype ) - { + private Builder(Builder prototype) { session = prototype.session; resource = prototype.resource; type = prototype.type; @@ -264,12 +246,11 @@ private Builder( Builder prototype ) /** * Creates a new transfer event builder from the current values of this builder. The state of this builder * remains unchanged. - * + * * @return The new event builder, never {@code null}. */ - public Builder copy() - { - return new Builder( this ); + public Builder copy() { + return new Builder(this); } /** @@ -280,13 +261,11 @@ public Builder copy() * @param type The type of the event, must not be {@code null}. * @return This event builder for chaining, never {@code null}. */ - public Builder resetType( EventType type ) - { - this.type = requireNonNull( type, "event type cannot be null" ); + public Builder resetType(EventType type) { + this.type = requireNonNull(type, "event type cannot be null"); dataBuffer = null; exception = null; - switch ( type ) - { + switch (type) { case INITIATED: case STARTED: transferredBytes = 0L; @@ -302,9 +281,8 @@ public Builder resetType( EventType type ) * @param type The type of the event, must not be {@code null}. * @return This event builder for chaining, never {@code null}. */ - public Builder setType( EventType type ) - { - this.type = requireNonNull( type, "event type cannot be null" ); + public Builder setType(EventType type) { + this.type = requireNonNull(type, "event type cannot be null"); return this; } @@ -314,9 +292,8 @@ public Builder setType( EventType type ) * @param requestType The request/transfer type, must not be {@code null}. * @return This event builder for chaining, never {@code null}. */ - public Builder setRequestType( RequestType requestType ) - { - this.requestType = requireNonNull( requestType, "request type cannot be null" ); + public Builder setRequestType(RequestType requestType) { + this.requestType = requireNonNull(requestType, "request type cannot be null"); return this; } @@ -325,17 +302,15 @@ public Builder setRequestType( RequestType requestType ) * If a download is being resumed, the count must include the bytes that were already downloaded in the previous * attempt and from which the current transfer started. In this case, the event type {@link EventType#STARTED} * should indicate from what byte the download resumes. - * + * * @param transferredBytes The total number of bytes that have been transferred so far during the * download/upload of the resource, must not be negative. * @return This event builder for chaining, never {@code null}. * @see TransferResource#setResumeOffset(long) */ - public Builder setTransferredBytes( long transferredBytes ) - { - if ( transferredBytes < 0L ) - { - throw new IllegalArgumentException( "number of transferred bytes cannot be negative" ); + public Builder setTransferredBytes(long transferredBytes) { + if (transferredBytes < 0L) { + throw new IllegalArgumentException("number of transferred bytes cannot be negative"); } this.transferredBytes = transferredBytes; return this; @@ -348,11 +323,9 @@ public Builder setTransferredBytes( long transferredBytes ) * negative. * @return This event builder for chaining, never {@code null}. */ - public Builder addTransferredBytes( long transferredBytes ) - { - if ( transferredBytes < 0L ) - { - throw new IllegalArgumentException( "number of transferred bytes cannot be negative" ); + public Builder addTransferredBytes(long transferredBytes) { + if (transferredBytes < 0L) { + throw new IllegalArgumentException("number of transferred bytes cannot be negative"); } this.transferredBytes += transferredBytes; return this; @@ -360,39 +333,36 @@ public Builder addTransferredBytes( long transferredBytes ) /** * Sets the byte buffer holding the transferred bytes since the last event. - * + * * @param buffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if not * applicable to the event. * @param offset The starting point of valid bytes in the array. * @param length The number of valid bytes, must not be negative. * @return This event builder for chaining, never {@code null}. */ - public Builder setDataBuffer( byte[] buffer, int offset, int length ) - { - return setDataBuffer( ( buffer != null ) ? ByteBuffer.wrap( buffer, offset, length ) : null ); + public Builder setDataBuffer(byte[] buffer, int offset, int length) { + return setDataBuffer((buffer != null) ? ByteBuffer.wrap(buffer, offset, length) : null); } /** * Sets the byte buffer holding the transferred bytes since the last event. - * + * * @param dataBuffer The byte buffer holding the transferred bytes since the last event, may be {@code null} if * not applicable to the event. * @return This event builder for chaining, never {@code null}. */ - public Builder setDataBuffer( ByteBuffer dataBuffer ) - { + public Builder setDataBuffer(ByteBuffer dataBuffer) { this.dataBuffer = dataBuffer; return this; } /** * Sets the error that occurred during the transfer. - * + * * @param exception The error that occurred during the transfer, may be {@code null} if none. * @return This event builder for chaining, never {@code null}. */ - public Builder setException( Exception exception ) - { + public Builder setException(Exception exception) { this.exception = exception; return this; } @@ -400,14 +370,11 @@ public Builder setException( Exception exception ) /** * Builds a new transfer event from the current values of this builder. The state of the builder itself remains * unchanged. - * + * * @return The transfer event, never {@code null}. */ - public TransferEvent build() - { - return new TransferEvent( this ); + public TransferEvent build() { + return new TransferEvent(this); } - } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferListener.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferListener.java index 18019a9f5..ab2383d30 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferListener.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,83 +16,78 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; /** * A listener being notified of artifact/metadata transfers from/to remote repositories. The listener may be called from * an arbitrary thread. Reusing common regular expression syntax, the sequence of events is roughly as follows: - * + * *
      * INITIATED ( STARTED PROGRESSED* CORRUPTED? )* ( SUCCEEDED | FAILED )
      * 
    - * + * * Note: Implementors are strongly advised to inherit from {@link AbstractTransferListener} instead of directly * implementing this interface. - * + * * @see org.eclipse.aether.RepositorySystemSession#getTransferListener() * @see org.eclipse.aether.RepositoryListener * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface TransferListener -{ +public interface TransferListener { /** * Notifies the listener about the initiation of a transfer. This event gets fired before any actual network access * to the remote repository and usually indicates some thread is now about to perform the transfer. For a given * transfer request, this event is the first one being fired and it must be emitted exactly once. - * + * * @param event The event details, must not be {@code null}. * @throws TransferCancelledException If the transfer should be aborted. */ - void transferInitiated( TransferEvent event ) - throws TransferCancelledException; + void transferInitiated(TransferEvent event) throws TransferCancelledException; /** * Notifies the listener about the start of a data transfer. This event indicates a successful connection to the * remote repository. In case of a download, the requested remote resource exists and its size is given by * {@link TransferResource#getContentLength()} if possible. This event may be fired multiple times for given * transfer request if said transfer needs to be repeated (e.g. in response to an authentication challenge). - * + * * @param event The event details, must not be {@code null}. * @throws TransferCancelledException If the transfer should be aborted. */ - void transferStarted( TransferEvent event ) - throws TransferCancelledException; + void transferStarted(TransferEvent event) throws TransferCancelledException; /** * Notifies the listener about some progress in the data transfer. This event may even be fired if actually zero * bytes have been transferred since the last event, for instance to enable cancellation. - * + * * @param event The event details, must not be {@code null}. * @throws TransferCancelledException If the transfer should be aborted. */ - void transferProgressed( TransferEvent event ) - throws TransferCancelledException; + void transferProgressed(TransferEvent event) throws TransferCancelledException; /** * Notifies the listener that a checksum validation failed. {@link TransferEvent#getException()} will be of type * {@link ChecksumFailureException} and can be used to query further details about the expected/actual checksums. - * + * * @param event The event details, must not be {@code null}. * @throws TransferCancelledException If the transfer should be aborted. */ - void transferCorrupted( TransferEvent event ) - throws TransferCancelledException; + void transferCorrupted(TransferEvent event) throws TransferCancelledException; /** * Notifies the listener about the successful completion of a transfer. This event must be fired exactly once for a * given transfer request unless said request failed. - * + * * @param event The event details, must not be {@code null}. */ - void transferSucceeded( TransferEvent event ); + void transferSucceeded(TransferEvent event); /** * Notifies the listener about the unsuccessful termination of a transfer. {@link TransferEvent#getException()} will * provide further information about the failure. - * + * * @param event The event details, must not be {@code null}. */ - void transferFailed( TransferEvent event ); - + void transferFailed(TransferEvent event); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferResource.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferResource.java index 7c578645b..e25317964 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferResource.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/TransferResource.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transfer; import java.io.File; @@ -26,8 +25,7 @@ /** * Describes a resource being uploaded or downloaded by the repository system. */ -public final class TransferResource -{ +public final class TransferResource { private final String repositoryId; @@ -59,9 +57,8 @@ public final class TransferResource * java.lang.String, java.io.File, org.eclipse.aether.RequestTrace)} */ @Deprecated - public TransferResource( String repositoryUrl, String resourceName, File file, RequestTrace trace ) - { - this( null, repositoryUrl, resourceName, file, trace ); + public TransferResource(String repositoryUrl, String resourceName, File file, RequestTrace trace) { + this(null, repositoryUrl, resourceName, file, trace); } /** @@ -78,41 +75,27 @@ public TransferResource( String repositoryUrl, String resourceName, File file, R * * @since 1.1.0 */ - public TransferResource( String repositoryId, String repositoryUrl, String resourceName, - File file, RequestTrace trace ) - { - if ( repositoryId == null || repositoryId.isEmpty() ) - { + public TransferResource( + String repositoryId, String repositoryUrl, String resourceName, File file, RequestTrace trace) { + if (repositoryId == null || repositoryId.isEmpty()) { this.repositoryId = ""; - } - else - { + } else { this.repositoryId = repositoryId; } - if ( repositoryUrl == null || repositoryUrl.isEmpty() ) - { + if (repositoryUrl == null || repositoryUrl.isEmpty()) { this.repositoryUrl = ""; - } - else if ( repositoryUrl.endsWith( "/" ) ) - { + } else if (repositoryUrl.endsWith("/")) { this.repositoryUrl = repositoryUrl; - } - else - { + } else { this.repositoryUrl = repositoryUrl + '/'; } - if ( resourceName == null || resourceName.isEmpty() ) - { + if (resourceName == null || resourceName.isEmpty()) { this.resourceName = ""; - } - else if ( resourceName.startsWith( "/" ) ) - { - this.resourceName = resourceName.substring( 1 ); - } - else - { + } else if (resourceName.startsWith("/")) { + this.resourceName = resourceName.substring(1); + } else { this.resourceName = resourceName; } @@ -130,8 +113,7 @@ else if ( resourceName.startsWith( "/" ) ) * * @since 1.1.0 */ - public String getRepositoryId() - { + public String getRepositoryId() { return repositoryId; } @@ -141,8 +123,7 @@ public String getRepositoryId() * * @return The base URL of the repository or an empty string if unknown, never {@code null}. */ - public String getRepositoryUrl() - { + public String getRepositoryUrl() { return repositoryUrl; } @@ -151,8 +132,7 @@ public String getRepositoryUrl() * * @return The path of the resource, never {@code null}. */ - public String getResourceName() - { + public String getResourceName() { return resourceName; } @@ -162,8 +142,7 @@ public String getResourceName() * * @return The source/target file involved in the transfer or {@code null} if none. */ - public File getFile() - { + public File getFile() { return file; } @@ -174,8 +153,7 @@ public File getFile() * * @return The size of the resource in bytes or a negative value if unknown. */ - public long getContentLength() - { + public long getContentLength() { return contentLength; } @@ -185,8 +163,7 @@ public long getContentLength() * @param contentLength The size of the resource in bytes or a negative value if unknown. * @return This resource for chaining, never {@code null}. */ - public TransferResource setContentLength( long contentLength ) - { + public TransferResource setContentLength(long contentLength) { this.contentLength = contentLength; return this; } @@ -197,8 +174,7 @@ public TransferResource setContentLength( long contentLength ) * * @return The zero-based index of the first byte being transferred, never negative. */ - public long getResumeOffset() - { + public long getResumeOffset() { return resumeOffset; } @@ -208,11 +184,9 @@ public long getResumeOffset() * @param resumeOffset The zero-based index of the first byte being transferred, must not be negative. * @return This resource for chaining, never {@code null}. */ - public TransferResource setResumeOffset( long resumeOffset ) - { - if ( resumeOffset < 0L ) - { - throw new IllegalArgumentException( "resume offset cannot be negative" ); + public TransferResource setResumeOffset(long resumeOffset) { + if (resumeOffset < 0L) { + throw new IllegalArgumentException("resume offset cannot be negative"); } this.resumeOffset = resumeOffset; return this; @@ -223,8 +197,7 @@ public TransferResource setResumeOffset( long resumeOffset ) * * @return The timestamp when the transfer of this resource was started. */ - public long getTransferStartTime() - { + public long getTransferStartTime() { return startTime; } @@ -234,15 +207,12 @@ public long getTransferStartTime() * * @return The trace information about the higher level operation or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } @Override - public String toString() - { + public String toString() { return getRepositoryUrl() + getResourceName() + " <> " + getFile(); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/package-info.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/package-info.java index 541b24417..6f2d9dc26 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/package-info.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transfer/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -22,4 +22,3 @@ * repository. */ package org.eclipse.aether.transfer; - diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transform/FileTransformer.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transform/FileTransformer.java index 45c0b5b14..bf45d9755 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transform/FileTransformer.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transform/FileTransformer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transform; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transform; import java.io.File; import java.io.IOException; @@ -27,31 +26,29 @@ /** * Can transform a file while installing/deploying - * + * * @author Robert Scholte * @since 1.3.0 * @deprecated Without any direct replacement for now. This API is OOM-prone, and also lacks a lot of context about * transforming. */ @Deprecated -public interface FileTransformer -{ +public interface FileTransformer { /** - * Transform the target location - * + * Transform the target location + * * @param artifact the original artifact * @return the transformed artifact */ - Artifact transformArtifact( Artifact artifact ); - + Artifact transformArtifact(Artifact artifact); + /** * Transform the data - * + * * @param file the file with the original data * @return the transformed data * @throws IOException If an I/O error occurred * @throws TransformException If the file could not be transformed */ - InputStream transformData( File file ) - throws IOException, TransformException; + InputStream transformData(File file) throws IOException, TransformException; } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transform/FileTransformerManager.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transform/FileTransformerManager.java index 1a472e597..7b7c87d7d 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transform/FileTransformerManager.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transform/FileTransformerManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transform; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,35 +16,35 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transform; import java.util.Collection; import org.eclipse.aether.artifact.Artifact; /** - * Manager the FileTransformers - * + * Manager the FileTransformers + * * @author Robert Scholte * @since 1.3.0 * @deprecated Without any direct replacement for now. This API is OOM-prone, and also lacks a lot of context about * transforming. */ @Deprecated -public interface FileTransformerManager -{ +public interface FileTransformerManager { /** *

    * All transformers for this specific artifact. Be aware that if you want to create additional files, but also want * to the original to be deployed, you must add an explicit transformer for that file too (one that doesn't * transform the artifact and data). *

    - * + * *

    IMPORTANT When using a fileTransformer, the content of the file is stored in memory to ensure * that file content and checksums stay in sync! *

    - * + * * @param artifact the artifact * @return a collection of FileTransformers to apply on the artifact, never {@code null} */ - Collection getTransformersForArtifact( Artifact artifact ); + Collection getTransformersForArtifact(Artifact artifact); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/transform/TransformException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/transform/TransformException.java index 748b39d2c..9e24b1d3d 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/transform/TransformException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/transform/TransformException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transform; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transform; /** * Thrown when transformation failed. @@ -26,16 +25,13 @@ * transforming. */ @Deprecated -public class TransformException - extends Exception -{ +public class TransformException extends Exception { /** * Creates a new exception with default detail message. */ - public TransformException() - { - super( "Transformation failed" ); + public TransformException() { + super("Transformation failed"); } /** @@ -43,9 +39,8 @@ public TransformException() * * @param message The detail message, may be {@code null}. */ - public TransformException( String message ) - { - super( message ); + public TransformException(String message) { + super(message); } /** @@ -53,9 +48,8 @@ public TransformException( String message ) * * @param cause The exception that caused this one, may be {@code null}. */ - public TransformException( Throwable cause ) - { - super( cause ); + public TransformException(Throwable cause) { + super(cause); } /** @@ -64,9 +58,7 @@ public TransformException( Throwable cause ) * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public TransformException( String message, Throwable cause ) - { - super( message, cause ); + public TransformException(String message, Throwable cause) { + super(message, cause); } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/version/InvalidVersionSpecificationException.java b/maven-resolver-api/src/main/java/org/eclipse/aether/version/InvalidVersionSpecificationException.java index a57684420..75c6c0444 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/version/InvalidVersionSpecificationException.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/version/InvalidVersionSpecificationException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,63 +16,57 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.version; import org.eclipse.aether.RepositoryException; /** * Thrown when a version or version range could not be parsed. */ -public class InvalidVersionSpecificationException - extends RepositoryException -{ +public class InvalidVersionSpecificationException extends RepositoryException { private final String version; /** * Creates a new exception with the specified version and detail message. - * + * * @param version The invalid version specification, may be {@code null}. * @param message The detail message, may be {@code null}. */ - public InvalidVersionSpecificationException( String version, String message ) - { - super( message ); + public InvalidVersionSpecificationException(String version, String message) { + super(message); this.version = version; } /** * Creates a new exception with the specified version and cause. - * + * * @param version The invalid version specification, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public InvalidVersionSpecificationException( String version, Throwable cause ) - { - super( "Could not parse version specification " + version + getMessage( ": ", cause ), cause ); + public InvalidVersionSpecificationException(String version, Throwable cause) { + super("Could not parse version specification " + version + getMessage(": ", cause), cause); this.version = version; } /** * Creates a new exception with the specified version, detail message and cause. - * + * * @param version The invalid version specification, may be {@code null}. * @param message The detail message, may be {@code null}. * @param cause The exception that caused this one, may be {@code null}. */ - public InvalidVersionSpecificationException( String version, String message, Throwable cause ) - { - super( message, cause ); + public InvalidVersionSpecificationException(String version, String message, Throwable cause) { + super(message, cause); this.version = version; } /** * Gets the version or version range that could not be parsed. - * + * * @return The invalid version specification or {@code null} if unknown. */ - public String getVersion() - { + public String getVersion() { return version; } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/version/Version.java b/maven-resolver-api/src/main/java/org/eclipse/aether/version/Version.java index 41c02c008..c53daf91a 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/version/Version.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/version/Version.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,19 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.version; /** * A parsed artifact version. */ -public interface Version - extends Comparable -{ +public interface Version extends Comparable { /** * Gets the original string representation of the version. - * + * * @return The string representation of the version, never {@code null}. */ String toString(); - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionConstraint.java b/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionConstraint.java index 1c685870e..4c568b735 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionConstraint.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionConstraint.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,25 +16,25 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.version; /** * A constraint on versions for a dependency. A constraint can either consist of a version range (e.g. "[1, ]") or a * single version (e.g. "1.1"). In the first case, the constraint expresses a hard requirement on a version matching the * range. In the second case, the constraint expresses a soft requirement on a specific version (i.e. a recommendation). */ -public interface VersionConstraint -{ +public interface VersionConstraint { /** * Gets the version range of this constraint. - * + * * @return The version range or {@code null} if none. */ VersionRange getRange(); /** * Gets the version recommended by this constraint. - * + * * @return The recommended version or {@code null} if none. */ Version getVersion(); @@ -45,10 +43,9 @@ public interface VersionConstraint * Determines whether the specified version satisfies this constraint. In more detail, a version satisfies this * constraint if it matches its version range or if this constraint has no version range and the specified version * equals the version recommended by the constraint. - * + * * @param version The version to test, must not be {@code null}. * @return {@code true} if the specified version satisfies this constraint, {@code false} otherwise. */ - boolean containsVersion( Version version ); - + boolean containsVersion(Version version); } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionRange.java b/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionRange.java index bca24d201..d9c8bc411 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionRange.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionRange.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,27 +16,27 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.version; import static java.util.Objects.requireNonNull; /** * A range of versions. */ -public interface VersionRange -{ +public interface VersionRange { /** * Determines whether the specified version is contained within this range. - * + * * @param version The version to test, must not be {@code null}. * @return {@code true} if this range contains the specified version, {@code false} otherwise. */ - boolean containsVersion( Version version ); + boolean containsVersion(Version version); /** * Gets a lower bound (if any) for this range. If existent, this range does not contain any version smaller than its * lower bound. Note that complex version ranges might exclude some versions even within their bounds. - * + * * @return A lower bound for this range or {@code null} is there is none. */ Bound getLowerBound(); @@ -46,7 +44,7 @@ public interface VersionRange /** * Gets an upper bound (if any) for this range. If existent, this range does not contain any version greater than * its upper bound. Note that complex version ranges might exclude some versions even within their bounds. - * + * * @return An upper bound for this range or {@code null} is there is none. */ Bound getUpperBound(); @@ -54,8 +52,7 @@ public interface VersionRange /** * A bound of a version range. */ - final class Bound - { + final class Bound { private final Version version; @@ -67,9 +64,8 @@ final class Bound * @param version The bounding version, must not be {@code null}. * @param inclusive A flag whether the specified version is included in the range or not. */ - public Bound( Version version, boolean inclusive ) - { - this.version = requireNonNull( version, "version cannot be null" ); + public Bound(Version version, boolean inclusive) { + this.version = requireNonNull(version, "version cannot be null"); this.inclusive = inclusive; } @@ -78,52 +74,42 @@ public Bound( Version version, boolean inclusive ) * * @return The bounding version, never {@code null}. */ - public Version getVersion() - { + public Version getVersion() { return version; } /** * Indicates whether the bounding version is included in the range or not. - * + * * @return {@code true} if the bounding version is included in the range, {@code false} if not. */ - public boolean isInclusive() - { + public boolean isInclusive() { return inclusive; } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + } else if (obj == null || !getClass().equals(obj.getClass())) { return false; } Bound that = (Bound) obj; - return inclusive == that.inclusive && version.equals( that.version ); + return inclusive == that.inclusive && version.equals(that.version); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + version.hashCode(); - hash = hash * 31 + ( inclusive ? 1 : 0 ); + hash = hash * 31 + (inclusive ? 1 : 0); return hash; } @Override - public String toString() - { - return String.valueOf( version ); + public String toString() { + return String.valueOf(version); } - } - } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionScheme.java b/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionScheme.java index c765a0377..0587d4595 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionScheme.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/version/VersionScheme.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,42 +16,38 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.version; /** * A version scheme that handles interpretation of version strings to facilitate their comparison. */ -public interface VersionScheme -{ +public interface VersionScheme { /** * Parses the specified version string, for example "1.0". - * + * * @param version The version string to parse, must not be {@code null}. * @return The parsed version, never {@code null}. * @throws InvalidVersionSpecificationException If the string violates the syntax rules of this scheme. */ - Version parseVersion( String version ) - throws InvalidVersionSpecificationException; + Version parseVersion(String version) throws InvalidVersionSpecificationException; /** * Parses the specified version range specification, for example "[1.0,2.0)". - * + * * @param range The range specification to parse, must not be {@code null}. * @return The parsed version range, never {@code null}. * @throws InvalidVersionSpecificationException If the range specification violates the syntax rules of this scheme. */ - VersionRange parseVersionRange( String range ) - throws InvalidVersionSpecificationException; + VersionRange parseVersionRange(String range) throws InvalidVersionSpecificationException; /** * Parses the specified version constraint specification, for example "1.0" or "[1.0,2.0),(2.0,)". - * + * * @param constraint The constraint specification to parse, must not be {@code null}. * @return The parsed version constraint, never {@code null}. * @throws InvalidVersionSpecificationException If the constraint specification violates the syntax rules of this * scheme. */ - VersionConstraint parseVersionConstraint( final String constraint ) - throws InvalidVersionSpecificationException; - + VersionConstraint parseVersionConstraint(String constraint) throws InvalidVersionSpecificationException; } diff --git a/maven-resolver-api/src/main/java/org/eclipse/aether/version/package-info.java b/maven-resolver-api/src/main/java/org/eclipse/aether/version/package-info.java index a16dd64dc..d6901d47a 100644 --- a/maven-resolver-api/src/main/java/org/eclipse/aether/version/package-info.java +++ b/maven-resolver-api/src/main/java/org/eclipse/aether/version/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * The definition of a version scheme for parsing and comparing versions. */ package org.eclipse.aether.version; - diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/AbstractForwardingRepositorySystemSessionTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/AbstractForwardingRepositorySystemSessionTest.java index 5ad24758d..1dd24ed66 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/AbstractForwardingRepositorySystemSessionTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/AbstractForwardingRepositorySystemSessionTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,27 +16,22 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether; import java.lang.reflect.Method; import org.junit.Test; -public class AbstractForwardingRepositorySystemSessionTest -{ +import static org.junit.Assert.*; + +public class AbstractForwardingRepositorySystemSessionTest { @Test - public void testAllMethodsImplemented() - throws Exception - { - for ( Method method : RepositorySystemSession.class.getMethods() ) - { - Method m = - AbstractForwardingRepositorySystemSession.class.getDeclaredMethod( method.getName(), - method.getParameterTypes() ); - assertNotNull( method.toString(), m ); + public void testAllMethodsImplemented() throws Exception { + for (Method method : RepositorySystemSession.class.getMethods()) { + Method m = AbstractForwardingRepositorySystemSession.class.getDeclaredMethod( + method.getName(), method.getParameterTypes()); + assertNotNull(method.toString(), m); } } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/AbstractRepositoryListenerTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/AbstractRepositoryListenerTest.java index 74c617f45..39302e93e 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/AbstractRepositoryListenerTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/AbstractRepositoryListenerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,29 +16,23 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether; import java.lang.reflect.Method; -import org.eclipse.aether.AbstractRepositoryListener; -import org.eclipse.aether.RepositoryListener; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class AbstractRepositoryListenerTest -{ +public class AbstractRepositoryListenerTest { @Test - public void testAllEventTypesHandled() - throws Exception - { - for ( Method method : RepositoryListener.class.getMethods() ) - { - assertNotNull( AbstractRepositoryListener.class.getDeclaredMethod( method.getName(), - method.getParameterTypes() ) ); + public void testAllEventTypesHandled() throws Exception { + for (Method method : RepositoryListener.class.getMethods()) { + assertNotNull( + AbstractRepositoryListener.class.getDeclaredMethod(method.getName(), method.getParameterTypes())); } } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultRepositoryCacheTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultRepositoryCacheTest.java index 0586d8bee..596900451 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultRepositoryCacheTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultRepositoryCacheTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,95 +16,78 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; -public class DefaultRepositoryCacheTest -{ +import static org.junit.Assert.*; + +public class DefaultRepositoryCacheTest { private DefaultRepositoryCache cache = new DefaultRepositoryCache(); private RepositorySystemSession session = new DefaultRepositorySystemSession(); - private Object get( Object key ) - { - return cache.get( session, key ); + private Object get(Object key) { + return cache.get(session, key); } - private void put( Object key, Object value ) - { - cache.put( session, key, value ); + private void put(Object key, Object value) { + cache.put(session, key, value); } - @Test( expected = RuntimeException.class ) - public void testGet_NullKey() - { - get( null ); + @Test(expected = RuntimeException.class) + public void testGet_NullKey() { + get(null); } - @Test( expected = RuntimeException.class ) - public void testPut_NullKey() - { - put( null, "data" ); + @Test(expected = RuntimeException.class) + public void testPut_NullKey() { + put(null, "data"); } @Test - public void testGetPut() - { + public void testGetPut() { Object key = "key"; - assertNull( get( key ) ); - put( key, "value" ); - assertEquals( "value", get( key ) ); - put( key, "changed" ); - assertEquals( "changed", get( key ) ); - put( key, null ); - assertNull( get( key ) ); + assertNull(get(key)); + put(key, "value"); + assertEquals("value", get(key)); + put(key, "changed"); + assertEquals("changed", get(key)); + put(key, null); + assertNull(get(key)); } - @Test( timeout = 10000L ) - public void testConcurrency() - throws Exception - { + @Test(timeout = 10000L) + public void testConcurrency() throws Exception { final AtomicReference error = new AtomicReference<>(); Thread[] threads = new Thread[20]; - for ( int i = 0; i < threads.length; i++ ) - { - threads[i] = new Thread() - { + for (int i = 0; i < threads.length; i++) { + threads[i] = new Thread() { @Override - public void run() - { - for ( int i = 0; i < 100; i++ ) - { + public void run() { + for (int i = 0; i < 100; i++) { String key = UUID.randomUUID().toString(); - try - { - put( key, Boolean.TRUE ); - assertEquals( Boolean.TRUE, get( key ) ); - } - catch ( Throwable t ) - { - error.compareAndSet( null, t ); + try { + put(key, Boolean.TRUE); + assertEquals(Boolean.TRUE, get(key)); + } catch (Throwable t) { + error.compareAndSet(null, t); t.printStackTrace(); } } } }; } - for ( Thread thread : threads ) - { + for (Thread thread : threads) { thread.start(); } - for ( Thread thread : threads ) - { + for (Thread thread : threads) { thread.join(); } - assertNull( String.valueOf( error.get() ), error.get() ); + assertNull(String.valueOf(error.get()), error.get()); } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultRepositorySystemSessionTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultRepositorySystemSessionTest.java index 1fe084640..371b53633 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultRepositorySystemSessionTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultRepositorySystemSessionTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,10 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +package org.eclipse.aether; import java.lang.reflect.Method; import java.util.Map; @@ -34,117 +29,98 @@ import org.junit.Test; import org.mockito.Mockito; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + /** */ -public class DefaultRepositorySystemSessionTest -{ +public class DefaultRepositorySystemSessionTest { @Test - public void testDefaultProxySelectorUsesExistingProxy() - { + public void testDefaultProxySelectorUsesExistingProxy() { DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(); - RemoteRepository repo = new RemoteRepository.Builder( "id", "default", "void" ).build(); - assertSame( null, session.getProxySelector().getProxy( repo ) ); + RemoteRepository repo = new RemoteRepository.Builder("id", "default", "void").build(); + assertSame(null, session.getProxySelector().getProxy(repo)); - Proxy proxy = new Proxy( "http", "localhost", 8080, null ); - repo = new RemoteRepository.Builder( repo ).setProxy( proxy ).build(); - assertSame( proxy, session.getProxySelector().getProxy( repo ) ); + Proxy proxy = new Proxy("http", "localhost", 8080, null); + repo = new RemoteRepository.Builder(repo).setProxy(proxy).build(); + assertSame(proxy, session.getProxySelector().getProxy(repo)); } @Test - public void testDefaultAuthenticationSelectorUsesExistingAuth() - { + public void testDefaultAuthenticationSelectorUsesExistingAuth() { DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(); - RemoteRepository repo = new RemoteRepository.Builder( "id", "default", "void" ).build(); - assertSame( null, session.getAuthenticationSelector().getAuthentication( repo ) ); + RemoteRepository repo = new RemoteRepository.Builder("id", "default", "void").build(); + assertSame(null, session.getAuthenticationSelector().getAuthentication(repo)); - Authentication auth = new Authentication() - { - public void fill( AuthenticationContext context, String key, Map data ) - { - } + Authentication auth = new Authentication() { + public void fill(AuthenticationContext context, String key, Map data) {} - public void digest( AuthenticationDigest digest ) - { - } + public void digest(AuthenticationDigest digest) {} }; - repo = new RemoteRepository.Builder( repo ).setAuthentication( auth ).build(); - assertSame( auth, session.getAuthenticationSelector().getAuthentication( repo ) ); + repo = new RemoteRepository.Builder(repo).setAuthentication(auth).build(); + assertSame(auth, session.getAuthenticationSelector().getAuthentication(repo)); } @Test - public void testCopyConstructorCopiesPropertiesDeep() - { + public void testCopyConstructorCopiesPropertiesDeep() { DefaultRepositorySystemSession session1 = new DefaultRepositorySystemSession(); - session1.setUserProperties( System.getProperties() ); - session1.setSystemProperties( System.getProperties() ); - session1.setConfigProperties( System.getProperties() ); - - DefaultRepositorySystemSession session2 = new DefaultRepositorySystemSession( session1 ); - session2.setUserProperty( "key", "test" ); - session2.setSystemProperty( "key", "test" ); - session2.setConfigProperty( "key", "test" ); - - assertNull( session1.getUserProperties().get( "key" ) ); - assertNull( session1.getSystemProperties().get( "key" ) ); - assertNull( session1.getConfigProperties().get( "key" ) ); + session1.setUserProperties(System.getProperties()); + session1.setSystemProperties(System.getProperties()); + session1.setConfigProperties(System.getProperties()); + + DefaultRepositorySystemSession session2 = new DefaultRepositorySystemSession(session1); + session2.setUserProperty("key", "test"); + session2.setSystemProperty("key", "test"); + session2.setConfigProperty("key", "test"); + + assertNull(session1.getUserProperties().get("key")); + assertNull(session1.getSystemProperties().get("key")); + assertNull(session1.getConfigProperties().get("key")); } @Test - public void testReadOnlyProperties() - { + public void testReadOnlyProperties() { DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(); - try - { - session.getUserProperties().put( "key", "test" ); - fail( "user properties are modifiable" ); - } - catch ( UnsupportedOperationException e ) - { + try { + session.getUserProperties().put("key", "test"); + fail("user properties are modifiable"); + } catch (UnsupportedOperationException e) { // expected } - try - { - session.getSystemProperties().put( "key", "test" ); - fail( "system properties are modifiable" ); - } - catch ( UnsupportedOperationException e ) - { + try { + session.getSystemProperties().put("key", "test"); + fail("system properties are modifiable"); + } catch (UnsupportedOperationException e) { // expected } - try - { - session.getConfigProperties().put( "key", "test" ); - fail( "config properties are modifiable" ); - } - catch ( UnsupportedOperationException e ) - { + try { + session.getConfigProperties().put("key", "test"); + fail("config properties are modifiable"); + } catch (UnsupportedOperationException e) { // expected } } - @Test - public void testCopyRepositorySystemSession() throws Exception - { - RepositorySystemSession session = Mockito.mock( RepositorySystemSession.class, Mockito.RETURNS_MOCKS ); + public void testCopyRepositorySystemSession() throws Exception { + RepositorySystemSession session = Mockito.mock(RepositorySystemSession.class, Mockito.RETURNS_MOCKS); - RepositorySystemSession newSession = new DefaultRepositorySystemSession( session ); + RepositorySystemSession newSession = new DefaultRepositorySystemSession(session); Method[] methods = RepositorySystemSession.class.getMethods(); - for ( Method method : methods ) - { - if ( method.getParameterCount() == 0 ) - { - assertEquals( method.getName(), method.invoke( session ) == null, method.invoke( newSession ) == null ); + for (Method method : methods) { + if (method.getParameterCount() == 0) { + assertEquals(method.getName(), method.invoke(session) == null, method.invoke(newSession) == null); } } } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultSessionDataTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultSessionDataTest.java index 50b0683e1..f59eaaab9 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultSessionDataTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/DefaultSessionDataTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,136 +16,115 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Function; import java.util.function.Supplier; import org.junit.Test; -public class DefaultSessionDataTest -{ +import static org.junit.Assert.*; + +public class DefaultSessionDataTest { private DefaultSessionData data = new DefaultSessionData(); - private Object get( Object key ) - { - return data.get( key ); + private Object get(Object key) { + return data.get(key); } - private void set( Object key, Object value ) - { - data.set( key, value ); + private void set(Object key, Object value) { + data.set(key, value); } - private boolean set( Object key, Object oldValue, Object newValue ) - { - return data.set( key, oldValue, newValue ); + private boolean set(Object key, Object oldValue, Object newValue) { + return data.set(key, oldValue, newValue); } - private Object computeIfAbsent( Object key, Supplier supplier ) - { - return data.computeIfAbsent( key, supplier ); + private Object computeIfAbsent(Object key, Supplier supplier) { + return data.computeIfAbsent(key, supplier); } - @Test( expected = RuntimeException.class ) - public void testGet_NullKey() - { - get( null ); + @Test(expected = RuntimeException.class) + public void testGet_NullKey() { + get(null); } - @Test( expected = RuntimeException.class ) - public void testSet_NullKey() - { - set( null, "data" ); + @Test(expected = RuntimeException.class) + public void testSet_NullKey() { + set(null, "data"); } @Test - public void testGetSet() - { + public void testGetSet() { Object key = "key"; - assertNull( get( key ) ); - set( key, "value" ); - assertEquals( "value", get( key ) ); - set( key, "changed" ); - assertEquals( "changed", get( key ) ); - set( key, null ); - assertNull( get( key ) ); + assertNull(get(key)); + set(key, "value"); + assertEquals("value", get(key)); + set(key, "changed"); + assertEquals("changed", get(key)); + set(key, null); + assertNull(get(key)); } @Test - public void testGetSafeSet() - { + public void testGetSafeSet() { Object key = "key"; - assertNull( get( key ) ); - assertFalse( set( key, "wrong", "value" ) ); - assertNull( get( key ) ); - assertTrue( set( key, null, "value" ) ); - assertEquals( "value", get( key ) ); - assertTrue( set( key, "value", "value" ) ); - assertEquals( "value", get( key ) ); - assertFalse( set( key, "wrong", "changed" ) ); - assertEquals( "value", get( key ) ); - assertTrue( set( key, "value", "changed" ) ); - assertEquals( "changed", get( key ) ); - assertFalse( set( key, "wrong", null ) ); - assertEquals( "changed", get( key ) ); - assertTrue( set( key, "changed", null ) ); - assertNull( get( key ) ); - assertTrue( set( key, null, null ) ); - assertNull( get( key ) ); + assertNull(get(key)); + assertFalse(set(key, "wrong", "value")); + assertNull(get(key)); + assertTrue(set(key, null, "value")); + assertEquals("value", get(key)); + assertTrue(set(key, "value", "value")); + assertEquals("value", get(key)); + assertFalse(set(key, "wrong", "changed")); + assertEquals("value", get(key)); + assertTrue(set(key, "value", "changed")); + assertEquals("changed", get(key)); + assertFalse(set(key, "wrong", null)); + assertEquals("changed", get(key)); + assertTrue(set(key, "changed", null)); + assertNull(get(key)); + assertTrue(set(key, null, null)); + assertNull(get(key)); } @Test - public void testComputeIfAbsent() - { + public void testComputeIfAbsent() { Object key = "key"; - assertNull( get( key ) ); - assertEquals( "value", computeIfAbsent( key, () -> "value" ) ); - assertEquals( "value", computeIfAbsent( key, () -> "changed" ) ); + assertNull(get(key)); + assertEquals("value", computeIfAbsent(key, () -> "value")); + assertEquals("value", computeIfAbsent(key, () -> "changed")); } - @Test( timeout = 10000L ) - public void testConcurrency() - throws Exception - { + @Test(timeout = 10000L) + public void testConcurrency() throws Exception { final AtomicReference error = new AtomicReference<>(); Thread[] threads = new Thread[20]; - for ( int i = 0; i < threads.length; i++ ) - { - threads[i] = new Thread() - { + for (int i = 0; i < threads.length; i++) { + threads[i] = new Thread() { @Override - public void run() - { - for ( int i = 0; i < 100; i++ ) - { + public void run() { + for (int i = 0; i < 100; i++) { String key = UUID.randomUUID().toString(); - try - { - set( key, Boolean.TRUE ); - assertEquals( Boolean.TRUE, get( key ) ); - } - catch ( Throwable t ) - { - error.compareAndSet( null, t ); + try { + set(key, Boolean.TRUE); + assertEquals(Boolean.TRUE, get(key)); + } catch (Throwable t) { + error.compareAndSet(null, t); t.printStackTrace(); } } } }; } - for ( Thread thread : threads ) - { + for (Thread thread : threads) { thread.start(); } - for ( Thread thread : threads ) - { + for (Thread thread : threads) { thread.join(); } - assertNull( String.valueOf( error.get() ), error.get() ); + assertNull(String.valueOf(error.get()), error.get()); } } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/RepositoryExceptionTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/RepositoryExceptionTest.java index c3246be07..0b4e993fc 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/RepositoryExceptionTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/RepositoryExceptionTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -65,164 +64,140 @@ import org.eclipse.aether.transfer.RepositoryOfflineException; import org.junit.Test; -public class RepositoryExceptionTest -{ +public class RepositoryExceptionTest { - private void assertSerializable( RepositoryException e ) - { - try - { - ObjectOutputStream oos = new ObjectOutputStream( new ByteArrayOutputStream() ); - oos.writeObject( e ); + private void assertSerializable(RepositoryException e) { + try { + ObjectOutputStream oos = new ObjectOutputStream(new ByteArrayOutputStream()); + oos.writeObject(e); oos.close(); - } - catch ( IOException ioe ) - { - throw new IllegalStateException( ioe ); + } catch (IOException ioe) { + throw new IllegalStateException(ioe); } } - private RequestTrace newTrace() - { - return new RequestTrace( "test" ); + private RequestTrace newTrace() { + return new RequestTrace("test"); } - private Artifact newArtifact() - { - return new DefaultArtifact( "gid", "aid", "ext", "1" ); + private Artifact newArtifact() { + return new DefaultArtifact("gid", "aid", "ext", "1"); } - private Metadata newMetadata() - { - return new DefaultMetadata( "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); + private Metadata newMetadata() { + return new DefaultMetadata("maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); } - private RemoteRepository newRepo() - { - Proxy proxy = new Proxy( Proxy.TYPE_HTTP, "localhost", 8080, null ); - return new RemoteRepository.Builder( "id", "test", "http://localhost" ).setProxy( proxy ).build(); + private RemoteRepository newRepo() { + Proxy proxy = new Proxy(Proxy.TYPE_HTTP, "localhost", 8080, null); + return new RemoteRepository.Builder("id", "test", "http://localhost") + .setProxy(proxy) + .build(); } @Test - public void testArtifactDescriptorException_Serializable() - { + public void testArtifactDescriptorException_Serializable() { ArtifactDescriptorRequest request = new ArtifactDescriptorRequest(); - request.setArtifact( newArtifact() ).addRepository( newRepo() ).setTrace( newTrace() ); - ArtifactDescriptorResult result = new ArtifactDescriptorResult( request ); - assertSerializable( new ArtifactDescriptorException( result ) ); + request.setArtifact(newArtifact()).addRepository(newRepo()).setTrace(newTrace()); + ArtifactDescriptorResult result = new ArtifactDescriptorResult(request); + assertSerializable(new ArtifactDescriptorException(result)); } @Test - public void testArtifactResolutionException_Serializable() - { + public void testArtifactResolutionException_Serializable() { ArtifactRequest request = new ArtifactRequest(); - request.setArtifact( newArtifact() ).addRepository( newRepo() ).setTrace( newTrace() ); - ArtifactResult result = new ArtifactResult( request ); - assertSerializable( new ArtifactResolutionException( Arrays.asList( result ) ) ); + request.setArtifact(newArtifact()).addRepository(newRepo()).setTrace(newTrace()); + ArtifactResult result = new ArtifactResult(request); + assertSerializable(new ArtifactResolutionException(Arrays.asList(result))); } @Test - public void testArtifactTransferException_Serializable() - { - assertSerializable( new ArtifactTransferException( newArtifact(), newRepo(), "error" ) ); + public void testArtifactTransferException_Serializable() { + assertSerializable(new ArtifactTransferException(newArtifact(), newRepo(), "error")); } @Test - public void testArtifactNotFoundException_Serializable() - { - assertSerializable( new ArtifactNotFoundException( newArtifact(), newRepo(), "error" ) ); + public void testArtifactNotFoundException_Serializable() { + assertSerializable(new ArtifactNotFoundException(newArtifact(), newRepo(), "error")); } @Test - public void testDependencyCollectionException_Serializable() - { + public void testDependencyCollectionException_Serializable() { CollectRequest request = new CollectRequest(); - request.addDependency( new Dependency( newArtifact(), "compile" ) ); - request.addRepository( newRepo() ); - request.setTrace( newTrace() ); - CollectResult result = new CollectResult( request ); - assertSerializable( new DependencyCollectionException( result ) ); + request.addDependency(new Dependency(newArtifact(), "compile")); + request.addRepository(newRepo()); + request.setTrace(newTrace()); + CollectResult result = new CollectResult(request); + assertSerializable(new DependencyCollectionException(result)); } @Test - public void testDependencyResolutionException_Serializable() - { + public void testDependencyResolutionException_Serializable() { CollectRequest request = new CollectRequest(); - request.addDependency( new Dependency( newArtifact(), "compile" ) ); - request.addRepository( newRepo() ); - request.setTrace( newTrace() ); + request.addDependency(new Dependency(newArtifact(), "compile")); + request.addRepository(newRepo()); + request.setTrace(newTrace()); DependencyRequest req = new DependencyRequest(); - req.setTrace( newTrace() ); - req.setCollectRequest( request ); - DependencyResult result = new DependencyResult( req ); - assertSerializable( new DependencyResolutionException( result, null ) ); + req.setTrace(newTrace()); + req.setCollectRequest(request); + DependencyResult result = new DependencyResult(req); + assertSerializable(new DependencyResolutionException(result, null)); } @Test - public void testMetadataTransferException_Serializable() - { - assertSerializable( new MetadataTransferException( newMetadata(), newRepo(), "error" ) ); + public void testMetadataTransferException_Serializable() { + assertSerializable(new MetadataTransferException(newMetadata(), newRepo(), "error")); } @Test - public void testMetadataNotFoundException_Serializable() - { - assertSerializable( new MetadataNotFoundException( newMetadata(), newRepo(), "error" ) ); + public void testMetadataNotFoundException_Serializable() { + assertSerializable(new MetadataNotFoundException(newMetadata(), newRepo(), "error")); } @Test - public void testNoLocalRepositoryManagerException_Serializable() - { - assertSerializable( new NoLocalRepositoryManagerException( new LocalRepository( "/tmp" ) ) ); + public void testNoLocalRepositoryManagerException_Serializable() { + assertSerializable(new NoLocalRepositoryManagerException(new LocalRepository("/tmp"))); } @Test - public void testNoRepositoryConnectorException_Serializable() - { - assertSerializable( new NoRepositoryConnectorException( newRepo() ) ); + public void testNoRepositoryConnectorException_Serializable() { + assertSerializable(new NoRepositoryConnectorException(newRepo())); } @Test - public void testNoRepositoryLayoutException_Serializable() - { - assertSerializable( new NoRepositoryLayoutException( newRepo() ) ); + public void testNoRepositoryLayoutException_Serializable() { + assertSerializable(new NoRepositoryLayoutException(newRepo())); } @Test - public void testNoTransporterException_Serializable() - { - assertSerializable( new NoTransporterException( newRepo() ) ); + public void testNoTransporterException_Serializable() { + assertSerializable(new NoTransporterException(newRepo())); } @Test - public void testRepositoryOfflineException_Serializable() - { - assertSerializable( new RepositoryOfflineException( newRepo() ) ); + public void testRepositoryOfflineException_Serializable() { + assertSerializable(new RepositoryOfflineException(newRepo())); } @Test - public void testUnsolvableVersionConflictException_Serializable() - { - DependencyNode node = new DefaultDependencyNode( new Dependency( newArtifact(), "test" ) ); - assertSerializable( new UnsolvableVersionConflictException( Collections.singleton( Arrays.asList( node ) ) ) ); + public void testUnsolvableVersionConflictException_Serializable() { + DependencyNode node = new DefaultDependencyNode(new Dependency(newArtifact(), "test")); + assertSerializable(new UnsolvableVersionConflictException(Collections.singleton(Arrays.asList(node)))); } @Test - public void testVersionResolutionException_Serializable() - { + public void testVersionResolutionException_Serializable() { VersionRequest request = new VersionRequest(); - request.setArtifact( newArtifact() ).addRepository( newRepo() ).setTrace( newTrace() ); - VersionResult result = new VersionResult( request ); - assertSerializable( new VersionResolutionException( result ) ); + request.setArtifact(newArtifact()).addRepository(newRepo()).setTrace(newTrace()); + VersionResult result = new VersionResult(request); + assertSerializable(new VersionResolutionException(result)); } @Test - public void testVersionRangeResolutionException_Serializable() - { + public void testVersionRangeResolutionException_Serializable() { VersionRangeRequest request = new VersionRangeRequest(); - request.setArtifact( newArtifact() ).addRepository( newRepo() ).setTrace( newTrace() ); - VersionRangeResult result = new VersionRangeResult( request ); - assertSerializable( new VersionRangeResolutionException( result ) ); + request.setArtifact(newArtifact()).addRepository(newRepo()).setTrace(newTrace()); + VersionRangeResult result = new VersionRangeResult(request); + assertSerializable(new VersionRangeResolutionException(result)); } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/RequestTraceTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/RequestTraceTest.java index 63e5877ff..80e6a7813 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/RequestTraceTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/RequestTraceTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,45 +16,41 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class RequestTraceTest -{ +public class RequestTraceTest { @Test - public void testConstructor() - { - RequestTrace trace = new RequestTrace( null ); - assertSame( null, trace.getData() ); + public void testConstructor() { + RequestTrace trace = new RequestTrace(null); + assertSame(null, trace.getData()); - trace = new RequestTrace( this ); - assertSame( this, trace.getData() ); + trace = new RequestTrace(this); + assertSame(this, trace.getData()); } @Test - public void testParentChaining() - { - RequestTrace trace1 = new RequestTrace( null ); - RequestTrace trace2 = trace1.newChild( this ); - - assertSame( null, trace1.getParent() ); - assertSame( null, trace1.getData() ); - assertSame( trace1, trace2.getParent() ); - assertSame( this, trace2.getData() ); + public void testParentChaining() { + RequestTrace trace1 = new RequestTrace(null); + RequestTrace trace2 = trace1.newChild(this); + + assertSame(null, trace1.getParent()); + assertSame(null, trace1.getData()); + assertSame(trace1, trace2.getParent()); + assertSame(this, trace2.getData()); } @Test - public void testNewChildRequestTrace() - { - RequestTrace trace = RequestTrace.newChild( null, this ); - assertNotNull( trace ); - assertSame( null, trace.getParent() ); - assertSame( this, trace.getData() ); + public void testNewChildRequestTrace() { + RequestTrace trace = RequestTrace.newChild(null, this); + assertNotNull(trace); + assertSame(null, trace.getParent()); + assertSame(this, trace.getData()); } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/artifact/DefaultArtifactTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/artifact/DefaultArtifactTest.java index 7aec3e4d5..d8e02bfbc 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/artifact/DefaultArtifactTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/artifact/DefaultArtifactTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,177 +16,166 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.artifact; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.eclipse.aether.artifact.Artifact; -import org.eclipse.aether.artifact.ArtifactProperties; -import org.eclipse.aether.artifact.DefaultArtifact; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DefaultArtifactTest -{ +public class DefaultArtifactTest { @Test - public void testDefaultArtifactString() - { + public void testDefaultArtifactString() { Artifact a; - a = new DefaultArtifact( "gid:aid:ver" ); - assertEquals( "gid", a.getGroupId() ); - assertEquals( "aid", a.getArtifactId() ); - assertEquals( "ver", a.getVersion() ); - assertEquals( "ver", a.getBaseVersion() ); - assertEquals( "jar", a.getExtension() ); - assertEquals( "", a.getClassifier() ); - - a = new DefaultArtifact( "gid:aid:ext:ver" ); - assertEquals( "gid", a.getGroupId() ); - assertEquals( "aid", a.getArtifactId() ); - assertEquals( "ver", a.getVersion() ); - assertEquals( "ver", a.getBaseVersion() ); - assertEquals( "ext", a.getExtension() ); - assertEquals( "", a.getClassifier() ); - - a = new DefaultArtifact( "org.gid:foo-bar:jar:1.1-20101116.150650-3" ); - assertEquals( "org.gid", a.getGroupId() ); - assertEquals( "foo-bar", a.getArtifactId() ); - assertEquals( "1.1-20101116.150650-3", a.getVersion() ); - assertEquals( "1.1-SNAPSHOT", a.getBaseVersion() ); - assertEquals( "jar", a.getExtension() ); - assertEquals( "", a.getClassifier() ); - - a = new DefaultArtifact( "gid:aid:ext:cls:ver" ); - assertEquals( "gid", a.getGroupId() ); - assertEquals( "aid", a.getArtifactId() ); - assertEquals( "ver", a.getVersion() ); - assertEquals( "ver", a.getBaseVersion() ); - assertEquals( "ext", a.getExtension() ); - assertEquals( "cls", a.getClassifier() ); - - a = new DefaultArtifact( "gid:aid::cls:ver" ); - assertEquals( "gid", a.getGroupId() ); - assertEquals( "aid", a.getArtifactId() ); - assertEquals( "ver", a.getVersion() ); - assertEquals( "ver", a.getBaseVersion() ); - assertEquals( "jar", a.getExtension() ); - assertEquals( "cls", a.getClassifier() ); - - a = new DefaultArtifact( new DefaultArtifact( "gid:aid:ext:cls:ver" ).toString() ); - assertEquals( "gid", a.getGroupId() ); - assertEquals( "aid", a.getArtifactId() ); - assertEquals( "ver", a.getVersion() ); - assertEquals( "ver", a.getBaseVersion() ); - assertEquals( "ext", a.getExtension() ); - assertEquals( "cls", a.getClassifier() ); + a = new DefaultArtifact("gid:aid:ver"); + assertEquals("gid", a.getGroupId()); + assertEquals("aid", a.getArtifactId()); + assertEquals("ver", a.getVersion()); + assertEquals("ver", a.getBaseVersion()); + assertEquals("jar", a.getExtension()); + assertEquals("", a.getClassifier()); + + a = new DefaultArtifact("gid:aid:ext:ver"); + assertEquals("gid", a.getGroupId()); + assertEquals("aid", a.getArtifactId()); + assertEquals("ver", a.getVersion()); + assertEquals("ver", a.getBaseVersion()); + assertEquals("ext", a.getExtension()); + assertEquals("", a.getClassifier()); + + a = new DefaultArtifact("org.gid:foo-bar:jar:1.1-20101116.150650-3"); + assertEquals("org.gid", a.getGroupId()); + assertEquals("foo-bar", a.getArtifactId()); + assertEquals("1.1-20101116.150650-3", a.getVersion()); + assertEquals("1.1-SNAPSHOT", a.getBaseVersion()); + assertEquals("jar", a.getExtension()); + assertEquals("", a.getClassifier()); + + a = new DefaultArtifact("gid:aid:ext:cls:ver"); + assertEquals("gid", a.getGroupId()); + assertEquals("aid", a.getArtifactId()); + assertEquals("ver", a.getVersion()); + assertEquals("ver", a.getBaseVersion()); + assertEquals("ext", a.getExtension()); + assertEquals("cls", a.getClassifier()); + + a = new DefaultArtifact("gid:aid::cls:ver"); + assertEquals("gid", a.getGroupId()); + assertEquals("aid", a.getArtifactId()); + assertEquals("ver", a.getVersion()); + assertEquals("ver", a.getBaseVersion()); + assertEquals("jar", a.getExtension()); + assertEquals("cls", a.getClassifier()); + + a = new DefaultArtifact(new DefaultArtifact("gid:aid:ext:cls:ver").toString()); + assertEquals("gid", a.getGroupId()); + assertEquals("aid", a.getArtifactId()); + assertEquals("ver", a.getVersion()); + assertEquals("ver", a.getBaseVersion()); + assertEquals("ext", a.getExtension()); + assertEquals("cls", a.getClassifier()); } - @Test( expected = IllegalArgumentException.class ) - public void testDefaultArtifactContainsGroupAndArtifactOnly() - { - new DefaultArtifact( "gid:aid" ); + @Test(expected = IllegalArgumentException.class) + public void testDefaultArtifactContainsGroupAndArtifactOnly() { + new DefaultArtifact("gid:aid"); } - @Test( expected = IllegalArgumentException.class ) - public void testDefaultArtifactContainsGroupOnly() - { - new DefaultArtifact( "gid" ); + @Test(expected = IllegalArgumentException.class) + public void testDefaultArtifactContainsGroupOnly() { + new DefaultArtifact("gid"); } @Test - public void testImmutability() - { - Artifact a = new DefaultArtifact( "gid:aid:ext:cls:ver" ); - assertNotSame( a, a.setFile( new File( "file" ) ) ); - assertNotSame( a, a.setVersion( "otherVersion" ) ); - assertNotSame( a, a.setProperties( Collections.singletonMap( "key", "value" ) ) ); + public void testImmutability() { + Artifact a = new DefaultArtifact("gid:aid:ext:cls:ver"); + assertNotSame(a, a.setFile(new File("file"))); + assertNotSame(a, a.setVersion("otherVersion")); + assertNotSame(a, a.setProperties(Collections.singletonMap("key", "value"))); } @Test - public void testArtifactType() - { - DefaultArtifactType type = new DefaultArtifactType( "typeId", "typeExt", "typeCls", "typeLang", true, true ); - - Artifact a = new DefaultArtifact( "gid", "aid", null, null, null, null, type ); - assertEquals( "typeExt", a.getExtension() ); - assertEquals( "typeCls", a.getClassifier() ); - assertEquals( "typeLang", a.getProperties().get( ArtifactProperties.LANGUAGE ) ); - assertEquals( "typeId", a.getProperties().get( ArtifactProperties.TYPE ) ); - assertEquals( "true", a.getProperties().get( ArtifactProperties.INCLUDES_DEPENDENCIES ) ); - assertEquals( "true", a.getProperties().get( ArtifactProperties.CONSTITUTES_BUILD_PATH ) ); - - a = new DefaultArtifact( "gid", "aid", "cls", "ext", "ver", null, type ); - assertEquals( "ext", a.getExtension() ); - assertEquals( "cls", a.getClassifier() ); - assertEquals( "typeLang", a.getProperties().get( ArtifactProperties.LANGUAGE ) ); - assertEquals( "typeId", a.getProperties().get( ArtifactProperties.TYPE ) ); - assertEquals( "true", a.getProperties().get( ArtifactProperties.INCLUDES_DEPENDENCIES ) ); - assertEquals( "true", a.getProperties().get( ArtifactProperties.CONSTITUTES_BUILD_PATH ) ); + public void testArtifactType() { + DefaultArtifactType type = new DefaultArtifactType("typeId", "typeExt", "typeCls", "typeLang", true, true); + + Artifact a = new DefaultArtifact("gid", "aid", null, null, null, null, type); + assertEquals("typeExt", a.getExtension()); + assertEquals("typeCls", a.getClassifier()); + assertEquals("typeLang", a.getProperties().get(ArtifactProperties.LANGUAGE)); + assertEquals("typeId", a.getProperties().get(ArtifactProperties.TYPE)); + assertEquals("true", a.getProperties().get(ArtifactProperties.INCLUDES_DEPENDENCIES)); + assertEquals("true", a.getProperties().get(ArtifactProperties.CONSTITUTES_BUILD_PATH)); + + a = new DefaultArtifact("gid", "aid", "cls", "ext", "ver", null, type); + assertEquals("ext", a.getExtension()); + assertEquals("cls", a.getClassifier()); + assertEquals("typeLang", a.getProperties().get(ArtifactProperties.LANGUAGE)); + assertEquals("typeId", a.getProperties().get(ArtifactProperties.TYPE)); + assertEquals("true", a.getProperties().get(ArtifactProperties.INCLUDES_DEPENDENCIES)); + assertEquals("true", a.getProperties().get(ArtifactProperties.CONSTITUTES_BUILD_PATH)); Map props = new HashMap<>(); - props.put( "someNonStandardProperty", "someNonStandardProperty" ); - a = new DefaultArtifact( "gid", "aid", "cls", "ext", "ver", props, type ); - assertEquals( "ext", a.getExtension() ); - assertEquals( "cls", a.getClassifier() ); - assertEquals( "typeLang", a.getProperties().get( ArtifactProperties.LANGUAGE ) ); - assertEquals( "typeId", a.getProperties().get( ArtifactProperties.TYPE ) ); - assertEquals( "true", a.getProperties().get( ArtifactProperties.INCLUDES_DEPENDENCIES ) ); - assertEquals( "true", a.getProperties().get( ArtifactProperties.CONSTITUTES_BUILD_PATH ) ); - assertEquals( "someNonStandardProperty", a.getProperties().get( "someNonStandardProperty" ) ); + props.put("someNonStandardProperty", "someNonStandardProperty"); + a = new DefaultArtifact("gid", "aid", "cls", "ext", "ver", props, type); + assertEquals("ext", a.getExtension()); + assertEquals("cls", a.getClassifier()); + assertEquals("typeLang", a.getProperties().get(ArtifactProperties.LANGUAGE)); + assertEquals("typeId", a.getProperties().get(ArtifactProperties.TYPE)); + assertEquals("true", a.getProperties().get(ArtifactProperties.INCLUDES_DEPENDENCIES)); + assertEquals("true", a.getProperties().get(ArtifactProperties.CONSTITUTES_BUILD_PATH)); + assertEquals("someNonStandardProperty", a.getProperties().get("someNonStandardProperty")); props = new HashMap<>(); - props.put( "someNonStandardProperty", "someNonStandardProperty" ); - props.put( ArtifactProperties.CONSTITUTES_BUILD_PATH, "rubbish" ); - props.put( ArtifactProperties.INCLUDES_DEPENDENCIES, "rubbish" ); - a = new DefaultArtifact( "gid", "aid", "cls", "ext", "ver", props, type ); - assertEquals( "ext", a.getExtension() ); - assertEquals( "cls", a.getClassifier() ); - assertEquals( "typeLang", a.getProperties().get( ArtifactProperties.LANGUAGE ) ); - assertEquals( "typeId", a.getProperties().get( ArtifactProperties.TYPE ) ); - assertEquals( "rubbish", a.getProperties().get( ArtifactProperties.INCLUDES_DEPENDENCIES ) ); - assertEquals( "rubbish", a.getProperties().get( ArtifactProperties.CONSTITUTES_BUILD_PATH ) ); - assertEquals( "someNonStandardProperty", a.getProperties().get( "someNonStandardProperty" ) ); + props.put("someNonStandardProperty", "someNonStandardProperty"); + props.put(ArtifactProperties.CONSTITUTES_BUILD_PATH, "rubbish"); + props.put(ArtifactProperties.INCLUDES_DEPENDENCIES, "rubbish"); + a = new DefaultArtifact("gid", "aid", "cls", "ext", "ver", props, type); + assertEquals("ext", a.getExtension()); + assertEquals("cls", a.getClassifier()); + assertEquals("typeLang", a.getProperties().get(ArtifactProperties.LANGUAGE)); + assertEquals("typeId", a.getProperties().get(ArtifactProperties.TYPE)); + assertEquals("rubbish", a.getProperties().get(ArtifactProperties.INCLUDES_DEPENDENCIES)); + assertEquals("rubbish", a.getProperties().get(ArtifactProperties.CONSTITUTES_BUILD_PATH)); + assertEquals("someNonStandardProperty", a.getProperties().get("someNonStandardProperty")); } @Test - public void testPropertiesCopied() - { + public void testPropertiesCopied() { Map props = new HashMap<>(); - props.put( "key", "value1" ); + props.put("key", "value1"); - Artifact a = new DefaultArtifact( "gid:aid:1", props ); - assertEquals( "value1", a.getProperty( "key", null ) ); + Artifact a = new DefaultArtifact("gid:aid:1", props); + assertEquals("value1", a.getProperty("key", null)); props.clear(); - assertEquals( "value1", a.getProperty( "key", null ) ); + assertEquals("value1", a.getProperty("key", null)); - props.put( "key", "value2" ); - a = a.setProperties( props ); - assertEquals( "value2", a.getProperty( "key", null ) ); + props.put("key", "value2"); + a = a.setProperties(props); + assertEquals("value2", a.getProperty("key", null)); props.clear(); - assertEquals( "value2", a.getProperty( "key", null ) ); + assertEquals("value2", a.getProperty("key", null)); } @Test - public void testIsSnapshot() - { - Artifact a = new DefaultArtifact( "gid:aid:ext:cls:1.0" ); - assertFalse( a.getVersion(), a.isSnapshot() ); + public void testIsSnapshot() { + Artifact a = new DefaultArtifact("gid:aid:ext:cls:1.0"); + assertFalse(a.getVersion(), a.isSnapshot()); - a = new DefaultArtifact( "gid:aid:ext:cls:1.0-SNAPSHOT" ); - assertTrue( a.getVersion(), a.isSnapshot() ); + a = new DefaultArtifact("gid:aid:ext:cls:1.0-SNAPSHOT"); + assertTrue(a.getVersion(), a.isSnapshot()); - a = new DefaultArtifact( "gid:aid:ext:cls:1.0-20101116.150650-3" ); - assertTrue( a.getVersion(), a.isSnapshot() ); + a = new DefaultArtifact("gid:aid:ext:cls:1.0-20101116.150650-3"); + assertTrue(a.getVersion(), a.isSnapshot()); - a = new DefaultArtifact( "gid:aid:ext:cls:1.0-20101116x150650-3" ); - assertFalse( a.getVersion(), a.isSnapshot() ); + a = new DefaultArtifact("gid:aid:ext:cls:1.0-20101116x150650-3"); + assertFalse(a.getVersion(), a.isSnapshot()); } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/graph/DependencyTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/graph/DependencyTest.java index c96746d9a..97178d258 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/graph/DependencyTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/graph/DependencyTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.graph; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,56 +16,53 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.graph; import java.util.Arrays; import java.util.Collections; import org.eclipse.aether.artifact.DefaultArtifact; -import org.eclipse.aether.graph.Dependency; -import org.eclipse.aether.graph.Exclusion; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DependencyTest -{ +public class DependencyTest { @Test - public void testSetScope() - { - Dependency d1 = new Dependency( new DefaultArtifact( "gid:aid:ver" ), "compile" ); + public void testSetScope() { + Dependency d1 = new Dependency(new DefaultArtifact("gid:aid:ver"), "compile"); - Dependency d2 = d1.setScope( null ); - assertNotSame( d2, d1 ); - assertEquals( "", d2.getScope() ); + Dependency d2 = d1.setScope(null); + assertNotSame(d2, d1); + assertEquals("", d2.getScope()); - Dependency d3 = d1.setScope( "test" ); - assertNotSame( d3, d1 ); - assertEquals( "test", d3.getScope() ); + Dependency d3 = d1.setScope("test"); + assertNotSame(d3, d1); + assertEquals("test", d3.getScope()); } @Test - public void testSetExclusions() - { - Dependency d1 = - new Dependency( new DefaultArtifact( "gid:aid:ver" ), "compile", false, - Collections.singleton( new Exclusion( "g", "a", "c", "e" ) ) ); + public void testSetExclusions() { + Dependency d1 = new Dependency( + new DefaultArtifact("gid:aid:ver"), + "compile", + false, + Collections.singleton(new Exclusion("g", "a", "c", "e"))); - Dependency d2 = d1.setExclusions( null ); - assertNotSame( d2, d1 ); - assertEquals( 0, d2.getExclusions().size() ); + Dependency d2 = d1.setExclusions(null); + assertNotSame(d2, d1); + assertEquals(0, d2.getExclusions().size()); - assertSame( d2, d2.setExclusions( null ) ); - assertSame( d2, d2.setExclusions( Collections. emptyList() ) ); - assertSame( d2, d2.setExclusions( Collections. emptySet() ) ); - assertSame( d1, d1.setExclusions( Arrays.asList( new Exclusion( "g", "a", "c", "e" ) ) ) ); + assertSame(d2, d2.setExclusions(null)); + assertSame(d2, d2.setExclusions(Collections.emptyList())); + assertSame(d2, d2.setExclusions(Collections.emptySet())); + assertSame(d1, d1.setExclusions(Arrays.asList(new Exclusion("g", "a", "c", "e")))); Dependency d3 = - d1.setExclusions( Arrays.asList( new Exclusion( "g", "a", "c", "e" ), new Exclusion( "g", "a", "c", "f" ) ) ); - assertNotSame( d3, d1 ); - assertEquals( 2, d3.getExclusions().size() ); + d1.setExclusions(Arrays.asList(new Exclusion("g", "a", "c", "e"), new Exclusion("g", "a", "c", "f"))); + assertNotSame(d3, d1); + assertEquals(2, d3.getExclusions().size()); } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/repository/AuthenticationContextTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/repository/AuthenticationContextTest.java index 6d579a103..18d26fceb 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/repository/AuthenticationContextTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/repository/AuthenticationContextTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.repository; import java.io.File; import java.util.Map; @@ -28,143 +25,129 @@ import org.eclipse.aether.RepositorySystemSession; import org.junit.Test; -public class AuthenticationContextTest -{ +import static org.junit.Assert.*; + +public class AuthenticationContextTest { - private RepositorySystemSession newSession() - { + private RepositorySystemSession newSession() { return new DefaultRepositorySystemSession(); } - private RemoteRepository newRepo( Authentication auth, Proxy proxy ) - { - return new RemoteRepository.Builder( "test", "default", "http://localhost" ) // - .setAuthentication( auth ).setProxy( proxy ).build(); + private RemoteRepository newRepo(Authentication auth, Proxy proxy) { + return new RemoteRepository.Builder("test", "default", "http://localhost") // + .setAuthentication(auth) + .setProxy(proxy) + .build(); } - private Proxy newProxy( Authentication auth ) - { - return new Proxy( Proxy.TYPE_HTTP, "localhost", 8080, auth ); + private Proxy newProxy(Authentication auth) { + return new Proxy(Proxy.TYPE_HTTP, "localhost", 8080, auth); } - private Authentication newAuth() - { - return new Authentication() - { - public void fill( AuthenticationContext context, String key, Map data ) - { - assertNotNull( context ); - assertNotNull( context.getSession() ); - assertNotNull( context.getRepository() ); - assertNull( "fill() should only be called once", context.get( "key" ) ); - context.put( "key", "value" ); + private Authentication newAuth() { + return new Authentication() { + public void fill(AuthenticationContext context, String key, Map data) { + assertNotNull(context); + assertNotNull(context.getSession()); + assertNotNull(context.getRepository()); + assertNull("fill() should only be called once", context.get("key")); + context.put("key", "value"); } - public void digest( AuthenticationDigest digest ) - { - fail( "AuthenticationContext should not call digest()" ); + public void digest(AuthenticationDigest digest) { + fail("AuthenticationContext should not call digest()"); } }; } @Test - public void testForRepository() - { + public void testForRepository() { RepositorySystemSession session = newSession(); - RemoteRepository repo = newRepo( newAuth(), newProxy( newAuth() ) ); - AuthenticationContext context = AuthenticationContext.forRepository( session, repo ); - assertNotNull( context ); - assertSame( session, context.getSession() ); - assertSame( repo, context.getRepository() ); - assertNull( context.getProxy() ); - assertEquals( "value", context.get( "key" ) ); - assertEquals( "value", context.get( "key" ) ); + RemoteRepository repo = newRepo(newAuth(), newProxy(newAuth())); + AuthenticationContext context = AuthenticationContext.forRepository(session, repo); + assertNotNull(context); + assertSame(session, context.getSession()); + assertSame(repo, context.getRepository()); + assertNull(context.getProxy()); + assertEquals("value", context.get("key")); + assertEquals("value", context.get("key")); } @Test - public void testForRepository_NoAuth() - { + public void testForRepository_NoAuth() { RepositorySystemSession session = newSession(); - RemoteRepository repo = newRepo( null, newProxy( newAuth() ) ); - AuthenticationContext context = AuthenticationContext.forRepository( session, repo ); - assertNull( context ); + RemoteRepository repo = newRepo(null, newProxy(newAuth())); + AuthenticationContext context = AuthenticationContext.forRepository(session, repo); + assertNull(context); } @Test - public void testForProxy() - { + public void testForProxy() { RepositorySystemSession session = newSession(); - Proxy proxy = newProxy( newAuth() ); - RemoteRepository repo = newRepo( newAuth(), proxy ); - AuthenticationContext context = AuthenticationContext.forProxy( session, repo ); - assertNotNull( context ); - assertSame( session, context.getSession() ); - assertSame( repo, context.getRepository() ); - assertSame( proxy, context.getProxy() ); - assertEquals( "value", context.get( "key" ) ); - assertEquals( "value", context.get( "key" ) ); + Proxy proxy = newProxy(newAuth()); + RemoteRepository repo = newRepo(newAuth(), proxy); + AuthenticationContext context = AuthenticationContext.forProxy(session, repo); + assertNotNull(context); + assertSame(session, context.getSession()); + assertSame(repo, context.getRepository()); + assertSame(proxy, context.getProxy()); + assertEquals("value", context.get("key")); + assertEquals("value", context.get("key")); } @Test - public void testForProxy_NoProxy() - { + public void testForProxy_NoProxy() { RepositorySystemSession session = newSession(); Proxy proxy = null; - RemoteRepository repo = newRepo( newAuth(), proxy ); - AuthenticationContext context = AuthenticationContext.forProxy( session, repo ); - assertNull( context ); + RemoteRepository repo = newRepo(newAuth(), proxy); + AuthenticationContext context = AuthenticationContext.forProxy(session, repo); + assertNull(context); } @Test - public void testForProxy_NoProxyAuth() - { + public void testForProxy_NoProxyAuth() { RepositorySystemSession session = newSession(); - Proxy proxy = newProxy( null ); - RemoteRepository repo = newRepo( newAuth(), proxy ); - AuthenticationContext context = AuthenticationContext.forProxy( session, repo ); - assertNull( context ); + Proxy proxy = newProxy(null); + RemoteRepository repo = newRepo(newAuth(), proxy); + AuthenticationContext context = AuthenticationContext.forProxy(session, repo); + assertNull(context); } @Test - public void testGet_StringVsChars() - { - AuthenticationContext context = AuthenticationContext.forRepository( newSession(), newRepo( newAuth(), null ) ); - context.put( "key", new char[] { 'v', 'a', 'l', '1' } ); - assertEquals( "val1", context.get( "key" ) ); - context.put( "key", "val2" ); - assertArrayEquals( new char[] { 'v', 'a', 'l', '2' }, context.get( "key", char[].class ) ); + public void testGet_StringVsChars() { + AuthenticationContext context = AuthenticationContext.forRepository(newSession(), newRepo(newAuth(), null)); + context.put("key", new char[] {'v', 'a', 'l', '1'}); + assertEquals("val1", context.get("key")); + context.put("key", "val2"); + assertArrayEquals(new char[] {'v', 'a', 'l', '2'}, context.get("key", char[].class)); } @Test - public void testGet_StringVsFile() - { - AuthenticationContext context = AuthenticationContext.forRepository( newSession(), newRepo( newAuth(), null ) ); - context.put( "key", "val1" ); - assertEquals( new File( "val1" ), context.get( "key", File.class ) ); - context.put( "key", new File( "val2" ) ); - assertEquals( "val2", context.get( "key" ) ); + public void testGet_StringVsFile() { + AuthenticationContext context = AuthenticationContext.forRepository(newSession(), newRepo(newAuth(), null)); + context.put("key", "val1"); + assertEquals(new File("val1"), context.get("key", File.class)); + context.put("key", new File("val2")); + assertEquals("val2", context.get("key")); } @Test - public void testPut_EraseCharArrays() - { - AuthenticationContext context = AuthenticationContext.forRepository( newSession(), newRepo( newAuth(), null ) ); - char[] secret = { 'v', 'a', 'l', 'u', 'e' }; - context.put( "key", secret ); - context.put( "key", secret.clone() ); - assertArrayEquals( new char[] { 0, 0, 0, 0, 0 }, secret ); + public void testPut_EraseCharArrays() { + AuthenticationContext context = AuthenticationContext.forRepository(newSession(), newRepo(newAuth(), null)); + char[] secret = {'v', 'a', 'l', 'u', 'e'}; + context.put("key", secret); + context.put("key", secret.clone()); + assertArrayEquals(new char[] {0, 0, 0, 0, 0}, secret); } @Test - public void testClose_EraseCharArrays() - { - AuthenticationContext.close( null ); - - AuthenticationContext context = AuthenticationContext.forRepository( newSession(), newRepo( newAuth(), null ) ); - char[] secret = { 'v', 'a', 'l', 'u', 'e' }; - context.put( "key", secret ); - AuthenticationContext.close( context ); - assertArrayEquals( new char[] { 0, 0, 0, 0, 0 }, secret ); + public void testClose_EraseCharArrays() { + AuthenticationContext.close(null); + + AuthenticationContext context = AuthenticationContext.forRepository(newSession(), newRepo(newAuth(), null)); + char[] secret = {'v', 'a', 'l', 'u', 'e'}; + context.put("key", secret); + AuthenticationContext.close(context); + assertArrayEquals(new char[] {0, 0, 0, 0, 0}, secret); } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/repository/AuthenticationDigestTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/repository/AuthenticationDigestTest.java index 387a3da1c..edad59de0 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/repository/AuthenticationDigestTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/repository/AuthenticationDigestTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.repository; import java.util.Map; @@ -27,124 +24,112 @@ import org.eclipse.aether.RepositorySystemSession; import org.junit.Test; -public class AuthenticationDigestTest -{ +import static org.junit.Assert.*; + +public class AuthenticationDigestTest { - private RepositorySystemSession newSession() - { + private RepositorySystemSession newSession() { return new DefaultRepositorySystemSession(); } - private RemoteRepository newRepo( Authentication auth, Proxy proxy ) - { - return new RemoteRepository.Builder( "test", "default", "http://localhost" ) // - .setAuthentication( auth ).setProxy( proxy ).build(); + private RemoteRepository newRepo(Authentication auth, Proxy proxy) { + return new RemoteRepository.Builder("test", "default", "http://localhost") // + .setAuthentication(auth) + .setProxy(proxy) + .build(); } - private Proxy newProxy( Authentication auth ) - { - return new Proxy( Proxy.TYPE_HTTP, "localhost", 8080, auth ); + private Proxy newProxy(Authentication auth) { + return new Proxy(Proxy.TYPE_HTTP, "localhost", 8080, auth); } @Test - public void testForRepository() - { + public void testForRepository() { final RepositorySystemSession session = newSession(); - final RemoteRepository[] repos = { null }; + final RemoteRepository[] repos = {null}; - Authentication auth = new Authentication() - { - public void fill( AuthenticationContext context, String key, Map data ) - { - fail( "AuthenticationDigest should not call fill()" ); + Authentication auth = new Authentication() { + public void fill(AuthenticationContext context, String key, Map data) { + fail("AuthenticationDigest should not call fill()"); } - public void digest( AuthenticationDigest digest ) - { - assertNotNull( digest ); - assertSame( session, digest.getSession() ); - assertNotNull( digest.getRepository() ); - assertNull( digest.getProxy() ); - assertNull( "digest() should only be called once", repos[0] ); + public void digest(AuthenticationDigest digest) { + assertNotNull(digest); + assertSame(session, digest.getSession()); + assertNotNull(digest.getRepository()); + assertNull(digest.getProxy()); + assertNull("digest() should only be called once", repos[0]); repos[0] = digest.getRepository(); - digest.update( (byte[]) null ); - digest.update( (char[]) null ); - digest.update( (String[]) null ); - digest.update( null, null ); + digest.update((byte[]) null); + digest.update((char[]) null); + digest.update((String[]) null); + digest.update(null, null); } }; - RemoteRepository repo = newRepo( auth, newProxy( null ) ); + RemoteRepository repo = newRepo(auth, newProxy(null)); - String digest = AuthenticationDigest.forRepository( session, repo ); - assertSame( repo, repos[0] ); - assertNotNull( digest ); - assertTrue( digest.length() > 0 ); + String digest = AuthenticationDigest.forRepository(session, repo); + assertSame(repo, repos[0]); + assertNotNull(digest); + assertTrue(digest.length() > 0); } @Test - public void testForRepository_NoAuth() - { - RemoteRepository repo = newRepo( null, null ); + public void testForRepository_NoAuth() { + RemoteRepository repo = newRepo(null, null); - String digest = AuthenticationDigest.forRepository( newSession(), repo ); - assertEquals( "", digest ); + String digest = AuthenticationDigest.forRepository(newSession(), repo); + assertEquals("", digest); } @Test - public void testForProxy() - { + public void testForProxy() { final RepositorySystemSession session = newSession(); - final Proxy[] proxies = { null }; + final Proxy[] proxies = {null}; - Authentication auth = new Authentication() - { - public void fill( AuthenticationContext context, String key, Map data ) - { - fail( "AuthenticationDigest should not call fill()" ); + Authentication auth = new Authentication() { + public void fill(AuthenticationContext context, String key, Map data) { + fail("AuthenticationDigest should not call fill()"); } - public void digest( AuthenticationDigest digest ) - { - assertNotNull( digest ); - assertSame( session, digest.getSession() ); - assertNotNull( digest.getRepository() ); - assertNotNull( digest.getProxy() ); - assertNull( "digest() should only be called once", proxies[0] ); + public void digest(AuthenticationDigest digest) { + assertNotNull(digest); + assertSame(session, digest.getSession()); + assertNotNull(digest.getRepository()); + assertNotNull(digest.getProxy()); + assertNull("digest() should only be called once", proxies[0]); proxies[0] = digest.getProxy(); - digest.update( (byte[]) null ); - digest.update( (char[]) null ); - digest.update( (String[]) null ); - digest.update( null, null ); + digest.update((byte[]) null); + digest.update((char[]) null); + digest.update((String[]) null); + digest.update(null, null); } }; - Proxy proxy = newProxy( auth ); + Proxy proxy = newProxy(auth); - String digest = AuthenticationDigest.forProxy( session, newRepo( null, proxy ) ); - assertSame( proxy, proxies[0] ); - assertNotNull( digest ); - assertTrue( digest.length() > 0 ); + String digest = AuthenticationDigest.forProxy(session, newRepo(null, proxy)); + assertSame(proxy, proxies[0]); + assertNotNull(digest); + assertTrue(digest.length() > 0); } @Test - public void testForProxy_NoProxy() - { - RemoteRepository repo = newRepo( null, null ); + public void testForProxy_NoProxy() { + RemoteRepository repo = newRepo(null, null); - String digest = AuthenticationDigest.forProxy( newSession(), repo ); - assertEquals( "", digest ); + String digest = AuthenticationDigest.forProxy(newSession(), repo); + assertEquals("", digest); } @Test - public void testForProxy_NoProxyAuth() - { - RemoteRepository repo = newRepo( null, newProxy( null ) ); + public void testForProxy_NoProxyAuth() { + RemoteRepository repo = newRepo(null, newProxy(null)); - String digest = AuthenticationDigest.forProxy( newSession(), repo ); - assertEquals( "", digest ); + String digest = AuthenticationDigest.forProxy(newSession(), repo); + assertEquals("", digest); } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/repository/RemoteRepositoryBuilderTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/repository/RemoteRepositoryBuilderTest.java index 0d6b19041..d76fcb8e3 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/repository/RemoteRepositoryBuilderTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/repository/RemoteRepositoryBuilderTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.repository; import java.util.ArrayList; import java.util.Arrays; @@ -30,156 +27,143 @@ import org.junit.Before; import org.junit.Test; -public class RemoteRepositoryBuilderTest -{ +import static org.junit.Assert.*; + +public class RemoteRepositoryBuilderTest { private RemoteRepository prototype; @Before - public void init() - { - prototype = new Builder( "id", "type", "file:void" ).build(); + public void init() { + prototype = new Builder("id", "type", "file:void").build(); } @Test - public void testReusePrototype() - { - Builder builder = new Builder( prototype ); - assertSame( prototype, builder.build() ); + public void testReusePrototype() { + Builder builder = new Builder(prototype); + assertSame(prototype, builder.build()); } - @Test( expected = NullPointerException.class ) - public void testPrototypeMandatory() - { - new Builder( null ); + @Test(expected = NullPointerException.class) + public void testPrototypeMandatory() { + new Builder(null); } @Test - public void testSetId() - { - Builder builder = new Builder( prototype ); - RemoteRepository repo = builder.setId( prototype.getId() ).build(); - assertSame( prototype, repo ); - repo = builder.setId( "new-id" ).build(); - assertEquals( "new-id", repo.getId() ); + public void testSetId() { + Builder builder = new Builder(prototype); + RemoteRepository repo = builder.setId(prototype.getId()).build(); + assertSame(prototype, repo); + repo = builder.setId("new-id").build(); + assertEquals("new-id", repo.getId()); } @Test - public void testSetContentType() - { - Builder builder = new Builder( prototype ); - RemoteRepository repo = builder.setContentType( prototype.getContentType() ).build(); - assertSame( prototype, repo ); - repo = builder.setContentType( "new-type" ).build(); - assertEquals( "new-type", repo.getContentType() ); + public void testSetContentType() { + Builder builder = new Builder(prototype); + RemoteRepository repo = + builder.setContentType(prototype.getContentType()).build(); + assertSame(prototype, repo); + repo = builder.setContentType("new-type").build(); + assertEquals("new-type", repo.getContentType()); } @Test - public void testSetUrl() - { - Builder builder = new Builder( prototype ); - RemoteRepository repo = builder.setUrl( prototype.getUrl() ).build(); - assertSame( prototype, repo ); - repo = builder.setUrl( "file:new" ).build(); - assertEquals( "file:new", repo.getUrl() ); + public void testSetUrl() { + Builder builder = new Builder(prototype); + RemoteRepository repo = builder.setUrl(prototype.getUrl()).build(); + assertSame(prototype, repo); + repo = builder.setUrl("file:new").build(); + assertEquals("file:new", repo.getUrl()); } @Test - public void testSetPolicy() - { - Builder builder = new Builder( prototype ); - RemoteRepository repo = builder.setPolicy( prototype.getPolicy( false ) ).build(); - assertSame( prototype, repo ); - RepositoryPolicy policy = new RepositoryPolicy( true, "never", "fail" ); - repo = builder.setPolicy( policy ).build(); - assertEquals( policy, repo.getPolicy( true ) ); - assertEquals( policy, repo.getPolicy( false ) ); + public void testSetPolicy() { + Builder builder = new Builder(prototype); + RemoteRepository repo = builder.setPolicy(prototype.getPolicy(false)).build(); + assertSame(prototype, repo); + RepositoryPolicy policy = new RepositoryPolicy(true, "never", "fail"); + repo = builder.setPolicy(policy).build(); + assertEquals(policy, repo.getPolicy(true)); + assertEquals(policy, repo.getPolicy(false)); } @Test - public void testSetReleasePolicy() - { - Builder builder = new Builder( prototype ); - RemoteRepository repo = builder.setReleasePolicy( prototype.getPolicy( false ) ).build(); - assertSame( prototype, repo ); - RepositoryPolicy policy = new RepositoryPolicy( true, "never", "fail" ); - repo = builder.setReleasePolicy( policy ).build(); - assertEquals( policy, repo.getPolicy( false ) ); - assertEquals( prototype.getPolicy( true ), repo.getPolicy( true ) ); + public void testSetReleasePolicy() { + Builder builder = new Builder(prototype); + RemoteRepository repo = + builder.setReleasePolicy(prototype.getPolicy(false)).build(); + assertSame(prototype, repo); + RepositoryPolicy policy = new RepositoryPolicy(true, "never", "fail"); + repo = builder.setReleasePolicy(policy).build(); + assertEquals(policy, repo.getPolicy(false)); + assertEquals(prototype.getPolicy(true), repo.getPolicy(true)); } @Test - public void testSetSnapshotPolicy() - { - Builder builder = new Builder( prototype ); - RemoteRepository repo = builder.setSnapshotPolicy( prototype.getPolicy( true ) ).build(); - assertSame( prototype, repo ); - RepositoryPolicy policy = new RepositoryPolicy( true, "never", "fail" ); - repo = builder.setSnapshotPolicy( policy ).build(); - assertEquals( policy, repo.getPolicy( true ) ); - assertEquals( prototype.getPolicy( false ), repo.getPolicy( false ) ); + public void testSetSnapshotPolicy() { + Builder builder = new Builder(prototype); + RemoteRepository repo = + builder.setSnapshotPolicy(prototype.getPolicy(true)).build(); + assertSame(prototype, repo); + RepositoryPolicy policy = new RepositoryPolicy(true, "never", "fail"); + repo = builder.setSnapshotPolicy(policy).build(); + assertEquals(policy, repo.getPolicy(true)); + assertEquals(prototype.getPolicy(false), repo.getPolicy(false)); } @Test - public void testSetProxy() - { - Builder builder = new Builder( prototype ); - RemoteRepository repo = builder.setProxy( prototype.getProxy() ).build(); - assertSame( prototype, repo ); - Proxy proxy = new Proxy( "http", "localhost", 8080 ); - repo = builder.setProxy( proxy ).build(); - assertEquals( proxy, repo.getProxy() ); + public void testSetProxy() { + Builder builder = new Builder(prototype); + RemoteRepository repo = builder.setProxy(prototype.getProxy()).build(); + assertSame(prototype, repo); + Proxy proxy = new Proxy("http", "localhost", 8080); + repo = builder.setProxy(proxy).build(); + assertEquals(proxy, repo.getProxy()); } @Test - public void testSetAuthentication() - { - Builder builder = new Builder( prototype ); - RemoteRepository repo = builder.setAuthentication( prototype.getAuthentication() ).build(); - assertSame( prototype, repo ); - Authentication auth = new Authentication() - { - public void fill( AuthenticationContext context, String key, Map data ) - { - } - - public void digest( AuthenticationDigest digest ) - { - } + public void testSetAuthentication() { + Builder builder = new Builder(prototype); + RemoteRepository repo = + builder.setAuthentication(prototype.getAuthentication()).build(); + assertSame(prototype, repo); + Authentication auth = new Authentication() { + public void fill(AuthenticationContext context, String key, Map data) {} + + public void digest(AuthenticationDigest digest) {} }; - repo = builder.setAuthentication( auth ).build(); - assertEquals( auth, repo.getAuthentication() ); + repo = builder.setAuthentication(auth).build(); + assertEquals(auth, repo.getAuthentication()); } @Test - public void testSetMirroredRepositories() - { - Builder builder = new Builder( prototype ); - RemoteRepository repo = builder.setMirroredRepositories( prototype.getMirroredRepositories() ).build(); - assertSame( prototype, repo ); - List mirrored = new ArrayList<>( Arrays.asList( repo ) ); - repo = builder.setMirroredRepositories( mirrored ).build(); - assertEquals( mirrored, repo.getMirroredRepositories() ); + public void testSetMirroredRepositories() { + Builder builder = new Builder(prototype); + RemoteRepository repo = builder.setMirroredRepositories(prototype.getMirroredRepositories()) + .build(); + assertSame(prototype, repo); + List mirrored = new ArrayList<>(Arrays.asList(repo)); + repo = builder.setMirroredRepositories(mirrored).build(); + assertEquals(mirrored, repo.getMirroredRepositories()); } @Test - public void testAddMirroredRepository() - { - Builder builder = new Builder( prototype ); - RemoteRepository repo = builder.addMirroredRepository( null ).build(); - assertSame( prototype, repo ); - repo = builder.addMirroredRepository( prototype ).build(); - assertEquals( Arrays.asList( prototype ), repo.getMirroredRepositories() ); + public void testAddMirroredRepository() { + Builder builder = new Builder(prototype); + RemoteRepository repo = builder.addMirroredRepository(null).build(); + assertSame(prototype, repo); + repo = builder.addMirroredRepository(prototype).build(); + assertEquals(Arrays.asList(prototype), repo.getMirroredRepositories()); } @Test - public void testSetRepositoryManager() - { - Builder builder = new Builder( prototype ); - RemoteRepository repo = builder.setRepositoryManager( prototype.isRepositoryManager() ).build(); - assertSame( prototype, repo ); - repo = builder.setRepositoryManager( !prototype.isRepositoryManager() ).build(); - assertEquals( !prototype.isRepositoryManager(), repo.isRepositoryManager() ); + public void testSetRepositoryManager() { + Builder builder = new Builder(prototype); + RemoteRepository repo = + builder.setRepositoryManager(prototype.isRepositoryManager()).build(); + assertSame(prototype, repo); + repo = builder.setRepositoryManager(!prototype.isRepositoryManager()).build(); + assertEquals(!prototype.isRepositoryManager(), repo.isRepositoryManager()); } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/repository/RemoteRepositoryTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/repository/RemoteRepositoryTest.java index 97f0b3ef7..2f50b7944 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/repository/RemoteRepositoryTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/repository/RemoteRepositoryTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,79 +16,75 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.repository; -import static org.junit.Assert.*; - -import org.eclipse.aether.repository.RemoteRepository; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class RemoteRepositoryTest -{ +public class RemoteRepositoryTest { @Test - public void testGetProtocol() - { - RemoteRepository.Builder builder = new RemoteRepository.Builder( "id", "type", "" ); + public void testGetProtocol() { + RemoteRepository.Builder builder = new RemoteRepository.Builder("id", "type", ""); RemoteRepository repo = builder.build(); - assertEquals( "", repo.getProtocol() ); + assertEquals("", repo.getProtocol()); - repo = builder.setUrl( "http://localhost" ).build(); - assertEquals( "http", repo.getProtocol() ); + repo = builder.setUrl("http://localhost").build(); + assertEquals("http", repo.getProtocol()); - repo = builder.setUrl( "HTTP://localhost" ).build(); - assertEquals( "HTTP", repo.getProtocol() ); + repo = builder.setUrl("HTTP://localhost").build(); + assertEquals("HTTP", repo.getProtocol()); - repo = builder.setUrl( "dav+http://www.sonatype.org/" ).build(); - assertEquals( "dav+http", repo.getProtocol() ); + repo = builder.setUrl("dav+http://www.sonatype.org/").build(); + assertEquals("dav+http", repo.getProtocol()); - repo = builder.setUrl( "dav:http://www.sonatype.org/" ).build(); - assertEquals( "dav:http", repo.getProtocol() ); + repo = builder.setUrl("dav:http://www.sonatype.org/").build(); + assertEquals("dav:http", repo.getProtocol()); - repo = builder.setUrl( "file:/path" ).build(); - assertEquals( "file", repo.getProtocol() ); + repo = builder.setUrl("file:/path").build(); + assertEquals("file", repo.getProtocol()); - repo = builder.setUrl( "file:path" ).build(); - assertEquals( "file", repo.getProtocol() ); + repo = builder.setUrl("file:path").build(); + assertEquals("file", repo.getProtocol()); - repo = builder.setUrl( "file:C:\\dir" ).build(); - assertEquals( "file", repo.getProtocol() ); + repo = builder.setUrl("file:C:\\dir").build(); + assertEquals("file", repo.getProtocol()); - repo = builder.setUrl( "file:C:/dir" ).build(); - assertEquals( "file", repo.getProtocol() ); + repo = builder.setUrl("file:C:/dir").build(); + assertEquals("file", repo.getProtocol()); } @Test - public void testGetHost() - { - RemoteRepository.Builder builder = new RemoteRepository.Builder( "id", "type", "" ); + public void testGetHost() { + RemoteRepository.Builder builder = new RemoteRepository.Builder("id", "type", ""); RemoteRepository repo = builder.build(); - assertEquals( "", repo.getHost() ); + assertEquals("", repo.getHost()); - repo = builder.setUrl( "http://localhost" ).build(); - assertEquals( "localhost", repo.getHost() ); + repo = builder.setUrl("http://localhost").build(); + assertEquals("localhost", repo.getHost()); - repo = builder.setUrl( "http://localhost/" ).build(); - assertEquals( "localhost", repo.getHost() ); + repo = builder.setUrl("http://localhost/").build(); + assertEquals("localhost", repo.getHost()); - repo = builder.setUrl( "http://localhost:1234/" ).build(); - assertEquals( "localhost", repo.getHost() ); + repo = builder.setUrl("http://localhost:1234/").build(); + assertEquals("localhost", repo.getHost()); - repo = builder.setUrl( "http://127.0.0.1" ).build(); - assertEquals( "127.0.0.1", repo.getHost() ); + repo = builder.setUrl("http://127.0.0.1").build(); + assertEquals("127.0.0.1", repo.getHost()); - repo = builder.setUrl( "http://127.0.0.1/" ).build(); - assertEquals( "127.0.0.1", repo.getHost() ); + repo = builder.setUrl("http://127.0.0.1/").build(); + assertEquals("127.0.0.1", repo.getHost()); - repo = builder.setUrl( "http://user@localhost/path" ).build(); - assertEquals( "localhost", repo.getHost() ); + repo = builder.setUrl("http://user@localhost/path").build(); + assertEquals("localhost", repo.getHost()); - repo = builder.setUrl( "http://user:pass@localhost/path" ).build(); - assertEquals( "localhost", repo.getHost() ); + repo = builder.setUrl("http://user:pass@localhost/path").build(); + assertEquals("localhost", repo.getHost()); - repo = builder.setUrl( "http://user:pass@localhost:1234/path" ).build(); - assertEquals( "localhost", repo.getHost() ); + repo = builder.setUrl("http://user:pass@localhost:1234/path").build(); + assertEquals("localhost", repo.getHost()); } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/transfer/AbstractTransferListenerTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/transfer/AbstractTransferListenerTest.java index 87c1472b7..dc9fce91e 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/transfer/AbstractTransferListenerTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/transfer/AbstractTransferListenerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,29 +16,23 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.transfer; import java.lang.reflect.Method; -import org.eclipse.aether.transfer.AbstractTransferListener; -import org.eclipse.aether.transfer.TransferListener; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class AbstractTransferListenerTest -{ +public class AbstractTransferListenerTest { @Test - public void testAllEventTypesHandled() - throws Exception - { - for ( Method method : TransferListener.class.getMethods() ) - { - assertNotNull( AbstractTransferListener.class.getDeclaredMethod( method.getName(), - method.getParameterTypes() ) ); + public void testAllEventTypesHandled() throws Exception { + for (Method method : TransferListener.class.getMethods()) { + assertNotNull( + AbstractTransferListener.class.getDeclaredMethod(method.getName(), method.getParameterTypes())); } } - } diff --git a/maven-resolver-api/src/test/java/org/eclipse/aether/transfer/TransferEventTest.java b/maven-resolver-api/src/test/java/org/eclipse/aether/transfer/TransferEventTest.java index 7d4c07065..ddf5f1727 100644 --- a/maven-resolver-api/src/test/java/org/eclipse/aether/transfer/TransferEventTest.java +++ b/maven-resolver-api/src/test/java/org/eclipse/aether/transfer/TransferEventTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transfer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,68 +16,66 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.transfer; import java.nio.ByteBuffer; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystemSession; -import org.eclipse.aether.transfer.TransferEvent; -import org.eclipse.aether.transfer.TransferResource; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class TransferEventTest -{ +public class TransferEventTest { - private static TransferResource res = new TransferResource( "none", "file://nil", "void", null, null ); + private static TransferResource res = new TransferResource("none", "file://nil", "void", null, null); private static RepositorySystemSession session = new DefaultRepositorySystemSession(); @Test - public void testByteArrayConversion() - { - byte[] buffer = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + public void testByteArrayConversion() { + byte[] buffer = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int length = buffer.length - 2; int offset = 1; - TransferEvent event = new TransferEvent.Builder( session, res ).setDataBuffer( buffer, offset, length ).build(); + TransferEvent event = new TransferEvent.Builder(session, res) + .setDataBuffer(buffer, offset, length) + .build(); ByteBuffer bb = event.getDataBuffer(); byte[] dst = new byte[bb.remaining()]; - bb.get( dst ); + bb.get(dst); - byte[] expected = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; - assertArrayEquals( expected, dst ); + byte[] expected = new byte[] {1, 2, 3, 4, 5, 6, 7, 8}; + assertArrayEquals(expected, dst); } @Test - public void testRepeatableReadingOfDataBuffer() - { - byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7 }; - ByteBuffer buffer = ByteBuffer.wrap( data ); + public void testRepeatableReadingOfDataBuffer() { + byte[] data = {0, 1, 2, 3, 4, 5, 6, 7}; + ByteBuffer buffer = ByteBuffer.wrap(data); - TransferEvent event = new TransferEvent.Builder( session, res ).setDataBuffer( buffer ).build(); + TransferEvent event = + new TransferEvent.Builder(session, res).setDataBuffer(buffer).build(); - assertEquals( 8, event.getDataLength() ); + assertEquals(8, event.getDataLength()); ByteBuffer eventBuffer = event.getDataBuffer(); - assertNotNull( eventBuffer ); - assertEquals( 8, eventBuffer.remaining() ); + assertNotNull(eventBuffer); + assertEquals(8, eventBuffer.remaining()); byte[] eventData = new byte[8]; - eventBuffer.get( eventData ); - assertArrayEquals( data, eventData ); - assertEquals( 0, eventBuffer.remaining() ); - assertEquals( 8, event.getDataLength() ); + eventBuffer.get(eventData); + assertArrayEquals(data, eventData); + assertEquals(0, eventBuffer.remaining()); + assertEquals(8, event.getDataLength()); eventBuffer = event.getDataBuffer(); - assertNotNull( eventBuffer ); - assertEquals( 8, eventBuffer.remaining() ); - eventBuffer.get( eventData ); - assertArrayEquals( data, eventData ); + assertNotNull(eventBuffer); + assertEquals(8, eventBuffer.remaining()); + eventBuffer.get(eventData); + assertArrayEquals(data, eventData); } - } diff --git a/maven-resolver-connector-basic/pom.xml b/maven-resolver-connector-basic/pom.xml index 5c8ec5bba..ca515d92c 100644 --- a/maven-resolver-connector-basic/pom.xml +++ b/maven-resolver-connector-basic/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-connector-basic Maven Artifact Resolver Connector Basic - - A repository connector implementation for repositories using URI-based layouts. - + A repository connector implementation for repositories using URI-based layouts. org.apache.maven.resolver.connector.basic @@ -64,9 +60,9 @@ slf4j-api - org.slf4j - slf4j-simple - test + org.slf4j + slf4j-simple + test com.google.inject diff --git a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ArtifactTransportListener.java b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ArtifactTransportListener.java index 22e8437b9..5e3d6d755 100644 --- a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ArtifactTransportListener.java +++ b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ArtifactTransportListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.connector.basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.connector.basic; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.spi.connector.ArtifactTransfer; @@ -26,33 +25,25 @@ import org.eclipse.aether.transfer.ArtifactTransferException; import org.eclipse.aether.transfer.TransferEvent; -final class ArtifactTransportListener - extends TransferTransportListener -{ +final class ArtifactTransportListener extends TransferTransportListener { private final RemoteRepository repository; - ArtifactTransportListener( ArtifactTransfer transfer, RemoteRepository repository, - TransferEvent.Builder eventBuilder ) - { - super( transfer, eventBuilder ); + ArtifactTransportListener( + ArtifactTransfer transfer, RemoteRepository repository, TransferEvent.Builder eventBuilder) { + super(transfer, eventBuilder); this.repository = repository; } @Override - public void transferFailed( Exception exception, int classification ) - { + public void transferFailed(Exception exception, int classification) { ArtifactTransferException e; - if ( classification == Transporter.ERROR_NOT_FOUND ) - { - e = new ArtifactNotFoundException( getTransfer().getArtifact(), repository ); + if (classification == Transporter.ERROR_NOT_FOUND) { + e = new ArtifactNotFoundException(getTransfer().getArtifact(), repository); + } else { + e = new ArtifactTransferException(getTransfer().getArtifact(), repository, exception); } - else - { - e = new ArtifactTransferException( getTransfer().getArtifact(), repository, exception ); - } - getTransfer().setException( e ); - super.transferFailed( e, classification ); + getTransfer().setException(e); + super.transferFailed(e, classification); } - } diff --git a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/BasicRepositoryConnector.java b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/BasicRepositoryConnector.java index 5a635c854..6afcac2c2 100644 --- a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/BasicRepositoryConnector.java +++ b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/BasicRepositoryConnector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.connector.basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Objects.requireNonNull; +package org.eclipse.aether.connector.basic; import java.io.ByteArrayOutputStream; import java.io.File; @@ -72,12 +69,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; + /** * */ -final class BasicRepositoryConnector - implements RepositoryConnector -{ +final class BasicRepositoryConnector implements RepositoryConnector { private static final String CONFIG_PROP_THREADS = "aether.connector.basic.threads"; @@ -85,7 +82,7 @@ final class BasicRepositoryConnector private static final String CONFIG_PROP_PARALLEL_PUT = "aether.connector.basic.parallelPut"; - private static final Logger LOGGER = LoggerFactory.getLogger( BasicRepositoryConnector.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(BasicRepositoryConnector.class); private final Map providedChecksumsSources; @@ -113,30 +110,24 @@ final class BasicRepositoryConnector private final AtomicBoolean closed; - BasicRepositoryConnector( RepositorySystemSession session, - RemoteRepository repository, - TransporterProvider transporterProvider, - RepositoryLayoutProvider layoutProvider, - ChecksumPolicyProvider checksumPolicyProvider, - FileProcessor fileProcessor, - Map providedChecksumsSources ) - throws NoRepositoryConnectorException - { - try - { - layout = layoutProvider.newRepositoryLayout( session, repository ); - } - catch ( NoRepositoryLayoutException e ) - { - throw new NoRepositoryConnectorException( repository, e.getMessage(), e ); - } - try - { - transporter = transporterProvider.newTransporter( session, repository ); - } - catch ( NoTransporterException e ) - { - throw new NoRepositoryConnectorException( repository, e.getMessage(), e ); + BasicRepositoryConnector( + RepositorySystemSession session, + RemoteRepository repository, + TransporterProvider transporterProvider, + RepositoryLayoutProvider layoutProvider, + ChecksumPolicyProvider checksumPolicyProvider, + FileProcessor fileProcessor, + Map providedChecksumsSources) + throws NoRepositoryConnectorException { + try { + layout = layoutProvider.newRepositoryLayout(session, repository); + } catch (NoRepositoryLayoutException e) { + throw new NoRepositoryConnectorException(repository, e.getMessage(), e); + } + try { + transporter = transporterProvider.newTransporter(session, repository); + } catch (NoTransporterException e) { + throw new NoRepositoryConnectorException(repository, e.getMessage(), e); } this.checksumPolicyProvider = checksumPolicyProvider; @@ -144,142 +135,132 @@ final class BasicRepositoryConnector this.repository = repository; this.fileProcessor = fileProcessor; this.providedChecksumsSources = providedChecksumsSources; - this.closed = new AtomicBoolean( false ); - - maxThreads = ExecutorUtils.threadCount( session, 5, CONFIG_PROP_THREADS, "maven.artifact.threads" ); - smartChecksums = ConfigUtils.getBoolean( session, true, CONFIG_PROP_SMART_CHECKSUMS ); - parallelPut = ConfigUtils.getBoolean( session, true, - CONFIG_PROP_PARALLEL_PUT + "." + repository.getId(), CONFIG_PROP_PARALLEL_PUT ); - persistedChecksums = - ConfigUtils.getBoolean( session, ConfigurationProperties.DEFAULT_PERSISTED_CHECKSUMS, - ConfigurationProperties.PERSISTED_CHECKSUMS ); + this.closed = new AtomicBoolean(false); + + maxThreads = ExecutorUtils.threadCount(session, 5, CONFIG_PROP_THREADS, "maven.artifact.threads"); + smartChecksums = ConfigUtils.getBoolean(session, true, CONFIG_PROP_SMART_CHECKSUMS); + parallelPut = ConfigUtils.getBoolean( + session, true, CONFIG_PROP_PARALLEL_PUT + "." + repository.getId(), CONFIG_PROP_PARALLEL_PUT); + persistedChecksums = ConfigUtils.getBoolean( + session, + ConfigurationProperties.DEFAULT_PERSISTED_CHECKSUMS, + ConfigurationProperties.PERSISTED_CHECKSUMS); } - private Executor getExecutor( int tasks ) - { - if ( maxThreads <= 1 ) - { + private Executor getExecutor(int tasks) { + if (maxThreads <= 1) { return ExecutorUtils.DIRECT_EXECUTOR; } - if ( tasks <= 1 ) - { + if (tasks <= 1) { return ExecutorUtils.DIRECT_EXECUTOR; } - if ( executor == null ) - { - executor = ExecutorUtils.threadPool( maxThreads, - getClass().getSimpleName() + '-' + repository.getHost() + '-' ); + if (executor == null) { + executor = + ExecutorUtils.threadPool(maxThreads, getClass().getSimpleName() + '-' + repository.getHost() + '-'); } return executor; } @Override - public void close() - { - if ( closed.compareAndSet( false, true ) ) - { - ExecutorUtils.shutdown( executor ); + public void close() { + if (closed.compareAndSet(false, true)) { + ExecutorUtils.shutdown(executor); transporter.close(); } } - private void failIfClosed() - { - if ( closed.get() ) - { - throw new IllegalStateException( "connector already closed" ); + private void failIfClosed() { + if (closed.get()) { + throw new IllegalStateException("connector already closed"); } } @Override - public void get( Collection artifactDownloads, - Collection metadataDownloads ) - { + public void get( + Collection artifactDownloads, + Collection metadataDownloads) { failIfClosed(); - Collection safeArtifactDownloads = safe( artifactDownloads ); - Collection safeMetadataDownloads = safe( metadataDownloads ); + Collection safeArtifactDownloads = safe(artifactDownloads); + Collection safeMetadataDownloads = safe(metadataDownloads); - Executor executor = getExecutor( safeArtifactDownloads.size() + safeMetadataDownloads.size() ); + Executor executor = getExecutor(safeArtifactDownloads.size() + safeMetadataDownloads.size()); RunnableErrorForwarder errorForwarder = new RunnableErrorForwarder(); List checksumAlgorithmFactories = layout.getChecksumAlgorithmFactories(); boolean first = true; - for ( MetadataDownload transfer : safeMetadataDownloads ) - { - URI location = layout.getLocation( transfer.getMetadata(), false ); + for (MetadataDownload transfer : safeMetadataDownloads) { + URI location = layout.getLocation(transfer.getMetadata(), false); - TransferResource resource = newTransferResource( location, transfer.getFile(), transfer.getTrace() ); - TransferEvent.Builder builder = newEventBuilder( resource, false, false ); - MetadataTransportListener listener = new MetadataTransportListener( transfer, repository, builder ); + TransferResource resource = newTransferResource(location, transfer.getFile(), transfer.getTrace()); + TransferEvent.Builder builder = newEventBuilder(resource, false, false); + MetadataTransportListener listener = new MetadataTransportListener(transfer, repository, builder); - ChecksumPolicy checksumPolicy = newChecksumPolicy( transfer.getChecksumPolicy(), resource ); + ChecksumPolicy checksumPolicy = newChecksumPolicy(transfer.getChecksumPolicy(), resource); List checksumLocations = null; - if ( checksumPolicy != null ) - { - checksumLocations = layout.getChecksumLocations( transfer.getMetadata(), false, location ); + if (checksumPolicy != null) { + checksumLocations = layout.getChecksumLocations(transfer.getMetadata(), false, location); } - Runnable task = new GetTaskRunner( location, transfer.getFile(), checksumPolicy, - checksumAlgorithmFactories, checksumLocations, null, listener ); - if ( first ) - { + Runnable task = new GetTaskRunner( + location, + transfer.getFile(), + checksumPolicy, + checksumAlgorithmFactories, + checksumLocations, + null, + listener); + if (first) { task.run(); first = false; - } - else - { - executor.execute( errorForwarder.wrap( task ) ); + } else { + executor.execute(errorForwarder.wrap(task)); } } - for ( ArtifactDownload transfer : safeArtifactDownloads ) - { + for (ArtifactDownload transfer : safeArtifactDownloads) { Map providedChecksums = Collections.emptyMap(); - for ( ProvidedChecksumsSource providedChecksumsSource : providedChecksumsSources.values() ) - { + for (ProvidedChecksumsSource providedChecksumsSource : providedChecksumsSources.values()) { Map provided = providedChecksumsSource.getProvidedArtifactChecksums( - session, transfer, checksumAlgorithmFactories ); + session, transfer, checksumAlgorithmFactories); - if ( provided != null ) - { + if (provided != null) { providedChecksums = provided; break; } } - URI location = layout.getLocation( transfer.getArtifact(), false ); + URI location = layout.getLocation(transfer.getArtifact(), false); - TransferResource resource = newTransferResource( location, transfer.getFile(), transfer.getTrace() ); - TransferEvent.Builder builder = newEventBuilder( resource, false, transfer.isExistenceCheck() ); - ArtifactTransportListener listener = new ArtifactTransportListener( transfer, repository, builder ); + TransferResource resource = newTransferResource(location, transfer.getFile(), transfer.getTrace()); + TransferEvent.Builder builder = newEventBuilder(resource, false, transfer.isExistenceCheck()); + ArtifactTransportListener listener = new ArtifactTransportListener(transfer, repository, builder); Runnable task; - if ( transfer.isExistenceCheck() ) - { - task = new PeekTaskRunner( location, listener ); - } - else - { - ChecksumPolicy checksumPolicy = newChecksumPolicy( transfer.getChecksumPolicy(), resource ); + if (transfer.isExistenceCheck()) { + task = new PeekTaskRunner(location, listener); + } else { + ChecksumPolicy checksumPolicy = newChecksumPolicy(transfer.getChecksumPolicy(), resource); List checksumLocations = null; - if ( checksumPolicy != null ) - { - checksumLocations = layout.getChecksumLocations( transfer.getArtifact(), false, location ); + if (checksumPolicy != null) { + checksumLocations = layout.getChecksumLocations(transfer.getArtifact(), false, location); } - task = new GetTaskRunner( location, transfer.getFile(), checksumPolicy, - checksumAlgorithmFactories, checksumLocations, providedChecksums, listener ); + task = new GetTaskRunner( + location, + transfer.getFile(), + checksumPolicy, + checksumAlgorithmFactories, + checksumLocations, + providedChecksums, + listener); } - if ( first ) - { + if (first) { task.run(); first = false; - } - else - { - executor.execute( errorForwarder.wrap( task ) ); + } else { + executor.execute(errorForwarder.wrap(task)); } } @@ -287,67 +268,58 @@ public void get( Collection artifactDownloads, } @Override - public void put( Collection artifactUploads, - Collection metadataUploads ) - { + public void put( + Collection artifactUploads, + Collection metadataUploads) { failIfClosed(); - Collection safeArtifactUploads = safe( artifactUploads ); - Collection safeMetadataUploads = safe( metadataUploads ); + Collection safeArtifactUploads = safe(artifactUploads); + Collection safeMetadataUploads = safe(metadataUploads); - Executor executor = getExecutor( parallelPut ? safeArtifactUploads.size() + safeMetadataUploads.size() : 1 ); + Executor executor = getExecutor(parallelPut ? safeArtifactUploads.size() + safeMetadataUploads.size() : 1); RunnableErrorForwarder errorForwarder = new RunnableErrorForwarder(); boolean first = true; - for ( ArtifactUpload transfer : safeArtifactUploads ) - { - URI location = layout.getLocation( transfer.getArtifact(), true ); + for (ArtifactUpload transfer : safeArtifactUploads) { + URI location = layout.getLocation(transfer.getArtifact(), true); - TransferResource resource = newTransferResource( location, transfer.getFile(), transfer.getTrace() ); - TransferEvent.Builder builder = newEventBuilder( resource, true, false ); - ArtifactTransportListener listener = new ArtifactTransportListener( transfer, repository, builder ); + TransferResource resource = newTransferResource(location, transfer.getFile(), transfer.getTrace()); + TransferEvent.Builder builder = newEventBuilder(resource, true, false); + ArtifactTransportListener listener = new ArtifactTransportListener(transfer, repository, builder); List checksumLocations = - layout.getChecksumLocations( transfer.getArtifact(), true, location ); + layout.getChecksumLocations(transfer.getArtifact(), true, location); - Runnable task = new PutTaskRunner( location, transfer.getFile(), transfer.getFileTransformer(), - checksumLocations, listener ); - if ( first ) - { + Runnable task = new PutTaskRunner( + location, transfer.getFile(), transfer.getFileTransformer(), checksumLocations, listener); + if (first) { task.run(); first = false; - } - else - { - executor.execute( errorForwarder.wrap( task ) ); + } else { + executor.execute(errorForwarder.wrap(task)); } } errorForwarder.await(); // make sure all artifacts are PUT before we go with Metadata - for ( List transferGroup : groupUploads( safeMetadataUploads ) ) - { - for ( MetadataUpload transfer : transferGroup ) - { - URI location = layout.getLocation( transfer.getMetadata(), true ); + for (List transferGroup : groupUploads(safeMetadataUploads)) { + for (MetadataUpload transfer : transferGroup) { + URI location = layout.getLocation(transfer.getMetadata(), true); - TransferResource resource = newTransferResource( location, transfer.getFile(), transfer.getTrace() ); - TransferEvent.Builder builder = newEventBuilder( resource, true, false ); - MetadataTransportListener listener = new MetadataTransportListener( transfer, repository, builder ); + TransferResource resource = newTransferResource(location, transfer.getFile(), transfer.getTrace()); + TransferEvent.Builder builder = newEventBuilder(resource, true, false); + MetadataTransportListener listener = new MetadataTransportListener(transfer, repository, builder); List checksumLocations = - layout.getChecksumLocations( transfer.getMetadata(), true, location ); + layout.getChecksumLocations(transfer.getMetadata(), true, location); - Runnable task = new PutTaskRunner( location, transfer.getFile(), checksumLocations, listener ); - if ( first ) - { + Runnable task = new PutTaskRunner(location, transfer.getFile(), checksumLocations, listener); + if (first) { task.run(); first = false; - } - else - { - executor.execute( errorForwarder.wrap( task ) ); + } else { + executor.execute(errorForwarder.wrap(task)); } } @@ -360,178 +332,139 @@ public void put( Collection artifactUploads, * as clients consume metadata in opposite order (root, group, artifact, version), and hence, we must deploy and * ensure (in case of parallel deploy) that all V level metadata is deployed before we start deploying A level, etc. */ - private static List> groupUploads( Collection metadataUploads ) - { + private static List> groupUploads(Collection metadataUploads) { ArrayList v = new ArrayList<>(); ArrayList a = new ArrayList<>(); ArrayList g = new ArrayList<>(); ArrayList r = new ArrayList<>(); - for ( MetadataUpload transfer : metadataUploads ) - { + for (MetadataUpload transfer : metadataUploads) { Metadata metadata = transfer.getMetadata(); - if ( !"".equals( metadata.getVersion() ) ) - { - v.add( transfer ); - } - else if ( !"".equals( metadata.getArtifactId() ) ) - { - a.add( transfer ); - } - else if ( !"".equals( metadata.getGroupId() ) ) - { - g.add( transfer ); - } - else - { - r.add( transfer ); + if (!"".equals(metadata.getVersion())) { + v.add(transfer); + } else if (!"".equals(metadata.getArtifactId())) { + a.add(transfer); + } else if (!"".equals(metadata.getGroupId())) { + g.add(transfer); + } else { + r.add(transfer); } } - List> result = new ArrayList<>( 4 ); - if ( !v.isEmpty() ) - { - result.add( v ); + List> result = new ArrayList<>(4); + if (!v.isEmpty()) { + result.add(v); } - if ( !a.isEmpty() ) - { - result.add( a ); + if (!a.isEmpty()) { + result.add(a); } - if ( !g.isEmpty() ) - { - result.add( g ); + if (!g.isEmpty()) { + result.add(g); } - if ( !r.isEmpty() ) - { - result.add( r ); + if (!r.isEmpty()) { + result.add(r); } return result; } - private static Collection safe( Collection items ) - { - return ( items != null ) ? items : Collections.emptyList(); + private static Collection safe(Collection items) { + return (items != null) ? items : Collections.emptyList(); } - private TransferResource newTransferResource( URI path, File file, RequestTrace trace ) - { - return new TransferResource( repository.getId(), repository.getUrl(), path.toString(), file, trace ); + private TransferResource newTransferResource(URI path, File file, RequestTrace trace) { + return new TransferResource(repository.getId(), repository.getUrl(), path.toString(), file, trace); } - private TransferEvent.Builder newEventBuilder( TransferResource resource, boolean upload, boolean peek ) - { - TransferEvent.Builder builder = new TransferEvent.Builder( session, resource ); - if ( upload ) - { - builder.setRequestType( TransferEvent.RequestType.PUT ); - } - else if ( !peek ) - { - builder.setRequestType( TransferEvent.RequestType.GET ); - } - else - { - builder.setRequestType( TransferEvent.RequestType.GET_EXISTENCE ); + private TransferEvent.Builder newEventBuilder(TransferResource resource, boolean upload, boolean peek) { + TransferEvent.Builder builder = new TransferEvent.Builder(session, resource); + if (upload) { + builder.setRequestType(TransferEvent.RequestType.PUT); + } else if (!peek) { + builder.setRequestType(TransferEvent.RequestType.GET); + } else { + builder.setRequestType(TransferEvent.RequestType.GET_EXISTENCE); } return builder; } - private ChecksumPolicy newChecksumPolicy( String policy, TransferResource resource ) - { - return checksumPolicyProvider.newChecksumPolicy( session, repository, resource, policy ); + private ChecksumPolicy newChecksumPolicy(String policy, TransferResource resource) { + return checksumPolicyProvider.newChecksumPolicy(session, repository, resource, policy); } @Override - public String toString() - { - return String.valueOf( repository ); + public String toString() { + return String.valueOf(repository); } - abstract class TaskRunner - implements Runnable - { + abstract class TaskRunner implements Runnable { protected final URI path; protected final TransferTransportListener listener; - TaskRunner( URI path, TransferTransportListener listener ) - { + TaskRunner(URI path, TransferTransportListener listener) { this.path = path; this.listener = listener; } @Override - public void run() - { - try - { + public void run() { + try { listener.transferInitiated(); runTask(); listener.transferSucceeded(); - } - catch ( Exception e ) - { - listener.transferFailed( e, transporter.classify( e ) ); + } catch (Exception e) { + listener.transferFailed(e, transporter.classify(e)); } } - protected abstract void runTask() - throws Exception; - + protected abstract void runTask() throws Exception; } - class PeekTaskRunner - extends TaskRunner - { + class PeekTaskRunner extends TaskRunner { - PeekTaskRunner( URI path, TransferTransportListener listener ) - { - super( path, listener ); + PeekTaskRunner(URI path, TransferTransportListener listener) { + super(path, listener); } @Override - protected void runTask() - throws Exception - { - transporter.peek( new PeekTask( path ) ); + protected void runTask() throws Exception { + transporter.peek(new PeekTask(path)); } - } - class GetTaskRunner - extends TaskRunner - implements ChecksumValidator.ChecksumFetcher - { + class GetTaskRunner extends TaskRunner implements ChecksumValidator.ChecksumFetcher { private final File file; private final ChecksumValidator checksumValidator; - GetTaskRunner( URI path, File file, ChecksumPolicy checksumPolicy, - List checksumAlgorithmFactories, - List checksumLocations, - Map providedChecksums, - TransferTransportListener listener ) - { - super( path, listener ); - this.file = requireNonNull( file, "destination file cannot be null" ); - checksumValidator = new ChecksumValidator( file, checksumAlgorithmFactories, fileProcessor, this, - checksumPolicy, providedChecksums, safe( checksumLocations ) ); + GetTaskRunner( + URI path, + File file, + ChecksumPolicy checksumPolicy, + List checksumAlgorithmFactories, + List checksumLocations, + Map providedChecksums, + TransferTransportListener listener) { + super(path, listener); + this.file = requireNonNull(file, "destination file cannot be null"); + checksumValidator = new ChecksumValidator( + file, + checksumAlgorithmFactories, + fileProcessor, + this, + checksumPolicy, + providedChecksums, + safe(checksumLocations)); } @Override - public boolean fetchChecksum( URI remote, File local ) - throws Exception - { - try - { - transporter.get( new GetTask( remote ).setDataFile( local ) ); - } - catch ( Exception e ) - { - if ( transporter.classify( e ) == Transporter.ERROR_NOT_FOUND ) - { + public boolean fetchChecksum(URI remote, File local) throws Exception { + try { + transporter.get(new GetTask(remote).setDataFile(local)); + } catch (Exception e) { + if (transporter.classify(e) == Transporter.ERROR_NOT_FOUND) { return false; } throw e; @@ -540,54 +473,39 @@ public boolean fetchChecksum( URI remote, File local ) } @Override - protected void runTask() - throws Exception - { - try ( FileUtils.CollocatedTempFile tempFile = FileUtils.newTempFile( file.toPath() ) ) - { + protected void runTask() throws Exception { + try (FileUtils.CollocatedTempFile tempFile = FileUtils.newTempFile(file.toPath())) { final File tmp = tempFile.getPath().toFile(); - listener.setChecksumCalculator( checksumValidator.newChecksumCalculator( tmp ) ); - for ( int firstTrial = 0, lastTrial = 1, trial = firstTrial; ; trial++ ) - { - GetTask task = new GetTask( path ).setDataFile( tmp, false ).setListener( listener ); - transporter.get( task ); - try - { - checksumValidator.validate( listener.getChecksums(), smartChecksums ? task.getChecksums() - : null ); + listener.setChecksumCalculator(checksumValidator.newChecksumCalculator(tmp)); + for (int firstTrial = 0, lastTrial = 1, trial = firstTrial; ; trial++) { + GetTask task = new GetTask(path).setDataFile(tmp, false).setListener(listener); + transporter.get(task); + try { + checksumValidator.validate( + listener.getChecksums(), smartChecksums ? task.getChecksums() : null); break; - } - catch ( ChecksumFailureException e ) - { + } catch (ChecksumFailureException e) { boolean retry = trial < lastTrial && e.isRetryWorthy(); - if ( !retry && !checksumValidator.handle( e ) ) - { + if (!retry && !checksumValidator.handle(e)) { throw e; } - listener.transferCorrupted( e ); - if ( retry ) - { + listener.transferCorrupted(e); + if (retry) { checksumValidator.retry(); - } - else - { + } else { break; } } } tempFile.move(); - if ( persistedChecksums ) - { + if (persistedChecksums) { checksumValidator.commit(); } } } - } - class PutTaskRunner - extends TaskRunner - { + class PutTaskRunner extends TaskRunner { private final File file; @@ -595,10 +513,12 @@ class PutTaskRunner private final Collection checksumLocations; - PutTaskRunner( URI path, File file, List checksumLocations, - TransferTransportListener listener ) - { - this( path, file, null, checksumLocations, listener ); + PutTaskRunner( + URI path, + File file, + List checksumLocations, + TransferTransportListener listener) { + this(path, file, null, checksumLocations, listener); } /** @@ -611,43 +531,38 @@ class PutTaskRunner * @param checksumLocations * @param listener */ - PutTaskRunner( URI path, File file, FileTransformer fileTransformer, - List checksumLocations, - TransferTransportListener listener ) - { - super( path, listener ); - this.file = requireNonNull( file, "source file cannot be null" ); + PutTaskRunner( + URI path, + File file, + FileTransformer fileTransformer, + List checksumLocations, + TransferTransportListener listener) { + super(path, listener); + this.file = requireNonNull(file, "source file cannot be null"); this.fileTransformer = fileTransformer; - this.checksumLocations = safe( checksumLocations ); + this.checksumLocations = safe(checksumLocations); } - @SuppressWarnings( "checkstyle:innerassignment" ) + @SuppressWarnings("checkstyle:innerassignment") @Override - protected void runTask() - throws Exception - { - if ( fileTransformer != null ) - { + protected void runTask() throws Exception { + if (fileTransformer != null) { // transform data once to byte array, ensure constant data for checksum ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; - try ( InputStream transformData = fileTransformer.transformData( file ) ) - { - for ( int read; ( read = transformData.read( buffer, 0, buffer.length ) ) != -1; ) - { - baos.write( buffer, 0, read ); + try (InputStream transformData = fileTransformer.transformData(file)) { + for (int read; (read = transformData.read(buffer, 0, buffer.length)) != -1; ) { + baos.write(buffer, 0, read); } } byte[] bytes = baos.toByteArray(); - transporter.put( new PutTask( path ).setDataBytes( bytes ).setListener( listener ) ); - uploadChecksums( file, bytes ); - } - else - { - transporter.put( new PutTask( path ).setDataFile( file ).setListener( listener ) ); - uploadChecksums( file, null ); + transporter.put(new PutTask(path).setDataBytes(bytes).setListener(listener)); + uploadChecksums(file, bytes); + } else { + transporter.put(new PutTask(path).setDataFile(file).setListener(listener)); + uploadChecksums(file, null); } } @@ -655,58 +570,45 @@ protected void runTask() * @param file source * @param bytes transformed data from file or {@code null} */ - private void uploadChecksums( File file, byte[] bytes ) - { - if ( checksumLocations.isEmpty() ) - { + private void uploadChecksums(File file, byte[] bytes) { + if (checksumLocations.isEmpty()) { return; } - try - { + try { ArrayList algorithms = new ArrayList<>(); - for ( RepositoryLayout.ChecksumLocation checksumLocation : checksumLocations ) - { - algorithms.add( checksumLocation.getChecksumAlgorithmFactory() ); + for (RepositoryLayout.ChecksumLocation checksumLocation : checksumLocations) { + algorithms.add(checksumLocation.getChecksumAlgorithmFactory()); } Map sumsByAlgo; - if ( bytes != null ) - { - sumsByAlgo = ChecksumAlgorithmHelper.calculate( bytes, algorithms ); - } - else - { - sumsByAlgo = ChecksumAlgorithmHelper.calculate( file, algorithms ); + if (bytes != null) { + sumsByAlgo = ChecksumAlgorithmHelper.calculate(bytes, algorithms); + } else { + sumsByAlgo = ChecksumAlgorithmHelper.calculate(file, algorithms); } - for ( RepositoryLayout.ChecksumLocation checksumLocation : checksumLocations ) - { - uploadChecksum( checksumLocation.getLocation(), - sumsByAlgo.get( checksumLocation.getChecksumAlgorithmFactory().getName() ) ); + for (RepositoryLayout.ChecksumLocation checksumLocation : checksumLocations) { + uploadChecksum( + checksumLocation.getLocation(), + sumsByAlgo.get(checksumLocation + .getChecksumAlgorithmFactory() + .getName())); } - } - catch ( IOException e ) - { - LOGGER.warn( "Failed to upload checksums for {}", file, e ); - throw new UncheckedIOException( e ); + } catch (IOException e) { + LOGGER.warn("Failed to upload checksums for {}", file, e); + throw new UncheckedIOException(e); } } - private void uploadChecksum( URI location, Object checksum ) - { - try - { - if ( checksum instanceof Exception ) - { + private void uploadChecksum(URI location, Object checksum) { + try { + if (checksum instanceof Exception) { throw (Exception) checksum; } - transporter.put( new PutTask( location ).setDataString( (String) checksum ) ); - } - catch ( Exception e ) - { - LOGGER.warn( "Failed to upload checksum to {}", location, e ); + transporter.put(new PutTask(location).setDataString((String) checksum)); + } catch (Exception e) { + LOGGER.warn("Failed to upload checksum to {}", location, e); } } - } } diff --git a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/BasicRepositoryConnectorFactory.java b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/BasicRepositoryConnectorFactory.java index 576d12160..b7ba2de7d 100644 --- a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/BasicRepositoryConnectorFactory.java +++ b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/BasicRepositoryConnectorFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.connector.basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,13 @@ * specific language governing permissions and limitations * under the License. */ - -import java.util.Collections; -import java.util.Map; +package org.eclipse.aether.connector.basic; import javax.inject.Inject; import javax.inject.Named; -import static java.util.Objects.requireNonNull; +import java.util.Collections; +import java.util.Map; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; @@ -40,15 +37,15 @@ import org.eclipse.aether.spi.locator.ServiceLocator; import org.eclipse.aether.transfer.NoRepositoryConnectorException; +import static java.util.Objects.requireNonNull; + /** * A repository connector factory that employs pluggable * {@link org.eclipse.aether.spi.connector.transport.TransporterFactory transporters} and * {@link org.eclipse.aether.spi.connector.layout.RepositoryLayoutFactory repository layouts} for the transfers. */ -@Named( "basic" ) -public final class BasicRepositoryConnectorFactory - implements RepositoryConnectorFactory, Service -{ +@Named("basic") +public final class BasicRepositoryConnectorFactory implements RepositoryConnectorFactory, Service { private TransporterProvider transporterProvider; private RepositoryLayoutProvider layoutProvider; @@ -66,32 +63,30 @@ public final class BasicRepositoryConnectorFactory * clients, the new factory needs to be configured via its various mutators before first use or runtime errors will * occur. */ - public BasicRepositoryConnectorFactory() - { + public BasicRepositoryConnectorFactory() { // enables default constructor } @Inject - BasicRepositoryConnectorFactory( TransporterProvider transporterProvider, - RepositoryLayoutProvider layoutProvider, - ChecksumPolicyProvider checksumPolicyProvider, - FileProcessor fileProcessor, - Map providedChecksumsSources ) - { - setTransporterProvider( transporterProvider ); - setRepositoryLayoutProvider( layoutProvider ); - setChecksumPolicyProvider( checksumPolicyProvider ); - setFileProcessor( fileProcessor ); - setProvidedChecksumSources( providedChecksumsSources ); + BasicRepositoryConnectorFactory( + TransporterProvider transporterProvider, + RepositoryLayoutProvider layoutProvider, + ChecksumPolicyProvider checksumPolicyProvider, + FileProcessor fileProcessor, + Map providedChecksumsSources) { + setTransporterProvider(transporterProvider); + setRepositoryLayoutProvider(layoutProvider); + setChecksumPolicyProvider(checksumPolicyProvider); + setFileProcessor(fileProcessor); + setProvidedChecksumSources(providedChecksumsSources); } - public void initService( ServiceLocator locator ) - { - setTransporterProvider( locator.getService( TransporterProvider.class ) ); - setRepositoryLayoutProvider( locator.getService( RepositoryLayoutProvider.class ) ); - setChecksumPolicyProvider( locator.getService( ChecksumPolicyProvider.class ) ); - setFileProcessor( locator.getService( FileProcessor.class ) ); - setProvidedChecksumSources( Collections.emptyMap() ); + public void initService(ServiceLocator locator) { + setTransporterProvider(locator.getService(TransporterProvider.class)); + setRepositoryLayoutProvider(locator.getService(RepositoryLayoutProvider.class)); + setChecksumPolicyProvider(locator.getService(ChecksumPolicyProvider.class)); + setFileProcessor(locator.getService(FileProcessor.class)); + setProvidedChecksumSources(Collections.emptyMap()); } /** @@ -100,9 +95,8 @@ public void initService( ServiceLocator locator ) * @param transporterProvider The transporter provider to use, must not be {@code null}. * @return This component for chaining, never {@code null}. */ - public BasicRepositoryConnectorFactory setTransporterProvider( TransporterProvider transporterProvider ) - { - this.transporterProvider = requireNonNull( transporterProvider, "transporter provider cannot be null" ); + public BasicRepositoryConnectorFactory setTransporterProvider(TransporterProvider transporterProvider) { + this.transporterProvider = requireNonNull(transporterProvider, "transporter provider cannot be null"); return this; } @@ -112,9 +106,8 @@ public BasicRepositoryConnectorFactory setTransporterProvider( TransporterProvid * @param layoutProvider The repository layout provider to use, must not be {@code null}. * @return This component for chaining, never {@code null}. */ - public BasicRepositoryConnectorFactory setRepositoryLayoutProvider( RepositoryLayoutProvider layoutProvider ) - { - this.layoutProvider = requireNonNull( layoutProvider, "repository layout provider cannot be null" ); + public BasicRepositoryConnectorFactory setRepositoryLayoutProvider(RepositoryLayoutProvider layoutProvider) { + this.layoutProvider = requireNonNull(layoutProvider, "repository layout provider cannot be null"); return this; } @@ -124,10 +117,8 @@ public BasicRepositoryConnectorFactory setRepositoryLayoutProvider( RepositoryLa * @param checksumPolicyProvider The checksum policy provider to use, must not be {@code null}. * @return This component for chaining, never {@code null}. */ - public BasicRepositoryConnectorFactory setChecksumPolicyProvider( ChecksumPolicyProvider checksumPolicyProvider ) - { - this.checksumPolicyProvider = requireNonNull( - checksumPolicyProvider, "checksum policy provider cannot be null" ); + public BasicRepositoryConnectorFactory setChecksumPolicyProvider(ChecksumPolicyProvider checksumPolicyProvider) { + this.checksumPolicyProvider = requireNonNull(checksumPolicyProvider, "checksum policy provider cannot be null"); return this; } @@ -137,9 +128,8 @@ public BasicRepositoryConnectorFactory setChecksumPolicyProvider( ChecksumPolicy * @param fileProcessor The file processor to use, must not be {@code null}. * @return This component for chaining, never {@code null}. */ - public BasicRepositoryConnectorFactory setFileProcessor( FileProcessor fileProcessor ) - { - this.fileProcessor = requireNonNull( fileProcessor, "file processor cannot be null" ); + public BasicRepositoryConnectorFactory setFileProcessor(FileProcessor fileProcessor) { + this.fileProcessor = requireNonNull(fileProcessor, "file processor cannot be null"); return this; } @@ -151,16 +141,13 @@ public BasicRepositoryConnectorFactory setFileProcessor( FileProcessor fileProce * @since 1.8.0 */ public BasicRepositoryConnectorFactory setProvidedChecksumSources( - Map providedChecksumsSources ) - { - this.providedChecksumsSources = requireNonNull( - providedChecksumsSources, "provided checksum sources cannot be null" - ); + Map providedChecksumsSources) { + this.providedChecksumsSources = + requireNonNull(providedChecksumsSources, "provided checksum sources cannot be null"); return this; } - public float getPriority() - { + public float getPriority() { return priority; } @@ -170,20 +157,23 @@ public float getPriority() * @param priority The priority. * @return This component for chaining, never {@code null}. */ - public BasicRepositoryConnectorFactory setPriority( float priority ) - { + public BasicRepositoryConnectorFactory setPriority(float priority) { this.priority = priority; return this; } - public RepositoryConnector newInstance( RepositorySystemSession session, RemoteRepository repository ) - throws NoRepositoryConnectorException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); - - return new BasicRepositoryConnector( session, repository, transporterProvider, layoutProvider, - checksumPolicyProvider, fileProcessor, providedChecksumsSources ); + public RepositoryConnector newInstance(RepositorySystemSession session, RemoteRepository repository) + throws NoRepositoryConnectorException { + requireNonNull(session, "session cannot be null"); + requireNonNull(repository, "repository cannot be null"); + + return new BasicRepositoryConnector( + session, + repository, + transporterProvider, + layoutProvider, + checksumPolicyProvider, + fileProcessor, + providedChecksumsSources); } - } diff --git a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ChecksumCalculator.java b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ChecksumCalculator.java index b1b353680..94fe01fe8 100644 --- a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ChecksumCalculator.java +++ b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ChecksumCalculator.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.connector.basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.connector.basic; import java.io.BufferedInputStream; import java.io.File; @@ -42,137 +41,107 @@ /** * Calculates checksums for a downloaded file. */ -final class ChecksumCalculator -{ +final class ChecksumCalculator { - static class Checksum - { + static class Checksum { final ChecksumAlgorithmFactory checksumAlgorithmFactory; ChecksumAlgorithm algorithm; Exception error; - Checksum( ChecksumAlgorithmFactory checksumAlgorithmFactory ) - { - this.checksumAlgorithmFactory = requireNonNull( checksumAlgorithmFactory ); + Checksum(ChecksumAlgorithmFactory checksumAlgorithmFactory) { + this.checksumAlgorithmFactory = requireNonNull(checksumAlgorithmFactory); this.algorithm = checksumAlgorithmFactory.getAlgorithm(); } - public void reset() - { + public void reset() { this.algorithm = checksumAlgorithmFactory.getAlgorithm(); this.error = null; } - public void update( ByteBuffer buffer ) - { - this.algorithm.update( buffer ); + public void update(ByteBuffer buffer) { + this.algorithm.update(buffer); } - public void error( Exception error ) - { + public void error(Exception error) { this.error = error; } - public Object get() - { - if ( error != null ) - { + public Object get() { + if (error != null) { return error; } return algorithm.checksum(); } - } private final List checksums; private final File targetFile; - public static ChecksumCalculator newInstance( File targetFile, - Collection checksumAlgorithmFactories ) - { - if ( checksumAlgorithmFactories == null || checksumAlgorithmFactories.isEmpty() ) - { + public static ChecksumCalculator newInstance( + File targetFile, Collection checksumAlgorithmFactories) { + if (checksumAlgorithmFactories == null || checksumAlgorithmFactories.isEmpty()) { return null; } - return new ChecksumCalculator( targetFile, checksumAlgorithmFactories ); + return new ChecksumCalculator(targetFile, checksumAlgorithmFactories); } - private ChecksumCalculator( File targetFile, - Collection checksumAlgorithmFactories ) - { + private ChecksumCalculator(File targetFile, Collection checksumAlgorithmFactories) { this.checksums = new ArrayList<>(); Set algos = new HashSet<>(); - for ( ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories ) - { - if ( algos.add( checksumAlgorithmFactory.getName() ) ) - { - this.checksums.add( new Checksum( checksumAlgorithmFactory ) ); + for (ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories) { + if (algos.add(checksumAlgorithmFactory.getName())) { + this.checksums.add(new Checksum(checksumAlgorithmFactory)); } } this.targetFile = targetFile; } - public void init( long dataOffset ) - { - for ( Checksum checksum : checksums ) - { + public void init(long dataOffset) { + for (Checksum checksum : checksums) { checksum.reset(); } - if ( dataOffset <= 0L ) - { + if (dataOffset <= 0L) { return; } - try ( InputStream in = new BufferedInputStream( Files.newInputStream( targetFile.toPath() ) ) ) - { + try (InputStream in = new BufferedInputStream(Files.newInputStream(targetFile.toPath()))) { long total = 0; - final byte[] buffer = new byte[ 1024 * 32 ]; - while ( total < dataOffset ) - { - int read = in.read( buffer ); - if ( read < 0 ) - { - throw new IOException( targetFile + " contains only " + total - + " bytes, cannot resume download from offset " + dataOffset ); + final byte[] buffer = new byte[1024 * 32]; + while (total < dataOffset) { + int read = in.read(buffer); + if (read < 0) { + throw new IOException(targetFile + " contains only " + total + + " bytes, cannot resume download from offset " + dataOffset); } total += read; - if ( total > dataOffset ) - { + if (total > dataOffset) { read -= total - dataOffset; } - update( ByteBuffer.wrap( buffer, 0, read ) ); + update(ByteBuffer.wrap(buffer, 0, read)); } - } - catch ( IOException e ) - { - for ( Checksum checksum : checksums ) - { - checksum.error( e ); + } catch (IOException e) { + for (Checksum checksum : checksums) { + checksum.error(e); } } } - public void update( ByteBuffer data ) - { - for ( Checksum checksum : checksums ) - { - ( (Buffer) data ).mark(); - checksum.update( data ); - ( (Buffer) data ).reset(); + public void update(ByteBuffer data) { + for (Checksum checksum : checksums) { + ((Buffer) data).mark(); + checksum.update(data); + ((Buffer) data).reset(); } } - public Map get() - { + public Map get() { Map results = new HashMap<>(); - for ( Checksum checksum : checksums ) - { - results.put( checksum.checksumAlgorithmFactory.getName(), checksum.get() ); + for (Checksum checksum : checksums) { + results.put(checksum.checksumAlgorithmFactory.getName(), checksum.get()); } return results; } - } diff --git a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ChecksumValidator.java b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ChecksumValidator.java index 922336224..6cfb425da 100644 --- a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ChecksumValidator.java +++ b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/ChecksumValidator.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.connector.basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.connector.basic; import java.io.File; import java.io.IOException; @@ -40,22 +39,18 @@ /** * Performs checksum validation for a downloaded file. */ -final class ChecksumValidator -{ +final class ChecksumValidator { - interface ChecksumFetcher - { + interface ChecksumFetcher { /** * Fetches the checksums from remote location into provided local file. The checksums fetched in this way * are of kind {@link ChecksumKind#REMOTE_EXTERNAL}. */ - boolean fetchChecksum( URI remote, File local ) - throws Exception; - + boolean fetchChecksum(URI remote, File local) throws Exception; } - private static final Logger LOGGER = LoggerFactory.getLogger( ChecksumValidator.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(ChecksumValidator.class); private final File dataFile; @@ -73,14 +68,14 @@ boolean fetchChecksum( URI remote, File local ) private final Map checksumExpectedValues; - ChecksumValidator( File dataFile, - Collection checksumAlgorithmFactories, - FileProcessor fileProcessor, - ChecksumFetcher checksumFetcher, - ChecksumPolicy checksumPolicy, - Map providedChecksums, - Collection checksumLocations ) - { + ChecksumValidator( + File dataFile, + Collection checksumAlgorithmFactories, + FileProcessor fileProcessor, + ChecksumFetcher checksumFetcher, + ChecksumPolicy checksumPolicy, + Map providedChecksums, + Collection checksumLocations) { this.dataFile = dataFile; this.checksumAlgorithmFactories = checksumAlgorithmFactories; this.fileProcessor = fileProcessor; @@ -91,176 +86,133 @@ boolean fetchChecksum( URI remote, File local ) this.checksumExpectedValues = new HashMap<>(); } - public ChecksumCalculator newChecksumCalculator( File targetFile ) - { - if ( checksumPolicy != null ) - { - return ChecksumCalculator.newInstance( targetFile, checksumAlgorithmFactories ); + public ChecksumCalculator newChecksumCalculator(File targetFile) { + if (checksumPolicy != null) { + return ChecksumCalculator.newInstance(targetFile, checksumAlgorithmFactories); } return null; } - public void validate( Map actualChecksums, Map includedChecksums ) - throws ChecksumFailureException - { - if ( checksumPolicy == null ) - { + public void validate(Map actualChecksums, Map includedChecksums) + throws ChecksumFailureException { + if (checksumPolicy == null) { return; } - if ( providedChecksums != null - && validateChecksums( actualChecksums, ChecksumKind.PROVIDED, providedChecksums ) ) - { + if (providedChecksums != null && validateChecksums(actualChecksums, ChecksumKind.PROVIDED, providedChecksums)) { return; } - if ( includedChecksums != null - && validateChecksums( actualChecksums, ChecksumKind.REMOTE_INCLUDED, includedChecksums ) ) - { + if (includedChecksums != null + && validateChecksums(actualChecksums, ChecksumKind.REMOTE_INCLUDED, includedChecksums)) { return; } - if ( !checksumLocations.isEmpty() ) - { - if ( validateExternalChecksums( actualChecksums ) ) - { + if (!checksumLocations.isEmpty()) { + if (validateExternalChecksums(actualChecksums)) { return; } checksumPolicy.onNoMoreChecksums(); } } - private boolean validateChecksums( Map actualChecksums, ChecksumKind kind, Map checksums ) - throws ChecksumFailureException - { - for ( Map.Entry entry : checksums.entrySet() ) - { + private boolean validateChecksums(Map actualChecksums, ChecksumKind kind, Map checksums) + throws ChecksumFailureException { + for (Map.Entry entry : checksums.entrySet()) { String algo = entry.getKey(); - Object calculated = actualChecksums.get( algo ); - if ( !( calculated instanceof String ) ) - { + Object calculated = actualChecksums.get(algo); + if (!(calculated instanceof String)) { continue; } ChecksumAlgorithmFactory checksumAlgorithmFactory = checksumAlgorithmFactories.stream() - .filter( a -> a.getName().equals( algo ) ) + .filter(a -> a.getName().equals(algo)) .findFirst() - .orElse( null ); - if ( checksumAlgorithmFactory == null ) - { + .orElse(null); + if (checksumAlgorithmFactory == null) { continue; } - String actual = String.valueOf( calculated ); + String actual = String.valueOf(calculated); String expected = entry.getValue().toString(); - checksumExpectedValues.put( getChecksumFile( checksumAlgorithmFactory ), expected ); - - if ( !isEqualChecksum( expected, actual ) ) - { - checksumPolicy.onChecksumMismatch( checksumAlgorithmFactory.getName(), kind, - new ChecksumFailureException( expected, kind.name(), actual ) - ); - } - else if ( checksumPolicy.onChecksumMatch( checksumAlgorithmFactory.getName(), kind ) ) - { + checksumExpectedValues.put(getChecksumFile(checksumAlgorithmFactory), expected); + + if (!isEqualChecksum(expected, actual)) { + checksumPolicy.onChecksumMismatch( + checksumAlgorithmFactory.getName(), + kind, + new ChecksumFailureException(expected, kind.name(), actual)); + } else if (checksumPolicy.onChecksumMatch(checksumAlgorithmFactory.getName(), kind)) { return true; } } return false; } - private boolean validateExternalChecksums( Map actualChecksums ) - throws ChecksumFailureException - { - for ( ChecksumLocation checksumLocation : checksumLocations ) - { + private boolean validateExternalChecksums(Map actualChecksums) throws ChecksumFailureException { + for (ChecksumLocation checksumLocation : checksumLocations) { ChecksumAlgorithmFactory factory = checksumLocation.getChecksumAlgorithmFactory(); - Object calculated = actualChecksums.get( factory.getName() ); - if ( calculated instanceof Exception ) - { + Object calculated = actualChecksums.get(factory.getName()); + if (calculated instanceof Exception) { checksumPolicy.onChecksumError( - factory.getName(), ChecksumKind.REMOTE_EXTERNAL, - new ChecksumFailureException( (Exception) calculated ) - ); + factory.getName(), ChecksumKind.REMOTE_EXTERNAL, new ChecksumFailureException((Exception) + calculated)); continue; } - File checksumFile = getChecksumFile( checksumLocation.getChecksumAlgorithmFactory() ); - try ( FileUtils.TempFile tempFile = FileUtils.newTempFile() ) - { + File checksumFile = getChecksumFile(checksumLocation.getChecksumAlgorithmFactory()); + try (FileUtils.TempFile tempFile = FileUtils.newTempFile()) { File tmp = tempFile.getPath().toFile(); - try - { - if ( !checksumFetcher.fetchChecksum( - checksumLocation.getLocation(), tmp - ) ) - { + try { + if (!checksumFetcher.fetchChecksum(checksumLocation.getLocation(), tmp)) { continue; } - } - catch ( Exception e ) - { + } catch (Exception e) { checksumPolicy.onChecksumError( - factory.getName(), ChecksumKind.REMOTE_EXTERNAL, new ChecksumFailureException( e ) - ); + factory.getName(), ChecksumKind.REMOTE_EXTERNAL, new ChecksumFailureException(e)); continue; } - String actual = String.valueOf( calculated ); - String expected = fileProcessor.readChecksum( tmp ); - checksumExpectedValues.put( checksumFile, expected ); + String actual = String.valueOf(calculated); + String expected = fileProcessor.readChecksum(tmp); + checksumExpectedValues.put(checksumFile, expected); - if ( !isEqualChecksum( expected, actual ) ) - { + if (!isEqualChecksum(expected, actual)) { checksumPolicy.onChecksumMismatch( - factory.getName(), ChecksumKind.REMOTE_EXTERNAL, - new ChecksumFailureException( expected, ChecksumKind.REMOTE_EXTERNAL.name(), actual ) - ); - } - else if ( checksumPolicy.onChecksumMatch( factory.getName(), ChecksumKind.REMOTE_EXTERNAL ) ) - { + factory.getName(), + ChecksumKind.REMOTE_EXTERNAL, + new ChecksumFailureException(expected, ChecksumKind.REMOTE_EXTERNAL.name(), actual)); + } else if (checksumPolicy.onChecksumMatch(factory.getName(), ChecksumKind.REMOTE_EXTERNAL)) { return true; } - } - catch ( IOException e ) - { + } catch (IOException e) { checksumPolicy.onChecksumError( - factory.getName(), ChecksumKind.REMOTE_EXTERNAL, new ChecksumFailureException( e ) - ); + factory.getName(), ChecksumKind.REMOTE_EXTERNAL, new ChecksumFailureException(e)); } } return false; } - private static boolean isEqualChecksum( String expected, String actual ) - { - return expected.equalsIgnoreCase( actual ); + private static boolean isEqualChecksum(String expected, String actual) { + return expected.equalsIgnoreCase(actual); } - private File getChecksumFile( ChecksumAlgorithmFactory factory ) - { - return new File( dataFile.getPath() + '.' + factory.getFileExtension() ); + private File getChecksumFile(ChecksumAlgorithmFactory factory) { + return new File(dataFile.getPath() + '.' + factory.getFileExtension()); } - public void retry() - { + public void retry() { checksumPolicy.onTransferRetry(); checksumExpectedValues.clear(); } - public boolean handle( ChecksumFailureException exception ) - { - return checksumPolicy.onTransferChecksumFailure( exception ); + public boolean handle(ChecksumFailureException exception) { + return checksumPolicy.onTransferChecksumFailure(exception); } - public void commit() - { - for ( Map.Entry entry : checksumExpectedValues.entrySet() ) - { + public void commit() { + for (Map.Entry entry : checksumExpectedValues.entrySet()) { File checksumFile = entry.getKey(); - try - { - fileProcessor.writeChecksum( checksumFile, entry.getValue() ); - } - catch ( IOException e ) - { - LOGGER.debug( "Failed to write checksum file {}", checksumFile, e ); - throw new UncheckedIOException( e ); + try { + fileProcessor.writeChecksum(checksumFile, entry.getValue()); + } catch (IOException e) { + LOGGER.debug("Failed to write checksum file {}", checksumFile, e); + throw new UncheckedIOException(e); } } checksumExpectedValues.clear(); diff --git a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/MetadataTransportListener.java b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/MetadataTransportListener.java index b0740e22f..10d67c57b 100644 --- a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/MetadataTransportListener.java +++ b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/MetadataTransportListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.connector.basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.connector.basic; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.spi.connector.MetadataTransfer; @@ -26,33 +25,25 @@ import org.eclipse.aether.transfer.MetadataTransferException; import org.eclipse.aether.transfer.TransferEvent; -final class MetadataTransportListener - extends TransferTransportListener -{ +final class MetadataTransportListener extends TransferTransportListener { private final RemoteRepository repository; - MetadataTransportListener( MetadataTransfer transfer, RemoteRepository repository, - TransferEvent.Builder eventBuilder ) - { - super( transfer, eventBuilder ); + MetadataTransportListener( + MetadataTransfer transfer, RemoteRepository repository, TransferEvent.Builder eventBuilder) { + super(transfer, eventBuilder); this.repository = repository; } @Override - public void transferFailed( Exception exception, int classification ) - { + public void transferFailed(Exception exception, int classification) { MetadataTransferException e; - if ( classification == Transporter.ERROR_NOT_FOUND ) - { - e = new MetadataNotFoundException( getTransfer().getMetadata(), repository ); + if (classification == Transporter.ERROR_NOT_FOUND) { + e = new MetadataNotFoundException(getTransfer().getMetadata(), repository); + } else { + e = new MetadataTransferException(getTransfer().getMetadata(), repository, exception); } - else - { - e = new MetadataTransferException( getTransfer().getMetadata(), repository, exception ); - } - getTransfer().setException( e ); - super.transferFailed( e, classification ); + getTransfer().setException(e); + super.transferFailed(e, classification); } - } diff --git a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/TransferTransportListener.java b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/TransferTransportListener.java index 3440d893b..fe5787960 100644 --- a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/TransferTransportListener.java +++ b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/TransferTransportListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.connector.basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.connector.basic; import java.nio.ByteBuffer; import java.util.Collections; @@ -30,9 +29,7 @@ import org.eclipse.aether.transfer.TransferEvent.EventType; import org.eclipse.aether.transfer.TransferListener; -class TransferTransportListener - extends TransportListener -{ +class TransferTransportListener extends TransportListener { private final T transfer; @@ -42,101 +39,79 @@ class TransferTransportListener private ChecksumCalculator checksumCalculator; - protected TransferTransportListener( T transfer, TransferEvent.Builder eventBuilder ) - { + protected TransferTransportListener(T transfer, TransferEvent.Builder eventBuilder) { this.transfer = transfer; this.listener = transfer.getListener(); this.eventBuilder = eventBuilder; } - protected T getTransfer() - { + protected T getTransfer() { return transfer; } - public void transferInitiated() - throws TransferCancelledException - { - if ( listener != null ) - { - eventBuilder.resetType( EventType.INITIATED ); - listener.transferInitiated( eventBuilder.build() ); + public void transferInitiated() throws TransferCancelledException { + if (listener != null) { + eventBuilder.resetType(EventType.INITIATED); + listener.transferInitiated(eventBuilder.build()); } } @Override - public void transportStarted( long dataOffset, long dataLength ) - throws TransferCancelledException - { - if ( checksumCalculator != null ) - { - checksumCalculator.init( dataOffset ); + public void transportStarted(long dataOffset, long dataLength) throws TransferCancelledException { + if (checksumCalculator != null) { + checksumCalculator.init(dataOffset); } - if ( listener != null ) - { - eventBuilder.resetType( EventType.STARTED ).setTransferredBytes( dataOffset ); + if (listener != null) { + eventBuilder.resetType(EventType.STARTED).setTransferredBytes(dataOffset); TransferEvent event = eventBuilder.build(); - event.getResource().setContentLength( dataLength ).setResumeOffset( dataOffset ); - listener.transferStarted( event ); + event.getResource().setContentLength(dataLength).setResumeOffset(dataOffset); + listener.transferStarted(event); } } @Override - public void transportProgressed( ByteBuffer data ) - throws TransferCancelledException - { - if ( checksumCalculator != null ) - { - checksumCalculator.update( data ); + public void transportProgressed(ByteBuffer data) throws TransferCancelledException { + if (checksumCalculator != null) { + checksumCalculator.update(data); } - if ( listener != null ) - { - eventBuilder.resetType( EventType.PROGRESSED ).addTransferredBytes( data.remaining() ) - .setDataBuffer( data ); - listener.transferProgressed( eventBuilder.build() ); + if (listener != null) { + eventBuilder + .resetType(EventType.PROGRESSED) + .addTransferredBytes(data.remaining()) + .setDataBuffer(data); + listener.transferProgressed(eventBuilder.build()); } } - public void transferCorrupted( Exception exception ) - throws TransferCancelledException - { - if ( listener != null ) - { - eventBuilder.resetType( EventType.CORRUPTED ).setException( exception ); - listener.transferCorrupted( eventBuilder.build() ); + public void transferCorrupted(Exception exception) throws TransferCancelledException { + if (listener != null) { + eventBuilder.resetType(EventType.CORRUPTED).setException(exception); + listener.transferCorrupted(eventBuilder.build()); } } - public void transferFailed( Exception exception, int classification ) - { - if ( listener != null ) - { - eventBuilder.resetType( EventType.FAILED ).setException( exception ); - listener.transferFailed( eventBuilder.build() ); + public void transferFailed(Exception exception, int classification) { + if (listener != null) { + eventBuilder.resetType(EventType.FAILED).setException(exception); + listener.transferFailed(eventBuilder.build()); } } - public void transferSucceeded() - { - if ( listener != null ) - { - eventBuilder.resetType( EventType.SUCCEEDED ); - listener.transferSucceeded( eventBuilder.build() ); + public void transferSucceeded() { + if (listener != null) { + eventBuilder.resetType(EventType.SUCCEEDED); + listener.transferSucceeded(eventBuilder.build()); } } - public Map getChecksums() - { - if ( checksumCalculator == null ) - { + public Map getChecksums() { + if (checksumCalculator == null) { return Collections.emptyMap(); } return checksumCalculator.get(); } - public void setChecksumCalculator( ChecksumCalculator checksumCalculator ) - { + public void setChecksumCalculator(ChecksumCalculator checksumCalculator) { this.checksumCalculator = checksumCalculator; } - } diff --git a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/package-info.java b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/package-info.java index df8689701..32574906f 100644 --- a/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/package-info.java +++ b/maven-resolver-connector-basic/src/main/java/org/eclipse/aether/connector/basic/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Support for downloads/uploads using remote repositories that have a URI-based content structure/layout. */ package org.eclipse.aether.connector.basic; - diff --git a/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/ChecksumCalculatorTest.java b/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/ChecksumCalculatorTest.java index 6560537f0..ea6c37626 100644 --- a/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/ChecksumCalculatorTest.java +++ b/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/ChecksumCalculatorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.connector.basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.MD5; -import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.SHA1; -import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.SHA256; -import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.SHA512; -import static org.junit.Assert.*; +package org.eclipse.aether.connector.basic; import java.io.File; import java.io.IOException; @@ -38,132 +31,135 @@ import org.junit.Before; import org.junit.Test; -public class ChecksumCalculatorTest -{ +import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.MD5; +import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.SHA1; +import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.SHA256; +import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.SHA512; +import static org.junit.Assert.*; + +public class ChecksumCalculatorTest { private File file; private final TestChecksumAlgorithmSelector selector = new TestChecksumAlgorithmSelector(); - private ChecksumCalculator newCalculator( String... algos ) - { + private ChecksumCalculator newCalculator(String... algos) { List checksumAlgorithmFactories = new ArrayList<>(); - for ( String algo : algos ) - { - checksumAlgorithmFactories.add( selector.select( algo ) ); + for (String algo : algos) { + checksumAlgorithmFactories.add(selector.select(algo)); } - return ChecksumCalculator.newInstance( file, checksumAlgorithmFactories ); + return ChecksumCalculator.newInstance(file, checksumAlgorithmFactories); } - private ByteBuffer toBuffer( String data ) - { - return ByteBuffer.wrap( data.getBytes( StandardCharsets.UTF_8 ) ); + private ByteBuffer toBuffer(String data) { + return ByteBuffer.wrap(data.getBytes(StandardCharsets.UTF_8)); } @Before - public void init() - throws Exception - { - file = TestFileUtils.createTempFile( "Hello World!" ); + public void init() throws Exception { + file = TestFileUtils.createTempFile("Hello World!"); } @Test - public void testNoOffset() - { - ChecksumCalculator calculator = newCalculator( SHA512, SHA256, SHA1, MD5 ); - calculator.init( 0 ); - calculator.update( toBuffer( "Hello World!" ) ); + public void testNoOffset() { + ChecksumCalculator calculator = newCalculator(SHA512, SHA256, SHA1, MD5); + calculator.init(0); + calculator.update(toBuffer("Hello World!")); Map digests = calculator.get(); - assertNotNull( digests ); - assertEquals( "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8", digests.get( SHA512 ) ); - assertEquals( "7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", digests.get( SHA256 ) ); - assertEquals( "2ef7bde608ce5404e97d5f042f95f89f1c232871", digests.get( SHA1 ) ); - assertEquals( "ed076287532e86365e841e92bfc50d8c", digests.get( MD5 ) ); - assertEquals( 4, digests.size() ); + assertNotNull(digests); + assertEquals( + "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8", + digests.get(SHA512)); + assertEquals("7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", digests.get(SHA256)); + assertEquals("2ef7bde608ce5404e97d5f042f95f89f1c232871", digests.get(SHA1)); + assertEquals("ed076287532e86365e841e92bfc50d8c", digests.get(MD5)); + assertEquals(4, digests.size()); } @Test - public void testWithOffset() - { - ChecksumCalculator calculator = newCalculator( SHA512, SHA256, SHA1, MD5 ); - calculator.init( 6 ); - calculator.update( toBuffer( "World!" ) ); + public void testWithOffset() { + ChecksumCalculator calculator = newCalculator(SHA512, SHA256, SHA1, MD5); + calculator.init(6); + calculator.update(toBuffer("World!")); Map digests = calculator.get(); - assertNotNull( digests ); - assertEquals( "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8", digests.get( SHA512 ) ); - assertEquals( "7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", digests.get( SHA256 ) ); - assertEquals( "2ef7bde608ce5404e97d5f042f95f89f1c232871", digests.get( SHA1 ) ); - assertEquals( "ed076287532e86365e841e92bfc50d8c", digests.get( MD5 ) ); - assertEquals( 4, digests.size() ); + assertNotNull(digests); + assertEquals( + "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8", + digests.get(SHA512)); + assertEquals("7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", digests.get(SHA256)); + assertEquals("2ef7bde608ce5404e97d5f042f95f89f1c232871", digests.get(SHA1)); + assertEquals("ed076287532e86365e841e92bfc50d8c", digests.get(MD5)); + assertEquals(4, digests.size()); } @Test - public void testWithExcessiveOffset() - { - ChecksumCalculator calculator = newCalculator( SHA512, SHA256, SHA1, MD5 ); - calculator.init( 100 ); - calculator.update( toBuffer( "World!" ) ); + public void testWithExcessiveOffset() { + ChecksumCalculator calculator = newCalculator(SHA512, SHA256, SHA1, MD5); + calculator.init(100); + calculator.update(toBuffer("World!")); Map digests = calculator.get(); - assertNotNull( digests ); - assertTrue( digests.get( SHA512 ) instanceof IOException ); - assertTrue( digests.get( SHA256 ) instanceof IOException ); - assertTrue( digests.get( SHA1 ) instanceof IOException ); - assertTrue( digests.get( MD5 ) instanceof IOException ); - assertEquals( 4, digests.size() ); + assertNotNull(digests); + assertTrue(digests.get(SHA512) instanceof IOException); + assertTrue(digests.get(SHA256) instanceof IOException); + assertTrue(digests.get(SHA1) instanceof IOException); + assertTrue(digests.get(MD5) instanceof IOException); + assertEquals(4, digests.size()); } - @Test( expected = IllegalArgumentException.class ) - public void testUnknownAlgorithm() - { - // resolver now does not tolerate unknown checksums: as they may be set by user only, it is user misconfiguration - newCalculator( "unknown", SHA1 ); + @Test(expected = IllegalArgumentException.class) + public void testUnknownAlgorithm() { + // resolver now does not tolerate unknown checksums: as they may be set by user only, it is user + // misconfiguration + newCalculator("unknown", SHA1); } @Test - public void testNoInitCall() - { - ChecksumCalculator calculator = newCalculator( SHA512, SHA256, SHA1, MD5 ); - calculator.update( toBuffer( "Hello World!" ) ); + public void testNoInitCall() { + ChecksumCalculator calculator = newCalculator(SHA512, SHA256, SHA1, MD5); + calculator.update(toBuffer("Hello World!")); Map digests = calculator.get(); - assertNotNull( digests ); - assertEquals( "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8", digests.get( SHA512 ) ); - assertEquals( "7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", digests.get( SHA256 ) ); - assertEquals( "2ef7bde608ce5404e97d5f042f95f89f1c232871", digests.get( SHA1 ) ); - assertEquals( "ed076287532e86365e841e92bfc50d8c", digests.get( MD5 ) ); - assertEquals( 4, digests.size() ); + assertNotNull(digests); + assertEquals( + "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8", + digests.get(SHA512)); + assertEquals("7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", digests.get(SHA256)); + assertEquals("2ef7bde608ce5404e97d5f042f95f89f1c232871", digests.get(SHA1)); + assertEquals("ed076287532e86365e841e92bfc50d8c", digests.get(MD5)); + assertEquals(4, digests.size()); } @Test - public void testRestart() - { - ChecksumCalculator calculator = newCalculator( SHA512, SHA256, SHA1, MD5 ); - calculator.init( 0 ); - calculator.update( toBuffer( "Ignored" ) ); - calculator.init( 0 ); - calculator.update( toBuffer( "Hello World!" ) ); + public void testRestart() { + ChecksumCalculator calculator = newCalculator(SHA512, SHA256, SHA1, MD5); + calculator.init(0); + calculator.update(toBuffer("Ignored")); + calculator.init(0); + calculator.update(toBuffer("Hello World!")); Map digests = calculator.get(); - assertNotNull( digests ); - assertEquals( "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8", digests.get( SHA512 ) ); - assertEquals( "7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", digests.get( SHA256 ) ); - assertEquals( "2ef7bde608ce5404e97d5f042f95f89f1c232871", digests.get( SHA1 ) ); - assertEquals( "ed076287532e86365e841e92bfc50d8c", digests.get( MD5 ) ); - assertEquals( 4, digests.size() ); + assertNotNull(digests); + assertEquals( + "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8", + digests.get(SHA512)); + assertEquals("7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", digests.get(SHA256)); + assertEquals("2ef7bde608ce5404e97d5f042f95f89f1c232871", digests.get(SHA1)); + assertEquals("ed076287532e86365e841e92bfc50d8c", digests.get(MD5)); + assertEquals(4, digests.size()); } @Test - public void testRestartAfterError() - { - ChecksumCalculator calculator = newCalculator( SHA512, SHA256, SHA1, MD5 ); - calculator.init( 100 ); - calculator.init( 0 ); - calculator.update( toBuffer( "Hello World!" ) ); + public void testRestartAfterError() { + ChecksumCalculator calculator = newCalculator(SHA512, SHA256, SHA1, MD5); + calculator.init(100); + calculator.init(0); + calculator.update(toBuffer("Hello World!")); Map digests = calculator.get(); - assertNotNull( digests ); - assertEquals( "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8", digests.get( SHA512 ) ); - assertEquals( "7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", digests.get( SHA256 ) ); - assertEquals( "2ef7bde608ce5404e97d5f042f95f89f1c232871", digests.get( SHA1 ) ); - assertEquals( "ed076287532e86365e841e92bfc50d8c", digests.get( MD5 ) ); - assertEquals( 4, digests.size() ); + assertNotNull(digests); + assertEquals( + "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8", + digests.get(SHA512)); + assertEquals("7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", digests.get(SHA256)); + assertEquals("2ef7bde608ce5404e97d5f042f95f89f1c232871", digests.get(SHA1)); + assertEquals("ed076287532e86365e841e92bfc50d8c", digests.get(MD5)); + assertEquals(4, digests.size()); } - } diff --git a/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/ChecksumValidatorTest.java b/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/ChecksumValidatorTest.java index 7534c2550..4718f6b8a 100644 --- a/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/ChecksumValidatorTest.java +++ b/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/ChecksumValidatorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.connector.basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,10 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.MD5; -import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.SHA1; -import static org.junit.Assert.*; +package org.eclipse.aether.connector.basic; import java.io.File; import java.io.IOException; @@ -43,12 +38,13 @@ import org.junit.Before; import org.junit.Test; -public class ChecksumValidatorTest -{ +import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.MD5; +import static org.eclipse.aether.connector.basic.TestChecksumAlgorithmSelector.SHA1; +import static org.junit.Assert.*; + +public class ChecksumValidatorTest { - private static class StubChecksumPolicy - implements ChecksumPolicy - { + private static class StubChecksumPolicy implements ChecksumPolicy { boolean inspectAll; @@ -59,13 +55,10 @@ private static class StubChecksumPolicy private Object conclusion; @Override - public boolean onChecksumMatch( String algorithm, ChecksumKind kind ) - { - callbacks.add( String.format( "match(%s, %s)", algorithm, kind ) ); - if ( inspectAll ) - { - if ( conclusion == null ) - { + public boolean onChecksumMatch(String algorithm, ChecksumKind kind) { + callbacks.add(String.format("match(%s, %s)", algorithm, kind)); + if (inspectAll) { + if (conclusion == null) { conclusion = true; } return false; @@ -74,12 +67,10 @@ public boolean onChecksumMatch( String algorithm, ChecksumKind kind ) } @Override - public void onChecksumMismatch( String algorithm, ChecksumKind kind, ChecksumFailureException exception ) - throws ChecksumFailureException - { - callbacks.add( String.format( "mismatch(%s, %s)", algorithm, kind ) ); - if ( inspectAll ) - { + public void onChecksumMismatch(String algorithm, ChecksumKind kind, ChecksumFailureException exception) + throws ChecksumFailureException { + callbacks.add(String.format("mismatch(%s, %s)", algorithm, kind)); + if (inspectAll) { conclusion = exception; return; } @@ -87,49 +78,38 @@ public void onChecksumMismatch( String algorithm, ChecksumKind kind, ChecksumFai } @Override - public void onChecksumError( String algorithm, ChecksumKind kind, ChecksumFailureException exception ) - { - callbacks.add( String.format( "error(%s, %s, %s)", algorithm, kind, exception.getCause().getMessage() ) ); + public void onChecksumError(String algorithm, ChecksumKind kind, ChecksumFailureException exception) { + callbacks.add(String.format( + "error(%s, %s, %s)", algorithm, kind, exception.getCause().getMessage())); } @Override - public void onNoMoreChecksums() - throws ChecksumFailureException - { - callbacks.add( String.format( "noMore()" ) ); - if ( conclusion instanceof ChecksumFailureException ) - { + public void onNoMoreChecksums() throws ChecksumFailureException { + callbacks.add(String.format("noMore()")); + if (conclusion instanceof ChecksumFailureException) { throw (ChecksumFailureException) conclusion; - } - else if ( !Boolean.TRUE.equals( conclusion ) ) - { - throw new ChecksumFailureException( "no checksums" ); + } else if (!Boolean.TRUE.equals(conclusion)) { + throw new ChecksumFailureException("no checksums"); } } @Override - public void onTransferRetry() - { - callbacks.add( String.format( "retry()" ) ); + public void onTransferRetry() { + callbacks.add(String.format("retry()")); } @Override - public boolean onTransferChecksumFailure( ChecksumFailureException exception ) - { - callbacks.add( String.format( "fail(%s)", exception.getMessage() ) ); + public boolean onTransferChecksumFailure(ChecksumFailureException exception) { + callbacks.add(String.format("fail(%s)", exception.getMessage())); return tolerateFailure; } - void assertCallbacks( String... callbacks ) - { - assertEquals( Arrays.asList( callbacks ), this.callbacks ); + void assertCallbacks(String... callbacks) { + assertEquals(Arrays.asList(callbacks), this.callbacks); } - } - private static class StubChecksumFetcher - implements ChecksumValidator.ChecksumFetcher - { + private static class StubChecksumFetcher implements ChecksumValidator.ChecksumFetcher { HashMap checksums = new HashMap<>(); @@ -138,44 +118,35 @@ private static class StubChecksumFetcher private final ArrayList fetchedFiles = new ArrayList<>(); @Override - public boolean fetchChecksum( URI remote, File local ) - throws Exception - { - fetchedFiles.add( remote ); - Object checksum = checksums.get( remote ); - if ( checksum == null ) - { + public boolean fetchChecksum(URI remote, File local) throws Exception { + fetchedFiles.add(remote); + Object checksum = checksums.get(remote); + if (checksum == null) { return false; } - if ( checksum instanceof Exception ) - { + if (checksum instanceof Exception) { throw (Exception) checksum; } - TestFileUtils.writeString( local, checksum.toString() ); - checksumFiles.add( local ); + TestFileUtils.writeString(local, checksum.toString()); + checksumFiles.add(local); return true; } - void mock( String algo, Object value ) - { - checksums.put( toUri( algo ), value ); + void mock(String algo, Object value) { + checksums.put(toUri(algo), value); } - void assertFetchedFiles( String... algos ) - { + void assertFetchedFiles(String... algos) { List expected = new ArrayList<>(); - for ( String algo : algos ) - { - expected.add( toUri( algo ) ); + for (String algo : algos) { + expected.add(toUri(algo)); } - assertEquals( expected, fetchedFiles ); + assertEquals(expected, fetchedFiles); } - private static URI toUri( String algo ) - { - return newChecksum( algo ).getLocation(); + private static URI toUri(String algo) { + return newChecksum(algo).getLocation(); } - } private StubChecksumPolicy policy; @@ -186,288 +157,250 @@ private static URI toUri( String algo ) private static final TestChecksumAlgorithmSelector selector = new TestChecksumAlgorithmSelector(); - private List newChecksumAlgorithmFactories( String... factories ) - { + private List newChecksumAlgorithmFactories(String... factories) { List checksums = new ArrayList<>(); - for ( String factory : factories ) - { - checksums.add( selector.select( factory ) ); + for (String factory : factories) { + checksums.add(selector.select(factory)); } return checksums; } - private static RepositoryLayout.ChecksumLocation newChecksum( String factory ) - { - return RepositoryLayout.ChecksumLocation.forLocation( URI.create( "file" ), selector.select( factory ) ); + private static RepositoryLayout.ChecksumLocation newChecksum(String factory) { + return RepositoryLayout.ChecksumLocation.forLocation(URI.create("file"), selector.select(factory)); } - private List newChecksums( List checksumAlgorithmFactories ) - { + private List newChecksums( + List checksumAlgorithmFactories) { List checksums = new ArrayList<>(); - for ( ChecksumAlgorithmFactory factory : checksumAlgorithmFactories ) - { - checksums.add( RepositoryLayout.ChecksumLocation.forLocation( URI.create( "file" ), factory ) ); + for (ChecksumAlgorithmFactory factory : checksumAlgorithmFactories) { + checksums.add(RepositoryLayout.ChecksumLocation.forLocation(URI.create("file"), factory)); } return checksums; } - private ChecksumValidator newValidator( String... factories ) - { - return newValidator( null, factories ); + private ChecksumValidator newValidator(String... factories) { + return newValidator(null, factories); } - private ChecksumValidator newValidator( Map providedChecksums, String... factories ) - { - List checksumAlgorithmFactories = newChecksumAlgorithmFactories( factories ); - return new ChecksumValidator( dataFile, checksumAlgorithmFactories, new TestFileProcessor(), fetcher, policy, providedChecksums, newChecksums( checksumAlgorithmFactories ) ); + private ChecksumValidator newValidator(Map providedChecksums, String... factories) { + List checksumAlgorithmFactories = newChecksumAlgorithmFactories(factories); + return new ChecksumValidator( + dataFile, + checksumAlgorithmFactories, + new TestFileProcessor(), + fetcher, + policy, + providedChecksums, + newChecksums(checksumAlgorithmFactories)); } - private Map checksums( String... algoDigestPairs ) - { + private Map checksums(String... algoDigestPairs) { Map checksums = new LinkedHashMap<>(); - for ( int i = 0; i < algoDigestPairs.length; i += 2 ) - { + for (int i = 0; i < algoDigestPairs.length; i += 2) { String algo = algoDigestPairs[i]; String digest = algoDigestPairs[i + 1]; - if ( digest == null ) - { - checksums.put( algo, new IOException( "error" ) ); - } - else - { - checksums.put( algo, digest ); + if (digest == null) { + checksums.put(algo, new IOException("error")); + } else { + checksums.put(algo, digest); } } return checksums; } @Before - public void init() - throws Exception - { - dataFile = TestFileUtils.createTempFile( "" ); + public void init() throws Exception { + dataFile = TestFileUtils.createTempFile(""); dataFile.delete(); policy = new StubChecksumPolicy(); fetcher = new StubChecksumFetcher(); } @Test - public void testValidate_NullPolicy() - throws Exception - { + public void testValidate_NullPolicy() throws Exception { policy = null; - ChecksumValidator validator = newValidator( SHA1 ); - validator.validate( checksums( SHA1, "ignored" ), null ); + ChecksumValidator validator = newValidator(SHA1); + validator.validate(checksums(SHA1, "ignored"), null); fetcher.assertFetchedFiles(); } @Test - public void testValidate_AcceptOnFirstMatch() - throws Exception - { - ChecksumValidator validator = newValidator( SHA1 ); - fetcher.mock( SHA1, "foo" ); - validator.validate( checksums( SHA1, "foo" ), null ); - fetcher.assertFetchedFiles( SHA1 ); - policy.assertCallbacks( "match(SHA-1, REMOTE_EXTERNAL)" ); + public void testValidate_AcceptOnFirstMatch() throws Exception { + ChecksumValidator validator = newValidator(SHA1); + fetcher.mock(SHA1, "foo"); + validator.validate(checksums(SHA1, "foo"), null); + fetcher.assertFetchedFiles(SHA1); + policy.assertCallbacks("match(SHA-1, REMOTE_EXTERNAL)"); } @Test - public void testValidate_FailOnFirstMismatch() - { - ChecksumValidator validator = newValidator( SHA1 ); - fetcher.mock( SHA1, "foo" ); - try - { - validator.validate( checksums( SHA1, "not-foo" ), null ); - fail( "expected exception" ); - } - catch ( ChecksumFailureException e ) - { - assertEquals( "foo", e.getExpected() ); - assertEquals( ChecksumKind.REMOTE_EXTERNAL.name(), e.getExpectedKind() ); - assertEquals( "not-foo", e.getActual() ); - assertTrue( e.isRetryWorthy() ); + public void testValidate_FailOnFirstMismatch() { + ChecksumValidator validator = newValidator(SHA1); + fetcher.mock(SHA1, "foo"); + try { + validator.validate(checksums(SHA1, "not-foo"), null); + fail("expected exception"); + } catch (ChecksumFailureException e) { + assertEquals("foo", e.getExpected()); + assertEquals(ChecksumKind.REMOTE_EXTERNAL.name(), e.getExpectedKind()); + assertEquals("not-foo", e.getActual()); + assertTrue(e.isRetryWorthy()); } - fetcher.assertFetchedFiles( SHA1 ); - policy.assertCallbacks( "mismatch(SHA-1, REMOTE_EXTERNAL)" ); + fetcher.assertFetchedFiles(SHA1); + policy.assertCallbacks("mismatch(SHA-1, REMOTE_EXTERNAL)"); } @Test - public void testValidate_AcceptOnEnd() - throws Exception - { + public void testValidate_AcceptOnEnd() throws Exception { policy.inspectAll = true; - ChecksumValidator validator = newValidator( SHA1, MD5 ); - fetcher.mock( SHA1, "foo" ); - fetcher.mock( MD5, "bar" ); - validator.validate( checksums( SHA1, "foo", MD5, "bar" ), null ); - fetcher.assertFetchedFiles( SHA1, MD5 ); - policy.assertCallbacks( "match(SHA-1, REMOTE_EXTERNAL)", "match(MD5, REMOTE_EXTERNAL)", "noMore()" ); + ChecksumValidator validator = newValidator(SHA1, MD5); + fetcher.mock(SHA1, "foo"); + fetcher.mock(MD5, "bar"); + validator.validate(checksums(SHA1, "foo", MD5, "bar"), null); + fetcher.assertFetchedFiles(SHA1, MD5); + policy.assertCallbacks("match(SHA-1, REMOTE_EXTERNAL)", "match(MD5, REMOTE_EXTERNAL)", "noMore()"); } @Test - public void testValidate_FailOnEnd() - { + public void testValidate_FailOnEnd() { policy.inspectAll = true; - ChecksumValidator validator = newValidator( SHA1, MD5 ); - fetcher.mock( SHA1, "foo" ); - fetcher.mock( MD5, "bar" ); - try - { - validator.validate( checksums( SHA1, "not-foo", MD5, "bar" ), null ); - fail( "expected exception" ); + ChecksumValidator validator = newValidator(SHA1, MD5); + fetcher.mock(SHA1, "foo"); + fetcher.mock(MD5, "bar"); + try { + validator.validate(checksums(SHA1, "not-foo", MD5, "bar"), null); + fail("expected exception"); + } catch (ChecksumFailureException e) { + assertEquals("foo", e.getExpected()); + assertEquals(ChecksumKind.REMOTE_EXTERNAL.name(), e.getExpectedKind()); + assertEquals("not-foo", e.getActual()); + assertTrue(e.isRetryWorthy()); } - catch ( ChecksumFailureException e ) - { - assertEquals( "foo", e.getExpected() ); - assertEquals( ChecksumKind.REMOTE_EXTERNAL.name(), e.getExpectedKind() ); - assertEquals( "not-foo", e.getActual() ); - assertTrue( e.isRetryWorthy() ); - } - fetcher.assertFetchedFiles( SHA1, MD5 ); - policy.assertCallbacks( "mismatch(SHA-1, REMOTE_EXTERNAL)", "match(MD5, REMOTE_EXTERNAL)", "noMore()" ); + fetcher.assertFetchedFiles(SHA1, MD5); + policy.assertCallbacks("mismatch(SHA-1, REMOTE_EXTERNAL)", "match(MD5, REMOTE_EXTERNAL)", "noMore()"); } @Test - public void testValidate_IncludedBeforeExternal() - throws Exception - { + public void testValidate_IncludedBeforeExternal() throws Exception { policy.inspectAll = true; HashMap provided = new HashMap<>(); - provided.put( SHA1, "foo" ); - ChecksumValidator validator = newValidator( provided, SHA1, MD5 ); - fetcher.mock( SHA1, "foo" ); - fetcher.mock( MD5, "bar" ); - validator.validate( checksums( SHA1, "foo", MD5, "bar" ), checksums( SHA1, "foo", MD5, "bar" ) ); - fetcher.assertFetchedFiles( SHA1, MD5 ); - policy.assertCallbacks( "match(SHA-1, PROVIDED)", "match(SHA-1, REMOTE_INCLUDED)", "match(MD5, REMOTE_INCLUDED)", - "match(SHA-1, REMOTE_EXTERNAL)", "match(MD5, REMOTE_EXTERNAL)", "noMore()" ); + provided.put(SHA1, "foo"); + ChecksumValidator validator = newValidator(provided, SHA1, MD5); + fetcher.mock(SHA1, "foo"); + fetcher.mock(MD5, "bar"); + validator.validate(checksums(SHA1, "foo", MD5, "bar"), checksums(SHA1, "foo", MD5, "bar")); + fetcher.assertFetchedFiles(SHA1, MD5); + policy.assertCallbacks( + "match(SHA-1, PROVIDED)", + "match(SHA-1, REMOTE_INCLUDED)", + "match(MD5, REMOTE_INCLUDED)", + "match(SHA-1, REMOTE_EXTERNAL)", + "match(MD5, REMOTE_EXTERNAL)", + "noMore()"); } @Test - public void testValidate_CaseInsensitive() - throws Exception - { + public void testValidate_CaseInsensitive() throws Exception { policy.inspectAll = true; - ChecksumValidator validator = newValidator( SHA1 ); - fetcher.mock( SHA1, "FOO" ); - validator.validate( checksums( SHA1, "foo" ), checksums( SHA1, "foo" ) ); - policy.assertCallbacks( "match(SHA-1, REMOTE_INCLUDED)", "match(SHA-1, REMOTE_EXTERNAL)", "noMore()" ); + ChecksumValidator validator = newValidator(SHA1); + fetcher.mock(SHA1, "FOO"); + validator.validate(checksums(SHA1, "foo"), checksums(SHA1, "foo")); + policy.assertCallbacks("match(SHA-1, REMOTE_INCLUDED)", "match(SHA-1, REMOTE_EXTERNAL)", "noMore()"); } @Test - public void testValidate_MissingRemoteChecksum() - throws Exception - { - ChecksumValidator validator = newValidator( SHA1, MD5 ); - fetcher.mock( MD5, "bar" ); - validator.validate( checksums( MD5, "bar" ), null ); - fetcher.assertFetchedFiles( SHA1, MD5 ); - policy.assertCallbacks( "match(MD5, REMOTE_EXTERNAL)" ); + public void testValidate_MissingRemoteChecksum() throws Exception { + ChecksumValidator validator = newValidator(SHA1, MD5); + fetcher.mock(MD5, "bar"); + validator.validate(checksums(MD5, "bar"), null); + fetcher.assertFetchedFiles(SHA1, MD5); + policy.assertCallbacks("match(MD5, REMOTE_EXTERNAL)"); } @Test - public void testValidate_InaccessibleRemoteChecksum() - throws Exception - { - ChecksumValidator validator = newValidator( SHA1, MD5 ); - fetcher.mock( SHA1, new IOException( "inaccessible" ) ); - fetcher.mock( MD5, "bar" ); - validator.validate( checksums( MD5, "bar" ), null ); - fetcher.assertFetchedFiles( SHA1, MD5 ); - policy.assertCallbacks( "error(SHA-1, REMOTE_EXTERNAL, inaccessible)", "match(MD5, REMOTE_EXTERNAL)" ); + public void testValidate_InaccessibleRemoteChecksum() throws Exception { + ChecksumValidator validator = newValidator(SHA1, MD5); + fetcher.mock(SHA1, new IOException("inaccessible")); + fetcher.mock(MD5, "bar"); + validator.validate(checksums(MD5, "bar"), null); + fetcher.assertFetchedFiles(SHA1, MD5); + policy.assertCallbacks("error(SHA-1, REMOTE_EXTERNAL, inaccessible)", "match(MD5, REMOTE_EXTERNAL)"); } @Test - public void testValidate_InaccessibleLocalChecksum() - throws Exception - { - ChecksumValidator validator = newValidator( SHA1, MD5 ); - fetcher.mock( SHA1, "foo" ); - fetcher.mock( MD5, "bar" ); - validator.validate( checksums( SHA1, null, MD5, "bar" ), null ); - fetcher.assertFetchedFiles( MD5 ); - policy.assertCallbacks( "error(SHA-1, REMOTE_EXTERNAL, error)", "match(MD5, REMOTE_EXTERNAL)" ); + public void testValidate_InaccessibleLocalChecksum() throws Exception { + ChecksumValidator validator = newValidator(SHA1, MD5); + fetcher.mock(SHA1, "foo"); + fetcher.mock(MD5, "bar"); + validator.validate(checksums(SHA1, null, MD5, "bar"), null); + fetcher.assertFetchedFiles(MD5); + policy.assertCallbacks("error(SHA-1, REMOTE_EXTERNAL, error)", "match(MD5, REMOTE_EXTERNAL)"); } @Test - public void testHandle_Accept() - { + public void testHandle_Accept() { policy.tolerateFailure = true; - ChecksumValidator validator = newValidator( SHA1 ); - assertTrue( validator.handle( new ChecksumFailureException( "accept" ) ) ); - policy.assertCallbacks( "fail(accept)" ); + ChecksumValidator validator = newValidator(SHA1); + assertTrue(validator.handle(new ChecksumFailureException("accept"))); + policy.assertCallbacks("fail(accept)"); } @Test - public void testHandle_Reject() - { + public void testHandle_Reject() { policy.tolerateFailure = false; - ChecksumValidator validator = newValidator( SHA1 ); - assertFalse( validator.handle( new ChecksumFailureException( "reject" ) ) ); - policy.assertCallbacks( "fail(reject)" ); + ChecksumValidator validator = newValidator(SHA1); + assertFalse(validator.handle(new ChecksumFailureException("reject"))); + policy.assertCallbacks("fail(reject)"); } @Test - public void testRetry_ResetPolicy() - { - ChecksumValidator validator = newValidator( SHA1 ); + public void testRetry_ResetPolicy() { + ChecksumValidator validator = newValidator(SHA1); validator.retry(); - policy.assertCallbacks( "retry()" ); + policy.assertCallbacks("retry()"); } @Test - public void testRetry_RemoveTempFiles() - throws Exception - { - ChecksumValidator validator = newValidator( SHA1 ); - fetcher.mock( SHA1, "foo" ); - validator.validate( checksums( SHA1, "foo" ), null ); - fetcher.assertFetchedFiles( SHA1 ); - assertEquals( 1, fetcher.checksumFiles.size() ); + public void testRetry_RemoveTempFiles() throws Exception { + ChecksumValidator validator = newValidator(SHA1); + fetcher.mock(SHA1, "foo"); + validator.validate(checksums(SHA1, "foo"), null); + fetcher.assertFetchedFiles(SHA1); + assertEquals(1, fetcher.checksumFiles.size()); validator.retry(); - for ( File file : fetcher.checksumFiles ) - { - assertFalse( file.getAbsolutePath(), file.exists() ); + for (File file : fetcher.checksumFiles) { + assertFalse(file.getAbsolutePath(), file.exists()); } } @Test - public void testCommit_SaveChecksumFiles() - throws Exception - { + public void testCommit_SaveChecksumFiles() throws Exception { policy.inspectAll = true; - ChecksumValidator validator = newValidator( SHA1, MD5 ); - fetcher.mock( MD5, "bar" ); - validator.validate( checksums( SHA1, "foo", MD5, "bar" ), checksums( SHA1, "foo" ) ); - assertEquals( 1, fetcher.checksumFiles.size() ); + ChecksumValidator validator = newValidator(SHA1, MD5); + fetcher.mock(MD5, "bar"); + validator.validate(checksums(SHA1, "foo", MD5, "bar"), checksums(SHA1, "foo")); + assertEquals(1, fetcher.checksumFiles.size()); validator.commit(); - File checksumFile = new File( dataFile.getPath() + ".sha1" ); - assertTrue( checksumFile.getAbsolutePath(), checksumFile.isFile() ); - assertEquals( "foo", TestFileUtils.readString( checksumFile ) ); - checksumFile = new File( dataFile.getPath() + ".md5" ); - assertTrue( checksumFile.getAbsolutePath(), checksumFile.isFile() ); - assertEquals( "bar", TestFileUtils.readString( checksumFile ) ); - for ( File file : fetcher.checksumFiles ) - { - assertFalse( file.getAbsolutePath(), file.exists() ); + File checksumFile = new File(dataFile.getPath() + ".sha1"); + assertTrue(checksumFile.getAbsolutePath(), checksumFile.isFile()); + assertEquals("foo", TestFileUtils.readString(checksumFile)); + checksumFile = new File(dataFile.getPath() + ".md5"); + assertTrue(checksumFile.getAbsolutePath(), checksumFile.isFile()); + assertEquals("bar", TestFileUtils.readString(checksumFile)); + for (File file : fetcher.checksumFiles) { + assertFalse(file.getAbsolutePath(), file.exists()); } } @Test - public void testNoCommit_NoTempFiles() - throws Exception - { - ChecksumValidator validator = newValidator( SHA1 ); - fetcher.mock( SHA1, "foo" ); - validator.validate( checksums( SHA1, "foo" ), null ); - fetcher.assertFetchedFiles( SHA1 ); - assertEquals( 1, fetcher.checksumFiles.size() ); - for ( File file : fetcher.checksumFiles ) - { - assertFalse( file.getAbsolutePath(), file.exists() ); + public void testNoCommit_NoTempFiles() throws Exception { + ChecksumValidator validator = newValidator(SHA1); + fetcher.mock(SHA1, "foo"); + validator.validate(checksums(SHA1, "foo"), null); + fetcher.assertFetchedFiles(SHA1); + assertEquals(1, fetcher.checksumFiles.size()); + for (File file : fetcher.checksumFiles) { + assertFalse(file.getAbsolutePath(), file.exists()); } } - } diff --git a/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/TestChecksumAlgorithmSelector.java b/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/TestChecksumAlgorithmSelector.java index 16afbe279..59d8a9913 100644 --- a/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/TestChecksumAlgorithmSelector.java +++ b/maven-resolver-connector-basic/src/test/java/org/eclipse/aether/connector/basic/TestChecksumAlgorithmSelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.connector.basic; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.connector.basic; import java.nio.ByteBuffer; import java.security.MessageDigest; @@ -39,9 +38,7 @@ /** * Test implementation of {@link ChecksumAlgorithmFactorySelector}. */ -public class TestChecksumAlgorithmSelector - implements ChecksumAlgorithmFactorySelector -{ +public class TestChecksumAlgorithmSelector implements ChecksumAlgorithmFactorySelector { public static final String SHA512 = "SHA-512"; public static final String SHA256 = "SHA-256"; @@ -55,87 +52,63 @@ public class TestChecksumAlgorithmSelector public static final String TEST_CHECKSUM_VALUE = "01020304"; @Override - public Set getChecksumAlgorithmFactories() - { + public Set getChecksumAlgorithmFactories() { return Collections.emptySet(); // irrelevant } @Override - public ChecksumAlgorithmFactory select( final String algorithm ) - { - if ( TEST_CHECKSUM.equals( algorithm ) ) - { - return new ChecksumAlgorithmFactorySupport( TEST_CHECKSUM, "test" ) - { + public ChecksumAlgorithmFactory select(final String algorithm) { + if (TEST_CHECKSUM.equals(algorithm)) { + return new ChecksumAlgorithmFactorySupport(TEST_CHECKSUM, "test") { @Override - public ChecksumAlgorithm getAlgorithm() - { - return new ChecksumAlgorithm() - { + public ChecksumAlgorithm getAlgorithm() { + return new ChecksumAlgorithm() { @Override - public void update( final ByteBuffer input ) - { - - } + public void update(final ByteBuffer input) {} @Override - public String checksum() - { + public String checksum() { return TEST_CHECKSUM_VALUE; } }; } }; } - return new MessageDigestChecksumAlgorithmFactory( algorithm ); + return new MessageDigestChecksumAlgorithmFactory(algorithm); } @Override - public List selectList( Collection algorithmNames ) - { - return algorithmNames.stream() - .map( this::select ) - .collect( toList() ); + public List selectList(Collection algorithmNames) { + return algorithmNames.stream().map(this::select).collect(toList()); } @Override - public boolean isChecksumExtension( String extension ) - { - throw new RuntimeException( "not implemented" ); + public boolean isChecksumExtension(String extension) { + throw new RuntimeException("not implemented"); } - private static class MessageDigestChecksumAlgorithmFactory - extends ChecksumAlgorithmFactorySupport - { - public MessageDigestChecksumAlgorithmFactory( String name ) - { - super( name, name.replace( "-", "" ).toLowerCase( Locale.ENGLISH ) ); + private static class MessageDigestChecksumAlgorithmFactory extends ChecksumAlgorithmFactorySupport { + public MessageDigestChecksumAlgorithmFactory(String name) { + super(name, name.replace("-", "").toLowerCase(Locale.ENGLISH)); } @Override - public ChecksumAlgorithm getAlgorithm() - { - try - { - MessageDigest messageDigest = MessageDigest.getInstance( getName() ); - return new ChecksumAlgorithm() - { + public ChecksumAlgorithm getAlgorithm() { + try { + MessageDigest messageDigest = MessageDigest.getInstance(getName()); + return new ChecksumAlgorithm() { @Override - public void update( final ByteBuffer input ) - { - messageDigest.update( input ); + public void update(final ByteBuffer input) { + messageDigest.update(input); } @Override - public String checksum() - { - return ChecksumUtils.toHexString( messageDigest.digest() ); + public String checksum() { + return ChecksumUtils.toHexString(messageDigest.digest()); } }; - } - catch ( NoSuchAlgorithmException e ) - { - throw new IllegalArgumentException( "Algorithm '" + getName() + "' not supported." ); + } catch (NoSuchAlgorithmException e) { + throw new IllegalArgumentException("Algorithm '" + getName() + "' not supported."); } } } diff --git a/maven-resolver-demos/maven-resolver-demo-maven-plugin/pom.xml b/maven-resolver-demos/maven-resolver-demo-maven-plugin/pom.xml index fd4de03b2..757bc21bd 100644 --- a/maven-resolver-demos/maven-resolver-demo-maven-plugin/pom.xml +++ b/maven-resolver-demos/maven-resolver-demo-maven-plugin/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -32,9 +30,7 @@ maven-plugin Maven Artifact Resolver Demo Maven Plugin - - A simple Maven plugin using Maven Artifact Resolver with Maven repositories. - + A simple Maven plugin using Maven Artifact Resolver with Maven repositories. ${mavenVersion} diff --git a/maven-resolver-demos/maven-resolver-demo-maven-plugin/src/main/java/org/apache/maven/resolver/examples/maven/ResolveArtifactMojo.java b/maven-resolver-demos/maven-resolver-demo-maven-plugin/src/main/java/org/apache/maven/resolver/examples/maven/ResolveArtifactMojo.java index bd3b430eb..3d157be56 100644 --- a/maven-resolver-demos/maven-resolver-demo-maven-plugin/src/main/java/org/apache/maven/resolver/examples/maven/ResolveArtifactMojo.java +++ b/maven-resolver-demos/maven-resolver-demo-maven-plugin/src/main/java/org/apache/maven/resolver/examples/maven/ResolveArtifactMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.maven; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.maven; import java.util.List; @@ -41,11 +40,9 @@ /** * Resolves a single artifact (not including its transitive dependencies). */ -@Mojo( name = "resolve-artifact", threadSafe = true ) -public class ResolveArtifactMojo - extends AbstractMojo -{ - private static final Logger LOGGER = LoggerFactory.getLogger( ResolveArtifactMojo.class ); +@Mojo(name = "resolve-artifact", threadSafe = true) +public class ResolveArtifactMojo extends AbstractMojo { + private static final Logger LOGGER = LoggerFactory.getLogger(ResolveArtifactMojo.class); /** * The entry point to Maven Artifact Resolver, i.e. the component doing all the work. */ @@ -55,55 +52,49 @@ public class ResolveArtifactMojo /** * The current repository/network configuration of Maven. */ - @Parameter( defaultValue = "${repositorySystemSession}", readonly = true ) + @Parameter(defaultValue = "${repositorySystemSession}", readonly = true) private RepositorySystemSession repoSession; /** * The project's remote repositories to use for the resolution. */ - @Parameter( defaultValue = "${project.remoteProjectRepositories}", readonly = true ) + @Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true) private List remoteRepos; /** * The {@code :[:[:]]:} of the artifact to resolve. */ - @Parameter ( property = "resolver.artifactCoords", readonly = true ) + @Parameter(property = "resolver.artifactCoords", readonly = true) private String artifactCoords; /** * The actual execution of the mojo. */ - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { Artifact artifact; - try - { - artifact = new DefaultArtifact( artifactCoords ); - } - catch ( IllegalArgumentException e ) - { - throw new MojoFailureException( e.getMessage(), e ); + try { + artifact = new DefaultArtifact(artifactCoords); + } catch (IllegalArgumentException e) { + throw new MojoFailureException(e.getMessage(), e); } ArtifactRequest request = new ArtifactRequest(); - request.setArtifact( artifact ); - request.setRepositories( remoteRepos ); + request.setArtifact(artifact); + request.setRepositories(remoteRepos); - LOGGER.info( "Resolving artifact {} from {}", artifact, remoteRepos ); + LOGGER.info("Resolving artifact {} from {}", artifact, remoteRepos); ArtifactResult result; - try - { - result = repoSystem.resolveArtifact( repoSession, request ); - } - catch ( ArtifactResolutionException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + try { + result = repoSystem.resolveArtifact(repoSession, request); + } catch (ArtifactResolutionException e) { + throw new MojoExecutionException(e.getMessage(), e); } - LOGGER.info( "Resolved artifact {} to {} from {}", artifact, result.getArtifact().getFile(), - result.getRepository() ); + LOGGER.info( + "Resolved artifact {} to {} from {}", + artifact, + result.getArtifact().getFile(), + result.getRepository()); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/pom.xml b/maven-resolver-demos/maven-resolver-demo-snippets/pom.xml index 4d2838379..57857b521 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/pom.xml +++ b/maven-resolver-demos/maven-resolver-demo-snippets/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,10 +29,8 @@ maven-resolver-demo-snippets Maven Artifact Resolver Demo Snippets - - A module to demonstrate the usage of Maven Artifact Resolver with Maven repositories - by means of various runnable code snippets. - + A module to demonstrate the usage of Maven Artifact Resolver with Maven repositories + by means of various runnable code snippets. org.apache.maven.resolver.demo.snippets diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/TestNioLock.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/TestNioLock.java deleted file mode 100644 index 8ec810a2f..000000000 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/TestNioLock.java +++ /dev/null @@ -1,196 +0,0 @@ -// CHECKSTYLE_OFF: RegexpHeader - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.file.FileStore; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * A simple tool to check file locking on your OS/FS/Java combo. To use this tool, just copy it to basedir on - * the volume you plan to use as local repository and compile and run it: - *
      - *
    • javac TestNioLock.java
    • - *
    • java TestNioLock test someFile 1000
    • - *
    - */ -public class TestNioLock -{ - private static final int EC_WON = 10; - - private static final int EC_LOST = 20; - - private static final int EC_FAILED = 30; - - private static final int EC_ERROR = 100; - - public static void main( String[] args ) throws IOException, InterruptedException - { - if ( args.length != 3 ) - { - System.out.println( "TestNioLock " ); - System.exit( EC_ERROR ); - } - - String mode = args[0]; - Path path = Paths.get( args[1] ).toAbsolutePath(); - Path latchFile = path.getParent().resolve( TestNioLock.class.getName() + ".latchFile" ); - - if ( Files.isDirectory( path ) ) - { - System.out.println( "The cannot be directory." ); - System.exit( EC_ERROR ); - } - if ( !Files.isRegularFile( latchFile ) ) - { - Files.createFile( latchFile ); - } - - if ( "test".equals( mode ) ) - { - System.out.println( "Testing file locking on" ); - System.out.println( - " Java " + System.getProperty( "java.version" ) + ", " + System.getProperty( "java.vendor" ) ); - System.out.println( - " OS " + System.getProperty( "os.name" ) + " " + System.getProperty( "os.version" ) + " " - + System.getProperty( "os.arch" ) ); - - FileStore fileStore = Files.getFileStore( path.getParent() ); - System.out.println( " FS " + fileStore.name() + " " + fileStore.type() ); - System.out.println(); - - AtomicInteger oneResult = new AtomicInteger( -1 ); - AtomicInteger twoResult = new AtomicInteger( -1 ); - CountDownLatch latch = new CountDownLatch( 2 ); - String javaCmd = System.getProperty( "java.home" ) + "/bin/java"; - - try ( FileChannel latchChannel = FileChannel.open( latchFile, StandardOpenOption.READ, - StandardOpenOption.WRITE ) ) - { - try ( FileLock latchLock = latchChannel.lock( 0L, 1L, false ) ) - { - new Thread( () -> - { - try - { - oneResult.set( new ProcessBuilder( javaCmd, TestNioLock.class.getName(), - "perform", args[1], args[2] ).inheritIO().start().waitFor() ); - } - catch ( Exception e ) - { - oneResult.set( EC_FAILED ); - } - finally - { - latch.countDown(); - } - } ).start(); - new Thread( () -> - { - try - { - twoResult.set( new ProcessBuilder( javaCmd, TestNioLock.class.getName(), - "perform", args[1], args[2] ).inheritIO().start().waitFor() ); - } - catch ( Exception e ) - { - twoResult.set( EC_FAILED ); - } - finally - { - latch.countDown(); - } - } ).start(); - - Thread.sleep( 1000 ); // give them a bit of time (to both block) - latchLock.release(); - latch.await(); - } - } - - - int oneExit = oneResult.get(); - int twoExit = twoResult.get(); - if ( ( oneExit == EC_WON && twoExit == EC_LOST ) || ( oneExit == EC_LOST && twoExit == EC_WON ) ) - { - System.out.println( "OK" ); - System.exit( 0 ); - } - else - { - System.out.println( "FAILED: one=" + oneExit + " two=" + twoExit ); - System.exit( EC_FAILED ); - } - } - else if ( "perform".equals( mode ) ) - { - String processName = ManagementFactory.getRuntimeMXBean().getName(); - System.out.println( processName + " > started" ); - boolean won = false; - long sleepMs = Long.parseLong( args[2] ); - try ( FileChannel latchChannel = FileChannel.open( latchFile, StandardOpenOption.READ ) ) - { - try ( FileLock latchLock = latchChannel.lock( 0L, 1L, true ) ) - { - System.out.println( processName + " > latchLock acquired" ); - try ( FileChannel channel = FileChannel.open( path, StandardOpenOption.READ, - StandardOpenOption.WRITE, StandardOpenOption.CREATE ) ) - { - try ( FileLock lock = channel.tryLock( 0L, 1L, false ) ) - { - if ( lock != null && lock.isValid() && !lock.isShared() ) - { - System.out.println( processName + " > WON" ); - won = true; - Thread.sleep( sleepMs ); - } - else - { - System.out.println( processName + " > LOST" ); - } - } - } - } - } - System.out.println( processName + " > ended" ); - if ( won ) - { - System.exit( EC_WON ); - } - else - { - System.exit( EC_LOST ); - } - } - else - { - System.err.println( "Unknown mode: " + mode ); - } - System.exit( EC_ERROR ); - } -} \ No newline at end of file diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/demo/TestNioLock.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/demo/TestNioLock.java new file mode 100644 index 000000000..bca65901e --- /dev/null +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/demo/TestNioLock.java @@ -0,0 +1,164 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package demo; // CHECKSTYLE_OFF: RegexpHeader + +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.file.FileStore; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * A simple tool to check file locking on your OS/FS/Java combo. To use this tool, just copy it to basedir on + * the volume you plan to use as local repository and compile and run it: + *
      + *
    • javac demo.TestNioLock.java
    • + *
    • java demo.TestNioLock test someFile 1000
    • + *
    + */ +public class TestNioLock { + private static final int EC_WON = 10; + + private static final int EC_LOST = 20; + + private static final int EC_FAILED = 30; + + private static final int EC_ERROR = 100; + + public static void main(String[] args) throws IOException, InterruptedException { + if (args.length != 3) { + System.out.println("demo.TestNioLock "); + System.exit(EC_ERROR); + } + + String mode = args[0]; + Path path = Paths.get(args[1]).toAbsolutePath(); + Path latchFile = path.getParent().resolve(TestNioLock.class.getName() + ".latchFile"); + + if (Files.isDirectory(path)) { + System.out.println("The cannot be directory."); + System.exit(EC_ERROR); + } + if (!Files.isRegularFile(latchFile)) { + Files.createFile(latchFile); + } + + if ("test".equals(mode)) { + System.out.println("Testing file locking on"); + System.out.println( + " Java " + System.getProperty("java.version") + ", " + System.getProperty("java.vendor")); + System.out.println(" OS " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + + System.getProperty("os.arch")); + + FileStore fileStore = Files.getFileStore(path.getParent()); + System.out.println(" FS " + fileStore.name() + " " + fileStore.type()); + System.out.println(); + + AtomicInteger oneResult = new AtomicInteger(-1); + AtomicInteger twoResult = new AtomicInteger(-1); + CountDownLatch latch = new CountDownLatch(2); + String javaCmd = System.getProperty("java.home") + "/bin/java"; + + try (FileChannel latchChannel = + FileChannel.open(latchFile, StandardOpenOption.READ, StandardOpenOption.WRITE)) { + try (FileLock latchLock = latchChannel.lock(0L, 1L, false)) { + new Thread(() -> { + try { + oneResult.set(new ProcessBuilder( + javaCmd, TestNioLock.class.getName(), "perform", args[1], args[2]) + .inheritIO() + .start() + .waitFor()); + } catch (Exception e) { + oneResult.set(EC_FAILED); + } finally { + latch.countDown(); + } + }) + .start(); + new Thread(() -> { + try { + twoResult.set(new ProcessBuilder( + javaCmd, TestNioLock.class.getName(), "perform", args[1], args[2]) + .inheritIO() + .start() + .waitFor()); + } catch (Exception e) { + twoResult.set(EC_FAILED); + } finally { + latch.countDown(); + } + }) + .start(); + + Thread.sleep(1000); // give them a bit of time (to both block) + latchLock.release(); + latch.await(); + } + } + + int oneExit = oneResult.get(); + int twoExit = twoResult.get(); + if ((oneExit == EC_WON && twoExit == EC_LOST) || (oneExit == EC_LOST && twoExit == EC_WON)) { + System.out.println("OK"); + System.exit(0); + } else { + System.out.println("FAILED: one=" + oneExit + " two=" + twoExit); + System.exit(EC_FAILED); + } + } else if ("perform".equals(mode)) { + String processName = ManagementFactory.getRuntimeMXBean().getName(); + System.out.println(processName + " > started"); + boolean won = false; + long sleepMs = Long.parseLong(args[2]); + try (FileChannel latchChannel = FileChannel.open(latchFile, StandardOpenOption.READ)) { + try (FileLock latchLock = latchChannel.lock(0L, 1L, true)) { + System.out.println(processName + " > latchLock acquired"); + try (FileChannel channel = FileChannel.open( + path, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) { + try (FileLock lock = channel.tryLock(0L, 1L, false)) { + if (lock != null && lock.isValid() && !lock.isShared()) { + System.out.println(processName + " > WON"); + won = true; + Thread.sleep(sleepMs); + } else { + System.out.println(processName + " > LOST"); + } + } + } + } + } + System.out.println(processName + " > ended"); + if (won) { + System.exit(EC_WON); + } else { + System.exit(EC_LOST); + } + } else { + System.err.println("Unknown mode: " + mode); + } + System.exit(EC_ERROR); + } +} diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/AllResolverDemos.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/AllResolverDemos.java index 703917450..1e5bab32a 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/AllResolverDemos.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/AllResolverDemos.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,34 +16,31 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import org.apache.maven.resolver.examples.resolver.ResolverDemo; /** * Runs all demos at once. */ -public class AllResolverDemos -{ +public class AllResolverDemos { /** - * Main + * Main * @param args * @throws Exception */ - public static void main( String[] args ) - throws Exception - { - FindAvailableVersions.main( args ); - FindNewestVersion.main( args ); - GetDirectDependencies.main( args ); - GetDependencyTree.main( args ); - GetDependencyHierarchy.main( args ); - ResolveArtifact.main( args ); - ResolveTransitiveDependencies.main( args ); - ReverseDependencyTree.main( args ); - InstallArtifacts.main( args ); - DeployArtifacts.main( args ); + public static void main(String[] args) throws Exception { + FindAvailableVersions.main(args); + FindNewestVersion.main(args); + GetDirectDependencies.main(args); + GetDependencyTree.main(args); + GetDependencyHierarchy.main(args); + ResolveArtifact.main(args); + ResolveTransitiveDependencies.main(args); + ReverseDependencyTree.main(args); + InstallArtifacts.main(args); + DeployArtifacts.main(args); - ResolverDemo.main( args ); + ResolverDemo.main(args); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/DeployArtifacts.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/DeployArtifacts.java index 4596cee61..5f26c112c 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/DeployArtifacts.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/DeployArtifacts.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import java.io.File; @@ -33,40 +32,38 @@ /** * Deploys a JAR and its POM to a remote repository. */ -public class DeployArtifacts -{ +public class DeployArtifacts { /** * Main. * @param args * @throws Exception */ - public static void main( String[] args ) - throws Exception - { - System.out.println( "------------------------------------------------------------" ); - System.out.println( DeployArtifacts.class.getSimpleName() ); + public static void main(String[] args) throws Exception { + System.out.println("------------------------------------------------------------"); + System.out.println(DeployArtifacts.class.getSimpleName()); - RepositorySystem system = Booter.newRepositorySystem( Booter.selectFactory( args ) ); + RepositorySystem system = Booter.newRepositorySystem(Booter.selectFactory(args)); - RepositorySystemSession session = Booter.newRepositorySystemSession( system ); + RepositorySystemSession session = Booter.newRepositorySystemSession(system); - Artifact jarArtifact = new DefaultArtifact( "test", "org.apache.maven.aether.examples", "", - "jar", "0.1-SNAPSHOT" ); - jarArtifact = jarArtifact.setFile( new File( "src/main/data/demo.jar" ) ); + Artifact jarArtifact = + new DefaultArtifact("test", "org.apache.maven.aether.examples", "", "jar", "0.1-SNAPSHOT"); + jarArtifact = jarArtifact.setFile(new File("src/main/data/demo.jar")); - Artifact pomArtifact = new SubArtifact( jarArtifact, "", "pom" ); - pomArtifact = pomArtifact.setFile( new File( "pom.xml" ) ); + Artifact pomArtifact = new SubArtifact(jarArtifact, "", "pom"); + pomArtifact = pomArtifact.setFile(new File("pom.xml")); - RemoteRepository distRepo = - new RemoteRepository.Builder( "org.apache.maven.aether.examples", "default", - new File( "target/dist-repo" ).toURI().toString() ).build(); + RemoteRepository distRepo = new RemoteRepository.Builder( + "org.apache.maven.aether.examples", + "default", + new File("target/dist-repo").toURI().toString()) + .build(); DeployRequest deployRequest = new DeployRequest(); - deployRequest.addArtifact( jarArtifact ).addArtifact( pomArtifact ); - deployRequest.setRepository( distRepo ); + deployRequest.addArtifact(jarArtifact).addArtifact(pomArtifact); + deployRequest.setRepository(distRepo); - system.deploy( session, deployRequest ); + system.deploy(session, deployRequest); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/FindAvailableVersions.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/FindAvailableVersions.java index 61a233871..c82cb27e6 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/FindAvailableVersions.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/FindAvailableVersions.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import java.util.List; @@ -33,35 +32,31 @@ /** * Determines all available versions of an artifact. */ -public class FindAvailableVersions -{ +public class FindAvailableVersions { /** * Main. * @param args * @throws Exception */ - public static void main( String[] args ) - throws Exception - { - System.out.println( "------------------------------------------------------------" ); - System.out.println( FindAvailableVersions.class.getSimpleName() ); + public static void main(String[] args) throws Exception { + System.out.println("------------------------------------------------------------"); + System.out.println(FindAvailableVersions.class.getSimpleName()); - RepositorySystem system = Booter.newRepositorySystem( Booter.selectFactory( args ) ); + RepositorySystem system = Booter.newRepositorySystem(Booter.selectFactory(args)); - RepositorySystemSession session = Booter.newRepositorySystemSession( system ); + RepositorySystemSession session = Booter.newRepositorySystemSession(system); - Artifact artifact = new DefaultArtifact( "org.apache.maven.resolver:maven-resolver-util:[0,)" ); + Artifact artifact = new DefaultArtifact("org.apache.maven.resolver:maven-resolver-util:[0,)"); VersionRangeRequest rangeRequest = new VersionRangeRequest(); - rangeRequest.setArtifact( artifact ); - rangeRequest.setRepositories( Booter.newRepositories( system, session ) ); + rangeRequest.setArtifact(artifact); + rangeRequest.setRepositories(Booter.newRepositories(system, session)); - VersionRangeResult rangeResult = system.resolveVersionRange( session, rangeRequest ); + VersionRangeResult rangeResult = system.resolveVersionRange(session, rangeRequest); List versions = rangeResult.getVersions(); - System.out.println( "Available versions " + versions ); + System.out.println("Available versions " + versions); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/FindNewestVersion.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/FindNewestVersion.java index 099e65a02..7cebfd24b 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/FindNewestVersion.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/FindNewestVersion.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import org.apache.maven.resolver.examples.util.Booter; import org.eclipse.aether.RepositorySystem; @@ -31,35 +30,31 @@ /** * Determines the newest version of an artifact. */ -public class FindNewestVersion -{ +public class FindNewestVersion { /** * Main. * @param args * @throws Exception */ - public static void main( String[] args ) - throws Exception - { - System.out.println( "------------------------------------------------------------" ); - System.out.println( FindNewestVersion.class.getSimpleName() ); + public static void main(String[] args) throws Exception { + System.out.println("------------------------------------------------------------"); + System.out.println(FindNewestVersion.class.getSimpleName()); - RepositorySystem system = Booter.newRepositorySystem( Booter.selectFactory( args ) ); + RepositorySystem system = Booter.newRepositorySystem(Booter.selectFactory(args)); - RepositorySystemSession session = Booter.newRepositorySystemSession( system ); + RepositorySystemSession session = Booter.newRepositorySystemSession(system); - Artifact artifact = new DefaultArtifact( "org.apache.maven.resolver:maven-resolver-util:[0,)" ); + Artifact artifact = new DefaultArtifact("org.apache.maven.resolver:maven-resolver-util:[0,)"); VersionRangeRequest rangeRequest = new VersionRangeRequest(); - rangeRequest.setArtifact( artifact ); - rangeRequest.setRepositories( Booter.newRepositories( system, session ) ); + rangeRequest.setArtifact(artifact); + rangeRequest.setRepositories(Booter.newRepositories(system, session)); - VersionRangeResult rangeResult = system.resolveVersionRange( session, rangeRequest ); + VersionRangeResult rangeResult = system.resolveVersionRange(session, rangeRequest); Version newestVersion = rangeResult.getHighestVersion(); - System.out.println( "Newest version " + newestVersion + " from repository " - + rangeResult.getRepository( newestVersion ) ); + System.out.println( + "Newest version " + newestVersion + " from repository " + rangeResult.getRepository(newestVersion)); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDependencyHierarchy.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDependencyHierarchy.java index 526ddb1a3..3d6441f51 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDependencyHierarchy.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDependencyHierarchy.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import org.apache.maven.resolver.examples.util.Booter; import org.apache.maven.resolver.examples.util.ConsoleDependencyGraphDumper; @@ -35,43 +34,39 @@ /** * Visualizes the transitive dependencies of an artifact similar to m2e's dependency hierarchy view. */ -public class GetDependencyHierarchy -{ +public class GetDependencyHierarchy { /** * Main. * @param args * @throws Exception */ - public static void main( String[] args ) - throws Exception - { - System.out.println( "------------------------------------------------------------" ); - System.out.println( GetDependencyHierarchy.class.getSimpleName() ); + public static void main(String[] args) throws Exception { + System.out.println("------------------------------------------------------------"); + System.out.println(GetDependencyHierarchy.class.getSimpleName()); - RepositorySystem system = Booter.newRepositorySystem( Booter.selectFactory( args ) ); + RepositorySystem system = Booter.newRepositorySystem(Booter.selectFactory(args)); - DefaultRepositorySystemSession session = Booter.newRepositorySystemSession( system ); + DefaultRepositorySystemSession session = Booter.newRepositorySystemSession(system); - session.setConfigProperty( ConflictResolver.CONFIG_PROP_VERBOSE, true ); - session.setConfigProperty( DependencyManagerUtils.CONFIG_PROP_VERBOSE, true ); + session.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true); + session.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, true); - Artifact artifact = new DefaultArtifact( "org.apache.maven:maven-resolver-provider:3.6.1" ); + Artifact artifact = new DefaultArtifact("org.apache.maven:maven-resolver-provider:3.6.1"); ArtifactDescriptorRequest descriptorRequest = new ArtifactDescriptorRequest(); - descriptorRequest.setArtifact( artifact ); - descriptorRequest.setRepositories( Booter.newRepositories( system, session ) ); - ArtifactDescriptorResult descriptorResult = system.readArtifactDescriptor( session, descriptorRequest ); + descriptorRequest.setArtifact(artifact); + descriptorRequest.setRepositories(Booter.newRepositories(system, session)); + ArtifactDescriptorResult descriptorResult = system.readArtifactDescriptor(session, descriptorRequest); CollectRequest collectRequest = new CollectRequest(); - collectRequest.setRootArtifact( descriptorResult.getArtifact() ); - collectRequest.setDependencies( descriptorResult.getDependencies() ); - collectRequest.setManagedDependencies( descriptorResult.getManagedDependencies() ); - collectRequest.setRepositories( descriptorRequest.getRepositories() ); + collectRequest.setRootArtifact(descriptorResult.getArtifact()); + collectRequest.setDependencies(descriptorResult.getDependencies()); + collectRequest.setManagedDependencies(descriptorResult.getManagedDependencies()); + collectRequest.setRepositories(descriptorRequest.getRepositories()); - CollectResult collectResult = system.collectDependencies( session, collectRequest ); + CollectResult collectResult = system.collectDependencies(session, collectRequest); - collectResult.getRoot().accept( new ConsoleDependencyGraphDumper() ); + collectResult.getRoot().accept(new ConsoleDependencyGraphDumper()); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDependencyTree.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDependencyTree.java index 78af7839a..e47129cb5 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDependencyTree.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDependencyTree.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import org.apache.maven.resolver.examples.util.Booter; import org.apache.maven.resolver.examples.util.ConsoleDependencyGraphDumper; @@ -32,33 +31,29 @@ /** * Collects the transitive dependencies of an artifact. */ -public class GetDependencyTree -{ +public class GetDependencyTree { /** * Main. * @param args * @throws Exception */ - public static void main( String[] args ) - throws Exception - { - System.out.println( "------------------------------------------------------------" ); - System.out.println( GetDependencyTree.class.getSimpleName() ); + public static void main(String[] args) throws Exception { + System.out.println("------------------------------------------------------------"); + System.out.println(GetDependencyTree.class.getSimpleName()); - RepositorySystem system = Booter.newRepositorySystem( Booter.selectFactory( args ) ); + RepositorySystem system = Booter.newRepositorySystem(Booter.selectFactory(args)); - RepositorySystemSession session = Booter.newRepositorySystemSession( system ); + RepositorySystemSession session = Booter.newRepositorySystemSession(system); - Artifact artifact = new DefaultArtifact( "org.apache.maven:maven-resolver-provider:3.6.1" ); + Artifact artifact = new DefaultArtifact("org.apache.maven:maven-resolver-provider:3.6.1"); CollectRequest collectRequest = new CollectRequest(); - collectRequest.setRoot( new Dependency( artifact, "" ) ); - collectRequest.setRepositories( Booter.newRepositories( system, session ) ); + collectRequest.setRoot(new Dependency(artifact, "")); + collectRequest.setRepositories(Booter.newRepositories(system, session)); - CollectResult collectResult = system.collectDependencies( session, collectRequest ); + CollectResult collectResult = system.collectDependencies(session, collectRequest); - collectResult.getRoot().accept( new ConsoleDependencyGraphDumper() ); + collectResult.getRoot().accept(new ConsoleDependencyGraphDumper()); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDirectDependencies.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDirectDependencies.java index e6042b340..7fcda35a6 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDirectDependencies.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/GetDirectDependencies.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import org.apache.maven.resolver.examples.util.Booter; import org.eclipse.aether.RepositorySystem; @@ -31,36 +30,31 @@ /** * Determines the direct dependencies of an artifact as declared in its artifact descriptor (POM). */ -public class GetDirectDependencies -{ +public class GetDirectDependencies { /** * Main. * @param args * @throws Exception */ - public static void main( String[] args ) - throws Exception - { - System.out.println( "------------------------------------------------------------" ); - System.out.println( GetDirectDependencies.class.getSimpleName() ); + public static void main(String[] args) throws Exception { + System.out.println("------------------------------------------------------------"); + System.out.println(GetDirectDependencies.class.getSimpleName()); - RepositorySystem system = Booter.newRepositorySystem( Booter.selectFactory( args ) ); + RepositorySystem system = Booter.newRepositorySystem(Booter.selectFactory(args)); - RepositorySystemSession session = Booter.newRepositorySystemSession( system ); + RepositorySystemSession session = Booter.newRepositorySystemSession(system); - Artifact artifact = new DefaultArtifact( "org.apache.maven.resolver:maven-resolver-impl:1.3.3" ); + Artifact artifact = new DefaultArtifact("org.apache.maven.resolver:maven-resolver-impl:1.3.3"); ArtifactDescriptorRequest descriptorRequest = new ArtifactDescriptorRequest(); - descriptorRequest.setArtifact( artifact ); - descriptorRequest.setRepositories( Booter.newRepositories( system, session ) ); + descriptorRequest.setArtifact(artifact); + descriptorRequest.setRepositories(Booter.newRepositories(system, session)); - ArtifactDescriptorResult descriptorResult = system.readArtifactDescriptor( session, descriptorRequest ); + ArtifactDescriptorResult descriptorResult = system.readArtifactDescriptor(session, descriptorRequest); - for ( Dependency dependency : descriptorResult.getDependencies() ) - { - System.out.println( dependency ); + for (Dependency dependency : descriptorResult.getDependencies()) { + System.out.println(dependency); } } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/InstallArtifacts.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/InstallArtifacts.java index 98fbb925c..7e2916365 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/InstallArtifacts.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/InstallArtifacts.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import java.io.File; @@ -32,35 +31,31 @@ /** * Installs a JAR and its POM to the local repository. */ -public class InstallArtifacts -{ +public class InstallArtifacts { /** * Main. * @param args * @throws Exception */ - public static void main( String[] args ) - throws Exception - { - System.out.println( "------------------------------------------------------------" ); - System.out.println( InstallArtifacts.class.getSimpleName() ); + public static void main(String[] args) throws Exception { + System.out.println("------------------------------------------------------------"); + System.out.println(InstallArtifacts.class.getSimpleName()); - RepositorySystem system = Booter.newRepositorySystem( Booter.selectFactory( args ) ); + RepositorySystem system = Booter.newRepositorySystem(Booter.selectFactory(args)); - RepositorySystemSession session = Booter.newRepositorySystemSession( system ); + RepositorySystemSession session = Booter.newRepositorySystemSession(system); Artifact jarArtifact = - new DefaultArtifact( "test", "org.apache.maven.resolver.examples", "", "jar", "0.1-SNAPSHOT" ); - jarArtifact = jarArtifact.setFile( new File( "src/main/data/demo.jar" ) ); + new DefaultArtifact("test", "org.apache.maven.resolver.examples", "", "jar", "0.1-SNAPSHOT"); + jarArtifact = jarArtifact.setFile(new File("src/main/data/demo.jar")); - Artifact pomArtifact = new SubArtifact( jarArtifact, "", "pom" ); - pomArtifact = pomArtifact.setFile( new File( "pom.xml" ) ); + Artifact pomArtifact = new SubArtifact(jarArtifact, "", "pom"); + pomArtifact = pomArtifact.setFile(new File("pom.xml")); InstallRequest installRequest = new InstallRequest(); - installRequest.addArtifact( jarArtifact ).addArtifact( pomArtifact ); + installRequest.addArtifact(jarArtifact).addArtifact(pomArtifact); - system.install( session, installRequest ); + system.install(session, installRequest); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ResolveArtifact.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ResolveArtifact.java index bd6a662c1..0359c6e1a 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ResolveArtifact.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ResolveArtifact.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import org.apache.maven.resolver.examples.util.Booter; import org.eclipse.aether.DefaultRepositorySystemSession; @@ -31,55 +30,51 @@ /** * Resolves a single artifact. */ -public class ResolveArtifact -{ +public class ResolveArtifact { /** * Main. * @param args * @throws Exception */ - public static void main( String[] args ) - throws Exception - { - System.out.println( "------------------------------------------------------------" ); - System.out.println( ResolveArtifact.class.getSimpleName() ); + public static void main(String[] args) throws Exception { + System.out.println("------------------------------------------------------------"); + System.out.println(ResolveArtifact.class.getSimpleName()); - RepositorySystem system = Booter.newRepositorySystem( Booter.selectFactory( args ) ); + RepositorySystem system = Booter.newRepositorySystem(Booter.selectFactory(args)); - DefaultRepositorySystemSession session = Booter.newRepositorySystemSession( system ); + DefaultRepositorySystemSession session = Booter.newRepositorySystemSession(system); Artifact artifact; ArtifactRequest artifactRequest; ArtifactResult artifactResult; // artifact - artifact = new DefaultArtifact( "org.apache.maven.resolver:maven-resolver-util:1.3.3" ); + artifact = new DefaultArtifact("org.apache.maven.resolver:maven-resolver-util:1.3.3"); artifactRequest = new ArtifactRequest(); - artifactRequest.setArtifact( artifact ); - artifactRequest.setRepositories( Booter.newRepositories( system, session ) ); + artifactRequest.setArtifact(artifact); + artifactRequest.setRepositories(Booter.newRepositories(system, session)); - artifactResult = system.resolveArtifact( session, artifactRequest ); + artifactResult = system.resolveArtifact(session, artifactRequest); artifact = artifactResult.getArtifact(); - System.out.println( artifact + " resolved to " + artifact.getFile() ); + System.out.println(artifact + " resolved to " + artifact.getFile()); // signature - session.setChecksumPolicy( RepositoryPolicy.CHECKSUM_POLICY_FAIL ); + session.setChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_FAIL); - artifact = new DefaultArtifact( "org.apache.maven.resolver:maven-resolver-util:jar.asc:1.3.3" ); + artifact = new DefaultArtifact("org.apache.maven.resolver:maven-resolver-util:jar.asc:1.3.3"); artifactRequest = new ArtifactRequest(); - artifactRequest.setArtifact( artifact ); - artifactRequest.setRepositories( Booter.newRepositories( system, session ) ); + artifactRequest.setArtifact(artifact); + artifactRequest.setRepositories(Booter.newRepositories(system, session)); - artifactResult = system.resolveArtifact( session, artifactRequest ); + artifactResult = system.resolveArtifact(session, artifactRequest); artifact = artifactResult.getArtifact(); - System.out.println( artifact + " resolved signature to " + artifact.getFile() ); + System.out.println(artifact + " resolved signature to " + artifact.getFile()); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ResolveTransitiveDependencies.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ResolveTransitiveDependencies.java index 88ee3ec3d..a9541b052 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ResolveTransitiveDependencies.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ResolveTransitiveDependencies.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import java.util.List; @@ -37,42 +36,37 @@ /** * Resolves the transitive (compile) dependencies of an artifact. */ -public class ResolveTransitiveDependencies -{ +public class ResolveTransitiveDependencies { /** * Main. * @param args * @throws Exception */ - public static void main( String[] args ) - throws Exception - { - System.out.println( "------------------------------------------------------------" ); - System.out.println( ResolveTransitiveDependencies.class.getSimpleName() ); + public static void main(String[] args) throws Exception { + System.out.println("------------------------------------------------------------"); + System.out.println(ResolveTransitiveDependencies.class.getSimpleName()); - RepositorySystem system = Booter.newRepositorySystem( Booter.selectFactory( args ) ); + RepositorySystem system = Booter.newRepositorySystem(Booter.selectFactory(args)); - RepositorySystemSession session = Booter.newRepositorySystemSession( system ); + RepositorySystemSession session = Booter.newRepositorySystemSession(system); - Artifact artifact = new DefaultArtifact( "org.apache.maven.resolver:maven-resolver-impl:1.3.3" ); + Artifact artifact = new DefaultArtifact("org.apache.maven.resolver:maven-resolver-impl:1.3.3"); - DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter( JavaScopes.COMPILE ); + DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE); CollectRequest collectRequest = new CollectRequest(); - collectRequest.setRoot( new Dependency( artifact, JavaScopes.COMPILE ) ); - collectRequest.setRepositories( Booter.newRepositories( system, session ) ); + collectRequest.setRoot(new Dependency(artifact, JavaScopes.COMPILE)); + collectRequest.setRepositories(Booter.newRepositories(system, session)); - DependencyRequest dependencyRequest = new DependencyRequest( collectRequest, classpathFlter ); + DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFlter); List artifactResults = - system.resolveDependencies( session, dependencyRequest ).getArtifactResults(); + system.resolveDependencies(session, dependencyRequest).getArtifactResults(); - for ( ArtifactResult artifactResult : artifactResults ) - { - System.out.println( artifactResult.getArtifact() + " resolved to " - + artifactResult.getArtifact().getFile() ); + for (ArtifactResult artifactResult : artifactResults) { + System.out.println(artifactResult.getArtifact() + " resolved to " + + artifactResult.getArtifact().getFile()); } } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ReverseDependencyTree.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ReverseDependencyTree.java index 97b0b4af1..663b26ccb 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ReverseDependencyTree.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/ReverseDependencyTree.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import org.apache.maven.resolver.examples.util.Booter; import org.apache.maven.resolver.examples.util.ReverseTreeRepositoryListener; @@ -35,49 +34,45 @@ /** * Example of building reverse dependency tree using custom {@link ReverseTreeRepositoryListener}. */ -public class ReverseDependencyTree -{ +public class ReverseDependencyTree { /** * Main. * @param args * @throws Exception */ - public static void main( String[] args ) - throws Exception - { - System.out.println( "------------------------------------------------------------" ); - System.out.println( ReverseDependencyTree.class.getSimpleName() ); + public static void main(String[] args) throws Exception { + System.out.println("------------------------------------------------------------"); + System.out.println(ReverseDependencyTree.class.getSimpleName()); - RepositorySystem system = Booter.newRepositorySystem( Booter.selectFactory( args ) ); + RepositorySystem system = Booter.newRepositorySystem(Booter.selectFactory(args)); - DefaultRepositorySystemSession session = Booter.newRepositorySystemSession( system ); + DefaultRepositorySystemSession session = Booter.newRepositorySystemSession(system); // install the listener into session - session.setRepositoryListener( new ChainedRepositoryListener( session.getRepositoryListener(), - new ReverseTreeRepositoryListener() ) ); + session.setRepositoryListener( + new ChainedRepositoryListener(session.getRepositoryListener(), new ReverseTreeRepositoryListener())); - session.setConfigProperty( ConflictResolver.CONFIG_PROP_VERBOSE, true ); - session.setConfigProperty( DependencyManagerUtils.CONFIG_PROP_VERBOSE, true ); + session.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true); + session.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, true); - Artifact artifact = new DefaultArtifact( "org.apache.maven:maven-resolver-provider:3.6.1" ); + Artifact artifact = new DefaultArtifact("org.apache.maven:maven-resolver-provider:3.6.1"); ArtifactDescriptorRequest descriptorRequest = new ArtifactDescriptorRequest(); - descriptorRequest.setArtifact( artifact ); - descriptorRequest.setRepositories( Booter.newRepositories( system, session ) ); - ArtifactDescriptorResult descriptorResult = system.readArtifactDescriptor( session, descriptorRequest ); + descriptorRequest.setArtifact(artifact); + descriptorRequest.setRepositories(Booter.newRepositories(system, session)); + ArtifactDescriptorResult descriptorResult = system.readArtifactDescriptor(session, descriptorRequest); CollectRequest collectRequest = new CollectRequest(); - collectRequest.setRequestContext( "demo" ); - collectRequest.setRootArtifact( descriptorResult.getArtifact() ); - collectRequest.setDependencies( descriptorResult.getDependencies() ); - collectRequest.setManagedDependencies( descriptorResult.getManagedDependencies() ); - collectRequest.setRepositories( descriptorRequest.getRepositories() ); + collectRequest.setRequestContext("demo"); + collectRequest.setRootArtifact(descriptorResult.getArtifact()); + collectRequest.setDependencies(descriptorResult.getDependencies()); + collectRequest.setManagedDependencies(descriptorResult.getManagedDependencies()); + collectRequest.setRepositories(descriptorRequest.getRepositories()); - system.collectDependencies( session, collectRequest ); + system.collectDependencies(session, collectRequest); // in this demo we are not interested in collect result, // as all the "demo work" is done by installed ReverseTreeRepositoryListener } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/guice/DemoResolverModule.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/guice/DemoResolverModule.java index 21f25bd5b..c382e7480 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/guice/DemoResolverModule.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/guice/DemoResolverModule.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.guice; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,15 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.guice; + +import javax.inject.Named; +import javax.inject.Singleton; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.inject.Named; -import javax.inject.Singleton; - +import com.google.inject.AbstractModule; +import com.google.inject.Provides; +import com.google.inject.name.Names; import org.apache.maven.model.building.DefaultModelBuilderFactory; import org.apache.maven.model.building.ModelBuilder; import org.apache.maven.repository.internal.DefaultArtifactDescriptorReader; @@ -46,42 +48,42 @@ import org.eclipse.aether.transport.http.ChecksumExtractor; import org.eclipse.aether.transport.http.HttpTransporterFactory; -import com.google.inject.AbstractModule; -import com.google.inject.Provides; -import com.google.inject.name.Names; - /** * Guice module for Demo Resolver snippets. * * Here, we assemble "complete" module by using {@link AetherModule} (see it's Javadoc) and adding bits from * Maven itself (binding those components that completes repository system). */ -class DemoResolverModule - extends AbstractModule -{ +class DemoResolverModule extends AbstractModule { @Override - protected void configure() - { + protected void configure() { // NOTE: see org.eclipse.aether.impl.guice.AetherModule Javadoc: // AetherModule alone is "ready-made" but incomplete. To have a complete resolver, we // actually need to bind the missing components making module complete. - install( new AetherModule() ); + install(new AetherModule()); // make module "complete" by binding things not bound by AetherModule - bind( ArtifactDescriptorReader.class ).to( DefaultArtifactDescriptorReader.class ).in( Singleton.class ); - bind( VersionResolver.class ).to( DefaultVersionResolver.class ).in( Singleton.class ); - bind( VersionRangeResolver.class ).to( DefaultVersionRangeResolver.class ).in( Singleton.class ); - bind( MetadataGeneratorFactory.class ).annotatedWith( Names.named( "snapshot" ) ) - .to( SnapshotMetadataGeneratorFactory.class ).in( Singleton.class ); + bind(ArtifactDescriptorReader.class) + .to(DefaultArtifactDescriptorReader.class) + .in(Singleton.class); + bind(VersionResolver.class).to(DefaultVersionResolver.class).in(Singleton.class); + bind(VersionRangeResolver.class).to(DefaultVersionRangeResolver.class).in(Singleton.class); + bind(MetadataGeneratorFactory.class) + .annotatedWith(Names.named("snapshot")) + .to(SnapshotMetadataGeneratorFactory.class) + .in(Singleton.class); - bind( MetadataGeneratorFactory.class ).annotatedWith( Names.named( "versions" ) ) - .to( VersionsMetadataGeneratorFactory.class ).in( Singleton.class ); + bind(MetadataGeneratorFactory.class) + .annotatedWith(Names.named("versions")) + .to(VersionsMetadataGeneratorFactory.class) + .in(Singleton.class); - bind( RepositoryConnectorFactory.class ).annotatedWith( Names.named( "basic" ) ) - .to( BasicRepositoryConnectorFactory.class ); - bind( TransporterFactory.class ).annotatedWith( Names.named( "file" ) ).to( FileTransporterFactory.class ); - bind( TransporterFactory.class ).annotatedWith( Names.named( "http" ) ).to( HttpTransporterFactory.class ); + bind(RepositoryConnectorFactory.class) + .annotatedWith(Names.named("basic")) + .to(BasicRepositoryConnectorFactory.class); + bind(TransporterFactory.class).annotatedWith(Names.named("file")).to(FileTransporterFactory.class); + bind(TransporterFactory.class).annotatedWith(Names.named("http")).to(HttpTransporterFactory.class); } /** @@ -89,8 +91,7 @@ protected void configure() */ @Provides @Singleton - Map provideChecksumExtractors() - { + Map provideChecksumExtractors() { return Collections.emptyMap(); } @@ -100,11 +101,10 @@ Map provideChecksumExtractors() @Provides @Singleton Set provideRepositoryConnectorFactories( - @Named( "basic" ) RepositoryConnectorFactory basic ) - { + @Named("basic") RepositoryConnectorFactory basic) { Set factories = new HashSet<>(); - factories.add( basic ); - return Collections.unmodifiableSet( factories ); + factories.add(basic); + return Collections.unmodifiableSet(factories); } /** @@ -112,13 +112,12 @@ Set provideRepositoryConnectorFactories( */ @Provides @Singleton - Set provideTransporterFactories( @Named( "file" ) TransporterFactory file, - @Named( "http" ) TransporterFactory http ) - { + Set provideTransporterFactories( + @Named("file") TransporterFactory file, @Named("http") TransporterFactory http) { Set factories = new HashSet<>(); - factories.add( file ); - factories.add( http ); - return Collections.unmodifiableSet( factories ); + factories.add(file); + factories.add(http); + return Collections.unmodifiableSet(factories); } /** @@ -127,13 +126,12 @@ Set provideTransporterFactories( @Named( "file" ) Transporte @Provides @Singleton Set provideMetadataGeneratorFactories( - @Named( "snapshot" ) MetadataGeneratorFactory snapshot, - @Named( "versions" ) MetadataGeneratorFactory versions ) - { - Set factories = new HashSet<>( 2 ); - factories.add( snapshot ); - factories.add( versions ); - return Collections.unmodifiableSet( factories ); + @Named("snapshot") MetadataGeneratorFactory snapshot, + @Named("versions") MetadataGeneratorFactory versions) { + Set factories = new HashSet<>(2); + factories.add(snapshot); + factories.add(versions); + return Collections.unmodifiableSet(factories); } /** @@ -141,8 +139,7 @@ Set provideMetadataGeneratorFactories( * and would require much more. */ @Provides - ModelBuilder provideModelBuilder() - { + ModelBuilder provideModelBuilder() { return new DefaultModelBuilderFactory().newInstance(); } } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/guice/GuiceRepositorySystemFactory.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/guice/GuiceRepositorySystemFactory.java index 3ff0db056..e780ef1a9 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/guice/GuiceRepositorySystemFactory.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/guice/GuiceRepositorySystemFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.guice; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,20 +16,17 @@ * specific language governing permissions and limitations * under the License. */ - -import org.eclipse.aether.RepositorySystem; +package org.apache.maven.resolver.examples.guice; import com.google.inject.Guice; +import org.eclipse.aether.RepositorySystem; /** * A factory for repository system instances that employs JSR-330 via Guice to wire up the system's components. */ -public class GuiceRepositorySystemFactory -{ +public class GuiceRepositorySystemFactory { - public static RepositorySystem newRepositorySystem() - { - return Guice.createInjector( new DemoResolverModule() ).getInstance( RepositorySystem.class ); + public static RepositorySystem newRepositorySystem() { + return Guice.createInjector(new DemoResolverModule()).getInstance(RepositorySystem.class); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/manual/ManualRepositorySystemFactory.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/manual/ManualRepositorySystemFactory.java index 77c37fb35..4d5457da5 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/manual/ManualRepositorySystemFactory.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/manual/ManualRepositorySystemFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.manual; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.manual; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.eclipse.aether.RepositorySystem; @@ -34,33 +33,27 @@ * A factory for repository system instances that employs Maven Artifact Resolver's built-in service locator * infrastructure to wire up the system's components. */ -public class ManualRepositorySystemFactory -{ - private static final Logger LOGGER = LoggerFactory.getLogger( ManualRepositorySystemFactory.class ); +public class ManualRepositorySystemFactory { + private static final Logger LOGGER = LoggerFactory.getLogger(ManualRepositorySystemFactory.class); - public static RepositorySystem newRepositorySystem() - { + public static RepositorySystem newRepositorySystem() { /* * Aether's components implement org.eclipse.aether.spi.locator.Service to ease manual wiring and using the * prepopulated DefaultServiceLocator, we only need to register the repository connector and transporter * factories. */ DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); - locator.addService( RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class ); - locator.addService( TransporterFactory.class, FileTransporterFactory.class ); - locator.addService( TransporterFactory.class, HttpTransporterFactory.class ); + locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); + locator.addService(TransporterFactory.class, FileTransporterFactory.class); + locator.addService(TransporterFactory.class, HttpTransporterFactory.class); - locator.setErrorHandler( new DefaultServiceLocator.ErrorHandler() - { + locator.setErrorHandler(new DefaultServiceLocator.ErrorHandler() { @Override - public void serviceCreationFailed( Class type, Class impl, Throwable exception ) - { - LOGGER.error( "Service creation failed for {} with implementation {}", - type, impl, exception ); + public void serviceCreationFailed(Class type, Class impl, Throwable exception) { + LOGGER.error("Service creation failed for {} with implementation {}", type, impl, exception); } - } ); + }); - return locator.getService( RepositorySystem.class ); + return locator.getService(RepositorySystem.class); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/Resolver.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/Resolver.java index 3a20e8719..a5a01f76d 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/Resolver.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/Resolver.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.resolver; import java.io.ByteArrayOutputStream; import java.io.PrintStream; @@ -46,90 +45,84 @@ /** */ -public class Resolver -{ +public class Resolver { private final String remoteRepository; private final RepositorySystem repositorySystem; private final LocalRepository localRepository; - public Resolver( String factory, String remoteRepository, String localRepository ) - { + public Resolver(String factory, String remoteRepository, String localRepository) { this.remoteRepository = remoteRepository; - this.repositorySystem = Booter.newRepositorySystem( factory ); - this.localRepository = new LocalRepository( localRepository ); + this.repositorySystem = Booter.newRepositorySystem(factory); + this.localRepository = new LocalRepository(localRepository); } - private RepositorySystemSession newSession() - { - DefaultRepositorySystemSession session = Booter.newRepositorySystemSession( repositorySystem ); - session.setLocalRepositoryManager( repositorySystem.newLocalRepositoryManager( session, localRepository ) ); - session.setTransferListener( null ); - session.setRepositoryListener( null ); + private RepositorySystemSession newSession() { + DefaultRepositorySystemSession session = Booter.newRepositorySystemSession(repositorySystem); + session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(session, localRepository)); + session.setTransferListener(null); + session.setRepositoryListener(null); return session; } - public ResolverResult resolve( String groupId, String artifactId, String version ) - throws DependencyResolutionException - { + public ResolverResult resolve(String groupId, String artifactId, String version) + throws DependencyResolutionException { RepositorySystemSession session = newSession(); - Dependency dependency = - new Dependency( new DefaultArtifact( groupId, artifactId, "", "jar", version ), "runtime" ); - RemoteRepository central = new RemoteRepository.Builder( "central", "default", remoteRepository ).build(); + Dependency dependency = new Dependency(new DefaultArtifact(groupId, artifactId, "", "jar", version), "runtime"); + RemoteRepository central = new RemoteRepository.Builder("central", "default", remoteRepository).build(); CollectRequest collectRequest = new CollectRequest(); - collectRequest.setRoot( dependency ); - collectRequest.addRepository( central ); + collectRequest.setRoot(dependency); + collectRequest.addRepository(central); DependencyRequest dependencyRequest = new DependencyRequest(); - dependencyRequest.setCollectRequest( collectRequest ); + dependencyRequest.setCollectRequest(collectRequest); - DependencyNode rootNode = repositorySystem.resolveDependencies( session, dependencyRequest ).getRoot(); + DependencyNode rootNode = + repositorySystem.resolveDependencies(session, dependencyRequest).getRoot(); StringBuilder dump = new StringBuilder(); - displayTree( rootNode, dump ); - System.out.println( "Tree:" ); - System.out.println( dump ); + displayTree(rootNode, dump); + System.out.println("Tree:"); + System.out.println(dump); PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); - rootNode.accept( nlg ); + rootNode.accept(nlg); - return new ResolverResult( rootNode, nlg.getFiles(), nlg.getClassPath() ); + return new ResolverResult(rootNode, nlg.getFiles(), nlg.getClassPath()); } - public void install( Artifact artifact, Artifact pom ) - throws InstallationException - { + public void install(Artifact artifact, Artifact pom) throws InstallationException { RepositorySystemSession session = newSession(); InstallRequest installRequest = new InstallRequest(); - installRequest.addArtifact( artifact ).addArtifact( pom ); + installRequest.addArtifact(artifact).addArtifact(pom); - repositorySystem.install( session, installRequest ); + repositorySystem.install(session, installRequest); } - public void deploy( Artifact artifact, Artifact pom, String remoteRepository ) - throws DeploymentException - { + public void deploy(Artifact artifact, Artifact pom, String remoteRepository) throws DeploymentException { RepositorySystemSession session = newSession(); - Authentication auth = new AuthenticationBuilder().addUsername( "admin" ).addPassword( "admin123" ).build(); - RemoteRepository nexus = - new RemoteRepository.Builder( "nexus", "default", remoteRepository ).setAuthentication( auth ).build(); + Authentication auth = new AuthenticationBuilder() + .addUsername("admin") + .addPassword("admin123") + .build(); + RemoteRepository nexus = new RemoteRepository.Builder("nexus", "default", remoteRepository) + .setAuthentication(auth) + .build(); DeployRequest deployRequest = new DeployRequest(); - deployRequest.addArtifact( artifact ).addArtifact( pom ); - deployRequest.setRepository( nexus ); + deployRequest.addArtifact(artifact).addArtifact(pom); + deployRequest.setRepository(nexus); - repositorySystem.deploy( session, deployRequest ); + repositorySystem.deploy(session, deployRequest); } - private void displayTree( DependencyNode node, StringBuilder sb ) - { - ByteArrayOutputStream os = new ByteArrayOutputStream( 1024 ); - node.accept( new ConsoleDependencyGraphDumper( new PrintStream( os ) ) ); - sb.append( os.toString() ); + private void displayTree(DependencyNode node, StringBuilder sb) { + ByteArrayOutputStream os = new ByteArrayOutputStream(1024); + node.accept(new ConsoleDependencyGraphDumper(new PrintStream(os))); + sb.append(os.toString()); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/ResolverDemo.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/ResolverDemo.java index 1ccd17f0f..47c0a5833 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/ResolverDemo.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/ResolverDemo.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.resolver; import java.io.File; import java.util.List; @@ -33,35 +32,27 @@ /** */ -@SuppressWarnings( "unused" ) -public class ResolverDemo -{ - public static void main( String[] args ) throws Exception - { - System.out.println( "------------------------------------------------------------" ); - System.out.println( ResolverDemo.class.getSimpleName() ); +@SuppressWarnings("unused") +public class ResolverDemo { + public static void main(String[] args) throws Exception { + System.out.println("------------------------------------------------------------"); + System.out.println(ResolverDemo.class.getSimpleName()); - Resolver resolver = new Resolver( - Booter.selectFactory( args ), - "https://repo.maven.apache.org/maven2/", - "target/aether-repo" - ); - ResolverResult result = resolver.resolve( "junit", "junit", "4.13.2" ); + Resolver resolver = + new Resolver(Booter.selectFactory(args), "https://repo.maven.apache.org/maven2/", "target/aether-repo"); + ResolverResult result = resolver.resolve("junit", "junit", "4.13.2"); - System.out.println( "Result:" ); - System.out.println( "classpath=" + result.getResolvedClassPath() ); - System.out.println( "files=" + result.getResolvedFiles() ); - System.out.println( "root=" + result.getRoot() ); + System.out.println("Result:"); + System.out.println("classpath=" + result.getResolvedClassPath()); + System.out.println("files=" + result.getResolvedFiles()); + System.out.println("root=" + result.getRoot()); } - public void resolve( final String factory ) - throws DependencyResolutionException - { - Resolver resolver = new Resolver( - factory, - "http://localhost:8081/nexus/content/groups/public", "target/aether-repo" ); - - ResolverResult result = resolver.resolve( "com.mycompany.app", "super-app", "1.0" ); + public void resolve(final String factory) throws DependencyResolutionException { + Resolver resolver = + new Resolver(factory, "http://localhost:8081/nexus/content/groups/public", "target/aether-repo"); + + ResolverResult result = resolver.resolve("com.mycompany.app", "super-app", "1.0"); // Get the root of the resolved tree of artifacts // @@ -70,31 +61,27 @@ public void resolve( final String factory ) // Get the list of files for the artifacts resolved // List artifacts = result.getResolvedFiles(); - + // Get the classpath of the artifacts resolved // - String classpath = result.getResolvedClassPath(); + String classpath = result.getResolvedClassPath(); } - - public void installAndDeploy( final String factory ) - throws InstallationException, DeploymentException - { - Resolver resolver = new Resolver( - factory, - "http://localhost:8081/nexus/content/groups/public", "target/aether-repo" ); - - Artifact artifact = new DefaultArtifact( "com.mycompany.super", "super-core", "jar", "0.1-SNAPSHOT" ); - artifact = artifact.setFile( new File( "jar-from-whatever-process.jar" ) ); - Artifact pom = new SubArtifact( artifact, null, "pom" ); - pom = pom.setFile( new File( "pom-from-whatever-process.xml" ) ); - + + public void installAndDeploy(final String factory) throws InstallationException, DeploymentException { + Resolver resolver = + new Resolver(factory, "http://localhost:8081/nexus/content/groups/public", "target/aether-repo"); + + Artifact artifact = new DefaultArtifact("com.mycompany.super", "super-core", "jar", "0.1-SNAPSHOT"); + artifact = artifact.setFile(new File("jar-from-whatever-process.jar")); + Artifact pom = new SubArtifact(artifact, null, "pom"); + pom = pom.setFile(new File("pom-from-whatever-process.xml")); + // Install into the local repository specified // - resolver.install( artifact, pom ); - + resolver.install(artifact, pom); + // Deploy to a remote reposistory // - resolver.deploy( artifact, pom, "http://localhost:8081/nexus/content/repositories/snapshots/" ); + resolver.deploy(artifact, pom, "http://localhost:8081/nexus/content/repositories/snapshots/"); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/ResolverResult.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/ResolverResult.java index 813e22be2..efd90ba0a 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/ResolverResult.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/resolver/ResolverResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.resolver; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.resolver; import java.io.File; import java.util.List; @@ -26,31 +25,26 @@ /** */ -public class ResolverResult -{ +public class ResolverResult { private final DependencyNode root; private final List resolvedFiles; private final String resolvedClassPath; - - public ResolverResult( DependencyNode root, List resolvedFiles, String resolvedClassPath ) - { + + public ResolverResult(DependencyNode root, List resolvedFiles, String resolvedClassPath) { this.root = root; this.resolvedFiles = resolvedFiles; this.resolvedClassPath = resolvedClassPath; } - public DependencyNode getRoot() - { + public DependencyNode getRoot() { return root; } - public List getResolvedFiles() - { + public List getResolvedFiles() { return resolvedFiles; } - public String getResolvedClassPath() - { + public String getResolvedClassPath() { return resolvedClassPath; } } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/sisu/SisuRepositorySystemDemoModule.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/sisu/SisuRepositorySystemDemoModule.java index d4a43c8fd..87b423d22 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/sisu/SisuRepositorySystemDemoModule.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/sisu/SisuRepositorySystemDemoModule.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.sisu; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.sisu; import javax.inject.Inject; @@ -29,31 +28,25 @@ /** * Sisu module for demo snippets. */ -public class SisuRepositorySystemDemoModule implements Module -{ +public class SisuRepositorySystemDemoModule implements Module { @Override - public void configure( final Binder binder ) - { + public void configure(final Binder binder) { // NOTE: Maven 3.8.1 used in demo has Sisu Index for ALL components (older Maven does NOT have!) - binder.bind( ParameterKeys.PROPERTIES ).toInstance( System.getProperties() ); - binder.bind( ShutdownThread.class ).asEagerSingleton(); + binder.bind(ParameterKeys.PROPERTIES).toInstance(System.getProperties()); + binder.bind(ShutdownThread.class).asEagerSingleton(); } - static final class ShutdownThread - extends Thread - { + static final class ShutdownThread extends Thread { private final MutableBeanLocator locator; @Inject - ShutdownThread( final MutableBeanLocator locator ) - { + ShutdownThread(final MutableBeanLocator locator) { this.locator = locator; - Runtime.getRuntime().addShutdownHook( this ); + Runtime.getRuntime().addShutdownHook(this); } @Override - public void run() - { + public void run() { locator.clear(); } } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/sisu/SisuRepositorySystemFactory.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/sisu/SisuRepositorySystemFactory.java index 1403e1292..9e267b4fe 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/sisu/SisuRepositorySystemFactory.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/sisu/SisuRepositorySystemFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.sisu; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.sisu; import javax.inject.Inject; import javax.inject.Named; @@ -35,26 +34,18 @@ * A factory for repository system instances that employs Eclipse Sisu to wire up the system's components. */ @Named -public class SisuRepositorySystemFactory -{ +public class SisuRepositorySystemFactory { @Inject private RepositorySystem repositorySystem; - public static RepositorySystem newRepositorySystem() - { - final Module app = Main.wire( - BeanScanning.INDEX, - new SisuRepositorySystemDemoModule() - ); - return Guice.createInjector( app ).getInstance( SisuRepositorySystemFactory.class ).repositorySystem; + public static RepositorySystem newRepositorySystem() { + final Module app = Main.wire(BeanScanning.INDEX, new SisuRepositorySystemDemoModule()); + return Guice.createInjector(app).getInstance(SisuRepositorySystemFactory.class).repositorySystem; } @Named - private static class ModelBuilderProvider - implements Provider - { - public ModelBuilder get() - { + private static class ModelBuilderProvider implements Provider { + public ModelBuilder get() { return new DefaultModelBuilderFactory().newInstance(); } } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/Booter.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/Booter.java index 399f2f997..93ade9c4f 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/Booter.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/Booter.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.util; import java.util.ArrayList; import java.util.Collections; @@ -33,30 +32,23 @@ /** * A helper to boot the repository system and a repository system session. */ -public class Booter -{ +public class Booter { public static final String SERVICE_LOCATOR = "serviceLocator"; public static final String GUICE = "guice"; public static final String SISU = "sisu"; - public static String selectFactory( String[] args ) - { - if ( args == null || args.length == 0 ) - { + public static String selectFactory(String[] args) { + if (args == null || args.length == 0) { return SERVICE_LOCATOR; - } - else - { + } else { return args[0]; } } - public static RepositorySystem newRepositorySystem( final String factory ) - { - switch ( factory ) - { + public static RepositorySystem newRepositorySystem(final String factory) { + switch (factory) { case SERVICE_LOCATOR: return org.apache.maven.resolver.examples.manual.ManualRepositorySystemFactory.newRepositorySystem(); case GUICE: @@ -64,19 +56,18 @@ public static RepositorySystem newRepositorySystem( final String factory ) case SISU: return org.apache.maven.resolver.examples.sisu.SisuRepositorySystemFactory.newRepositorySystem(); default: - throw new IllegalArgumentException( "Unknown factory: " + factory ); + throw new IllegalArgumentException("Unknown factory: " + factory); } } - public static DefaultRepositorySystemSession newRepositorySystemSession( RepositorySystem system ) - { + public static DefaultRepositorySystemSession newRepositorySystemSession(RepositorySystem system) { DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); - LocalRepository localRepo = new LocalRepository( "target/local-repo" ); - session.setLocalRepositoryManager( system.newLocalRepositoryManager( session, localRepo ) ); + LocalRepository localRepo = new LocalRepository("target/local-repo"); + session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo)); - session.setTransferListener( new ConsoleTransferListener() ); - session.setRepositoryListener( new ConsoleRepositoryListener() ); + session.setTransferListener(new ConsoleTransferListener()); + session.setRepositoryListener(new ConsoleRepositoryListener()); // uncomment to generate dirty trees // session.setDependencyGraphTransformer( null ); @@ -84,14 +75,11 @@ public static DefaultRepositorySystemSession newRepositorySystemSession( Reposit return session; } - public static List newRepositories( RepositorySystem system, RepositorySystemSession session ) - { - return new ArrayList<>( Collections.singletonList( newCentralRepository() ) ); + public static List newRepositories(RepositorySystem system, RepositorySystemSession session) { + return new ArrayList<>(Collections.singletonList(newCentralRepository())); } - private static RemoteRepository newCentralRepository() - { - return new RemoteRepository.Builder( "central", "default", "https://repo.maven.apache.org/maven2/" ).build(); + private static RemoteRepository newCentralRepository() { + return new RemoteRepository.Builder("central", "default", "https://repo.maven.apache.org/maven2/").build(); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleDependencyGraphDumper.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleDependencyGraphDumper.java index b5f65daa7..e94ae2c32 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleDependencyGraphDumper.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleDependencyGraphDumper.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.util; import java.io.PrintStream; import java.util.ArrayList; @@ -35,120 +34,95 @@ /** * A dependency visitor that dumps the graph to the console. */ -public class ConsoleDependencyGraphDumper - implements DependencyVisitor -{ +public class ConsoleDependencyGraphDumper implements DependencyVisitor { private final PrintStream out; private final List childInfos = new ArrayList<>(); - public ConsoleDependencyGraphDumper() - { - this( null ); + public ConsoleDependencyGraphDumper() { + this(null); } - public ConsoleDependencyGraphDumper( PrintStream out ) - { - this.out = ( out != null ) ? out : System.out; + public ConsoleDependencyGraphDumper(PrintStream out) { + this.out = (out != null) ? out : System.out; } - public boolean visitEnter( DependencyNode node ) - { - out.println( formatIndentation() + formatNode( node ) ); - childInfos.add( new ChildInfo( node.getChildren().size() ) ); + public boolean visitEnter(DependencyNode node) { + out.println(formatIndentation() + formatNode(node)); + childInfos.add(new ChildInfo(node.getChildren().size())); return true; } - private String formatIndentation() - { - StringBuilder buffer = new StringBuilder( 128 ); - for ( Iterator it = childInfos.iterator(); it.hasNext(); ) - { - buffer.append( it.next().formatIndentation( !it.hasNext() ) ); + private String formatIndentation() { + StringBuilder buffer = new StringBuilder(128); + for (Iterator it = childInfos.iterator(); it.hasNext(); ) { + buffer.append(it.next().formatIndentation(!it.hasNext())); } return buffer.toString(); } - private String formatNode( DependencyNode node ) - { - StringBuilder buffer = new StringBuilder( 128 ); + private String formatNode(DependencyNode node) { + StringBuilder buffer = new StringBuilder(128); Artifact a = node.getArtifact(); Dependency d = node.getDependency(); - buffer.append( a ); - if ( d != null && d.getScope().length() > 0 ) - { - buffer.append( " [" ).append( d.getScope() ); - if ( d.isOptional() ) - { - buffer.append( ", optional" ); + buffer.append(a); + if (d != null && d.getScope().length() > 0) { + buffer.append(" [").append(d.getScope()); + if (d.isOptional()) { + buffer.append(", optional"); } - buffer.append( "]" ); + buffer.append("]"); } - String premanaged = DependencyManagerUtils.getPremanagedVersion( node ); - if ( premanaged != null && !premanaged.equals( a.getBaseVersion() ) ) - { - buffer.append( " (version managed from " ).append( premanaged ).append( ")" ); + String premanaged = DependencyManagerUtils.getPremanagedVersion(node); + if (premanaged != null && !premanaged.equals(a.getBaseVersion())) { + buffer.append(" (version managed from ").append(premanaged).append(")"); } - premanaged = DependencyManagerUtils.getPremanagedScope( node ); - if ( premanaged != null && !premanaged.equals( d.getScope() ) ) - { - buffer.append( " (scope managed from " ).append( premanaged ).append( ")" ); + premanaged = DependencyManagerUtils.getPremanagedScope(node); + if (premanaged != null && !premanaged.equals(d.getScope())) { + buffer.append(" (scope managed from ").append(premanaged).append(")"); } - DependencyNode winner = (DependencyNode) node.getData().get( ConflictResolver.NODE_DATA_WINNER ); - if ( winner != null && !ArtifactIdUtils.equalsId( a, winner.getArtifact() ) ) - { + DependencyNode winner = (DependencyNode) node.getData().get(ConflictResolver.NODE_DATA_WINNER); + if (winner != null && !ArtifactIdUtils.equalsId(a, winner.getArtifact())) { Artifact w = winner.getArtifact(); - buffer.append( " (conflicts with " ); - if ( ArtifactIdUtils.toVersionlessId( a ).equals( ArtifactIdUtils.toVersionlessId( w ) ) ) - { - buffer.append( w.getVersion() ); + buffer.append(" (conflicts with "); + if (ArtifactIdUtils.toVersionlessId(a).equals(ArtifactIdUtils.toVersionlessId(w))) { + buffer.append(w.getVersion()); + } else { + buffer.append(w); } - else - { - buffer.append( w ); - } - buffer.append( ")" ); + buffer.append(")"); } return buffer.toString(); } - public boolean visitLeave( DependencyNode node ) - { - if ( !childInfos.isEmpty() ) - { - childInfos.remove( childInfos.size() - 1 ); + public boolean visitLeave(DependencyNode node) { + if (!childInfos.isEmpty()) { + childInfos.remove(childInfos.size() - 1); } - if ( !childInfos.isEmpty() ) - { - childInfos.get( childInfos.size() - 1 ).index++; + if (!childInfos.isEmpty()) { + childInfos.get(childInfos.size() - 1).index++; } return true; } - private static class ChildInfo - { + private static class ChildInfo { final int count; int index; - ChildInfo( int count ) - { + ChildInfo(int count) { this.count = count; } - public String formatIndentation( boolean end ) - { + public String formatIndentation(boolean end) { boolean last = index + 1 >= count; - if ( end ) - { + if (end) { return last ? "\\- " : "+- "; } return last ? " " : "| "; } - } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleRepositoryListener.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleRepositoryListener.java index 2d5fbafe8..11f6ec0ee 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleRepositoryListener.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleRepositoryListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.util; import java.io.PrintStream; @@ -29,123 +28,101 @@ /** * A simplistic repository listener that logs events to the console. */ -public class ConsoleRepositoryListener - extends AbstractRepositoryListener -{ +public class ConsoleRepositoryListener extends AbstractRepositoryListener { private final PrintStream out; - public ConsoleRepositoryListener() - { - this( null ); + public ConsoleRepositoryListener() { + this(null); } - public ConsoleRepositoryListener( PrintStream out ) - { - this.out = ( out != null ) ? out : System.out; + public ConsoleRepositoryListener(PrintStream out) { + this.out = (out != null) ? out : System.out; } - public void artifactDeployed( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Deployed " + event.getArtifact() + " to " + event.getRepository() ); + public void artifactDeployed(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Deployed " + event.getArtifact() + " to " + event.getRepository()); } - public void artifactDeploying( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Deploying " + event.getArtifact() + " to " + event.getRepository() ); + public void artifactDeploying(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Deploying " + event.getArtifact() + " to " + event.getRepository()); } - public void artifactDescriptorInvalid( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Invalid artifact descriptor for " + event.getArtifact() + ": " - + event.getException().getMessage() ); + public void artifactDescriptorInvalid(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Invalid artifact descriptor for " + event.getArtifact() + ": " + + event.getException().getMessage()); } - public void artifactDescriptorMissing( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Missing artifact descriptor for " + event.getArtifact() ); + public void artifactDescriptorMissing(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Missing artifact descriptor for " + event.getArtifact()); } - public void artifactInstalled( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Installed " + event.getArtifact() + " to " + event.getFile() ); + public void artifactInstalled(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Installed " + event.getArtifact() + " to " + event.getFile()); } - public void artifactInstalling( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Installing " + event.getArtifact() + " to " + event.getFile() ); + public void artifactInstalling(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Installing " + event.getArtifact() + " to " + event.getFile()); } - public void artifactResolved( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Resolved artifact " + event.getArtifact() + " from " + event.getRepository() ); + public void artifactResolved(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Resolved artifact " + event.getArtifact() + " from " + event.getRepository()); } - public void artifactDownloading( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Downloading artifact " + event.getArtifact() + " from " + event.getRepository() ); + public void artifactDownloading(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Downloading artifact " + event.getArtifact() + " from " + event.getRepository()); } - public void artifactDownloaded( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Downloaded artifact " + event.getArtifact() + " from " + event.getRepository() ); + public void artifactDownloaded(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Downloaded artifact " + event.getArtifact() + " from " + event.getRepository()); } - public void artifactResolving( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Resolving artifact " + event.getArtifact() ); + public void artifactResolving(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Resolving artifact " + event.getArtifact()); } - public void metadataDeployed( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Deployed " + event.getMetadata() + " to " + event.getRepository() ); + public void metadataDeployed(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Deployed " + event.getMetadata() + " to " + event.getRepository()); } - public void metadataDeploying( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Deploying " + event.getMetadata() + " to " + event.getRepository() ); + public void metadataDeploying(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Deploying " + event.getMetadata() + " to " + event.getRepository()); } - public void metadataInstalled( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Installed " + event.getMetadata() + " to " + event.getFile() ); + public void metadataInstalled(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Installed " + event.getMetadata() + " to " + event.getFile()); } - public void metadataInstalling( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Installing " + event.getMetadata() + " to " + event.getFile() ); + public void metadataInstalling(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Installing " + event.getMetadata() + " to " + event.getFile()); } - public void metadataInvalid( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Invalid metadata " + event.getMetadata() ); + public void metadataInvalid(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Invalid metadata " + event.getMetadata()); } - public void metadataResolved( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Resolved metadata " + event.getMetadata() + " from " + event.getRepository() ); + public void metadataResolved(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Resolved metadata " + event.getMetadata() + " from " + event.getRepository()); } - public void metadataResolving( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - out.println( "Resolving metadata " + event.getMetadata() + " from " + event.getRepository() ); + public void metadataResolving(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + out.println("Resolving metadata " + event.getMetadata() + " from " + event.getRepository()); } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleTransferListener.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleTransferListener.java index c5de1e2de..e25839d7e 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleTransferListener.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ConsoleTransferListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.util; import java.io.PrintStream; import java.text.DecimalFormat; @@ -36,9 +35,7 @@ /** * A simplistic transfer listener that logs uploads/downloads to the console. */ -public class ConsoleTransferListener - extends AbstractTransferListener -{ +public class ConsoleTransferListener extends AbstractTransferListener { private final PrintStream out; @@ -46,142 +43,119 @@ public class ConsoleTransferListener private int lastLength; - public ConsoleTransferListener() - { - this( null ); + public ConsoleTransferListener() { + this(null); } - public ConsoleTransferListener( PrintStream out ) - { - this.out = ( out != null ) ? out : System.out; + public ConsoleTransferListener(PrintStream out) { + this.out = (out != null) ? out : System.out; } @Override - public void transferInitiated( TransferEvent event ) - { - requireNonNull( event, "event cannot be null" ); + public void transferInitiated(TransferEvent event) { + requireNonNull(event, "event cannot be null"); String message = event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploading" : "Downloading"; - out.println( message + ": " + event.getResource().getRepositoryUrl() + event.getResource().getResourceName() ); + out.println(message + ": " + event.getResource().getRepositoryUrl() + + event.getResource().getResourceName()); } @Override - public void transferProgressed( TransferEvent event ) - { - requireNonNull( event, "event cannot be null" ); + public void transferProgressed(TransferEvent event) { + requireNonNull(event, "event cannot be null"); TransferResource resource = event.getResource(); - downloads.put( resource, event.getTransferredBytes() ); + downloads.put(resource, event.getTransferredBytes()); - StringBuilder buffer = new StringBuilder( 64 ); + StringBuilder buffer = new StringBuilder(64); - for ( Map.Entry entry : downloads.entrySet() ) - { + for (Map.Entry entry : downloads.entrySet()) { long total = entry.getKey().getContentLength(); long complete = entry.getValue(); - buffer.append( getStatus( complete, total ) ).append( " " ); + buffer.append(getStatus(complete, total)).append(" "); } int pad = lastLength - buffer.length(); lastLength = buffer.length(); - pad( buffer, pad ); - buffer.append( '\r' ); + pad(buffer, pad); + buffer.append('\r'); - out.print( buffer ); + out.print(buffer); } - private String getStatus( long complete, long total ) - { - if ( total >= 1024 ) - { - return toKB( complete ) + "/" + toKB( total ) + " KB "; - } - else if ( total >= 0 ) - { + 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 - { + } else if (complete >= 1024) { + return toKB(complete) + " KB "; + } else { return complete + " B "; } } - private void pad( StringBuilder buffer, int spaces ) - { + private void pad(StringBuilder buffer, int spaces) { String block = " "; - while ( spaces > 0 ) - { - int n = Math.min( spaces, block.length() ); - buffer.append( block, 0, n ); + while (spaces > 0) { + int n = Math.min(spaces, block.length()); + buffer.append(block, 0, n); spaces -= n; } } @Override - public void transferSucceeded( TransferEvent event ) - { - requireNonNull( event, "event cannot be null" ); - transferCompleted( event ); + public void transferSucceeded(TransferEvent event) { + requireNonNull(event, "event cannot be null"); + transferCompleted(event); TransferResource resource = event.getResource(); long contentLength = event.getTransferredBytes(); - if ( contentLength >= 0 ) - { - String type = ( event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded" ); - String len = contentLength >= 1024 ? toKB( contentLength ) + " KB" : contentLength + " B"; + if (contentLength >= 0) { + String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded"); + String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B"; String throughput = ""; long duration = System.currentTimeMillis() - resource.getTransferStartTime(); - if ( duration > 0 ) - { + if (duration > 0) { long bytes = contentLength - resource.getResumeOffset(); - DecimalFormat format = new DecimalFormat( "0.0", new DecimalFormatSymbols( Locale.ENGLISH ) ); - double kbPerSec = ( bytes / 1024.0 ) / ( duration / 1000.0 ); - throughput = " at " + format.format( kbPerSec ) + " KB/sec"; + DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH)); + double kbPerSec = (bytes / 1024.0) / (duration / 1000.0); + throughput = " at " + format.format(kbPerSec) + " KB/sec"; } - out.println( type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len - + throughput + ")" ); + out.println(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len + throughput + + ")"); } } @Override - public void transferFailed( TransferEvent event ) - { - requireNonNull( event, "event cannot be null" ); - transferCompleted( event ); - - if ( !( event.getException() instanceof MetadataNotFoundException ) ) - { - event.getException().printStackTrace( out ); + public void transferFailed(TransferEvent event) { + requireNonNull(event, "event cannot be null"); + transferCompleted(event); + + if (!(event.getException() instanceof MetadataNotFoundException)) { + event.getException().printStackTrace(out); } } - private void transferCompleted( TransferEvent event ) - { - requireNonNull( event, "event cannot be null" ); - downloads.remove( event.getResource() ); + private void transferCompleted(TransferEvent event) { + requireNonNull(event, "event cannot be null"); + downloads.remove(event.getResource()); - StringBuilder buffer = new StringBuilder( 64 ); - pad( buffer, lastLength ); - buffer.append( '\r' ); - out.print( buffer ); + StringBuilder buffer = new StringBuilder(64); + pad(buffer, lastLength); + buffer.append('\r'); + out.print(buffer); } - public void transferCorrupted( TransferEvent event ) - { - requireNonNull( event, "event cannot be null" ); - event.getException().printStackTrace( out ); + public void transferCorrupted(TransferEvent event) { + requireNonNull(event, "event cannot be null"); + event.getException().printStackTrace(out); } - @SuppressWarnings( "checkstyle:magicnumber" ) - protected long toKB( long bytes ) - { - return ( bytes + 1023 ) / 1024; + @SuppressWarnings("checkstyle:magicnumber") + protected long toKB(long bytes) { + return (bytes + 1023) / 1024; } - } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ReverseTreeRepositoryListener.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ReverseTreeRepositoryListener.java index a13a768a8..00d3a297f 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ReverseTreeRepositoryListener.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/main/java/org/apache/maven/resolver/examples/util/ReverseTreeRepositoryListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples.util; import java.io.IOException; import java.io.UncheckedIOException; @@ -41,61 +40,56 @@ * A demo class building reverse tree using {@link CollectStepData} trace data provided in {@link RepositoryEvent} * events fired during collection. */ -public class ReverseTreeRepositoryListener - extends AbstractRepositoryListener -{ +public class ReverseTreeRepositoryListener extends AbstractRepositoryListener { private static final String EOL = System.lineSeparator(); @Override - public void artifactResolved( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); + public void artifactResolved(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); RequestTrace trace = event.getTrace(); CollectStepData collectStepTrace = null; - while ( trace != null ) - { - if ( trace.getData() instanceof CollectStepData ) - { + while (trace != null) { + if (trace.getData() instanceof CollectStepData) { collectStepTrace = (CollectStepData) trace.getData(); break; } trace = trace.getParent(); } - if ( collectStepTrace == null ) - { + if (collectStepTrace == null) { return; } Artifact resolvedArtifact = event.getArtifact(); Artifact nodeArtifact = collectStepTrace.getNode().getArtifact(); - if ( isInScope( resolvedArtifact, nodeArtifact ) ) - { + if (isInScope(resolvedArtifact, nodeArtifact)) { Dependency node = collectStepTrace.getNode(); String trackingData = node + " (" + collectStepTrace.getContext() + ")" + EOL; String indent = ""; - ListIterator iter = collectStepTrace.getPath() - .listIterator( collectStepTrace.getPath().size() ); - while ( iter.hasPrevious() ) - { + ListIterator iter = collectStepTrace + .getPath() + .listIterator(collectStepTrace.getPath().size()); + while (iter.hasPrevious()) { DependencyNode curr = iter.previous(); indent += " "; trackingData += indent + curr + " (" + collectStepTrace.getContext() + ")" + EOL; } - try - { - Path trackingDir = resolvedArtifact.getFile().getParentFile().toPath().resolve( ".tracking" ); - Files.createDirectories( trackingDir ); - Path trackingFile = trackingDir.resolve( collectStepTrace.getPath().get( 0 ) - .getArtifact().toString().replace( ":", "_" ) ); - Files.write( trackingFile, trackingData.getBytes( StandardCharsets.UTF_8 ) ); - System.out.println( trackingData ); - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + try { + Path trackingDir = + resolvedArtifact.getFile().getParentFile().toPath().resolve(".tracking"); + Files.createDirectories(trackingDir); + Path trackingFile = trackingDir.resolve(collectStepTrace + .getPath() + .get(0) + .getArtifact() + .toString() + .replace(":", "_")); + Files.write(trackingFile, trackingData.getBytes(StandardCharsets.UTF_8)); + System.out.println(trackingData); + } catch (IOException e) { + throw new UncheckedIOException(e); } } } @@ -106,10 +100,9 @@ public void artifactResolved( RepositoryEvent event ) * method "filters" out in WHICH artifact are we interested in, but it intentionally neglects extension as * ArtifactDescriptorReader modifies extension to "pom" during collect. So all we have to rely on is GAV only. */ - private boolean isInScope( Artifact artifact, Artifact nodeArtifact ) - { - return Objects.equals( artifact.getGroupId(), nodeArtifact.getGroupId() ) - && Objects.equals( artifact.getArtifactId(), nodeArtifact.getArtifactId() ) - && Objects.equals( artifact.getVersion(), nodeArtifact.getVersion() ); + private boolean isInScope(Artifact artifact, Artifact nodeArtifact) { + return Objects.equals(artifact.getGroupId(), nodeArtifact.getGroupId()) + && Objects.equals(artifact.getArtifactId(), nodeArtifact.getArtifactId()) + && Objects.equals(artifact.getVersion(), nodeArtifact.getVersion()); } } diff --git a/maven-resolver-demos/maven-resolver-demo-snippets/src/test/java/org/apache/maven/resolver/examples/AllResolverDemosTest.java b/maven-resolver-demos/maven-resolver-demo-snippets/src/test/java/org/apache/maven/resolver/examples/AllResolverDemosTest.java index f4a25fe1b..40024aec4 100644 --- a/maven-resolver-demos/maven-resolver-demo-snippets/src/test/java/org/apache/maven/resolver/examples/AllResolverDemosTest.java +++ b/maven-resolver-demos/maven-resolver-demo-snippets/src/test/java/org/apache/maven/resolver/examples/AllResolverDemosTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.resolver.examples; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.resolver.examples; import org.apache.maven.resolver.examples.util.Booter; import org.junit.Test; @@ -25,20 +24,19 @@ /** * Runs all demos at once as part of UT. */ -public class AllResolverDemosTest -{ +public class AllResolverDemosTest { @Test public void serviceLocator() throws Exception { - AllResolverDemos.main( new String[] {Booter.SERVICE_LOCATOR} ); + AllResolverDemos.main(new String[] {Booter.SERVICE_LOCATOR}); } @Test public void guice() throws Exception { - AllResolverDemos.main( new String[] {Booter.GUICE} ); + AllResolverDemos.main(new String[] {Booter.GUICE}); } @Test public void sisu() throws Exception { - AllResolverDemos.main( new String[] {Booter.SISU} ); + AllResolverDemos.main(new String[] {Booter.SISU}); } } diff --git a/maven-resolver-demos/pom.xml b/maven-resolver-demos/pom.xml index 666e3fd01..dfb05a7aa 100644 --- a/maven-resolver-demos/pom.xml +++ b/maven-resolver-demos/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -32,19 +30,17 @@ pom Maven Artifact Resolver Demos - - Maven Artifact Resolver demos, showing concrete code to use Maven Artifact Resolver with Maven repositories. - - - - 3.8.4 - + Maven Artifact Resolver demos, showing concrete code to use Maven Artifact Resolver with Maven repositories. maven-resolver-demo-snippets maven-resolver-demo-maven-plugin + + 3.8.4 + + diff --git a/maven-resolver-impl/pom.xml b/maven-resolver-impl/pom.xml index 3a38e80a6..ffab9ed78 100644 --- a/maven-resolver-impl/pom.xml +++ b/maven-resolver-impl/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-impl Maven Artifact Resolver Implementation - - An implementation of the repository system. - + An implementation of the repository system. org.apache.maven.resolver.impl diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/ArtifactDescriptorReader.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/ArtifactDescriptorReader.java index 1d6787b14..4a9291ffa 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/ArtifactDescriptorReader.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/ArtifactDescriptorReader.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; @@ -29,24 +28,21 @@ * Provides information about an artifact that is relevant to transitive dependency resolution. * Each artifact is expected to have an accompanying artifact descriptor that among others lists * the direct dependencies of the artifact. - * + * * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface ArtifactDescriptorReader -{ +public interface ArtifactDescriptorReader { /** * Gets information about an artifact like its direct dependencies and potential relocations. Implementations must * respect the {@link RepositorySystemSession#getArtifactDescriptorPolicy() artifact descriptor policy} of the * session when dealing with certain error cases. - * + * * @param session The repository session, must not be {@code null}. * @param request The descriptor request, must not be {@code null} * @return The descriptor result, never {@code null}. * @throws ArtifactDescriptorException If the artifact descriptor could not be read. * @see RepositorySystem#readArtifactDescriptor(RepositorySystemSession, ArtifactDescriptorRequest) */ - ArtifactDescriptorResult readArtifactDescriptor( RepositorySystemSession session, - ArtifactDescriptorRequest request ) - throws ArtifactDescriptorException; - + ArtifactDescriptorResult readArtifactDescriptor(RepositorySystemSession session, ArtifactDescriptorRequest request) + throws ArtifactDescriptorException; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/ArtifactResolver.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/ArtifactResolver.java index 3b4359232..d6552dcaa 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/ArtifactResolver.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/ArtifactResolver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import java.util.Collection; import java.util.List; @@ -31,19 +30,18 @@ /** * Resolves artifacts, that is gets a local filesystem path to their binary contents. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface ArtifactResolver -{ +public interface ArtifactResolver { /** * Resolves the path for an artifact. The artifact will be downloaded to the local repository if necessary. An * artifact that is already resolved will be skipped and is not re-resolved. Note that this method assumes that any * relocations have already been processed and the artifact coordinates are used as-is. - * + * * @param session The repository session, must not be {@code null}. * @param request The resolution request, must not be {@code null}. * @return The resolution result, never {@code null}. @@ -51,14 +49,14 @@ public interface ArtifactResolver * @see Artifact#getFile() * @see RepositorySystem#resolveArtifact(RepositorySystemSession, ArtifactRequest) */ - ArtifactResult resolveArtifact( RepositorySystemSession session, ArtifactRequest request ) - throws ArtifactResolutionException; + ArtifactResult resolveArtifact(RepositorySystemSession session, ArtifactRequest request) + throws ArtifactResolutionException; /** * Resolves the paths for a collection of artifacts. Artifacts will be downloaded to the local repository if * necessary. Artifacts that are already resolved will be skipped and are not re-resolved. Note that this method * assumes that any relocations have already been processed and the artifact coordinates are used as-is. - * + * * @param session The repository session, must not be {@code null}. * @param requests The resolution requests, must not be {@code null}. * @return The resolution results (in request order), never {@code null}. @@ -66,8 +64,7 @@ ArtifactResult resolveArtifact( RepositorySystemSession session, ArtifactRequest * @see Artifact#getFile() * @see RepositorySystem#resolveArtifacts(RepositorySystemSession, Collection) */ - List resolveArtifacts( RepositorySystemSession session, - Collection requests ) - throws ArtifactResolutionException; - + List resolveArtifacts( + RepositorySystemSession session, Collection requests) + throws ArtifactResolutionException; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/DefaultServiceLocator.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/DefaultServiceLocator.java index f197ebba7..0c8f7598f 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/DefaultServiceLocator.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/DefaultServiceLocator.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; @@ -28,21 +27,14 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositorySystem; -import org.eclipse.aether.internal.impl.DefaultRepositorySystemLifecycle; -import org.eclipse.aether.internal.impl.LocalPathComposer; -import org.eclipse.aether.internal.impl.DefaultLocalPathComposer; import org.eclipse.aether.internal.impl.DefaultArtifactResolver; import org.eclipse.aether.internal.impl.DefaultChecksumPolicyProvider; -import org.eclipse.aether.internal.impl.DefaultTrackingFileManager; -import org.eclipse.aether.internal.impl.TrackingFileManager; -import org.eclipse.aether.internal.impl.checksum.DefaultChecksumAlgorithmFactorySelector; -import org.eclipse.aether.internal.impl.collect.DefaultDependencyCollector; import org.eclipse.aether.internal.impl.DefaultDeployer; import org.eclipse.aether.internal.impl.DefaultFileProcessor; import org.eclipse.aether.internal.impl.DefaultInstaller; +import org.eclipse.aether.internal.impl.DefaultLocalPathComposer; import org.eclipse.aether.internal.impl.DefaultLocalRepositoryProvider; import org.eclipse.aether.internal.impl.DefaultMetadataResolver; import org.eclipse.aether.internal.impl.DefaultOfflineController; @@ -51,17 +43,23 @@ import org.eclipse.aether.internal.impl.DefaultRepositoryEventDispatcher; import org.eclipse.aether.internal.impl.DefaultRepositoryLayoutProvider; import org.eclipse.aether.internal.impl.DefaultRepositorySystem; +import org.eclipse.aether.internal.impl.DefaultRepositorySystemLifecycle; +import org.eclipse.aether.internal.impl.DefaultTrackingFileManager; import org.eclipse.aether.internal.impl.DefaultTransporterProvider; import org.eclipse.aether.internal.impl.DefaultUpdateCheckManager; import org.eclipse.aether.internal.impl.DefaultUpdatePolicyAnalyzer; import org.eclipse.aether.internal.impl.EnhancedLocalRepositoryManagerFactory; +import org.eclipse.aether.internal.impl.LocalPathComposer; import org.eclipse.aether.internal.impl.Maven2RepositoryLayoutFactory; import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; +import org.eclipse.aether.internal.impl.TrackingFileManager; +import org.eclipse.aether.internal.impl.checksum.DefaultChecksumAlgorithmFactorySelector; +import org.eclipse.aether.internal.impl.collect.DefaultDependencyCollector; import org.eclipse.aether.internal.impl.filter.DefaultRemoteRepositoryFilterManager; import org.eclipse.aether.internal.impl.slf4j.Slf4jLoggerFactory; import org.eclipse.aether.internal.impl.synccontext.DefaultSyncContextFactory; -import org.eclipse.aether.internal.impl.synccontext.named.NamedLockFactoryAdapterFactoryImpl; import org.eclipse.aether.internal.impl.synccontext.named.NamedLockFactoryAdapterFactory; +import org.eclipse.aether.internal.impl.synccontext.named.NamedLockFactoryAdapterFactoryImpl; import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactorySelector; import org.eclipse.aether.spi.connector.checksum.ChecksumPolicyProvider; import org.eclipse.aether.spi.connector.layout.RepositoryLayoutFactory; @@ -74,28 +72,27 @@ import org.eclipse.aether.spi.log.LoggerFactory; import org.eclipse.aether.spi.synccontext.SyncContextFactory; +import static java.util.Objects.requireNonNull; + /** * A simple service locator that is already setup with all components from this library. To acquire a complete * repository system, clients need to add an artifact descriptor reader, a version resolver, a version range resolver * and optionally some repository connector and transporter factories to access remote repositories. Once the locator is * fully populated, the repository system can be created like this: - * + * *
      * RepositorySystem repoSystem = serviceLocator.getService( RepositorySystem.class );
      * 
    - * + * * Note: This class is not thread-safe. Clients are expected to create the service locator and the repository * system on a single thread. * * @deprecated Use some out-of-the-box DI implementation instead. */ @Deprecated -public final class DefaultServiceLocator - implements ServiceLocator -{ +public final class DefaultServiceLocator implements ServiceLocator { - private class Entry - { + private class Entry { private final Class type; @@ -103,94 +100,73 @@ private class Entry private List instances; - Entry( Class type ) - { - this.type = requireNonNull( type, "service type cannot be null" ); - providers = new LinkedHashSet<>( 8 ); + Entry(Class type) { + this.type = requireNonNull(type, "service type cannot be null"); + providers = new LinkedHashSet<>(8); } - public synchronized void setServices( T... services ) - { + public synchronized void setServices(T... services) { providers.clear(); - if ( services != null ) - { - for ( T service : services ) - { - providers.add( requireNonNull( service, "service instance cannot be null" ) ); + if (services != null) { + for (T service : services) { + providers.add(requireNonNull(service, "service instance cannot be null")); } } instances = null; } - public synchronized void setService( Class impl ) - { + public synchronized void setService(Class impl) { providers.clear(); - addService( impl ); + addService(impl); } - public synchronized void addService( Class impl ) - { - providers.add( requireNonNull( impl, "implementation class cannot be null" ) ); + public synchronized void addService(Class impl) { + providers.add(requireNonNull(impl, "implementation class cannot be null")); instances = null; } - public T getInstance() - { + public T getInstance() { List instances = getInstances(); - return instances.isEmpty() ? null : instances.get( 0 ); + return instances.isEmpty() ? null : instances.get(0); } - public synchronized List getInstances() - { - if ( instances == null ) - { - instances = new ArrayList<>( providers.size() ); - for ( Object provider : providers ) - { + public synchronized List getInstances() { + if (instances == null) { + instances = new ArrayList<>(providers.size()); + for (Object provider : providers) { T instance; - if ( provider instanceof Class ) - { - instance = newInstance( (Class) provider ); + if (provider instanceof Class) { + instance = newInstance((Class) provider); + } else { + instance = type.cast(provider); } - else - { - instance = type.cast( provider ); - } - if ( instance != null ) - { - instances.add( instance ); + if (instance != null) { + instances.add(instance); } } - instances = Collections.unmodifiableList( instances ); + instances = Collections.unmodifiableList(instances); } return instances; } - private T newInstance( Class impl ) - { - try - { + private T newInstance(Class impl) { + try { Constructor constr = impl.getDeclaredConstructor(); - if ( !Modifier.isPublic( constr.getModifiers() ) ) - { - constr.setAccessible( true ); + if (!Modifier.isPublic(constr.getModifiers())) { + constr.setAccessible(true); } Object obj = constr.newInstance(); - T instance = type.cast( obj ); - if ( instance instanceof Service ) - { - ( (Service) instance ).initService( DefaultServiceLocator.this ); + T instance = type.cast(obj); + if (instance instanceof Service) { + ((Service) instance).initService(DefaultServiceLocator.this); } return instance; - } - catch ( Exception | LinkageError e ) - { - serviceCreationFailed( type, impl, e ); + } catch (Exception | LinkageError e) { + serviceCreationFailed(type, impl, e); } return null; } - } private final Map, Entry> entries; @@ -200,50 +176,48 @@ private T newInstance( Class impl ) /** * Creates a new service locator that already knows about all service implementations included this library. */ - public DefaultServiceLocator() - { + public DefaultServiceLocator() { entries = new HashMap<>(); - addService( RepositorySystem.class, DefaultRepositorySystem.class ); - addService( ArtifactResolver.class, DefaultArtifactResolver.class ); - addService( DependencyCollector.class, DefaultDependencyCollector.class ); - addService( Deployer.class, DefaultDeployer.class ); - addService( Installer.class, DefaultInstaller.class ); - addService( MetadataResolver.class, DefaultMetadataResolver.class ); - addService( RepositoryLayoutProvider.class, DefaultRepositoryLayoutProvider.class ); - addService( RepositoryLayoutFactory.class, Maven2RepositoryLayoutFactory.class ); - addService( TransporterProvider.class, DefaultTransporterProvider.class ); - addService( ChecksumPolicyProvider.class, DefaultChecksumPolicyProvider.class ); - addService( RepositoryConnectorProvider.class, DefaultRepositoryConnectorProvider.class ); - addService( RemoteRepositoryManager.class, DefaultRemoteRepositoryManager.class ); - addService( UpdateCheckManager.class, DefaultUpdateCheckManager.class ); - addService( UpdatePolicyAnalyzer.class, DefaultUpdatePolicyAnalyzer.class ); - addService( FileProcessor.class, DefaultFileProcessor.class ); - addService( org.eclipse.aether.impl.SyncContextFactory.class, - org.eclipse.aether.internal.impl.synccontext.legacy.DefaultSyncContextFactory.class ); - addService( SyncContextFactory.class, DefaultSyncContextFactory.class ); - addService( RepositoryEventDispatcher.class, DefaultRepositoryEventDispatcher.class ); - addService( OfflineController.class, DefaultOfflineController.class ); - addService( LocalRepositoryProvider.class, DefaultLocalRepositoryProvider.class ); - addService( LocalRepositoryManagerFactory.class, SimpleLocalRepositoryManagerFactory.class ); - addService( LocalRepositoryManagerFactory.class, EnhancedLocalRepositoryManagerFactory.class ); - addService( LoggerFactory.class, Slf4jLoggerFactory.class ); - addService( TrackingFileManager.class, DefaultTrackingFileManager.class ); - addService( ChecksumAlgorithmFactorySelector.class, DefaultChecksumAlgorithmFactorySelector.class ); - addService( LocalPathComposer.class, DefaultLocalPathComposer.class ); - addService( RemoteRepositoryFilterManager.class, DefaultRemoteRepositoryFilterManager.class ); - addService( RepositorySystemLifecycle.class, DefaultRepositorySystemLifecycle.class ); - addService( NamedLockFactoryAdapterFactory.class, NamedLockFactoryAdapterFactoryImpl.class ); + addService(RepositorySystem.class, DefaultRepositorySystem.class); + addService(ArtifactResolver.class, DefaultArtifactResolver.class); + addService(DependencyCollector.class, DefaultDependencyCollector.class); + addService(Deployer.class, DefaultDeployer.class); + addService(Installer.class, DefaultInstaller.class); + addService(MetadataResolver.class, DefaultMetadataResolver.class); + addService(RepositoryLayoutProvider.class, DefaultRepositoryLayoutProvider.class); + addService(RepositoryLayoutFactory.class, Maven2RepositoryLayoutFactory.class); + addService(TransporterProvider.class, DefaultTransporterProvider.class); + addService(ChecksumPolicyProvider.class, DefaultChecksumPolicyProvider.class); + addService(RepositoryConnectorProvider.class, DefaultRepositoryConnectorProvider.class); + addService(RemoteRepositoryManager.class, DefaultRemoteRepositoryManager.class); + addService(UpdateCheckManager.class, DefaultUpdateCheckManager.class); + addService(UpdatePolicyAnalyzer.class, DefaultUpdatePolicyAnalyzer.class); + addService(FileProcessor.class, DefaultFileProcessor.class); + addService( + org.eclipse.aether.impl.SyncContextFactory.class, + org.eclipse.aether.internal.impl.synccontext.legacy.DefaultSyncContextFactory.class); + addService(SyncContextFactory.class, DefaultSyncContextFactory.class); + addService(RepositoryEventDispatcher.class, DefaultRepositoryEventDispatcher.class); + addService(OfflineController.class, DefaultOfflineController.class); + addService(LocalRepositoryProvider.class, DefaultLocalRepositoryProvider.class); + addService(LocalRepositoryManagerFactory.class, SimpleLocalRepositoryManagerFactory.class); + addService(LocalRepositoryManagerFactory.class, EnhancedLocalRepositoryManagerFactory.class); + addService(LoggerFactory.class, Slf4jLoggerFactory.class); + addService(TrackingFileManager.class, DefaultTrackingFileManager.class); + addService(ChecksumAlgorithmFactorySelector.class, DefaultChecksumAlgorithmFactorySelector.class); + addService(LocalPathComposer.class, DefaultLocalPathComposer.class); + addService(RemoteRepositoryFilterManager.class, DefaultRemoteRepositoryFilterManager.class); + addService(RepositorySystemLifecycle.class, DefaultRepositorySystemLifecycle.class); + addService(NamedLockFactoryAdapterFactory.class, NamedLockFactoryAdapterFactoryImpl.class); } - private Entry getEntry( Class type, boolean create ) - { - @SuppressWarnings( "unchecked" ) - Entry entry = (Entry) entries.get( requireNonNull( type, "service type cannot be null" ) ); - if ( entry == null && create ) - { - entry = new Entry<>( type ); - entries.put( type, entry ); + private Entry getEntry(Class type, boolean create) { + @SuppressWarnings("unchecked") + Entry entry = (Entry) entries.get(requireNonNull(type, "service type cannot be null")); + if (entry == null && create) { + entry = new Entry<>(type); + entries.put(type, entry); } return entry; } @@ -252,15 +226,14 @@ private Entry getEntry( Class type, boolean create ) * Sets the implementation class for a service. The specified class must have a no-arg constructor (of any * visibility). If the service implementation itself requires other services for its operation, it should implement * {@link Service} to gain access to this service locator. - * + * * @param The service type. * @param type The interface describing the service, must not be {@code null}. * @param impl The implementation class of the service, must not be {@code null}. * @return This locator for chaining, never {@code null}. */ - public DefaultServiceLocator setService( Class type, Class impl ) - { - getEntry( type, true ).setService( impl ); + public DefaultServiceLocator setService(Class type, Class impl) { + getEntry(type, true).setService(impl); return this; } @@ -268,80 +241,68 @@ public DefaultServiceLocator setService( Class type, Class i * Adds an implementation class for a service. The specified class must have a no-arg constructor (of any * visibility). If the service implementation itself requires other services for its operation, it should implement * {@link Service} to gain access to this service locator. - * + * * @param The service type. * @param type The interface describing the service, must not be {@code null}. * @param impl The implementation class of the service, must not be {@code null}. * @return This locator for chaining, never {@code null}. */ - public DefaultServiceLocator addService( Class type, Class impl ) - { - getEntry( type, true ).addService( impl ); + public DefaultServiceLocator addService(Class type, Class impl) { + getEntry(type, true).addService(impl); return this; } /** * Sets the instances for a service. - * + * * @param The service type. * @param type The interface describing the service, must not be {@code null}. * @param services The instances of the service, may be {@code null} but must not contain {@code null} elements. * @return This locator for chaining, never {@code null}. */ - public DefaultServiceLocator setServices( Class type, T... services ) - { - getEntry( type, true ).setServices( services ); + public DefaultServiceLocator setServices(Class type, T... services) { + getEntry(type, true).setServices(services); return this; } - public T getService( Class type ) - { - Entry entry = getEntry( type, false ); - return ( entry != null ) ? entry.getInstance() : null; + public T getService(Class type) { + Entry entry = getEntry(type, false); + return (entry != null) ? entry.getInstance() : null; } - public List getServices( Class type ) - { - Entry entry = getEntry( type, false ); - return ( entry != null ) ? entry.getInstances() : null; + public List getServices(Class type) { + Entry entry = getEntry(type, false); + return (entry != null) ? entry.getInstances() : null; } - private void serviceCreationFailed( Class type, Class impl, Throwable exception ) - { - if ( errorHandler != null ) - { - errorHandler.serviceCreationFailed( type, impl, exception ); + private void serviceCreationFailed(Class type, Class impl, Throwable exception) { + if (errorHandler != null) { + errorHandler.serviceCreationFailed(type, impl, exception); } } /** * Sets the error handler to use. - * + * * @param errorHandler The error handler to use, may be {@code null} to ignore/swallow errors. */ - public void setErrorHandler( ErrorHandler errorHandler ) - { + public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * A hook to customize the handling of errors encountered while locating a service implementation. */ - public abstract static class ErrorHandler - { + public abstract static class ErrorHandler { /** * Handles errors during creation of a service. The default implemention does nothing. - * + * * @param type The interface describing the service, must not be {@code null}. * @param impl The implementation class of the service, must not be {@code null}. * @param exception The error that occurred while trying to instantiate the implementation class, must not be * {@code null}. */ - public void serviceCreationFailed( Class type, Class impl, Throwable exception ) - { - } - + public void serviceCreationFailed(Class type, Class impl, Throwable exception) {} } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/DependencyCollector.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/DependencyCollector.java index 9fa58178c..33432621e 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/DependencyCollector.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/DependencyCollector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; @@ -28,20 +27,19 @@ /** * Given a collection of direct dependencies, recursively gathers their transitive dependencies and calculates the * dependency graph. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface DependencyCollector -{ +public interface DependencyCollector { /** * Collects the transitive dependencies of some artifacts and builds a dependency graph. Note that this operation is * only concerned about determining the coordinates of the transitive dependencies and does not actually resolve the * artifact files. The supplied session carries various hooks to customize the dependency graph that must be invoked * throughout the operation. - * + * * @param session The repository session, must not be {@code null}. * @param request The collection request, must not be {@code null}. * @return The collection result, never {@code null}. @@ -53,7 +51,6 @@ public interface DependencyCollector * @see RepositorySystemSession#getDependencyGraphTransformer() * @see RepositorySystem#collectDependencies(RepositorySystemSession, CollectRequest) */ - CollectResult collectDependencies( RepositorySystemSession session, CollectRequest request ) - throws DependencyCollectionException; - + CollectResult collectDependencies(RepositorySystemSession session, CollectRequest request) + throws DependencyCollectionException; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/Deployer.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/Deployer.java index 8f6b8fc36..2aabdc450 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/Deployer.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/Deployer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; @@ -27,17 +26,16 @@ /** * Publishes artifacts to a remote repository. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface Deployer -{ +public interface Deployer { /** * Uploads a collection of artifacts and their accompanying metadata to a remote repository. - * + * * @param session The repository session, must not be {@code null}. * @param request The deployment request, must not be {@code null}. * @return The deployment result, never {@code null}. @@ -45,7 +43,5 @@ public interface Deployer * @see RepositorySystem#deploy(RepositorySystemSession, DeployRequest) * @see MetadataGeneratorFactory#newInstance(RepositorySystemSession, DeployRequest) */ - DeployResult deploy( RepositorySystemSession session, DeployRequest request ) - throws DeploymentException; - + DeployResult deploy(RepositorySystemSession session, DeployRequest request) throws DeploymentException; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/Installer.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/Installer.java index a9ebed638..17478f370 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/Installer.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/Installer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; @@ -27,17 +26,16 @@ /** * Publishes artifacts to the local repository. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface Installer -{ +public interface Installer { /** * Installs a collection of artifacts and their accompanying metadata to the local repository. - * + * * @param session The repository session, must not be {@code null}. * @param request The installation request, must not be {@code null}. * @return The installation result, never {@code null}. @@ -45,7 +43,5 @@ public interface Installer * @see RepositorySystem#install(RepositorySystemSession, InstallRequest) * @see MetadataGeneratorFactory#newInstance(RepositorySystemSession, InstallRequest) */ - InstallResult install( RepositorySystemSession session, InstallRequest request ) - throws InstallationException; - + InstallResult install(RepositorySystemSession session, InstallRequest request) throws InstallationException; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/LocalRepositoryProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/LocalRepositoryProvider.java index d5f4be28d..026644f1f 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/LocalRepositoryProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/LocalRepositoryProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; @@ -27,20 +26,19 @@ /** * Retrieves a local repository manager from the installed local repository manager factories. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface LocalRepositoryProvider -{ +public interface LocalRepositoryProvider { /** * Creates a new manager for the specified local repository. If the specified local repository has no type, the * default local repository type of the system will be used. Note: It is expected that this method * invocation is one of the last steps of setting up a new session, in particular any configuration properties * should have been set already. - * + * * @param session The repository system session from which to configure the manager, must not be {@code null}. * @param localRepository The local repository to create a manager for, must not be {@code null}. * @return The local repository manager, never {@code null}. @@ -48,7 +46,6 @@ public interface LocalRepositoryProvider * is given. * @see RepositorySystem#newLocalRepositoryManager(RepositorySystemSession, LocalRepository) */ - LocalRepositoryManager newLocalRepositoryManager( RepositorySystemSession session, LocalRepository localRepository ) - throws NoLocalRepositoryManagerException; - + LocalRepositoryManager newLocalRepositoryManager(RepositorySystemSession session, LocalRepository localRepository) + throws NoLocalRepositoryManagerException; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataGenerator.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataGenerator.java index b4356cc67..17ec33de6 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataGenerator.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataGenerator.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import java.util.Collection; @@ -26,35 +25,33 @@ /** * A metadata generator that participates in the installation/deployment of artifacts. - * + * * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface MetadataGenerator -{ +public interface MetadataGenerator { /** * Prepares the generator to transform artifacts. - * + * * @param artifacts The artifacts to install/deploy, must not be {@code null}. * @return The metadata to process (e.g. merge with existing metadata) before artifact transformations, never * {@code null}. */ - Collection prepare( Collection artifacts ); + Collection prepare(Collection artifacts); /** * Enables the metadata generator to transform the specified artifact. - * + * * @param artifact The artifact to transform, must not be {@code null}. * @return The transformed artifact (or just the input artifact), never {@code null}. */ - Artifact transformArtifact( Artifact artifact ); + Artifact transformArtifact(Artifact artifact); /** * Allows for metadata generation based on the transformed artifacts. - * + * * @param artifacts The (transformed) artifacts to install/deploy, must not be {@code null}. * @return The additional metadata to process after artifact transformations, never {@code null}. */ - Collection finish( Collection artifacts ); - + Collection finish(Collection artifacts); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataGeneratorFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataGeneratorFactory.java index 5f2b74052..5df74326c 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataGeneratorFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataGeneratorFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.deployment.DeployRequest; @@ -26,35 +25,33 @@ /** * A factory to create metadata generators. Metadata generators can contribute additional metadata during the * installation/deployment of artifacts. - * + * * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface MetadataGeneratorFactory -{ +public interface MetadataGeneratorFactory { /** * Creates a new metadata generator for the specified install request. - * + * * @param session The repository system session from which to configure the generator, must not be {@code null}. * @param request The install request the metadata generator is used for, must not be {@code null}. * @return The metadata generator for the request or {@code null} if none. */ - MetadataGenerator newInstance( RepositorySystemSession session, InstallRequest request ); + MetadataGenerator newInstance(RepositorySystemSession session, InstallRequest request); /** * Creates a new metadata generator for the specified deploy request. - * + * * @param session The repository system session from which to configure the generator, must not be {@code null}. * @param request The deploy request the metadata generator is used for, must not be {@code null}. * @return The metadata generator for the request or {@code null} if none. */ - MetadataGenerator newInstance( RepositorySystemSession session, DeployRequest request ); + MetadataGenerator newInstance(RepositorySystemSession session, DeployRequest request); /** * The priority of this factory. Factories with higher priority are invoked before those with lower priority. - * + * * @return The priority of this factory. */ float getPriority(); - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataResolver.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataResolver.java index 886e85686..149734fbd 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataResolver.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/MetadataResolver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import java.util.Collection; import java.util.List; @@ -30,25 +29,23 @@ /** * Resolves metadata, that is gets a local filesystem path to their binary contents. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface MetadataResolver -{ +public interface MetadataResolver { /** * Resolves the paths for a collection of metadata. Metadata will be downloaded to the local repository if * necessary, e.g. because it hasn't been cached yet or the cache is deemed outdated. - * + * * @param session The repository session, must not be {@code null}. * @param requests The resolution requests, must not be {@code null}. * @return The resolution results (in request order), never {@code null}. * @see Metadata#getFile() * @see RepositorySystem#resolveMetadata(RepositorySystemSession, Collection) */ - List resolveMetadata( RepositorySystemSession session, - Collection requests ); - + List resolveMetadata( + RepositorySystemSession session, Collection requests); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/OfflineController.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/OfflineController.java index 22f5a4b33..85cad813d 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/OfflineController.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/OfflineController.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; @@ -25,13 +24,12 @@ /** * Determines whether a remote repository is accessible in offline mode. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface OfflineController -{ +public interface OfflineController { /** * Determines whether the specified repository is accessible if the system was in offline mode. A simple @@ -40,14 +38,12 @@ public interface OfflineController * {@link RepositorySystemSession#getConfigProperties() configuration properties} of the session to check for some * kind of whitelist that allows certain remote repositories even when offline. At any rate, the session's current * {@link RepositorySystemSession#isOffline() offline state} is irrelevant to the outcome of the check. - * + * * @param session The repository session during which the check is made, must not be {@code null}. * @param repository The remote repository to check for offline access, must not be {@code null}. * @throws RepositoryOfflineException If the repository is not accessible in offline mode. If the method returns * normally, the repository is considered accessible even in offline mode. * @see RepositorySystemSession#isOffline() */ - void checkOffline( RepositorySystemSession session, RemoteRepository repository ) - throws RepositoryOfflineException; - + void checkOffline(RepositorySystemSession session, RemoteRepository repository) throws RepositoryOfflineException; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RemoteRepositoryFilterManager.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RemoteRepositoryFilterManager.java index c865a824d..6f350d1c5 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RemoteRepositoryFilterManager.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RemoteRepositoryFilterManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.spi.connector.filter.RemoteRepositoryFilter; @@ -27,12 +26,11 @@ * * @since 1.9.0 */ -public interface RemoteRepositoryFilterManager -{ +public interface RemoteRepositoryFilterManager { /** * Provides the filter instance for given session, or {@code null} if no filtering applied. * * @return The session bound filter or {@code null} if no filtering applied. */ - RemoteRepositoryFilter getRemoteRepositoryFilter( RepositorySystemSession session ); + RemoteRepositoryFilter getRemoteRepositoryFilter(RepositorySystemSession session); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RemoteRepositoryManager.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RemoteRepositoryManager.java index 94dae527c..2998bb661 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RemoteRepositoryManager.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RemoteRepositoryManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import java.util.List; @@ -27,18 +26,17 @@ /** * Helps dealing with remote repository definitions. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface RemoteRepositoryManager -{ +public interface RemoteRepositoryManager { /** * Aggregates repository definitions by merging duplicate repositories and optionally applies mirror, proxy and * authentication settings from the supplied session. - * + * * @param session The repository session during which the repositories will be accessed, must not be {@code null}. * @param dominantRepositories The current list of remote repositories to merge the new definitions into, must not * be {@code null}. @@ -50,15 +48,16 @@ public interface RemoteRepositoryManager * @see RepositorySystemSession#getProxySelector() * @see RepositorySystemSession#getAuthenticationSelector() */ - List aggregateRepositories( RepositorySystemSession session, - List dominantRepositories, - List recessiveRepositories, - boolean recessiveIsRaw ); + List aggregateRepositories( + RepositorySystemSession session, + List dominantRepositories, + List recessiveRepositories, + boolean recessiveIsRaw); /** * Gets the effective repository policy for the specified remote repository by merging the applicable * snapshot/release policy of the repository with global settings from the supplied session. - * + * * @param session The repository session during which the repository will be accessed, must not be {@code null}. * @param repository The remote repository to determine the effective policy for, must not be {@code null}. * @param releases {@code true} if the policy for release artifacts needs to be considered, {@code false} if not. @@ -67,7 +66,6 @@ List aggregateRepositories( RepositorySystemSession session, * @see RepositorySystemSession#getChecksumPolicy() * @see RepositorySystemSession#getUpdatePolicy() */ - RepositoryPolicy getPolicy( RepositorySystemSession session, RemoteRepository repository, boolean releases, - boolean snapshots ); - + RepositoryPolicy getPolicy( + RepositorySystemSession session, RemoteRepository repository, boolean releases, boolean snapshots); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositoryConnectorProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositoryConnectorProvider.java index 8d665c0a9..a50abaf51 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositoryConnectorProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositoryConnectorProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; @@ -26,24 +25,22 @@ /** * Retrieves a repository connector from the installed repository connector factories. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface RepositoryConnectorProvider -{ +public interface RepositoryConnectorProvider { /** * Tries to create a repository connector for the specified remote repository. - * + * * @param session The repository system session from which to configure the connector, must not be {@code null}. * @param repository The remote repository to create a connector for, must not be {@code null}. * @return The connector for the given repository, never {@code null}. * @throws NoRepositoryConnectorException If no available factory can create a connector for the specified remote * repository. */ - RepositoryConnector newRepositoryConnector( RepositorySystemSession session, RemoteRepository repository ) - throws NoRepositoryConnectorException; - + RepositoryConnector newRepositoryConnector(RepositorySystemSession session, RemoteRepository repository) + throws NoRepositoryConnectorException; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositoryEventDispatcher.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositoryEventDispatcher.java index 2d29eb7c7..46059c88e 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositoryEventDispatcher.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositoryEventDispatcher.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,24 +16,23 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositoryEvent; /** * Dispatches repository events to registered listeners. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface RepositoryEventDispatcher -{ +public interface RepositoryEventDispatcher { /** * Dispatches the specified repository event to all registered listeners. - * + * * @param event The event to dispatch, must not be {@code null}. */ - void dispatch( RepositoryEvent event ); - + void dispatch(RepositoryEvent event); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositorySystemLifecycle.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositorySystemLifecycle.java index 68fcf8147..b3a0c44e1 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositorySystemLifecycle.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/RepositorySystemLifecycle.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; /** * Lifecycle managing component for repository system. @@ -27,8 +26,7 @@ * @provisional This type is provisional and can be changed, moved or removed without prior notice. * @since 1.9.0 */ -public interface RepositorySystemLifecycle -{ +public interface RepositorySystemLifecycle { /** * Marks the repository system as ended (shut down): all "on close" handlers will be invoked. This method may be * invoked multiple times, only once will execute, subsequent calls will be no-op. @@ -40,5 +38,5 @@ public interface RepositorySystemLifecycle *

    * Throws if repository system is already shut down. */ - void addOnSystemEndedHandler( Runnable handler ); + void addOnSystemEndedHandler(Runnable handler); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/SyncContextFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/SyncContextFactory.java index c6f66332e..166fd42b4 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/SyncContextFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/SyncContextFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; /** * This class is here for binary compatibility only. @@ -25,6 +24,4 @@ * @deprecated For backward compatibility reasons only, do not use this interface. */ @Deprecated -public interface SyncContextFactory extends org.eclipse.aether.spi.synccontext.SyncContextFactory -{ -} +public interface SyncContextFactory extends org.eclipse.aether.spi.synccontext.SyncContextFactory {} diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdateCheck.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdateCheck.java index b77d2bcc6..f689c12fe 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdateCheck.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdateCheck.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import java.io.File; @@ -26,14 +25,13 @@ /** * A request to check if an update of an artifact/metadata from a remote repository is needed. - * + * * @param * @param * @see UpdateCheckManager * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public final class UpdateCheck -{ +public final class UpdateCheck { private long localLastUpdated; @@ -56,20 +54,17 @@ public final class UpdateCheck /** * Creates an uninitialized update check request. */ - public UpdateCheck() - { - } + public UpdateCheck() {} /** * Gets the last-modified timestamp of the corresponding item produced by a local installation. If non-zero, a * remote update will be surpressed if the local item is up-to-date, even if the remote item has not been cached * locally. - * + * * @return The last-modified timestamp of the corresponding item produced by a local installation or {@code 0} to * ignore any local item. */ - public long getLocalLastUpdated() - { + public long getLocalLastUpdated() { return localLastUpdated; } @@ -77,57 +72,52 @@ public long getLocalLastUpdated() * Sets the last-modified timestamp of the corresponding item produced by a local installation. If non-zero, a * remote update will be surpressed if the local item is up-to-date, even if the remote item has not been cached * locally. - * + * * @param localLastUpdated The last-modified timestamp of the corresponding item produced by a local installation or * {@code 0} to ignore any local item. * @return This object for chaining. */ - public UpdateCheck setLocalLastUpdated( long localLastUpdated ) - { + public UpdateCheck setLocalLastUpdated(long localLastUpdated) { this.localLastUpdated = localLastUpdated; return this; } /** * Gets the item of the check. - * + * * @return The item of the check, never {@code null}. */ - public T getItem() - { + public T getItem() { return item; } /** * Sets the item of the check. - * + * * @param item The item of the check, must not be {@code null}. * @return This object for chaining. */ - public UpdateCheck setItem( T item ) - { + public UpdateCheck setItem(T item) { this.item = item; return this; } /** * Returns the local file of the item. - * + * * @return The local file of the item. */ - public File getFile() - { + public File getFile() { return file; } /** * Sets the local file of the item. - * + * * @param file The file of the item, never {@code null} . * @return This object for chaining. */ - public UpdateCheck setFile( File file ) - { + public UpdateCheck setFile(File file) { this.file = file; return this; } @@ -135,71 +125,65 @@ public UpdateCheck setFile( File file ) /** * Indicates whether the local file given by {@link #getFile()}, if existent, should be considered valid or not. An * invalid file is equivalent to a physically missing file. - * + * * @return {@code true} if the file should be considered valid if existent, {@code false} if the file should be * treated as if it was missing. */ - public boolean isFileValid() - { + public boolean isFileValid() { return fileValid; } /** * Controls whether the local file given by {@link #getFile()}, if existent, should be considered valid or not. An * invalid file is equivalent to a physically missing file. - * + * * @param fileValid {@code true} if the file should be considered valid if existent, {@code false} if the file * should be treated as if it was missing. * @return This object for chaining. */ - public UpdateCheck setFileValid( boolean fileValid ) - { + public UpdateCheck setFileValid(boolean fileValid) { this.fileValid = fileValid; return this; } /** * Gets the policy to use for the check. - * + * * @return The policy to use for the check. * @see org.eclipse.aether.repository.RepositoryPolicy */ - public String getPolicy() - { + public String getPolicy() { return policy; } /** * Sets the policy to use for the check. - * + * * @param policy The policy to use for the check, may be {@code null}. * @return This object for chaining. * @see org.eclipse.aether.repository.RepositoryPolicy */ - public UpdateCheck setPolicy( String policy ) - { + public UpdateCheck setPolicy(String policy) { this.policy = policy; return this; } /** * Gets the repository from which a potential update/download will performed. - * + * * @return The repository to use for the check. */ - public RemoteRepository getRepository() - { + public RemoteRepository getRepository() { return repository; } /** * Sets the repository from which a potential update/download will performed. - * + * * @param repository The repository to use for the check, must not be {@code null}. * @return This object for chaining. */ - public UpdateCheck setRepository( RemoteRepository repository ) - { + public UpdateCheck setRepository(RemoteRepository repository) { this.repository = repository; return this; } @@ -207,79 +191,71 @@ public UpdateCheck setRepository( RemoteRepository repository ) /** * Gets the repository which ultimately hosts the metadata to update. This will be different from the repository * given by {@link #getRepository()} in case the latter denotes a repository manager. - * + * * @return The actual repository hosting the authoritative copy of the metadata to update, never {@code null} for a * metadata update check. */ - public RemoteRepository getAuthoritativeRepository() - { + public RemoteRepository getAuthoritativeRepository() { return authoritativeRepository != null ? authoritativeRepository : repository; } /** * Sets the repository which ultimately hosts the metadata to update. This will be different from the repository * given by {@link #getRepository()} in case the latter denotes a repository manager. - * + * * @param authoritativeRepository The actual repository hosting the authoritative copy of the metadata to update, * must not be {@code null} for a metadata update check. * @return This object for chaining. */ - public UpdateCheck setAuthoritativeRepository( RemoteRepository authoritativeRepository ) - { + public UpdateCheck setAuthoritativeRepository(RemoteRepository authoritativeRepository) { this.authoritativeRepository = authoritativeRepository; return this; } /** * Gets the result of a check, denoting whether the remote repository should be checked for updates. - * + * * @return The result of a check. */ - public boolean isRequired() - { + public boolean isRequired() { return required; } /** * Sets the result of an update check. - * + * * @param required The result of an update check. In case of {@code false} and the local file given by * {@link #getFile()} does actually not exist, {@link #setException(RepositoryException)} should be used * to provide the previous/cached failure that explains the absence of the file. * @return This object for chaining. */ - public UpdateCheck setRequired( boolean required ) - { + public UpdateCheck setRequired(boolean required) { this.required = required; return this; } /** * Gets the exception that occurred during the update check. - * + * * @return The occurred exception or {@code null} if the update check was successful. */ - public E getException() - { + public E getException() { return exception; } /** * Sets the exception for this update check. - * + * * @param exception The exception for this update check, may be {@code null} if the check was successful. * @return This object for chaining. */ - public UpdateCheck setException( E exception ) - { + public UpdateCheck setException(E exception) { this.exception = exception; return this; } @Override - public String toString() - { + public String toString() { return getPolicy() + ": " + getFile() + " < " + getRepository(); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdateCheckManager.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdateCheckManager.java index cd35df02d..b344789dd 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdateCheckManager.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdateCheckManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -27,44 +26,42 @@ /** * Determines if updates of artifacts and metadata from remote repositories are needed. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface UpdateCheckManager -{ +public interface UpdateCheckManager { /** * Checks whether an artifact has to be updated from a remote repository. - * + * * @param session The repository system session during which the request is made, must not be {@code null}. * @param check The update check request, must not be {@code null}. */ - void checkArtifact( RepositorySystemSession session, UpdateCheck check ); + void checkArtifact(RepositorySystemSession session, UpdateCheck check); /** * Updates the timestamp for the artifact contained in the update check. - * + * * @param session The repository system session during which the request is made, must not be {@code null}. * @param check The update check request, must not be {@code null}. */ - void touchArtifact( RepositorySystemSession session, UpdateCheck check ); + void touchArtifact(RepositorySystemSession session, UpdateCheck check); /** * Checks whether metadata has to be updated from a remote repository. - * + * * @param session The repository system session during which the request is made, must not be {@code null}. * @param check The update check request, must not be {@code null}. */ - void checkMetadata( RepositorySystemSession session, UpdateCheck check ); + void checkMetadata(RepositorySystemSession session, UpdateCheck check); /** * Updates the timestamp for the metadata contained in the update check. - * + * * @param session The repository system session during which the request is made, must not be {@code null}. * @param check The update check request, must not be {@code null}. */ - void touchMetadata( RepositorySystemSession session, UpdateCheck check ); - + void touchMetadata(RepositorySystemSession session, UpdateCheck check); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdatePolicyAnalyzer.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdatePolicyAnalyzer.java index ce8018a19..ce17a1e91 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdatePolicyAnalyzer.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/UpdatePolicyAnalyzer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,39 +16,38 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystemSession; /** * Evaluates update policies. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface UpdatePolicyAnalyzer -{ +public interface UpdatePolicyAnalyzer { /** * Returns the policy with the shorter update interval. - * + * * @param session The repository system session during which the request is made, must not be {@code null}. * @param policy1 A policy to compare, may be {@code null}. * @param policy2 A policy to compare, may be {@code null}. * @return The policy with the shorter update interval. */ - String getEffectiveUpdatePolicy( RepositorySystemSession session, String policy1, String policy2 ); + String getEffectiveUpdatePolicy(RepositorySystemSession session, String policy1, String policy2); /** * Determines whether the specified modification timestamp satisfies the freshness constraint expressed by the given * update policy. - * + * * @param session The repository system session during which the check is made, must not be {@code null}. * @param lastModified The timestamp to check against the update policy. * @param policy The update policy, may be {@code null}. * @return {@code true} if the specified timestamp is older than acceptable by the update policy, {@code false} * otherwise. */ - boolean isUpdatedRequired( RepositorySystemSession session, long lastModified, String policy ); - + boolean isUpdatedRequired(RepositorySystemSession session, long lastModified, String policy); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/VersionRangeResolver.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/VersionRangeResolver.java index 89bf706be..03846a696 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/VersionRangeResolver.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/VersionRangeResolver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; @@ -27,11 +26,10 @@ /** * Parses and evaluates version ranges encountered in dependency declarations. - * + * * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface VersionRangeResolver -{ +public interface VersionRangeResolver { /** * Expands a version range to a list of matching versions, in ascending order. For example, resolves "[3.8,4.0)" to @@ -41,7 +39,7 @@ public interface VersionRangeResolver *

    * The supplied request may also refer to a single concrete version rather than a version range. In this case * though, the result contains simply the (parsed) input version, regardless of the repositories and their contents. - * + * * @param session The repository session, must not be {@code null}. * @param request The version range request, must not be {@code null}. * @return The version range result, never {@code null}. @@ -49,7 +47,6 @@ public interface VersionRangeResolver * not raise an exception. * @see RepositorySystem#resolveVersionRange(RepositorySystemSession, VersionRangeRequest) */ - VersionRangeResult resolveVersionRange( RepositorySystemSession session, VersionRangeRequest request ) - throws VersionRangeResolutionException; - + VersionRangeResult resolveVersionRange(RepositorySystemSession session, VersionRangeRequest request) + throws VersionRangeResolutionException; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/VersionResolver.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/VersionResolver.java index e6a8a108f..13b5f572b 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/VersionResolver.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/VersionResolver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; @@ -27,23 +26,21 @@ /** * Evaluates artifact meta/pseudo versions. - * + * * @provisional This type is provisional and can be changed, moved or removed without prior notice. */ -public interface VersionResolver -{ +public interface VersionResolver { /** * Resolves an artifact's meta version (if any) to a concrete version. For example, resolves "1.0-SNAPSHOT" to * "1.0-20090208.132618-23" or "RELEASE"/"LATEST" to "2.0". - * + * * @param session The repository session, must not be {@code null}. * @param request The version request, must not be {@code null} * @return The version result, never {@code null}. * @throws VersionResolutionException If the metaversion could not be resolved. * @see RepositorySystem#resolveVersion(RepositorySystemSession, VersionRequest) */ - VersionResult resolveVersion( RepositorySystemSession session, VersionRequest request ) - throws VersionResolutionException; - + VersionResult resolveVersion(RepositorySystemSession session, VersionRequest request) + throws VersionResolutionException; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/guice/AetherModule.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/guice/AetherModule.java index fccf2e9ef..a77ba87c4 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/guice/AetherModule.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/guice/AetherModule.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl.guice; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl.guice; + +import javax.inject.Named; +import javax.inject.Singleton; import java.util.Collections; import java.util.HashMap; @@ -25,9 +27,9 @@ import java.util.Map; import java.util.Set; -import javax.inject.Named; -import javax.inject.Singleton; - +import com.google.inject.AbstractModule; +import com.google.inject.Provides; +import com.google.inject.name.Names; import org.eclipse.aether.RepositoryListener; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.impl.ArtifactResolver; @@ -42,21 +44,43 @@ import org.eclipse.aether.impl.RepositoryConnectorProvider; import org.eclipse.aether.impl.RepositoryEventDispatcher; import org.eclipse.aether.impl.RepositorySystemLifecycle; +import org.eclipse.aether.impl.UpdateCheckManager; +import org.eclipse.aether.impl.UpdatePolicyAnalyzer; +import org.eclipse.aether.internal.impl.DefaultArtifactResolver; +import org.eclipse.aether.internal.impl.DefaultChecksumPolicyProvider; +import org.eclipse.aether.internal.impl.DefaultDeployer; +import org.eclipse.aether.internal.impl.DefaultFileProcessor; +import org.eclipse.aether.internal.impl.DefaultInstaller; +import org.eclipse.aether.internal.impl.DefaultLocalPathComposer; import org.eclipse.aether.internal.impl.DefaultLocalPathPrefixComposerFactory; +import org.eclipse.aether.internal.impl.DefaultLocalRepositoryProvider; +import org.eclipse.aether.internal.impl.DefaultMetadataResolver; +import org.eclipse.aether.internal.impl.DefaultOfflineController; +import org.eclipse.aether.internal.impl.DefaultRemoteRepositoryManager; +import org.eclipse.aether.internal.impl.DefaultRepositoryConnectorProvider; +import org.eclipse.aether.internal.impl.DefaultRepositoryEventDispatcher; +import org.eclipse.aether.internal.impl.DefaultRepositoryLayoutProvider; +import org.eclipse.aether.internal.impl.DefaultRepositorySystem; import org.eclipse.aether.internal.impl.DefaultRepositorySystemLifecycle; -import org.eclipse.aether.internal.impl.LocalPathComposer; -import org.eclipse.aether.internal.impl.DefaultLocalPathComposer; import org.eclipse.aether.internal.impl.DefaultTrackingFileManager; +import org.eclipse.aether.internal.impl.DefaultTransporterProvider; +import org.eclipse.aether.internal.impl.DefaultUpdateCheckManager; +import org.eclipse.aether.internal.impl.DefaultUpdatePolicyAnalyzer; +import org.eclipse.aether.internal.impl.EnhancedLocalRepositoryManagerFactory; +import org.eclipse.aether.internal.impl.LocalPathComposer; import org.eclipse.aether.internal.impl.LocalPathPrefixComposerFactory; +import org.eclipse.aether.internal.impl.Maven2RepositoryLayoutFactory; +import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.internal.impl.TrackingFileManager; -import org.eclipse.aether.internal.impl.checksum.SummaryFileTrustedChecksumsSource; +import org.eclipse.aether.internal.impl.checksum.DefaultChecksumAlgorithmFactorySelector; import org.eclipse.aether.internal.impl.checksum.Md5ChecksumAlgorithmFactory; import org.eclipse.aether.internal.impl.checksum.Sha1ChecksumAlgorithmFactory; import org.eclipse.aether.internal.impl.checksum.Sha256ChecksumAlgorithmFactory; import org.eclipse.aether.internal.impl.checksum.Sha512ChecksumAlgorithmFactory; -import org.eclipse.aether.internal.impl.checksum.DefaultChecksumAlgorithmFactorySelector; import org.eclipse.aether.internal.impl.checksum.SparseDirectoryTrustedChecksumsSource; +import org.eclipse.aether.internal.impl.checksum.SummaryFileTrustedChecksumsSource; import org.eclipse.aether.internal.impl.checksum.TrustedToProvidedChecksumsSourceAdapter; +import org.eclipse.aether.internal.impl.collect.DefaultDependencyCollector; import org.eclipse.aether.internal.impl.collect.DependencyCollectorDelegate; import org.eclipse.aether.internal.impl.collect.bf.BfDependencyCollector; import org.eclipse.aether.internal.impl.collect.df.DfDependencyCollector; @@ -64,11 +88,12 @@ import org.eclipse.aether.internal.impl.filter.GroupIdRemoteRepositoryFilterSource; import org.eclipse.aether.internal.impl.filter.PrefixesRemoteRepositoryFilterSource; import org.eclipse.aether.internal.impl.resolution.TrustedChecksumsArtifactResolverPostProcessor; +import org.eclipse.aether.internal.impl.slf4j.Slf4jLoggerFactory; import org.eclipse.aether.internal.impl.synccontext.DefaultSyncContextFactory; -import org.eclipse.aether.internal.impl.synccontext.named.NameMappers; -import org.eclipse.aether.internal.impl.synccontext.named.NamedLockFactoryAdapterFactoryImpl; import org.eclipse.aether.internal.impl.synccontext.named.NameMapper; +import org.eclipse.aether.internal.impl.synccontext.named.NameMappers; import org.eclipse.aether.internal.impl.synccontext.named.NamedLockFactoryAdapterFactory; +import org.eclipse.aether.internal.impl.synccontext.named.NamedLockFactoryAdapterFactoryImpl; import org.eclipse.aether.internal.impl.synccontext.named.providers.DiscriminatingNameMapperProvider; import org.eclipse.aether.internal.impl.synccontext.named.providers.FileGAVNameMapperProvider; import org.eclipse.aether.internal.impl.synccontext.named.providers.FileHashingGAVNameMapperProvider; @@ -78,35 +103,12 @@ import org.eclipse.aether.named.providers.FileLockNamedLockFactory; import org.eclipse.aether.named.providers.LocalReadWriteLockNamedLockFactory; import org.eclipse.aether.named.providers.LocalSemaphoreNamedLockFactory; -import org.eclipse.aether.impl.UpdateCheckManager; -import org.eclipse.aether.impl.UpdatePolicyAnalyzer; -import org.eclipse.aether.internal.impl.DefaultArtifactResolver; -import org.eclipse.aether.internal.impl.DefaultChecksumPolicyProvider; -import org.eclipse.aether.internal.impl.collect.DefaultDependencyCollector; -import org.eclipse.aether.internal.impl.DefaultDeployer; -import org.eclipse.aether.internal.impl.DefaultFileProcessor; -import org.eclipse.aether.internal.impl.DefaultInstaller; -import org.eclipse.aether.internal.impl.DefaultLocalRepositoryProvider; -import org.eclipse.aether.internal.impl.DefaultMetadataResolver; -import org.eclipse.aether.internal.impl.DefaultOfflineController; -import org.eclipse.aether.internal.impl.DefaultRemoteRepositoryManager; -import org.eclipse.aether.internal.impl.DefaultRepositoryConnectorProvider; -import org.eclipse.aether.internal.impl.DefaultRepositoryEventDispatcher; -import org.eclipse.aether.internal.impl.DefaultRepositoryLayoutProvider; -import org.eclipse.aether.internal.impl.DefaultRepositorySystem; -import org.eclipse.aether.internal.impl.DefaultTransporterProvider; -import org.eclipse.aether.internal.impl.DefaultUpdateCheckManager; -import org.eclipse.aether.internal.impl.DefaultUpdatePolicyAnalyzer; -import org.eclipse.aether.internal.impl.EnhancedLocalRepositoryManagerFactory; -import org.eclipse.aether.internal.impl.Maven2RepositoryLayoutFactory; -import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; -import org.eclipse.aether.internal.impl.slf4j.Slf4jLoggerFactory; import org.eclipse.aether.named.providers.NoopNamedLockFactory; import org.eclipse.aether.spi.checksums.TrustedChecksumsSource; -import org.eclipse.aether.spi.connector.checksum.ProvidedChecksumsSource; +import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactory; import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactorySelector; import org.eclipse.aether.spi.connector.checksum.ChecksumPolicyProvider; -import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactory; +import org.eclipse.aether.spi.connector.checksum.ProvidedChecksumsSource; import org.eclipse.aether.spi.connector.filter.RemoteRepositoryFilterSource; import org.eclipse.aether.spi.connector.layout.RepositoryLayoutFactory; import org.eclipse.aether.spi.connector.layout.RepositoryLayoutProvider; @@ -118,10 +120,6 @@ import org.eclipse.aether.spi.synccontext.SyncContextFactory; import org.slf4j.ILoggerFactory; -import com.google.inject.AbstractModule; -import com.google.inject.Provides; -import com.google.inject.name.Names; - /** * A ready-made Guice module that sets up bindings * for all components from this library. To acquire a complete repository system, clients need to bind an artifact @@ -131,300 +129,334 @@ * @noextend This class must not be extended by clients and will eventually be marked {@code final} without prior * notice. */ -public class AetherModule - extends AbstractModule -{ +public class AetherModule extends AbstractModule { /** * Creates a new instance of this Guice module, typically for invoking * {@link com.google.inject.Binder#install(com.google.inject.Module)}. */ - public AetherModule() - { - } + public AetherModule() {} /** * Configures Guice with bindings for Aether components provided by this library. */ + // CHECKSTYLE_OFF: MethodLength @Override - protected void configure() - { - bind( RepositorySystem.class ) // - .to( DefaultRepositorySystem.class ).in( Singleton.class ); - bind( ArtifactResolver.class ) // - .to( DefaultArtifactResolver.class ).in( Singleton.class ); - - bind( DependencyCollector.class ) // - .to( DefaultDependencyCollector.class ).in( Singleton.class ); - bind( DependencyCollectorDelegate.class ).annotatedWith( Names.named( BfDependencyCollector.NAME ) ) - .to( BfDependencyCollector.class ).in( Singleton.class ); - bind( DependencyCollectorDelegate.class ).annotatedWith( Names.named( DfDependencyCollector.NAME ) ) - .to( DfDependencyCollector.class ).in( Singleton.class ); - - bind( Deployer.class ) // - .to( DefaultDeployer.class ).in( Singleton.class ); - bind( Installer.class ) // - .to( DefaultInstaller.class ).in( Singleton.class ); - bind( MetadataResolver.class ) // - .to( DefaultMetadataResolver.class ).in( Singleton.class ); - bind( RepositoryLayoutProvider.class ) // - .to( DefaultRepositoryLayoutProvider.class ).in( Singleton.class ); - bind( RepositoryLayoutFactory.class ).annotatedWith( Names.named( "maven2" ) ) // - .to( Maven2RepositoryLayoutFactory.class ).in( Singleton.class ); - bind( TransporterProvider.class ) // - .to( DefaultTransporterProvider.class ).in( Singleton.class ); - bind( ChecksumPolicyProvider.class ) // - .to( DefaultChecksumPolicyProvider.class ).in( Singleton.class ); - bind( RepositoryConnectorProvider.class ) // - .to( DefaultRepositoryConnectorProvider.class ).in( Singleton.class ); - bind( RemoteRepositoryManager.class ) // - .to( DefaultRemoteRepositoryManager.class ).in( Singleton.class ); - bind( UpdateCheckManager.class ) // - .to( DefaultUpdateCheckManager.class ).in( Singleton.class ); - bind( UpdatePolicyAnalyzer.class ) // - .to( DefaultUpdatePolicyAnalyzer.class ).in( Singleton.class ); - bind( FileProcessor.class ) // - .to( DefaultFileProcessor.class ).in( Singleton.class ); - bind( RepositoryEventDispatcher.class ) // - .to( DefaultRepositoryEventDispatcher.class ).in( Singleton.class ); - bind( OfflineController.class ) // - .to( DefaultOfflineController.class ).in( Singleton.class ); - - bind( LocalPathComposer.class ) - .to( DefaultLocalPathComposer.class ).in( Singleton.class ); - bind( LocalPathPrefixComposerFactory.class ) - .to( DefaultLocalPathPrefixComposerFactory.class ).in( Singleton.class ); - - bind( LocalRepositoryProvider.class ) // - .to( DefaultLocalRepositoryProvider.class ).in( Singleton.class ); - bind( LocalRepositoryManagerFactory.class ).annotatedWith( Names.named( "simple" ) ) // - .to( SimpleLocalRepositoryManagerFactory.class ).in( Singleton.class ); - bind( LocalRepositoryManagerFactory.class ).annotatedWith( Names.named( "enhanced" ) ) // - .to( EnhancedLocalRepositoryManagerFactory.class ).in( Singleton.class ); - bind( TrackingFileManager.class ).to( DefaultTrackingFileManager.class ).in( Singleton.class ); - - bind( ProvidedChecksumsSource.class ) - .annotatedWith( Names.named( TrustedToProvidedChecksumsSourceAdapter.NAME ) ) - .to( TrustedToProvidedChecksumsSourceAdapter.class ).in( Singleton.class ); - - bind( TrustedChecksumsSource.class ).annotatedWith( Names.named( SparseDirectoryTrustedChecksumsSource.NAME ) ) - .to( SparseDirectoryTrustedChecksumsSource.class ).in( Singleton.class ); - bind( TrustedChecksumsSource.class ).annotatedWith( Names.named( SummaryFileTrustedChecksumsSource.NAME ) ) - .to( SummaryFileTrustedChecksumsSource.class ).in( Singleton.class ); - - bind( ArtifactResolverPostProcessor.class ) - .annotatedWith( Names.named( TrustedChecksumsArtifactResolverPostProcessor.NAME ) ) - .to( TrustedChecksumsArtifactResolverPostProcessor.class ).in( Singleton.class ); - - bind( ChecksumAlgorithmFactory.class ).annotatedWith( Names.named( Md5ChecksumAlgorithmFactory.NAME ) ) - .to( Md5ChecksumAlgorithmFactory.class ); - bind( ChecksumAlgorithmFactory.class ).annotatedWith( Names.named( Sha1ChecksumAlgorithmFactory.NAME ) ) - .to( Sha1ChecksumAlgorithmFactory.class ); - bind( ChecksumAlgorithmFactory.class ).annotatedWith( Names.named( Sha256ChecksumAlgorithmFactory.NAME ) ) - .to( Sha256ChecksumAlgorithmFactory.class ); - bind( ChecksumAlgorithmFactory.class ).annotatedWith( Names.named( Sha512ChecksumAlgorithmFactory.NAME ) ) - .to( Sha512ChecksumAlgorithmFactory.class ); - bind( ChecksumAlgorithmFactorySelector.class ) - .to( DefaultChecksumAlgorithmFactorySelector.class ).in ( Singleton.class ); - - bind( RepositorySystemLifecycle.class ) - .to( DefaultRepositorySystemLifecycle.class ).in( Singleton.class ); - - bind( NamedLockFactoryAdapterFactory.class ) - .to( NamedLockFactoryAdapterFactoryImpl.class ).in( Singleton.class ); - bind( SyncContextFactory.class ).to( DefaultSyncContextFactory.class ).in( Singleton.class ); - bind( org.eclipse.aether.impl.SyncContextFactory.class ) - .to( org.eclipse.aether.internal.impl.synccontext.legacy.DefaultSyncContextFactory.class ) - .in( Singleton.class ); - - bind( NameMapper.class ).annotatedWith( Names.named( NameMappers.STATIC_NAME ) ) - .toProvider( StaticNameMapperProvider.class ).in( Singleton.class ); - bind( NameMapper.class ).annotatedWith( Names.named( NameMappers.GAV_NAME ) ) - .toProvider( GAVNameMapperProvider.class ).in( Singleton.class ); - bind( NameMapper.class ).annotatedWith( Names.named( NameMappers.DISCRIMINATING_NAME ) ) - .toProvider( DiscriminatingNameMapperProvider.class ).in( Singleton.class ); - bind( NameMapper.class ).annotatedWith( Names.named( NameMappers.FILE_GAV_NAME ) ) - .toProvider( FileGAVNameMapperProvider.class ).in( Singleton.class ); - bind( NameMapper.class ).annotatedWith( Names.named( NameMappers.FILE_HGAV_NAME ) ) - .toProvider( FileHashingGAVNameMapperProvider.class ).in( Singleton.class ); - - bind( NamedLockFactory.class ).annotatedWith( Names.named( NoopNamedLockFactory.NAME ) ) - .to( NoopNamedLockFactory.class ).in( Singleton.class ); - bind( NamedLockFactory.class ).annotatedWith( Names.named( LocalReadWriteLockNamedLockFactory.NAME ) ) - .to( LocalReadWriteLockNamedLockFactory.class ).in( Singleton.class ); - bind( NamedLockFactory.class ).annotatedWith( Names.named( LocalSemaphoreNamedLockFactory.NAME ) ) - .to( LocalSemaphoreNamedLockFactory.class ).in( Singleton.class ); - bind( NamedLockFactory.class ).annotatedWith( Names.named( FileLockNamedLockFactory.NAME ) ) - .to( FileLockNamedLockFactory.class ).in( Singleton.class ); - - bind( RemoteRepositoryFilterManager.class ) - .to( DefaultRemoteRepositoryFilterManager.class ).in( Singleton.class ); - bind( RemoteRepositoryFilterSource.class ).annotatedWith( - Names.named( GroupIdRemoteRepositoryFilterSource.NAME ) ) - .to( GroupIdRemoteRepositoryFilterSource.class ).in( Singleton.class ); - bind( RemoteRepositoryFilterSource.class ).annotatedWith( - Names.named( PrefixesRemoteRepositoryFilterSource.NAME ) ) - .to( PrefixesRemoteRepositoryFilterSource.class ).in( Singleton.class ); - - install( new Slf4jModule() ); - + protected void configure() { + bind(RepositorySystem.class) // + .to(DefaultRepositorySystem.class) + .in(Singleton.class); + bind(ArtifactResolver.class) // + .to(DefaultArtifactResolver.class) + .in(Singleton.class); + + bind(DependencyCollector.class) // + .to(DefaultDependencyCollector.class) + .in(Singleton.class); + bind(DependencyCollectorDelegate.class) + .annotatedWith(Names.named(BfDependencyCollector.NAME)) + .to(BfDependencyCollector.class) + .in(Singleton.class); + bind(DependencyCollectorDelegate.class) + .annotatedWith(Names.named(DfDependencyCollector.NAME)) + .to(DfDependencyCollector.class) + .in(Singleton.class); + + bind(Deployer.class) // + .to(DefaultDeployer.class) + .in(Singleton.class); + bind(Installer.class) // + .to(DefaultInstaller.class) + .in(Singleton.class); + bind(MetadataResolver.class) // + .to(DefaultMetadataResolver.class) + .in(Singleton.class); + bind(RepositoryLayoutProvider.class) // + .to(DefaultRepositoryLayoutProvider.class) + .in(Singleton.class); + bind(RepositoryLayoutFactory.class) + .annotatedWith(Names.named("maven2")) // + .to(Maven2RepositoryLayoutFactory.class) + .in(Singleton.class); + bind(TransporterProvider.class) // + .to(DefaultTransporterProvider.class) + .in(Singleton.class); + bind(ChecksumPolicyProvider.class) // + .to(DefaultChecksumPolicyProvider.class) + .in(Singleton.class); + bind(RepositoryConnectorProvider.class) // + .to(DefaultRepositoryConnectorProvider.class) + .in(Singleton.class); + bind(RemoteRepositoryManager.class) // + .to(DefaultRemoteRepositoryManager.class) + .in(Singleton.class); + bind(UpdateCheckManager.class) // + .to(DefaultUpdateCheckManager.class) + .in(Singleton.class); + bind(UpdatePolicyAnalyzer.class) // + .to(DefaultUpdatePolicyAnalyzer.class) + .in(Singleton.class); + bind(FileProcessor.class) // + .to(DefaultFileProcessor.class) + .in(Singleton.class); + bind(RepositoryEventDispatcher.class) // + .to(DefaultRepositoryEventDispatcher.class) + .in(Singleton.class); + bind(OfflineController.class) // + .to(DefaultOfflineController.class) + .in(Singleton.class); + + bind(LocalPathComposer.class).to(DefaultLocalPathComposer.class).in(Singleton.class); + bind(LocalPathPrefixComposerFactory.class) + .to(DefaultLocalPathPrefixComposerFactory.class) + .in(Singleton.class); + + bind(LocalRepositoryProvider.class) // + .to(DefaultLocalRepositoryProvider.class) + .in(Singleton.class); + bind(LocalRepositoryManagerFactory.class) + .annotatedWith(Names.named("simple")) // + .to(SimpleLocalRepositoryManagerFactory.class) + .in(Singleton.class); + bind(LocalRepositoryManagerFactory.class) + .annotatedWith(Names.named("enhanced")) // + .to(EnhancedLocalRepositoryManagerFactory.class) + .in(Singleton.class); + bind(TrackingFileManager.class).to(DefaultTrackingFileManager.class).in(Singleton.class); + + bind(ProvidedChecksumsSource.class) + .annotatedWith(Names.named(TrustedToProvidedChecksumsSourceAdapter.NAME)) + .to(TrustedToProvidedChecksumsSourceAdapter.class) + .in(Singleton.class); + + bind(TrustedChecksumsSource.class) + .annotatedWith(Names.named(SparseDirectoryTrustedChecksumsSource.NAME)) + .to(SparseDirectoryTrustedChecksumsSource.class) + .in(Singleton.class); + bind(TrustedChecksumsSource.class) + .annotatedWith(Names.named(SummaryFileTrustedChecksumsSource.NAME)) + .to(SummaryFileTrustedChecksumsSource.class) + .in(Singleton.class); + + bind(ArtifactResolverPostProcessor.class) + .annotatedWith(Names.named(TrustedChecksumsArtifactResolverPostProcessor.NAME)) + .to(TrustedChecksumsArtifactResolverPostProcessor.class) + .in(Singleton.class); + + bind(ChecksumAlgorithmFactory.class) + .annotatedWith(Names.named(Md5ChecksumAlgorithmFactory.NAME)) + .to(Md5ChecksumAlgorithmFactory.class); + bind(ChecksumAlgorithmFactory.class) + .annotatedWith(Names.named(Sha1ChecksumAlgorithmFactory.NAME)) + .to(Sha1ChecksumAlgorithmFactory.class); + bind(ChecksumAlgorithmFactory.class) + .annotatedWith(Names.named(Sha256ChecksumAlgorithmFactory.NAME)) + .to(Sha256ChecksumAlgorithmFactory.class); + bind(ChecksumAlgorithmFactory.class) + .annotatedWith(Names.named(Sha512ChecksumAlgorithmFactory.NAME)) + .to(Sha512ChecksumAlgorithmFactory.class); + bind(ChecksumAlgorithmFactorySelector.class) + .to(DefaultChecksumAlgorithmFactorySelector.class) + .in(Singleton.class); + + bind(RepositorySystemLifecycle.class) + .to(DefaultRepositorySystemLifecycle.class) + .in(Singleton.class); + + bind(NamedLockFactoryAdapterFactory.class) + .to(NamedLockFactoryAdapterFactoryImpl.class) + .in(Singleton.class); + bind(SyncContextFactory.class).to(DefaultSyncContextFactory.class).in(Singleton.class); + bind(org.eclipse.aether.impl.SyncContextFactory.class) + .to(org.eclipse.aether.internal.impl.synccontext.legacy.DefaultSyncContextFactory.class) + .in(Singleton.class); + + bind(NameMapper.class) + .annotatedWith(Names.named(NameMappers.STATIC_NAME)) + .toProvider(StaticNameMapperProvider.class) + .in(Singleton.class); + bind(NameMapper.class) + .annotatedWith(Names.named(NameMappers.GAV_NAME)) + .toProvider(GAVNameMapperProvider.class) + .in(Singleton.class); + bind(NameMapper.class) + .annotatedWith(Names.named(NameMappers.DISCRIMINATING_NAME)) + .toProvider(DiscriminatingNameMapperProvider.class) + .in(Singleton.class); + bind(NameMapper.class) + .annotatedWith(Names.named(NameMappers.FILE_GAV_NAME)) + .toProvider(FileGAVNameMapperProvider.class) + .in(Singleton.class); + bind(NameMapper.class) + .annotatedWith(Names.named(NameMappers.FILE_HGAV_NAME)) + .toProvider(FileHashingGAVNameMapperProvider.class) + .in(Singleton.class); + + bind(NamedLockFactory.class) + .annotatedWith(Names.named(NoopNamedLockFactory.NAME)) + .to(NoopNamedLockFactory.class) + .in(Singleton.class); + bind(NamedLockFactory.class) + .annotatedWith(Names.named(LocalReadWriteLockNamedLockFactory.NAME)) + .to(LocalReadWriteLockNamedLockFactory.class) + .in(Singleton.class); + bind(NamedLockFactory.class) + .annotatedWith(Names.named(LocalSemaphoreNamedLockFactory.NAME)) + .to(LocalSemaphoreNamedLockFactory.class) + .in(Singleton.class); + bind(NamedLockFactory.class) + .annotatedWith(Names.named(FileLockNamedLockFactory.NAME)) + .to(FileLockNamedLockFactory.class) + .in(Singleton.class); + + bind(RemoteRepositoryFilterManager.class) + .to(DefaultRemoteRepositoryFilterManager.class) + .in(Singleton.class); + bind(RemoteRepositoryFilterSource.class) + .annotatedWith(Names.named(GroupIdRemoteRepositoryFilterSource.NAME)) + .to(GroupIdRemoteRepositoryFilterSource.class) + .in(Singleton.class); + bind(RemoteRepositoryFilterSource.class) + .annotatedWith(Names.named(PrefixesRemoteRepositoryFilterSource.NAME)) + .to(PrefixesRemoteRepositoryFilterSource.class) + .in(Singleton.class); + + install(new Slf4jModule()); } @Provides @Singleton Map remoteRepositoryFilterSources( - @Named( GroupIdRemoteRepositoryFilterSource.NAME ) RemoteRepositoryFilterSource groupId, - @Named( PrefixesRemoteRepositoryFilterSource.NAME ) RemoteRepositoryFilterSource prefixes - ) - { + @Named(GroupIdRemoteRepositoryFilterSource.NAME) RemoteRepositoryFilterSource groupId, + @Named(PrefixesRemoteRepositoryFilterSource.NAME) RemoteRepositoryFilterSource prefixes) { Map result = new HashMap<>(); - result.put( GroupIdRemoteRepositoryFilterSource.NAME, groupId ); - result.put( PrefixesRemoteRepositoryFilterSource.NAME, prefixes ); - return Collections.unmodifiableMap( result ); + result.put(GroupIdRemoteRepositoryFilterSource.NAME, groupId); + result.put(PrefixesRemoteRepositoryFilterSource.NAME, prefixes); + return Collections.unmodifiableMap(result); } @Provides @Singleton Map artifactResolverProcessors( - @Named( TrustedChecksumsArtifactResolverPostProcessor.NAME ) ArtifactResolverPostProcessor trustedChecksums - ) - { + @Named(TrustedChecksumsArtifactResolverPostProcessor.NAME) ArtifactResolverPostProcessor trustedChecksums) { Map result = new HashMap<>(); - result.put( TrustedChecksumsArtifactResolverPostProcessor.NAME, trustedChecksums ); - return Collections.unmodifiableMap( result ); + result.put(TrustedChecksumsArtifactResolverPostProcessor.NAME, trustedChecksums); + return Collections.unmodifiableMap(result); } @Provides @Singleton Map dependencyCollectorDelegates( - @Named( BfDependencyCollector.NAME ) DependencyCollectorDelegate bf, - @Named( DfDependencyCollector.NAME ) DependencyCollectorDelegate df - ) - { + @Named(BfDependencyCollector.NAME) DependencyCollectorDelegate bf, + @Named(DfDependencyCollector.NAME) DependencyCollectorDelegate df) { Map result = new HashMap<>(); - result.put( BfDependencyCollector.NAME, bf ); - result.put( DfDependencyCollector.NAME, df ); - return Collections.unmodifiableMap( result ); + result.put(BfDependencyCollector.NAME, bf); + result.put(DfDependencyCollector.NAME, df); + return Collections.unmodifiableMap(result); } @Provides @Singleton Map providedChecksumSources( - @Named( TrustedToProvidedChecksumsSourceAdapter.NAME ) ProvidedChecksumsSource adapter - ) - { + @Named(TrustedToProvidedChecksumsSourceAdapter.NAME) ProvidedChecksumsSource adapter) { Map result = new HashMap<>(); - result.put( TrustedToProvidedChecksumsSourceAdapter.NAME, adapter ); - return Collections.unmodifiableMap( result ); + result.put(TrustedToProvidedChecksumsSourceAdapter.NAME, adapter); + return Collections.unmodifiableMap(result); } @Provides @Singleton Map trustedChecksumSources( - @Named( SparseDirectoryTrustedChecksumsSource.NAME ) TrustedChecksumsSource sparse, - @Named( SummaryFileTrustedChecksumsSource.NAME ) TrustedChecksumsSource compact - ) - { + @Named(SparseDirectoryTrustedChecksumsSource.NAME) TrustedChecksumsSource sparse, + @Named(SummaryFileTrustedChecksumsSource.NAME) TrustedChecksumsSource compact) { Map result = new HashMap<>(); - result.put( SparseDirectoryTrustedChecksumsSource.NAME, sparse ); - result.put( SummaryFileTrustedChecksumsSource.NAME, compact ); - return Collections.unmodifiableMap( result ); + result.put(SparseDirectoryTrustedChecksumsSource.NAME, sparse); + result.put(SummaryFileTrustedChecksumsSource.NAME, compact); + return Collections.unmodifiableMap(result); } @Provides @Singleton Map provideChecksumTypes( - @Named( Sha512ChecksumAlgorithmFactory.NAME ) ChecksumAlgorithmFactory sha512, - @Named( Sha256ChecksumAlgorithmFactory.NAME ) ChecksumAlgorithmFactory sha256, - @Named( Sha1ChecksumAlgorithmFactory.NAME ) ChecksumAlgorithmFactory sha1, - @Named( Md5ChecksumAlgorithmFactory.NAME ) ChecksumAlgorithmFactory md5 ) - { + @Named(Sha512ChecksumAlgorithmFactory.NAME) ChecksumAlgorithmFactory sha512, + @Named(Sha256ChecksumAlgorithmFactory.NAME) ChecksumAlgorithmFactory sha256, + @Named(Sha1ChecksumAlgorithmFactory.NAME) ChecksumAlgorithmFactory sha1, + @Named(Md5ChecksumAlgorithmFactory.NAME) ChecksumAlgorithmFactory md5) { Map result = new HashMap<>(); - result.put( Sha512ChecksumAlgorithmFactory.NAME, sha512 ); - result.put( Sha256ChecksumAlgorithmFactory.NAME, sha256 ); - result.put( Sha1ChecksumAlgorithmFactory.NAME, sha1 ); - result.put( Md5ChecksumAlgorithmFactory.NAME, md5 ); - return Collections.unmodifiableMap( result ); + result.put(Sha512ChecksumAlgorithmFactory.NAME, sha512); + result.put(Sha256ChecksumAlgorithmFactory.NAME, sha256); + result.put(Sha1ChecksumAlgorithmFactory.NAME, sha1); + result.put(Md5ChecksumAlgorithmFactory.NAME, md5); + return Collections.unmodifiableMap(result); } @Provides @Singleton Map provideNameMappers( - @Named( NameMappers.STATIC_NAME ) NameMapper staticNameMapper, - @Named( NameMappers.GAV_NAME ) NameMapper gavNameMapper, - @Named( NameMappers.DISCRIMINATING_NAME ) NameMapper discriminatingNameMapper, - @Named( NameMappers.FILE_GAV_NAME ) NameMapper fileGavNameMapper, - @Named( NameMappers.FILE_HGAV_NAME ) NameMapper fileHashingGavNameMapper ) - { + @Named(NameMappers.STATIC_NAME) NameMapper staticNameMapper, + @Named(NameMappers.GAV_NAME) NameMapper gavNameMapper, + @Named(NameMappers.DISCRIMINATING_NAME) NameMapper discriminatingNameMapper, + @Named(NameMappers.FILE_GAV_NAME) NameMapper fileGavNameMapper, + @Named(NameMappers.FILE_HGAV_NAME) NameMapper fileHashingGavNameMapper) { Map result = new HashMap<>(); - result.put( NameMappers.STATIC_NAME, staticNameMapper ); - result.put( NameMappers.GAV_NAME, gavNameMapper ); - result.put( NameMappers.DISCRIMINATING_NAME, discriminatingNameMapper ); - result.put( NameMappers.FILE_GAV_NAME, fileGavNameMapper ); - result.put( NameMappers.FILE_HGAV_NAME, fileHashingGavNameMapper ); - return Collections.unmodifiableMap( result ); + result.put(NameMappers.STATIC_NAME, staticNameMapper); + result.put(NameMappers.GAV_NAME, gavNameMapper); + result.put(NameMappers.DISCRIMINATING_NAME, discriminatingNameMapper); + result.put(NameMappers.FILE_GAV_NAME, fileGavNameMapper); + result.put(NameMappers.FILE_HGAV_NAME, fileHashingGavNameMapper); + return Collections.unmodifiableMap(result); } @Provides @Singleton Map provideNamedLockFactories( - @Named( LocalReadWriteLockNamedLockFactory.NAME ) NamedLockFactory localRwLock, - @Named( LocalSemaphoreNamedLockFactory.NAME ) NamedLockFactory localSemaphore, - @Named( FileLockNamedLockFactory.NAME ) NamedLockFactory fileLockFactory ) - { + @Named(LocalReadWriteLockNamedLockFactory.NAME) NamedLockFactory localRwLock, + @Named(LocalSemaphoreNamedLockFactory.NAME) NamedLockFactory localSemaphore, + @Named(FileLockNamedLockFactory.NAME) NamedLockFactory fileLockFactory) { Map result = new HashMap<>(); - result.put( LocalReadWriteLockNamedLockFactory.NAME, localRwLock ); - result.put( LocalSemaphoreNamedLockFactory.NAME, localSemaphore ); - result.put( FileLockNamedLockFactory.NAME, fileLockFactory ); - return Collections.unmodifiableMap( result ); + result.put(LocalReadWriteLockNamedLockFactory.NAME, localRwLock); + result.put(LocalSemaphoreNamedLockFactory.NAME, localSemaphore); + result.put(FileLockNamedLockFactory.NAME, fileLockFactory); + return Collections.unmodifiableMap(result); } @Provides @Singleton Set provideLocalRepositoryManagerFactories( - @Named( "simple" ) LocalRepositoryManagerFactory simple, - @Named( "enhanced" ) LocalRepositoryManagerFactory enhanced ) - { + @Named("simple") LocalRepositoryManagerFactory simple, + @Named("enhanced") LocalRepositoryManagerFactory enhanced) { Set result = new HashSet<>(); - result.add( simple ); - result.add( enhanced ); - return Collections.unmodifiableSet( result ); + result.add(simple); + result.add(enhanced); + return Collections.unmodifiableSet(result); } @Provides @Singleton - Set provideRepositoryLayoutFactories( @Named( "maven2" ) RepositoryLayoutFactory maven2 ) - { + Set provideRepositoryLayoutFactories(@Named("maven2") RepositoryLayoutFactory maven2) { Set result = new HashSet<>(); - result.add( maven2 ); - return Collections.unmodifiableSet( result ); + result.add(maven2); + return Collections.unmodifiableSet(result); } @Provides @Singleton - Set providesRepositoryListeners() - { + Set providesRepositoryListeners() { return Collections.emptySet(); } - private static class Slf4jModule - extends AbstractModule - { + private static class Slf4jModule extends AbstractModule { @Override - protected void configure() - { - bind( LoggerFactory.class ) // - .to( Slf4jLoggerFactory.class ); + protected void configure() { + bind(LoggerFactory.class) // + .to(Slf4jLoggerFactory.class); } @Provides @Singleton - ILoggerFactory getLoggerFactory() - { + ILoggerFactory getLoggerFactory() { return org.slf4j.LoggerFactory.getILoggerFactory(); } - } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/guice/package-info.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/guice/package-info.java index fd14dd7d8..a9ab92a79 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/guice/package-info.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/guice/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -22,4 +22,3 @@ * Google Guice. */ package org.eclipse.aether.impl.guice; - diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/package-info.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/package-info.java index 959a431fe..7c7344f06 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/package-info.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/impl/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -27,4 +27,3 @@ * metadata that is used to reason about an artifact's dependencies and available versions. */ package org.eclipse.aether.impl; - diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/AbstractChecksumPolicy.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/AbstractChecksumPolicy.java index 1fe9e900d..153994f60 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/AbstractChecksumPolicy.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/AbstractChecksumPolicy.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.spi.connector.checksum.ChecksumPolicy; import org.eclipse.aether.transfer.ChecksumFailureException; @@ -27,54 +26,43 @@ import static java.util.Objects.requireNonNull; -abstract class AbstractChecksumPolicy - implements ChecksumPolicy -{ +abstract class AbstractChecksumPolicy implements ChecksumPolicy { - protected final Logger logger = LoggerFactory.getLogger( getClass() ); + protected final Logger logger = LoggerFactory.getLogger(getClass()); protected final TransferResource resource; - protected AbstractChecksumPolicy( TransferResource resource ) - { + protected AbstractChecksumPolicy(TransferResource resource) { this.resource = resource; } @Override - public boolean onChecksumMatch( String algorithm, ChecksumKind kind ) - { - requireNonNull( algorithm, "algorithm cannot be null" ); + public boolean onChecksumMatch(String algorithm, ChecksumKind kind) { + requireNonNull(algorithm, "algorithm cannot be null"); return true; } @Override - public void onChecksumMismatch( String algorithm, ChecksumKind kind, ChecksumFailureException exception ) - throws ChecksumFailureException - { - requireNonNull( algorithm, "algorithm cannot be null" ); - requireNonNull( exception, "exception cannot be null" ); + public void onChecksumMismatch(String algorithm, ChecksumKind kind, ChecksumFailureException exception) + throws ChecksumFailureException { + requireNonNull(algorithm, "algorithm cannot be null"); + requireNonNull(exception, "exception cannot be null"); throw exception; } @Override - public void onChecksumError( String algorithm, ChecksumKind kind, ChecksumFailureException exception ) - throws ChecksumFailureException - { - requireNonNull( algorithm, "algorithm cannot be null" ); - requireNonNull( exception, "exception cannot be null" ); - logger.debug( "Could not validate {} checksum for {}", algorithm, resource.getResourceName(), exception ); + public void onChecksumError(String algorithm, ChecksumKind kind, ChecksumFailureException exception) + throws ChecksumFailureException { + requireNonNull(algorithm, "algorithm cannot be null"); + requireNonNull(exception, "exception cannot be null"); + logger.debug("Could not validate {} checksum for {}", algorithm, resource.getResourceName(), exception); } @Override - public void onNoMoreChecksums() - throws ChecksumFailureException - { - throw new ChecksumFailureException( "Checksum validation failed, no checksums available" ); + public void onNoMoreChecksums() throws ChecksumFailureException { + throw new ChecksumFailureException("Checksum validation failed, no checksums available"); } @Override - public void onTransferRetry() - { - } - + public void onTransferRetry() {} } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/ArtifactRequestBuilder.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/ArtifactRequestBuilder.java index 1c46eae26..e0e4d4b00 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/ArtifactRequestBuilder.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/ArtifactRequestBuilder.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import java.util.ArrayList; import java.util.List; @@ -29,40 +28,32 @@ /** */ -class ArtifactRequestBuilder - implements DependencyVisitor -{ +class ArtifactRequestBuilder implements DependencyVisitor { private final RequestTrace trace; private final List requests; - ArtifactRequestBuilder( RequestTrace trace ) - { + ArtifactRequestBuilder(RequestTrace trace) { this.trace = trace; this.requests = new ArrayList<>(); } - public List getRequests() - { + public List getRequests() { return requests; } - public boolean visitEnter( DependencyNode node ) - { - if ( node.getDependency() != null ) - { - ArtifactRequest request = new ArtifactRequest( node ); - request.setTrace( trace ); - requests.add( request ); + public boolean visitEnter(DependencyNode node) { + if (node.getDependency() != null) { + ArtifactRequest request = new ArtifactRequest(node); + request.setTrace(trace); + requests.add(request); } return true; } - public boolean visitLeave( DependencyNode node ) - { + public boolean visitLeave(DependencyNode node) { return true; } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultArtifactResolver.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultArtifactResolver.java index 08bf531e7..58b4a31a2 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultArtifactResolver.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultArtifactResolver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import javax.inject.Inject; import javax.inject.Named; @@ -30,8 +29,6 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; -import static java.util.Objects.requireNonNull; - import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; @@ -48,8 +45,6 @@ import org.eclipse.aether.impl.RemoteRepositoryManager; import org.eclipse.aether.impl.RepositoryConnectorProvider; import org.eclipse.aether.impl.RepositoryEventDispatcher; -import org.eclipse.aether.spi.resolution.ArtifactResolverPostProcessor; -import org.eclipse.aether.spi.synccontext.SyncContextFactory; import org.eclipse.aether.impl.UpdateCheck; import org.eclipse.aether.impl.UpdateCheckManager; import org.eclipse.aether.impl.VersionResolver; @@ -75,6 +70,8 @@ import org.eclipse.aether.spi.io.FileProcessor; import org.eclipse.aether.spi.locator.Service; import org.eclipse.aether.spi.locator.ServiceLocator; +import org.eclipse.aether.spi.resolution.ArtifactResolverPostProcessor; +import org.eclipse.aether.spi.synccontext.SyncContextFactory; import org.eclipse.aether.transfer.ArtifactNotFoundException; import org.eclipse.aether.transfer.ArtifactTransferException; import org.eclipse.aether.transfer.NoRepositoryConnectorException; @@ -83,14 +80,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; + /** * */ @Singleton @Named -public class DefaultArtifactResolver - implements ArtifactResolver, Service -{ +public class DefaultArtifactResolver implements ArtifactResolver, Service { /** * Configuration to enable "snapshot normalization", downloaded snapshots from remote with timestamped file names @@ -105,7 +102,7 @@ public class DefaultArtifactResolver */ private static final String CONFIG_PROP_SIMPLE_LRM_INTEROP = "aether.artifactResolver.simpleLrmInterop"; - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultArtifactResolver.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultArtifactResolver.class); private FileProcessor fileProcessor; @@ -127,403 +124,346 @@ public class DefaultArtifactResolver private RemoteRepositoryFilterManager remoteRepositoryFilterManager; - public DefaultArtifactResolver() - { + public DefaultArtifactResolver() { // enables default constructor } - @SuppressWarnings( "checkstyle:parameternumber" ) + @SuppressWarnings("checkstyle:parameternumber") @Inject - DefaultArtifactResolver( FileProcessor fileProcessor, RepositoryEventDispatcher repositoryEventDispatcher, - VersionResolver versionResolver, UpdateCheckManager updateCheckManager, - RepositoryConnectorProvider repositoryConnectorProvider, - RemoteRepositoryManager remoteRepositoryManager, SyncContextFactory syncContextFactory, - OfflineController offlineController, - Map artifactResolverPostProcessors, - RemoteRepositoryFilterManager remoteRepositoryFilterManager ) - { - setFileProcessor( fileProcessor ); - setRepositoryEventDispatcher( repositoryEventDispatcher ); - setVersionResolver( versionResolver ); - setUpdateCheckManager( updateCheckManager ); - setRepositoryConnectorProvider( repositoryConnectorProvider ); - setRemoteRepositoryManager( remoteRepositoryManager ); - setSyncContextFactory( syncContextFactory ); - setOfflineController( offlineController ); - setArtifactResolverPostProcessors( artifactResolverPostProcessors ); - setRemoteRepositoryFilterManager( remoteRepositoryFilterManager ); + DefaultArtifactResolver( + FileProcessor fileProcessor, + RepositoryEventDispatcher repositoryEventDispatcher, + VersionResolver versionResolver, + UpdateCheckManager updateCheckManager, + RepositoryConnectorProvider repositoryConnectorProvider, + RemoteRepositoryManager remoteRepositoryManager, + SyncContextFactory syncContextFactory, + OfflineController offlineController, + Map artifactResolverPostProcessors, + RemoteRepositoryFilterManager remoteRepositoryFilterManager) { + setFileProcessor(fileProcessor); + setRepositoryEventDispatcher(repositoryEventDispatcher); + setVersionResolver(versionResolver); + setUpdateCheckManager(updateCheckManager); + setRepositoryConnectorProvider(repositoryConnectorProvider); + setRemoteRepositoryManager(remoteRepositoryManager); + setSyncContextFactory(syncContextFactory); + setOfflineController(offlineController); + setArtifactResolverPostProcessors(artifactResolverPostProcessors); + setRemoteRepositoryFilterManager(remoteRepositoryFilterManager); } - public void initService( ServiceLocator locator ) - { - setFileProcessor( locator.getService( FileProcessor.class ) ); - setRepositoryEventDispatcher( locator.getService( RepositoryEventDispatcher.class ) ); - setVersionResolver( locator.getService( VersionResolver.class ) ); - setUpdateCheckManager( locator.getService( UpdateCheckManager.class ) ); - setRepositoryConnectorProvider( locator.getService( RepositoryConnectorProvider.class ) ); - setRemoteRepositoryManager( locator.getService( RemoteRepositoryManager.class ) ); - setSyncContextFactory( locator.getService( SyncContextFactory.class ) ); - setOfflineController( locator.getService( OfflineController.class ) ); - setArtifactResolverPostProcessors( Collections.emptyMap() ); - setRemoteRepositoryFilterManager( locator.getService( RemoteRepositoryFilterManager.class ) ); + public void initService(ServiceLocator locator) { + setFileProcessor(locator.getService(FileProcessor.class)); + setRepositoryEventDispatcher(locator.getService(RepositoryEventDispatcher.class)); + setVersionResolver(locator.getService(VersionResolver.class)); + setUpdateCheckManager(locator.getService(UpdateCheckManager.class)); + setRepositoryConnectorProvider(locator.getService(RepositoryConnectorProvider.class)); + setRemoteRepositoryManager(locator.getService(RemoteRepositoryManager.class)); + setSyncContextFactory(locator.getService(SyncContextFactory.class)); + setOfflineController(locator.getService(OfflineController.class)); + setArtifactResolverPostProcessors(Collections.emptyMap()); + setRemoteRepositoryFilterManager(locator.getService(RemoteRepositoryFilterManager.class)); } /** * @deprecated not used any more since MRESOLVER-36 move to slf4j, added back in MRESOLVER-64 for compatibility */ @Deprecated - public DefaultArtifactResolver setLoggerFactory( org.eclipse.aether.spi.log.LoggerFactory loggerFactory ) - { + public DefaultArtifactResolver setLoggerFactory(org.eclipse.aether.spi.log.LoggerFactory loggerFactory) { // this.logger = NullLoggerFactory.getSafeLogger( loggerFactory, getClass() ); return this; } - public DefaultArtifactResolver setFileProcessor( FileProcessor fileProcessor ) - { - this.fileProcessor = requireNonNull( fileProcessor, "file processor cannot be null" ); + public DefaultArtifactResolver setFileProcessor(FileProcessor fileProcessor) { + this.fileProcessor = requireNonNull(fileProcessor, "file processor cannot be null"); return this; } - public DefaultArtifactResolver setRepositoryEventDispatcher( RepositoryEventDispatcher repositoryEventDispatcher ) - { - this.repositoryEventDispatcher = requireNonNull( repositoryEventDispatcher, - "repository event dispatcher cannot be null" ); + public DefaultArtifactResolver setRepositoryEventDispatcher(RepositoryEventDispatcher repositoryEventDispatcher) { + this.repositoryEventDispatcher = + requireNonNull(repositoryEventDispatcher, "repository event dispatcher cannot be null"); return this; } - public DefaultArtifactResolver setVersionResolver( VersionResolver versionResolver ) - { - this.versionResolver = requireNonNull( versionResolver, "version resolver cannot be null" ); + public DefaultArtifactResolver setVersionResolver(VersionResolver versionResolver) { + this.versionResolver = requireNonNull(versionResolver, "version resolver cannot be null"); return this; } - public DefaultArtifactResolver setUpdateCheckManager( UpdateCheckManager updateCheckManager ) - { - this.updateCheckManager = requireNonNull( updateCheckManager, "update check manager cannot be null" ); + public DefaultArtifactResolver setUpdateCheckManager(UpdateCheckManager updateCheckManager) { + this.updateCheckManager = requireNonNull(updateCheckManager, "update check manager cannot be null"); return this; } public DefaultArtifactResolver setRepositoryConnectorProvider( - RepositoryConnectorProvider repositoryConnectorProvider ) - { - this.repositoryConnectorProvider = requireNonNull( repositoryConnectorProvider, - "repository connector provider cannot be null" ); + RepositoryConnectorProvider repositoryConnectorProvider) { + this.repositoryConnectorProvider = + requireNonNull(repositoryConnectorProvider, "repository connector provider cannot be null"); return this; } - public DefaultArtifactResolver setRemoteRepositoryManager( RemoteRepositoryManager remoteRepositoryManager ) - { - this.remoteRepositoryManager = requireNonNull( remoteRepositoryManager, - "remote repository provider cannot be null" ); + public DefaultArtifactResolver setRemoteRepositoryManager(RemoteRepositoryManager remoteRepositoryManager) { + this.remoteRepositoryManager = + requireNonNull(remoteRepositoryManager, "remote repository provider cannot be null"); return this; } - public DefaultArtifactResolver setSyncContextFactory( SyncContextFactory syncContextFactory ) - { - this.syncContextFactory = requireNonNull( syncContextFactory, "sync context factory cannot be null" ); + public DefaultArtifactResolver setSyncContextFactory(SyncContextFactory syncContextFactory) { + this.syncContextFactory = requireNonNull(syncContextFactory, "sync context factory cannot be null"); return this; } - public DefaultArtifactResolver setOfflineController( OfflineController offlineController ) - { - this.offlineController = requireNonNull( offlineController, "offline controller cannot be null" ); + public DefaultArtifactResolver setOfflineController(OfflineController offlineController) { + this.offlineController = requireNonNull(offlineController, "offline controller cannot be null"); return this; } public DefaultArtifactResolver setArtifactResolverPostProcessors( - Map artifactResolverPostProcessors ) - { - this.artifactResolverPostProcessors = requireNonNull( artifactResolverPostProcessors, - "artifact resolver post-processors cannot be null" ); + Map artifactResolverPostProcessors) { + this.artifactResolverPostProcessors = + requireNonNull(artifactResolverPostProcessors, "artifact resolver post-processors cannot be null"); return this; } public DefaultArtifactResolver setRemoteRepositoryFilterManager( - RemoteRepositoryFilterManager remoteRepositoryFilterManager ) - { - this.remoteRepositoryFilterManager = requireNonNull( remoteRepositoryFilterManager, - "remote repository filter manager cannot be null" ); + RemoteRepositoryFilterManager remoteRepositoryFilterManager) { + this.remoteRepositoryFilterManager = + requireNonNull(remoteRepositoryFilterManager, "remote repository filter manager cannot be null"); return this; } - public ArtifactResult resolveArtifact( RepositorySystemSession session, ArtifactRequest request ) - throws ArtifactResolutionException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( session, "session cannot be null" ); + public ArtifactResult resolveArtifact(RepositorySystemSession session, ArtifactRequest request) + throws ArtifactResolutionException { + requireNonNull(session, "session cannot be null"); + requireNonNull(session, "session cannot be null"); - return resolveArtifacts( session, Collections.singleton( request ) ).get( 0 ); + return resolveArtifacts(session, Collections.singleton(request)).get(0); } - public List resolveArtifacts( RepositorySystemSession session, - Collection requests ) - throws ArtifactResolutionException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( session, "session cannot be null" ); - try ( SyncContext syncContext = syncContextFactory.newInstance( session, false ) ) - { - Collection artifacts = new ArrayList<>( requests.size() ); - for ( ArtifactRequest request : requests ) - { - if ( request.getArtifact().getProperty( ArtifactProperties.LOCAL_PATH, null ) != null ) - { + public List resolveArtifacts( + RepositorySystemSession session, Collection requests) + throws ArtifactResolutionException { + requireNonNull(session, "session cannot be null"); + requireNonNull(session, "session cannot be null"); + try (SyncContext syncContext = syncContextFactory.newInstance(session, false)) { + Collection artifacts = new ArrayList<>(requests.size()); + for (ArtifactRequest request : requests) { + if (request.getArtifact().getProperty(ArtifactProperties.LOCAL_PATH, null) != null) { continue; } - artifacts.add( request.getArtifact() ); + artifacts.add(request.getArtifact()); } - syncContext.acquire( artifacts, null ); + syncContext.acquire(artifacts, null); - return resolve( session, requests ); + return resolve(session, requests); } } - @SuppressWarnings( "checkstyle:methodlength" ) - private List resolve( RepositorySystemSession session, - Collection requests ) - throws ArtifactResolutionException - { - List results = new ArrayList<>( requests.size() ); + @SuppressWarnings("checkstyle:methodlength") + private List resolve( + RepositorySystemSession session, Collection requests) + throws ArtifactResolutionException { + List results = new ArrayList<>(requests.size()); boolean failures = false; - final boolean simpleLrmInterop = ConfigUtils.getBoolean( session, false, CONFIG_PROP_SIMPLE_LRM_INTEROP ); + final boolean simpleLrmInterop = ConfigUtils.getBoolean(session, false, CONFIG_PROP_SIMPLE_LRM_INTEROP); LocalRepositoryManager lrm = session.getLocalRepositoryManager(); WorkspaceReader workspace = session.getWorkspaceReader(); List groups = new ArrayList<>(); // filter != null: means "filtering applied", if null no filtering applied (behave as before) - RemoteRepositoryFilter filter = remoteRepositoryFilterManager.getRemoteRepositoryFilter( session ); + RemoteRepositoryFilter filter = remoteRepositoryFilterManager.getRemoteRepositoryFilter(session); - for ( ArtifactRequest request : requests ) - { - RequestTrace trace = RequestTrace.newChild( request.getTrace(), request ); + for (ArtifactRequest request : requests) { + RequestTrace trace = RequestTrace.newChild(request.getTrace(), request); - ArtifactResult result = new ArtifactResult( request ); - results.add( result ); + ArtifactResult result = new ArtifactResult(request); + results.add(result); Artifact artifact = request.getArtifact(); - artifactResolving( session, trace, artifact ); + artifactResolving(session, trace, artifact); - String localPath = artifact.getProperty( ArtifactProperties.LOCAL_PATH, null ); - if ( localPath != null ) - { + String localPath = artifact.getProperty(ArtifactProperties.LOCAL_PATH, null); + if (localPath != null) { // unhosted artifact, just validate file - File file = new File( localPath ); - if ( !file.isFile() ) - { + File file = new File(localPath); + if (!file.isFile()) { failures = true; - result.addException( new ArtifactNotFoundException( artifact, null ) ); - } - else - { - artifact = artifact.setFile( file ); - result.setArtifact( artifact ); - artifactResolved( session, trace, artifact, null, result.getExceptions() ); + result.addException(new ArtifactNotFoundException(artifact, null)); + } else { + artifact = artifact.setFile(file); + result.setArtifact(artifact); + artifactResolved(session, trace, artifact, null, result.getExceptions()); } continue; } List remoteRepositories = request.getRepositories(); - List filteredRemoteRepositories = new ArrayList<>( remoteRepositories ); - if ( filter != null ) - { - for ( RemoteRepository repository : remoteRepositories ) - { - RemoteRepositoryFilter.Result filterResult = filter.acceptArtifact( repository, artifact ); - if ( !filterResult.isAccepted() ) - { - result.addException( new ArtifactNotFoundException( artifact, repository, - filterResult.reasoning() ) ); - filteredRemoteRepositories.remove( repository ); + List filteredRemoteRepositories = new ArrayList<>(remoteRepositories); + if (filter != null) { + for (RemoteRepository repository : remoteRepositories) { + RemoteRepositoryFilter.Result filterResult = filter.acceptArtifact(repository, artifact); + if (!filterResult.isAccepted()) { + result.addException( + new ArtifactNotFoundException(artifact, repository, filterResult.reasoning())); + filteredRemoteRepositories.remove(repository); } } } VersionResult versionResult; - try - { - VersionRequest versionRequest = new VersionRequest( - artifact, filteredRemoteRepositories, request.getRequestContext() ); - versionRequest.setTrace( trace ); - versionResult = versionResolver.resolveVersion( session, versionRequest ); - } - catch ( VersionResolutionException e ) - { - result.addException( e ); + try { + VersionRequest versionRequest = + new VersionRequest(artifact, filteredRemoteRepositories, request.getRequestContext()); + versionRequest.setTrace(trace); + versionResult = versionResolver.resolveVersion(session, versionRequest); + } catch (VersionResolutionException e) { + result.addException(e); continue; } - artifact = artifact.setVersion( versionResult.getVersion() ); + artifact = artifact.setVersion(versionResult.getVersion()); - if ( versionResult.getRepository() != null ) - { - if ( versionResult.getRepository() instanceof RemoteRepository ) - { + if (versionResult.getRepository() != null) { + if (versionResult.getRepository() instanceof RemoteRepository) { filteredRemoteRepositories = - Collections.singletonList( (RemoteRepository) versionResult.getRepository() ); - } - else - { + Collections.singletonList((RemoteRepository) versionResult.getRepository()); + } else { filteredRemoteRepositories = Collections.emptyList(); } } - if ( workspace != null ) - { - File file = workspace.findArtifact( artifact ); - if ( file != null ) - { - artifact = artifact.setFile( file ); - result.setArtifact( artifact ); - result.setRepository( workspace.getRepository() ); - artifactResolved( session, trace, artifact, result.getRepository(), null ); + if (workspace != null) { + File file = workspace.findArtifact(artifact); + if (file != null) { + artifact = artifact.setFile(file); + result.setArtifact(artifact); + result.setRepository(workspace.getRepository()); + artifactResolved(session, trace, artifact, result.getRepository(), null); continue; } } - LocalArtifactResult local = lrm.find( session, new LocalArtifactRequest( artifact, - filteredRemoteRepositories, request.getRequestContext() ) ); - boolean found = ( filter != null && local.isAvailable() ) || isLocallyInstalled( local, versionResult ); + LocalArtifactResult local = lrm.find( + session, + new LocalArtifactRequest(artifact, filteredRemoteRepositories, request.getRequestContext())); + boolean found = (filter != null && local.isAvailable()) || isLocallyInstalled(local, versionResult); // with filtering it is availability that drives logic // without filtering it is simply presence of file that drives the logic // "interop" logic with simple LRM leads to RRF breakage: hence is ignored when filtering in effect - if ( found ) - { - if ( local.getRepository() != null ) - { - result.setRepository( local.getRepository() ); - } - else - { - result.setRepository( lrm.getRepository() ); + if (found) { + if (local.getRepository() != null) { + result.setRepository(local.getRepository()); + } else { + result.setRepository(lrm.getRepository()); } - try - { - artifact = artifact.setFile( getFile( session, artifact, local.getFile() ) ); - result.setArtifact( artifact ); - artifactResolved( session, trace, artifact, result.getRepository(), null ); + try { + artifact = artifact.setFile(getFile(session, artifact, local.getFile())); + result.setArtifact(artifact); + artifactResolved(session, trace, artifact, result.getRepository(), null); + } catch (ArtifactTransferException e) { + result.addException(e); } - catch ( ArtifactTransferException e ) - { - result.addException( e ); - } - if ( filter == null && simpleLrmInterop && !local.isAvailable() ) - { + if (filter == null && simpleLrmInterop && !local.isAvailable()) { /* * NOTE: Interop with simple local repository: An artifact installed by a simple local repo * manager will not show up in the repository tracking file of the enhanced local repository. * If however the maven-metadata-local.xml tells us the artifact was installed locally, we * sync the repository tracking file. */ - lrm.add( session, new LocalArtifactRegistration( artifact ) ); + lrm.add(session, new LocalArtifactRegistration(artifact)); } continue; } - if ( local.getFile() != null ) - { - LOGGER.debug( "Verifying availability of {} from {}", local.getFile(), remoteRepositories ); + if (local.getFile() != null) { + LOGGER.debug("Verifying availability of {} from {}", local.getFile(), remoteRepositories); } - LOGGER.debug( "Resolving artifact {} from {}", artifact, remoteRepositories ); - AtomicBoolean resolved = new AtomicBoolean( false ); + LOGGER.debug("Resolving artifact {} from {}", artifact, remoteRepositories); + AtomicBoolean resolved = new AtomicBoolean(false); Iterator groupIt = groups.iterator(); - for ( RemoteRepository repo : filteredRemoteRepositories ) - { - if ( !repo.getPolicy( artifact.isSnapshot() ).isEnabled() ) - { + for (RemoteRepository repo : filteredRemoteRepositories) { + if (!repo.getPolicy(artifact.isSnapshot()).isEnabled()) { continue; } - try - { - Utils.checkOffline( session, offlineController, repo ); - } - catch ( RepositoryOfflineException e ) - { - Exception exception = - new ArtifactNotFoundException( artifact, repo, "Cannot access " + repo.getId() + " (" + try { + Utils.checkOffline(session, offlineController, repo); + } catch (RepositoryOfflineException e) { + Exception exception = new ArtifactNotFoundException( + artifact, + repo, + "Cannot access " + repo.getId() + " (" + repo.getUrl() + ") in offline mode and the artifact " + artifact - + " has not been downloaded from it before.", e ); - result.addException( exception ); + + " has not been downloaded from it before.", + e); + result.addException(exception); continue; } ResolutionGroup group = null; - while ( groupIt.hasNext() ) - { + while (groupIt.hasNext()) { ResolutionGroup t = groupIt.next(); - if ( t.matches( repo ) ) - { + if (t.matches(repo)) { group = t; break; } } - if ( group == null ) - { - group = new ResolutionGroup( repo ); - groups.add( group ); + if (group == null) { + group = new ResolutionGroup(repo); + groups.add(group); groupIt = Collections.emptyIterator(); } - group.items.add( new ResolutionItem( trace, artifact, resolved, result, local, repo ) ); + group.items.add(new ResolutionItem(trace, artifact, resolved, result, local, repo)); } } - for ( ResolutionGroup group : groups ) - { - performDownloads( session, group ); + for (ResolutionGroup group : groups) { + performDownloads(session, group); } - for ( ArtifactResolverPostProcessor artifactResolverPostProcessor : artifactResolverPostProcessors.values() ) - { - artifactResolverPostProcessor.postProcess( session, results ); + for (ArtifactResolverPostProcessor artifactResolverPostProcessor : artifactResolverPostProcessors.values()) { + artifactResolverPostProcessor.postProcess(session, results); } - for ( ArtifactResult result : results ) - { + for (ArtifactResult result : results) { ArtifactRequest request = result.getRequest(); Artifact artifact = result.getArtifact(); - if ( artifact == null || artifact.getFile() == null ) - { + if (artifact == null || artifact.getFile() == null) { failures = true; - if ( result.getExceptions().isEmpty() ) - { - Exception exception = new ArtifactNotFoundException( request.getArtifact(), null ); - result.addException( exception ); + if (result.getExceptions().isEmpty()) { + Exception exception = new ArtifactNotFoundException(request.getArtifact(), null); + result.addException(exception); } - RequestTrace trace = RequestTrace.newChild( request.getTrace(), request ); - artifactResolved( session, trace, request.getArtifact(), null, result.getExceptions() ); + RequestTrace trace = RequestTrace.newChild(request.getTrace(), request); + artifactResolved(session, trace, request.getArtifact(), null, result.getExceptions()); } } - if ( failures ) - { - throw new ArtifactResolutionException( results ); + if (failures) { + throw new ArtifactResolutionException(results); } return results; } - private boolean isLocallyInstalled( LocalArtifactResult lar, VersionResult vr ) - { - if ( lar.isAvailable() ) - { + private boolean isLocallyInstalled(LocalArtifactResult lar, VersionResult vr) { + if (lar.isAvailable()) { return true; } - if ( lar.getFile() != null ) - { - if ( vr.getRepository() instanceof LocalRepository ) - { + if (lar.getFile() != null) { + if (vr.getRepository() instanceof LocalRepository) { // resolution of (snapshot) version found locally installed artifact return true; - } - else if ( vr.getRepository() == null && lar.getRequest().getRepositories().isEmpty() ) - { + } else if (vr.getRepository() == null + && lar.getRequest().getRepositories().isEmpty()) { // resolution of version range found locally installed artifact return true; } @@ -531,26 +471,21 @@ else if ( vr.getRepository() == null && lar.getRequest().getRepositories().isEmp return false; } - private File getFile( RepositorySystemSession session, Artifact artifact, File file ) - throws ArtifactTransferException - { - if ( artifact.isSnapshot() && !artifact.getVersion().equals( artifact.getBaseVersion() ) - && ConfigUtils.getBoolean( session, true, CONFIG_PROP_SNAPSHOT_NORMALIZATION ) ) - { - String name = file.getName().replace( artifact.getVersion(), artifact.getBaseVersion() ); - File dst = new File( file.getParent(), name ); + private File getFile(RepositorySystemSession session, Artifact artifact, File file) + throws ArtifactTransferException { + if (artifact.isSnapshot() + && !artifact.getVersion().equals(artifact.getBaseVersion()) + && ConfigUtils.getBoolean(session, true, CONFIG_PROP_SNAPSHOT_NORMALIZATION)) { + String name = file.getName().replace(artifact.getVersion(), artifact.getBaseVersion()); + File dst = new File(file.getParent(), name); boolean copy = dst.length() != file.length() || dst.lastModified() != file.lastModified(); - if ( copy ) - { - try - { - fileProcessor.copy( file, dst ); - dst.setLastModified( file.lastModified() ); - } - catch ( IOException e ) - { - throw new ArtifactTransferException( artifact, null, e ); + if (copy) { + try { + fileProcessor.copy(file, dst); + dst.setLastModified(file.lastModified()); + } catch (IOException e) { + throw new ArtifactTransferException(artifact, null, e); } } @@ -560,230 +495,200 @@ private File getFile( RepositorySystemSession session, Artifact artifact, File f return file; } - private void performDownloads( RepositorySystemSession session, ResolutionGroup group ) - { - List downloads = gatherDownloads( session, group ); - if ( downloads.isEmpty() ) - { + private void performDownloads(RepositorySystemSession session, ResolutionGroup group) { + List downloads = gatherDownloads(session, group); + if (downloads.isEmpty()) { return; } - for ( ArtifactDownload download : downloads ) - { - artifactDownloading( session, download.getTrace(), download.getArtifact(), group.repository ); + for (ArtifactDownload download : downloads) { + artifactDownloading(session, download.getTrace(), download.getArtifact(), group.repository); } - try - { - try ( RepositoryConnector connector = - repositoryConnectorProvider.newRepositoryConnector( session, group.repository ) ) - { - connector.get( downloads, null ); + try { + try (RepositoryConnector connector = + repositoryConnectorProvider.newRepositoryConnector(session, group.repository)) { + connector.get(downloads, null); } - } - catch ( NoRepositoryConnectorException e ) - { - for ( ArtifactDownload download : downloads ) - { - download.setException( new ArtifactTransferException( download.getArtifact(), group.repository, e ) ); + } catch (NoRepositoryConnectorException e) { + for (ArtifactDownload download : downloads) { + download.setException(new ArtifactTransferException(download.getArtifact(), group.repository, e)); } } - evaluateDownloads( session, group ); + evaluateDownloads(session, group); } - private List gatherDownloads( RepositorySystemSession session, ResolutionGroup group ) - { + private List gatherDownloads(RepositorySystemSession session, ResolutionGroup group) { LocalRepositoryManager lrm = session.getLocalRepositoryManager(); List downloads = new ArrayList<>(); - for ( ResolutionItem item : group.items ) - { + for (ResolutionItem item : group.items) { Artifact artifact = item.artifact; - if ( item.resolved.get() ) - { + if (item.resolved.get()) { // resolved in previous resolution group continue; } ArtifactDownload download = new ArtifactDownload(); - download.setArtifact( artifact ); - download.setRequestContext( item.request.getRequestContext() ); - download.setListener( SafeTransferListener.wrap( session ) ); - download.setTrace( item.trace ); - if ( item.local.getFile() != null ) - { - download.setFile( item.local.getFile() ); - download.setExistenceCheck( true ); - } - else - { + download.setArtifact(artifact); + download.setRequestContext(item.request.getRequestContext()); + download.setListener(SafeTransferListener.wrap(session)); + download.setTrace(item.trace); + if (item.local.getFile() != null) { + download.setFile(item.local.getFile()); + download.setExistenceCheck(true); + } else { String path = - lrm.getPathForRemoteArtifact( artifact, group.repository, item.request.getRequestContext() ); - download.setFile( new File( lrm.getRepository().getBasedir(), path ) ); + lrm.getPathForRemoteArtifact(artifact, group.repository, item.request.getRequestContext()); + download.setFile(new File(lrm.getRepository().getBasedir(), path)); } boolean snapshot = artifact.isSnapshot(); - RepositoryPolicy policy = - remoteRepositoryManager.getPolicy( session, group.repository, !snapshot, snapshot ); + RepositoryPolicy policy = remoteRepositoryManager.getPolicy(session, group.repository, !snapshot, snapshot); - int errorPolicy = Utils.getPolicy( session, artifact, group.repository ); - if ( ( errorPolicy & ResolutionErrorPolicy.CACHE_ALL ) != 0 ) - { + int errorPolicy = Utils.getPolicy(session, artifact, group.repository); + if ((errorPolicy & ResolutionErrorPolicy.CACHE_ALL) != 0) { UpdateCheck check = new UpdateCheck<>(); - check.setItem( artifact ); - check.setFile( download.getFile() ); - check.setFileValid( false ); - check.setRepository( group.repository ); - check.setPolicy( policy.getUpdatePolicy() ); + check.setItem(artifact); + check.setFile(download.getFile()); + check.setFileValid(false); + check.setRepository(group.repository); + check.setPolicy(policy.getUpdatePolicy()); item.updateCheck = check; - updateCheckManager.checkArtifact( session, check ); - if ( !check.isRequired() ) - { - item.result.addException( check.getException() ); + updateCheckManager.checkArtifact(session, check); + if (!check.isRequired()) { + item.result.addException(check.getException()); continue; } } - download.setChecksumPolicy( policy.getChecksumPolicy() ); - download.setRepositories( item.repository.getMirroredRepositories() ); - downloads.add( download ); + download.setChecksumPolicy(policy.getChecksumPolicy()); + download.setRepositories(item.repository.getMirroredRepositories()); + downloads.add(download); item.download = download; } return downloads; } - private void evaluateDownloads( RepositorySystemSession session, ResolutionGroup group ) - { + private void evaluateDownloads(RepositorySystemSession session, ResolutionGroup group) { LocalRepositoryManager lrm = session.getLocalRepositoryManager(); - for ( ResolutionItem item : group.items ) - { + for (ResolutionItem item : group.items) { ArtifactDownload download = item.download; - if ( download == null ) - { + if (download == null) { continue; } Artifact artifact = download.getArtifact(); - if ( download.getException() == null ) - { - item.resolved.set( true ); - item.result.setRepository( group.repository ); - try - { - artifact = artifact.setFile( getFile( session, artifact, download.getFile() ) ); - item.result.setArtifact( artifact ); - - lrm.add( session, new LocalArtifactRegistration( - artifact, group.repository, download.getSupportedContexts() ) ); - } - catch ( ArtifactTransferException e ) - { - download.setException( e ); - item.result.addException( e ); + if (download.getException() == null) { + item.resolved.set(true); + item.result.setRepository(group.repository); + try { + artifact = artifact.setFile(getFile(session, artifact, download.getFile())); + item.result.setArtifact(artifact); + + lrm.add( + session, + new LocalArtifactRegistration(artifact, group.repository, download.getSupportedContexts())); + } catch (ArtifactTransferException e) { + download.setException(e); + item.result.addException(e); } - } - else - { - item.result.addException( download.getException() ); + } else { + item.result.addException(download.getException()); } /* * NOTE: Touch after registration with local repo to ensure concurrent resolution is not rejected with * "already updated" via session data when actual update to local repo is still pending. */ - if ( item.updateCheck != null ) - { - item.updateCheck.setException( download.getException() ); - updateCheckManager.touchArtifact( session, item.updateCheck ); + if (item.updateCheck != null) { + item.updateCheck.setException(download.getException()); + updateCheckManager.touchArtifact(session, item.updateCheck); } - artifactDownloaded( session, download.getTrace(), artifact, group.repository, download.getException() ); - if ( download.getException() == null ) - { - artifactResolved( session, download.getTrace(), artifact, group.repository, null ); + artifactDownloaded(session, download.getTrace(), artifact, group.repository, download.getException()); + if (download.getException() == null) { + artifactResolved(session, download.getTrace(), artifact, group.repository, null); } } } - private void artifactResolving( RepositorySystemSession session, RequestTrace trace, Artifact artifact ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.ARTIFACT_RESOLVING ); - event.setTrace( trace ); - event.setArtifact( artifact ); + private void artifactResolving(RepositorySystemSession session, RequestTrace trace, Artifact artifact) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_RESOLVING); + event.setTrace(trace); + event.setArtifact(artifact); - repositoryEventDispatcher.dispatch( event.build() ); + repositoryEventDispatcher.dispatch(event.build()); } - private void artifactResolved( RepositorySystemSession session, RequestTrace trace, Artifact artifact, - ArtifactRepository repository, List exceptions ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.ARTIFACT_RESOLVED ); - event.setTrace( trace ); - event.setArtifact( artifact ); - event.setRepository( repository ); - event.setExceptions( exceptions ); - if ( artifact != null ) - { - event.setFile( artifact.getFile() ); + private void artifactResolved( + RepositorySystemSession session, + RequestTrace trace, + Artifact artifact, + ArtifactRepository repository, + List exceptions) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_RESOLVED); + event.setTrace(trace); + event.setArtifact(artifact); + event.setRepository(repository); + event.setExceptions(exceptions); + if (artifact != null) { + event.setFile(artifact.getFile()); } - repositoryEventDispatcher.dispatch( event.build() ); + repositoryEventDispatcher.dispatch(event.build()); } - private void artifactDownloading( RepositorySystemSession session, RequestTrace trace, Artifact artifact, - RemoteRepository repository ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.ARTIFACT_DOWNLOADING ); - event.setTrace( trace ); - event.setArtifact( artifact ); - event.setRepository( repository ); + private void artifactDownloading( + RepositorySystemSession session, RequestTrace trace, Artifact artifact, RemoteRepository repository) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_DOWNLOADING); + event.setTrace(trace); + event.setArtifact(artifact); + event.setRepository(repository); - repositoryEventDispatcher.dispatch( event.build() ); + repositoryEventDispatcher.dispatch(event.build()); } - private void artifactDownloaded( RepositorySystemSession session, RequestTrace trace, Artifact artifact, - RemoteRepository repository, Exception exception ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.ARTIFACT_DOWNLOADED ); - event.setTrace( trace ); - event.setArtifact( artifact ); - event.setRepository( repository ); - event.setException( exception ); - if ( artifact != null ) - { - event.setFile( artifact.getFile() ); + private void artifactDownloaded( + RepositorySystemSession session, + RequestTrace trace, + Artifact artifact, + RemoteRepository repository, + Exception exception) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_DOWNLOADED); + event.setTrace(trace); + event.setArtifact(artifact); + event.setRepository(repository); + event.setException(exception); + if (artifact != null) { + event.setFile(artifact.getFile()); } - repositoryEventDispatcher.dispatch( event.build() ); + repositoryEventDispatcher.dispatch(event.build()); } - static class ResolutionGroup - { + static class ResolutionGroup { final RemoteRepository repository; final List items = new ArrayList<>(); - ResolutionGroup( RemoteRepository repository ) - { + ResolutionGroup(RemoteRepository repository) { this.repository = repository; } - boolean matches( RemoteRepository repo ) - { - return repository.getUrl().equals( repo.getUrl() ) - && repository.getContentType().equals( repo.getContentType() ) + boolean matches(RemoteRepository repo) { + return repository.getUrl().equals(repo.getUrl()) + && repository.getContentType().equals(repo.getContentType()) && repository.isRepositoryManager() == repo.isRepositoryManager(); } - } - static class ResolutionItem - { + static class ResolutionItem { final RequestTrace trace; @@ -803,9 +708,13 @@ static class ResolutionItem UpdateCheck updateCheck; - ResolutionItem( RequestTrace trace, Artifact artifact, AtomicBoolean resolved, ArtifactResult result, - LocalArtifactResult local, RemoteRepository repository ) - { + ResolutionItem( + RequestTrace trace, + Artifact artifact, + AtomicBoolean resolved, + ArtifactResult result, + LocalArtifactResult local, + RemoteRepository repository) { this.trace = trace; this.artifact = artifact; this.resolved = resolved; @@ -814,7 +723,5 @@ static class ResolutionItem this.local = local; this.repository = repository; } - } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultChecksumPolicyProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultChecksumPolicyProvider.java index 270ac86af..3043f1a24 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultChecksumPolicyProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultChecksumPolicyProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import javax.inject.Named; import javax.inject.Singleton; @@ -35,9 +34,7 @@ */ @Singleton @Named -public final class DefaultChecksumPolicyProvider - implements ChecksumPolicyProvider -{ +public final class DefaultChecksumPolicyProvider implements ChecksumPolicyProvider { private static final int ORDINAL_IGNORE = 0; @@ -45,58 +42,48 @@ public final class DefaultChecksumPolicyProvider private static final int ORDINAL_FAIL = 2; - public DefaultChecksumPolicyProvider() - { + public DefaultChecksumPolicyProvider() { // enables default constructor } - public ChecksumPolicy newChecksumPolicy( RepositorySystemSession session, RemoteRepository repository, - TransferResource resource, String policy ) - { - Objects.requireNonNull( session, "session cannot be null" ); - Objects.requireNonNull( repository, "repository cannot be null" ); - Objects.requireNonNull( resource, "resource cannot be null" ); - validatePolicy( "policy", policy ); + public ChecksumPolicy newChecksumPolicy( + RepositorySystemSession session, RemoteRepository repository, TransferResource resource, String policy) { + Objects.requireNonNull(session, "session cannot be null"); + Objects.requireNonNull(repository, "repository cannot be null"); + Objects.requireNonNull(resource, "resource cannot be null"); + validatePolicy("policy", policy); - switch ( policy ) - { + switch (policy) { case RepositoryPolicy.CHECKSUM_POLICY_IGNORE: return null; case RepositoryPolicy.CHECKSUM_POLICY_FAIL: - return new FailChecksumPolicy( resource ); + return new FailChecksumPolicy(resource); case RepositoryPolicy.CHECKSUM_POLICY_WARN: - return new WarnChecksumPolicy( resource ); + return new WarnChecksumPolicy(resource); default: - throw new IllegalArgumentException( "Unsupported policy: " + policy ); + throw new IllegalArgumentException("Unsupported policy: " + policy); } } - public String getEffectiveChecksumPolicy( RepositorySystemSession session, String policy1, String policy2 ) - { - Objects.requireNonNull( session, "session cannot be null" ); - validatePolicy( "policy1", policy1 ); - validatePolicy( "policy2", policy2 ); + public String getEffectiveChecksumPolicy(RepositorySystemSession session, String policy1, String policy2) { + Objects.requireNonNull(session, "session cannot be null"); + validatePolicy("policy1", policy1); + validatePolicy("policy2", policy2); - if ( policy1.equals( policy2 ) ) - { + if (policy1.equals(policy2)) { return policy1; } - int ordinal1 = ordinalOfPolicy( policy1 ); - int ordinal2 = ordinalOfPolicy( policy2 ); - if ( ordinal2 < ordinal1 ) - { - return ( ordinal2 != ORDINAL_WARN ) ? policy2 : RepositoryPolicy.CHECKSUM_POLICY_WARN; - } - else - { - return ( ordinal1 != ORDINAL_WARN ) ? policy1 : RepositoryPolicy.CHECKSUM_POLICY_WARN; + int ordinal1 = ordinalOfPolicy(policy1); + int ordinal2 = ordinalOfPolicy(policy2); + if (ordinal2 < ordinal1) { + return (ordinal2 != ORDINAL_WARN) ? policy2 : RepositoryPolicy.CHECKSUM_POLICY_WARN; + } else { + return (ordinal1 != ORDINAL_WARN) ? policy1 : RepositoryPolicy.CHECKSUM_POLICY_WARN; } } - private static int ordinalOfPolicy( String policy ) - { - switch ( policy ) - { + private static int ordinalOfPolicy(String policy) { + switch (policy) { case RepositoryPolicy.CHECKSUM_POLICY_IGNORE: return ORDINAL_IGNORE; case RepositoryPolicy.CHECKSUM_POLICY_FAIL: @@ -104,23 +91,20 @@ private static int ordinalOfPolicy( String policy ) case RepositoryPolicy.CHECKSUM_POLICY_WARN: return ORDINAL_WARN; default: - throw new IllegalArgumentException( "Unsupported policy: " + policy ); + throw new IllegalArgumentException("Unsupported policy: " + policy); } } - private static void validatePolicy( String paramName, String policy ) - { - Objects.requireNonNull( policy, paramName + "cannot be null" ); + private static void validatePolicy(String paramName, String policy) { + Objects.requireNonNull(policy, paramName + "cannot be null"); - switch ( policy ) - { + switch (policy) { case RepositoryPolicy.CHECKSUM_POLICY_IGNORE: case RepositoryPolicy.CHECKSUM_POLICY_FAIL: case RepositoryPolicy.CHECKSUM_POLICY_WARN: break; default: - throw new IllegalArgumentException( "Unsupported policy: " + policy ); + throw new IllegalArgumentException("Unsupported policy: " + policy); } } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultDeployer.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultDeployer.java index f582f50dd..df24742fe 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultDeployer.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultDeployer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import java.io.File; import java.io.IOException; @@ -26,15 +29,9 @@ import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; -import static java.util.Objects.requireNonNull; - import java.util.ListIterator; import java.util.Set; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import org.eclipse.aether.RepositoryEvent; import org.eclipse.aether.RepositoryEvent.EventType; import org.eclipse.aether.RepositoryException; @@ -52,7 +49,6 @@ import org.eclipse.aether.impl.RemoteRepositoryManager; import org.eclipse.aether.impl.RepositoryConnectorProvider; import org.eclipse.aether.impl.RepositoryEventDispatcher; -import org.eclipse.aether.spi.synccontext.SyncContextFactory; import org.eclipse.aether.impl.UpdateCheck; import org.eclipse.aether.impl.UpdateCheckManager; import org.eclipse.aether.metadata.MergeableMetadata; @@ -67,6 +63,7 @@ import org.eclipse.aether.spi.io.FileProcessor; import org.eclipse.aether.spi.locator.Service; import org.eclipse.aether.spi.locator.ServiceLocator; +import org.eclipse.aether.spi.synccontext.SyncContextFactory; import org.eclipse.aether.transfer.ArtifactTransferException; import org.eclipse.aether.transfer.MetadataNotFoundException; import org.eclipse.aether.transfer.MetadataTransferException; @@ -77,13 +74,13 @@ import org.eclipse.aether.transform.FileTransformer; import org.eclipse.aether.transform.FileTransformerManager; +import static java.util.Objects.requireNonNull; + /** */ @Singleton @Named -public class DefaultDeployer - implements Deployer, Service -{ +public class DefaultDeployer implements Deployer, Service { private FileProcessor fileProcessor; private RepositoryEventDispatcher repositoryEventDispatcher; @@ -100,148 +97,128 @@ public class DefaultDeployer private OfflineController offlineController; - public DefaultDeployer() - { + public DefaultDeployer() { // enables default constructor } - @SuppressWarnings( "checkstyle:parameternumber" ) + @SuppressWarnings("checkstyle:parameternumber") @Inject - DefaultDeployer( FileProcessor fileProcessor, RepositoryEventDispatcher repositoryEventDispatcher, - RepositoryConnectorProvider repositoryConnectorProvider, - RemoteRepositoryManager remoteRepositoryManager, UpdateCheckManager updateCheckManager, - Set metadataFactories, SyncContextFactory syncContextFactory, - OfflineController offlineController ) - { - setFileProcessor( fileProcessor ); - setRepositoryEventDispatcher( repositoryEventDispatcher ); - setRepositoryConnectorProvider( repositoryConnectorProvider ); - setRemoteRepositoryManager( remoteRepositoryManager ); - setUpdateCheckManager( updateCheckManager ); - setMetadataGeneratorFactories( metadataFactories ); - setSyncContextFactory( syncContextFactory ); - setOfflineController( offlineController ); + DefaultDeployer( + FileProcessor fileProcessor, + RepositoryEventDispatcher repositoryEventDispatcher, + RepositoryConnectorProvider repositoryConnectorProvider, + RemoteRepositoryManager remoteRepositoryManager, + UpdateCheckManager updateCheckManager, + Set metadataFactories, + SyncContextFactory syncContextFactory, + OfflineController offlineController) { + setFileProcessor(fileProcessor); + setRepositoryEventDispatcher(repositoryEventDispatcher); + setRepositoryConnectorProvider(repositoryConnectorProvider); + setRemoteRepositoryManager(remoteRepositoryManager); + setUpdateCheckManager(updateCheckManager); + setMetadataGeneratorFactories(metadataFactories); + setSyncContextFactory(syncContextFactory); + setOfflineController(offlineController); } - public void initService( ServiceLocator locator ) - { - setFileProcessor( locator.getService( FileProcessor.class ) ); - setRepositoryEventDispatcher( locator.getService( RepositoryEventDispatcher.class ) ); - setRepositoryConnectorProvider( locator.getService( RepositoryConnectorProvider.class ) ); - setRemoteRepositoryManager( locator.getService( RemoteRepositoryManager.class ) ); - setUpdateCheckManager( locator.getService( UpdateCheckManager.class ) ); - setMetadataGeneratorFactories( locator.getServices( MetadataGeneratorFactory.class ) ); - setSyncContextFactory( locator.getService( SyncContextFactory.class ) ); - setOfflineController( locator.getService( OfflineController.class ) ); + public void initService(ServiceLocator locator) { + setFileProcessor(locator.getService(FileProcessor.class)); + setRepositoryEventDispatcher(locator.getService(RepositoryEventDispatcher.class)); + setRepositoryConnectorProvider(locator.getService(RepositoryConnectorProvider.class)); + setRemoteRepositoryManager(locator.getService(RemoteRepositoryManager.class)); + setUpdateCheckManager(locator.getService(UpdateCheckManager.class)); + setMetadataGeneratorFactories(locator.getServices(MetadataGeneratorFactory.class)); + setSyncContextFactory(locator.getService(SyncContextFactory.class)); + setOfflineController(locator.getService(OfflineController.class)); } - public DefaultDeployer setFileProcessor( FileProcessor fileProcessor ) - { - this.fileProcessor = requireNonNull( fileProcessor, "file processor cannot be null" ); + public DefaultDeployer setFileProcessor(FileProcessor fileProcessor) { + this.fileProcessor = requireNonNull(fileProcessor, "file processor cannot be null"); return this; } - public DefaultDeployer setRepositoryEventDispatcher( RepositoryEventDispatcher repositoryEventDispatcher ) - { - this.repositoryEventDispatcher = requireNonNull( - repositoryEventDispatcher, "repository event dispatcher cannot be null" ); + public DefaultDeployer setRepositoryEventDispatcher(RepositoryEventDispatcher repositoryEventDispatcher) { + this.repositoryEventDispatcher = + requireNonNull(repositoryEventDispatcher, "repository event dispatcher cannot be null"); return this; } - public DefaultDeployer setRepositoryConnectorProvider( RepositoryConnectorProvider repositoryConnectorProvider ) - { - this.repositoryConnectorProvider = requireNonNull( - repositoryConnectorProvider, "repository connector provider cannot be null" ); + public DefaultDeployer setRepositoryConnectorProvider(RepositoryConnectorProvider repositoryConnectorProvider) { + this.repositoryConnectorProvider = + requireNonNull(repositoryConnectorProvider, "repository connector provider cannot be null"); return this; } - public DefaultDeployer setRemoteRepositoryManager( RemoteRepositoryManager remoteRepositoryManager ) - { - this.remoteRepositoryManager = requireNonNull( - remoteRepositoryManager, "remote repository provider cannot be null" ); + public DefaultDeployer setRemoteRepositoryManager(RemoteRepositoryManager remoteRepositoryManager) { + this.remoteRepositoryManager = + requireNonNull(remoteRepositoryManager, "remote repository provider cannot be null"); return this; } - public DefaultDeployer setUpdateCheckManager( UpdateCheckManager updateCheckManager ) - { - this.updateCheckManager = requireNonNull( updateCheckManager, "update check manager cannot be null" ); + public DefaultDeployer setUpdateCheckManager(UpdateCheckManager updateCheckManager) { + this.updateCheckManager = requireNonNull(updateCheckManager, "update check manager cannot be null"); return this; } - public DefaultDeployer addMetadataGeneratorFactory( MetadataGeneratorFactory factory ) - { - metadataFactories.add( requireNonNull( factory, "metadata generator factory cannot be null" ) ); + public DefaultDeployer addMetadataGeneratorFactory(MetadataGeneratorFactory factory) { + metadataFactories.add(requireNonNull(factory, "metadata generator factory cannot be null")); return this; } - public DefaultDeployer setMetadataGeneratorFactories( Collection metadataFactories ) - { - if ( metadataFactories == null ) - { + public DefaultDeployer setMetadataGeneratorFactories(Collection metadataFactories) { + if (metadataFactories == null) { this.metadataFactories = new ArrayList<>(); - } - else - { + } else { this.metadataFactories = metadataFactories; } return this; } - public DefaultDeployer setSyncContextFactory( SyncContextFactory syncContextFactory ) - { - this.syncContextFactory = requireNonNull( syncContextFactory, "sync context factory cannot be null" ); + public DefaultDeployer setSyncContextFactory(SyncContextFactory syncContextFactory) { + this.syncContextFactory = requireNonNull(syncContextFactory, "sync context factory cannot be null"); return this; } - public DefaultDeployer setOfflineController( OfflineController offlineController ) - { - this.offlineController = requireNonNull( offlineController, "offline controller cannot be null" ); + public DefaultDeployer setOfflineController(OfflineController offlineController) { + this.offlineController = requireNonNull(offlineController, "offline controller cannot be null"); return this; } - public DeployResult deploy( RepositorySystemSession session, DeployRequest request ) - throws DeploymentException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); - try - { - Utils.checkOffline( session, offlineController, request.getRepository() ); - } - catch ( RepositoryOfflineException e ) - { - throw new DeploymentException( "Cannot deploy while " + request.getRepository().getId() + " (" - + request.getRepository().getUrl() + ") is in offline mode", e ); + public DeployResult deploy(RepositorySystemSession session, DeployRequest request) throws DeploymentException { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); + try { + Utils.checkOffline(session, offlineController, request.getRepository()); + } catch (RepositoryOfflineException e) { + throw new DeploymentException( + "Cannot deploy while " + request.getRepository().getId() + " (" + + request.getRepository().getUrl() + ") is in offline mode", + e); } - try ( SyncContext syncContext = syncContextFactory.newInstance( session, false ) ) - { - return deploy( syncContext, session, request ); + try (SyncContext syncContext = syncContextFactory.newInstance(session, false)) { + return deploy(syncContext, session, request); } } - private DeployResult deploy( SyncContext syncContext, RepositorySystemSession session, DeployRequest request ) - throws DeploymentException - { - DeployResult result = new DeployResult( request ); + private DeployResult deploy(SyncContext syncContext, RepositorySystemSession session, DeployRequest request) + throws DeploymentException { + DeployResult result = new DeployResult(request); - RequestTrace trace = RequestTrace.newChild( request.getTrace(), request ); + RequestTrace trace = RequestTrace.newChild(request.getTrace(), request); RemoteRepository repository = request.getRepository(); RepositoryConnector connector; - try - { - connector = repositoryConnectorProvider.newRepositoryConnector( session, repository ); - } - catch ( NoRepositoryConnectorException e ) - { - throw new DeploymentException( "Failed to deploy artifacts/metadata: " + e.getMessage(), e ); + try { + connector = repositoryConnectorProvider.newRepositoryConnector(session, repository); + } catch (NoRepositoryConnectorException e) { + throw new DeploymentException("Failed to deploy artifacts/metadata: " + e.getMessage(), e); } - try - { - List generators = getMetadataGenerators( session, request ); + try { + List generators = getMetadataGenerators(session, request); FileTransformerManager fileTransformerManager = session.getFileTransformerManager(); @@ -249,239 +226,211 @@ private DeployResult deploy( SyncContext syncContext, RepositorySystemSession se List metadataUploads = new ArrayList<>(); IdentityHashMap processedMetadata = new IdentityHashMap<>(); - EventCatapult catapult = new EventCatapult( session, trace, repository, repositoryEventDispatcher ); + EventCatapult catapult = new EventCatapult(session, trace, repository, repositoryEventDispatcher); - List artifacts = new ArrayList<>( request.getArtifacts() ); + List artifacts = new ArrayList<>(request.getArtifacts()); - List metadatas = Utils.prepareMetadata( generators, artifacts ); + List metadatas = Utils.prepareMetadata(generators, artifacts); - syncContext.acquire( artifacts, Utils.combine( request.getMetadata(), metadatas ) ); + syncContext.acquire(artifacts, Utils.combine(request.getMetadata(), metadatas)); - for ( Metadata metadata : metadatas ) - { - upload( metadataUploads, session, metadata, repository, connector, catapult ); - processedMetadata.put( metadata, null ); + for (Metadata metadata : metadatas) { + upload(metadataUploads, session, metadata, repository, connector, catapult); + processedMetadata.put(metadata, null); } - for ( ListIterator iterator = artifacts.listIterator(); iterator.hasNext(); ) - { + for (ListIterator iterator = artifacts.listIterator(); iterator.hasNext(); ) { Artifact artifact = iterator.next(); - for ( MetadataGenerator generator : generators ) - { - artifact = generator.transformArtifact( artifact ); + for (MetadataGenerator generator : generators) { + artifact = generator.transformArtifact(artifact); } - iterator.set( artifact ); + iterator.set(artifact); Collection fileTransformers = - fileTransformerManager.getTransformersForArtifact( artifact ); - if ( !fileTransformers.isEmpty() ) - { - for ( FileTransformer fileTransformer : fileTransformers ) - { - Artifact targetArtifact = fileTransformer.transformArtifact( artifact ); - - ArtifactUpload upload = new ArtifactUpload( targetArtifact, artifact.getFile(), - fileTransformer ); - upload.setTrace( trace ); - upload.setListener( new ArtifactUploadListener( catapult, upload ) ); - artifactUploads.add( upload ); + fileTransformerManager.getTransformersForArtifact(artifact); + if (!fileTransformers.isEmpty()) { + for (FileTransformer fileTransformer : fileTransformers) { + Artifact targetArtifact = fileTransformer.transformArtifact(artifact); + + ArtifactUpload upload = new ArtifactUpload(targetArtifact, artifact.getFile(), fileTransformer); + upload.setTrace(trace); + upload.setListener(new ArtifactUploadListener(catapult, upload)); + artifactUploads.add(upload); } - } - else - { - ArtifactUpload upload = new ArtifactUpload( artifact, artifact.getFile() ); - upload.setTrace( trace ); - upload.setListener( new ArtifactUploadListener( catapult, upload ) ); - artifactUploads.add( upload ); + } else { + ArtifactUpload upload = new ArtifactUpload(artifact, artifact.getFile()); + upload.setTrace(trace); + upload.setListener(new ArtifactUploadListener(catapult, upload)); + artifactUploads.add(upload); } } - connector.put( artifactUploads, null ); + connector.put(artifactUploads, null); - for ( ArtifactUpload upload : artifactUploads ) - { - if ( upload.getException() != null ) - { - throw new DeploymentException( "Failed to deploy artifacts: " + upload.getException().getMessage(), - upload.getException() ); + for (ArtifactUpload upload : artifactUploads) { + if (upload.getException() != null) { + throw new DeploymentException( + "Failed to deploy artifacts: " + + upload.getException().getMessage(), + upload.getException()); } - result.addArtifact( upload.getArtifact() ); + result.addArtifact(upload.getArtifact()); } - metadatas = Utils.finishMetadata( generators, artifacts ); + metadatas = Utils.finishMetadata(generators, artifacts); - syncContext.acquire( null, metadatas ); + syncContext.acquire(null, metadatas); - for ( Metadata metadata : metadatas ) - { - upload( metadataUploads, session, metadata, repository, connector, catapult ); - processedMetadata.put( metadata, null ); + for (Metadata metadata : metadatas) { + upload(metadataUploads, session, metadata, repository, connector, catapult); + processedMetadata.put(metadata, null); } - for ( Metadata metadata : request.getMetadata() ) - { - if ( !processedMetadata.containsKey( metadata ) ) - { - upload( metadataUploads, session, metadata, repository, connector, catapult ); - processedMetadata.put( metadata, null ); + for (Metadata metadata : request.getMetadata()) { + if (!processedMetadata.containsKey(metadata)) { + upload(metadataUploads, session, metadata, repository, connector, catapult); + processedMetadata.put(metadata, null); } } - connector.put( null, metadataUploads ); + connector.put(null, metadataUploads); - for ( MetadataUpload upload : metadataUploads ) - { - if ( upload.getException() != null ) - { - throw new DeploymentException( "Failed to deploy metadata: " + upload.getException().getMessage(), - upload.getException() ); + for (MetadataUpload upload : metadataUploads) { + if (upload.getException() != null) { + throw new DeploymentException( + "Failed to deploy metadata: " + + upload.getException().getMessage(), + upload.getException()); } - result.addMetadata( upload.getMetadata() ); + result.addMetadata(upload.getMetadata()); } - } - finally - { + } finally { connector.close(); } return result; } - private List getMetadataGenerators( RepositorySystemSession session, - DeployRequest request ) - { + private List getMetadataGenerators( + RepositorySystemSession session, DeployRequest request) { PrioritizedComponents factories = - Utils.sortMetadataGeneratorFactories( session, this.metadataFactories ); + Utils.sortMetadataGeneratorFactories(session, this.metadataFactories); List generators = new ArrayList<>(); - for ( PrioritizedComponent factory : factories.getEnabled() ) - { - MetadataGenerator generator = factory.getComponent().newInstance( session, request ); - if ( generator != null ) - { - generators.add( generator ); + for (PrioritizedComponent factory : factories.getEnabled()) { + MetadataGenerator generator = factory.getComponent().newInstance(session, request); + if (generator != null) { + generators.add(generator); } } return generators; } - private void upload( Collection metadataUploads, RepositorySystemSession session, - Metadata metadata, RemoteRepository repository, RepositoryConnector connector, - EventCatapult catapult ) - throws DeploymentException - { + private void upload( + Collection metadataUploads, + RepositorySystemSession session, + Metadata metadata, + RemoteRepository repository, + RepositoryConnector connector, + EventCatapult catapult) + throws DeploymentException { LocalRepositoryManager lrm = session.getLocalRepositoryManager(); File basedir = lrm.getRepository().getBasedir(); - File dstFile = new File( basedir, lrm.getPathForRemoteMetadata( metadata, repository, "" ) ); - - if ( metadata instanceof MergeableMetadata ) - { - if ( !( (MergeableMetadata) metadata ).isMerged() ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.METADATA_RESOLVING ); - event.setTrace( catapult.getTrace() ); - event.setMetadata( metadata ); - event.setRepository( repository ); - repositoryEventDispatcher.dispatch( event.build() ); - - event = new RepositoryEvent.Builder( session, EventType.METADATA_DOWNLOADING ); - event.setTrace( catapult.getTrace() ); - event.setMetadata( metadata ); - event.setRepository( repository ); - repositoryEventDispatcher.dispatch( event.build() ); - - RepositoryPolicy policy = getPolicy( session, repository, metadata.getNature() ); + File dstFile = new File(basedir, lrm.getPathForRemoteMetadata(metadata, repository, "")); + + if (metadata instanceof MergeableMetadata) { + if (!((MergeableMetadata) metadata).isMerged()) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_RESOLVING); + event.setTrace(catapult.getTrace()); + event.setMetadata(metadata); + event.setRepository(repository); + repositoryEventDispatcher.dispatch(event.build()); + + event = new RepositoryEvent.Builder(session, EventType.METADATA_DOWNLOADING); + event.setTrace(catapult.getTrace()); + event.setMetadata(metadata); + event.setRepository(repository); + repositoryEventDispatcher.dispatch(event.build()); + + RepositoryPolicy policy = getPolicy(session, repository, metadata.getNature()); MetadataDownload download = new MetadataDownload(); - download.setMetadata( metadata ); - download.setFile( dstFile ); - download.setChecksumPolicy( policy.getChecksumPolicy() ); - download.setListener( SafeTransferListener.wrap( session ) ); - download.setTrace( catapult.getTrace() ); - connector.get( null, Collections.singletonList( download ) ); + download.setMetadata(metadata); + download.setFile(dstFile); + download.setChecksumPolicy(policy.getChecksumPolicy()); + download.setListener(SafeTransferListener.wrap(session)); + download.setTrace(catapult.getTrace()); + connector.get(null, Collections.singletonList(download)); Exception error = download.getException(); - if ( error instanceof MetadataNotFoundException ) - { + if (error instanceof MetadataNotFoundException) { dstFile.delete(); } - event = new RepositoryEvent.Builder( session, EventType.METADATA_DOWNLOADED ); - event.setTrace( catapult.getTrace() ); - event.setMetadata( metadata ); - event.setRepository( repository ); - event.setException( error ); - event.setFile( dstFile ); - repositoryEventDispatcher.dispatch( event.build() ); - - event = new RepositoryEvent.Builder( session, EventType.METADATA_RESOLVED ); - event.setTrace( catapult.getTrace() ); - event.setMetadata( metadata ); - event.setRepository( repository ); - event.setException( error ); - event.setFile( dstFile ); - repositoryEventDispatcher.dispatch( event.build() ); - - if ( error != null && !( error instanceof MetadataNotFoundException ) ) - { - throw new DeploymentException( "Failed to retrieve remote metadata " + metadata + ": " - + error.getMessage(), error ); + event = new RepositoryEvent.Builder(session, EventType.METADATA_DOWNLOADED); + event.setTrace(catapult.getTrace()); + event.setMetadata(metadata); + event.setRepository(repository); + event.setException(error); + event.setFile(dstFile); + repositoryEventDispatcher.dispatch(event.build()); + + event = new RepositoryEvent.Builder(session, EventType.METADATA_RESOLVED); + event.setTrace(catapult.getTrace()); + event.setMetadata(metadata); + event.setRepository(repository); + event.setException(error); + event.setFile(dstFile); + repositoryEventDispatcher.dispatch(event.build()); + + if (error != null && !(error instanceof MetadataNotFoundException)) { + throw new DeploymentException( + "Failed to retrieve remote metadata " + metadata + ": " + error.getMessage(), error); } } - try - { - ( (MergeableMetadata) metadata ).merge( dstFile, dstFile ); - } - catch ( RepositoryException e ) - { - throw new DeploymentException( "Failed to update metadata " + metadata + ": " + e.getMessage(), e ); - } - } - else - { - if ( metadata.getFile() == null ) - { - throw new DeploymentException( "Failed to update metadata " + metadata + ": No file attached." ); + try { + ((MergeableMetadata) metadata).merge(dstFile, dstFile); + } catch (RepositoryException e) { + throw new DeploymentException("Failed to update metadata " + metadata + ": " + e.getMessage(), e); } - try - { - fileProcessor.copy( metadata.getFile(), dstFile ); + } else { + if (metadata.getFile() == null) { + throw new DeploymentException("Failed to update metadata " + metadata + ": No file attached."); } - catch ( IOException e ) - { - throw new DeploymentException( "Failed to update metadata " + metadata + ": " + e.getMessage(), e ); + try { + fileProcessor.copy(metadata.getFile(), dstFile); + } catch (IOException e) { + throw new DeploymentException("Failed to update metadata " + metadata + ": " + e.getMessage(), e); } } UpdateCheck check = new UpdateCheck<>(); - check.setItem( metadata ); - check.setFile( dstFile ); - check.setRepository( repository ); - check.setAuthoritativeRepository( repository ); - updateCheckManager.touchMetadata( session, check ); - - MetadataUpload upload = new MetadataUpload( metadata, dstFile ); - upload.setTrace( catapult.getTrace() ); - upload.setListener( new MetadataUploadListener( catapult, upload ) ); - metadataUploads.add( upload ); + check.setItem(metadata); + check.setFile(dstFile); + check.setRepository(repository); + check.setAuthoritativeRepository(repository); + updateCheckManager.touchMetadata(session, check); + + MetadataUpload upload = new MetadataUpload(metadata, dstFile); + upload.setTrace(catapult.getTrace()); + upload.setListener(new MetadataUploadListener(catapult, upload)); + metadataUploads.add(upload); } - private RepositoryPolicy getPolicy( RepositorySystemSession session, RemoteRepository repository, - Metadata.Nature nature ) - { - boolean releases = !Metadata.Nature.SNAPSHOT.equals( nature ); - boolean snapshots = !Metadata.Nature.RELEASE.equals( nature ); - return remoteRepositoryManager.getPolicy( session, repository, releases, snapshots ); + private RepositoryPolicy getPolicy( + RepositorySystemSession session, RemoteRepository repository, Metadata.Nature nature) { + boolean releases = !Metadata.Nature.SNAPSHOT.equals(nature); + boolean snapshots = !Metadata.Nature.RELEASE.equals(nature); + return remoteRepositoryManager.getPolicy(session, repository, releases, snapshots); } - static final class EventCatapult - { + static final class EventCatapult { private final RepositorySystemSession session; @@ -491,155 +440,133 @@ static final class EventCatapult private final RepositoryEventDispatcher dispatcher; - EventCatapult( RepositorySystemSession session, RequestTrace trace, RemoteRepository repository, - RepositoryEventDispatcher dispatcher ) - { + EventCatapult( + RepositorySystemSession session, + RequestTrace trace, + RemoteRepository repository, + RepositoryEventDispatcher dispatcher) { this.session = session; this.trace = trace; this.repository = repository; this.dispatcher = dispatcher; } - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } - public void artifactDeploying( Artifact artifact, File file ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.ARTIFACT_DEPLOYING ); - event.setTrace( trace ); - event.setArtifact( artifact ); - event.setRepository( repository ); - event.setFile( file ); + public void artifactDeploying(Artifact artifact, File file) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_DEPLOYING); + event.setTrace(trace); + event.setArtifact(artifact); + event.setRepository(repository); + event.setFile(file); - dispatcher.dispatch( event.build() ); + dispatcher.dispatch(event.build()); } - public void artifactDeployed( Artifact artifact, File file, ArtifactTransferException exception ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.ARTIFACT_DEPLOYED ); - event.setTrace( trace ); - event.setArtifact( artifact ); - event.setRepository( repository ); - event.setFile( file ); - event.setException( exception ); + public void artifactDeployed(Artifact artifact, File file, ArtifactTransferException exception) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_DEPLOYED); + event.setTrace(trace); + event.setArtifact(artifact); + event.setRepository(repository); + event.setFile(file); + event.setException(exception); - dispatcher.dispatch( event.build() ); + dispatcher.dispatch(event.build()); } - public void metadataDeploying( Metadata metadata, File file ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.METADATA_DEPLOYING ); - event.setTrace( trace ); - event.setMetadata( metadata ); - event.setRepository( repository ); - event.setFile( file ); + public void metadataDeploying(Metadata metadata, File file) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_DEPLOYING); + event.setTrace(trace); + event.setMetadata(metadata); + event.setRepository(repository); + event.setFile(file); - dispatcher.dispatch( event.build() ); + dispatcher.dispatch(event.build()); } - public void metadataDeployed( Metadata metadata, File file, Exception exception ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.METADATA_DEPLOYED ); - event.setTrace( trace ); - event.setMetadata( metadata ); - event.setRepository( repository ); - event.setFile( file ); - event.setException( exception ); + public void metadataDeployed(Metadata metadata, File file, Exception exception) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_DEPLOYED); + event.setTrace(trace); + event.setMetadata(metadata); + event.setRepository(repository); + event.setFile(file); + event.setException(exception); - dispatcher.dispatch( event.build() ); + dispatcher.dispatch(event.build()); } - } - static final class ArtifactUploadListener - extends SafeTransferListener - { + static final class ArtifactUploadListener extends SafeTransferListener { private final EventCatapult catapult; private final ArtifactUpload transfer; - ArtifactUploadListener( EventCatapult catapult, ArtifactUpload transfer ) - { - super( catapult.getSession() ); + ArtifactUploadListener(EventCatapult catapult, ArtifactUpload transfer) { + super(catapult.getSession()); this.catapult = catapult; this.transfer = transfer; } @Override - public void transferInitiated( TransferEvent event ) - throws TransferCancelledException - { - super.transferInitiated( event ); - requireNonNull( event, "event cannot be null" ); - catapult.artifactDeploying( transfer.getArtifact(), transfer.getFile() ); + public void transferInitiated(TransferEvent event) throws TransferCancelledException { + super.transferInitiated(event); + requireNonNull(event, "event cannot be null"); + catapult.artifactDeploying(transfer.getArtifact(), transfer.getFile()); } @Override - public void transferFailed( TransferEvent event ) - { - super.transferFailed( event ); - requireNonNull( event, "event cannot be null" ); - catapult.artifactDeployed( transfer.getArtifact(), transfer.getFile(), transfer.getException() ); + public void transferFailed(TransferEvent event) { + super.transferFailed(event); + requireNonNull(event, "event cannot be null"); + catapult.artifactDeployed(transfer.getArtifact(), transfer.getFile(), transfer.getException()); } @Override - public void transferSucceeded( TransferEvent event ) - { - super.transferSucceeded( event ); - requireNonNull( event, "event cannot be null" ); - catapult.artifactDeployed( transfer.getArtifact(), transfer.getFile(), null ); + public void transferSucceeded(TransferEvent event) { + super.transferSucceeded(event); + requireNonNull(event, "event cannot be null"); + catapult.artifactDeployed(transfer.getArtifact(), transfer.getFile(), null); } - } - static final class MetadataUploadListener - extends SafeTransferListener - { + static final class MetadataUploadListener extends SafeTransferListener { private final EventCatapult catapult; private final MetadataUpload transfer; - MetadataUploadListener( EventCatapult catapult, MetadataUpload transfer ) - { - super( catapult.getSession() ); + MetadataUploadListener(EventCatapult catapult, MetadataUpload transfer) { + super(catapult.getSession()); this.catapult = catapult; this.transfer = transfer; } @Override - public void transferInitiated( TransferEvent event ) - throws TransferCancelledException - { - super.transferInitiated( event ); - requireNonNull( event, "event cannot be null" ); - catapult.metadataDeploying( transfer.getMetadata(), transfer.getFile() ); + public void transferInitiated(TransferEvent event) throws TransferCancelledException { + super.transferInitiated(event); + requireNonNull(event, "event cannot be null"); + catapult.metadataDeploying(transfer.getMetadata(), transfer.getFile()); } @Override - public void transferFailed( TransferEvent event ) - { - super.transferFailed( event ); - requireNonNull( event, "event cannot be null" ); - catapult.metadataDeployed( transfer.getMetadata(), transfer.getFile(), transfer.getException() ); + public void transferFailed(TransferEvent event) { + super.transferFailed(event); + requireNonNull(event, "event cannot be null"); + catapult.metadataDeployed(transfer.getMetadata(), transfer.getFile(), transfer.getException()); } @Override - public void transferSucceeded( TransferEvent event ) - { - super.transferSucceeded( event ); - requireNonNull( event, "event cannot be null" ); - catapult.metadataDeployed( transfer.getMetadata(), transfer.getFile(), null ); + public void transferSucceeded(TransferEvent event) { + super.transferSucceeded(event); + requireNonNull(event, "event cannot be null"); + catapult.metadataDeployed(transfer.getMetadata(), transfer.getFile(), null); } - } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultFileProcessor.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultFileProcessor.java index d9385cbe9..39028e99f 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultFileProcessor.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultFileProcessor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import javax.inject.Named; import javax.inject.Singleton; @@ -43,9 +42,7 @@ */ @Singleton @Named -public class DefaultFileProcessor - implements FileProcessor -{ +public class DefaultFileProcessor implements FileProcessor { /** * Thread-safe variant of {@link File#mkdirs()}. Creates the directory named by the given abstract pathname, @@ -56,92 +53,68 @@ public class DefaultFileProcessor * @return {@code true} if and only if the directory was created, along with all necessary parent directories; * {@code false} otherwise */ - public boolean mkdirs( File directory ) - { - if ( directory == null ) - { + public boolean mkdirs(File directory) { + if (directory == null) { return false; } - if ( directory.exists() ) - { + if (directory.exists()) { return false; } - if ( directory.mkdir() ) - { + if (directory.mkdir()) { return true; } File canonDir; - try - { + try { canonDir = directory.getCanonicalFile(); - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + } catch (IOException e) { + throw new UncheckedIOException(e); } File parentDir = canonDir.getParentFile(); - return ( parentDir != null && ( mkdirs( parentDir ) || parentDir.exists() ) && canonDir.mkdir() ); + return (parentDir != null && (mkdirs(parentDir) || parentDir.exists()) && canonDir.mkdir()); } - public void write( File target, String data ) - throws IOException - { - FileUtils.writeFile( target.toPath(), p -> Files.write( p, data.getBytes( StandardCharsets.UTF_8 ) ) ); + public void write(File target, String data) throws IOException { + FileUtils.writeFile(target.toPath(), p -> Files.write(p, data.getBytes(StandardCharsets.UTF_8))); } - public void write( File target, InputStream source ) - throws IOException - { - FileUtils.writeFile( target.toPath(), p -> Files.copy( source, p, StandardCopyOption.REPLACE_EXISTING ) ); + public void write(File target, InputStream source) throws IOException { + FileUtils.writeFile(target.toPath(), p -> Files.copy(source, p, StandardCopyOption.REPLACE_EXISTING)); } - public void copy( File source, File target ) - throws IOException - { - copy( source, target, null ); + public void copy(File source, File target) throws IOException { + copy(source, target, null); } - public long copy( File source, File target, ProgressListener listener ) - throws IOException - { - try ( InputStream in = new BufferedInputStream( Files.newInputStream( source.toPath() ) ); - FileUtils.CollocatedTempFile tempTarget = FileUtils.newTempFile( target.toPath() ); - OutputStream out = new BufferedOutputStream( Files.newOutputStream( tempTarget.getPath() ) ) ) - { - long result = copy( out, in, listener ); + public long copy(File source, File target, ProgressListener listener) throws IOException { + try (InputStream in = new BufferedInputStream(Files.newInputStream(source.toPath())); + FileUtils.CollocatedTempFile tempTarget = FileUtils.newTempFile(target.toPath()); + OutputStream out = new BufferedOutputStream(Files.newOutputStream(tempTarget.getPath()))) { + long result = copy(out, in, listener); tempTarget.move(); return result; } } - private long copy( OutputStream os, InputStream is, ProgressListener listener ) - throws IOException - { + private long copy(OutputStream os, InputStream is, ProgressListener listener) throws IOException { long total = 0L; byte[] buffer = new byte[1024 * 32]; - while ( true ) - { - int bytes = is.read( buffer ); - if ( bytes < 0 ) - { + while (true) { + int bytes = is.read(buffer); + if (bytes < 0) { break; } - os.write( buffer, 0, bytes ); + os.write(buffer, 0, bytes); total += bytes; - if ( listener != null && bytes > 0 ) - { - try - { - listener.progressed( ByteBuffer.wrap( buffer, 0, bytes ) ); - } - catch ( Exception e ) - { + if (listener != null && bytes > 0) { + try { + listener.progressed(ByteBuffer.wrap(buffer, 0, bytes)); + } catch (Exception e) { // too bad } } @@ -150,30 +123,25 @@ private long copy( OutputStream os, InputStream is, ProgressListener listener ) return total; } - public void move( File source, File target ) - throws IOException - { - if ( !source.renameTo( target ) ) - { - copy( source, target ); + public void move(File source, File target) throws IOException { + if (!source.renameTo(target)) { + copy(source, target); - target.setLastModified( source.lastModified() ); + target.setLastModified(source.lastModified()); source.delete(); } } @Override - public String readChecksum( final File checksumFile ) throws IOException - { + public String readChecksum(final File checksumFile) throws IOException { // for now do exactly same as happened before, but FileProcessor is a component and can be replaced - return ChecksumUtils.read( checksumFile ); + return ChecksumUtils.read(checksumFile); } @Override - public void writeChecksum( final File checksumFile, final String checksum ) throws IOException - { + public void writeChecksum(final File checksumFile, final String checksum) throws IOException { // for now do exactly same as happened before, but FileProcessor is a component and can be replaced - write( checksumFile, checksum ); + write(checksumFile, checksum); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultInstaller.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultInstaller.java index 6b3f7a7d1..6ce59e6bb 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultInstaller.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultInstaller.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; -import static java.util.Objects.requireNonNull; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import java.io.File; import java.io.InputStream; @@ -30,10 +31,6 @@ import java.util.ListIterator; import java.util.Set; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import org.eclipse.aether.RepositoryEvent; import org.eclipse.aether.RepositoryEvent.EventType; import org.eclipse.aether.RepositorySystemSession; @@ -44,7 +41,6 @@ import org.eclipse.aether.impl.MetadataGenerator; import org.eclipse.aether.impl.MetadataGeneratorFactory; import org.eclipse.aether.impl.RepositoryEventDispatcher; -import org.eclipse.aether.spi.synccontext.SyncContextFactory; import org.eclipse.aether.installation.InstallRequest; import org.eclipse.aether.installation.InstallResult; import org.eclipse.aether.installation.InstallationException; @@ -56,19 +52,20 @@ import org.eclipse.aether.spi.io.FileProcessor; import org.eclipse.aether.spi.locator.Service; import org.eclipse.aether.spi.locator.ServiceLocator; +import org.eclipse.aether.spi.synccontext.SyncContextFactory; import org.eclipse.aether.transform.FileTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; + /** */ @Singleton @Named -public class DefaultInstaller - implements Installer, Service -{ +public class DefaultInstaller implements Installer, Service { - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultInstaller.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultInstaller.class); private FileProcessor fileProcessor; @@ -78,330 +75,278 @@ public class DefaultInstaller private SyncContextFactory syncContextFactory; - public DefaultInstaller() - { + public DefaultInstaller() { // enables default constructor } @Inject - DefaultInstaller( FileProcessor fileProcessor, RepositoryEventDispatcher repositoryEventDispatcher, - Set metadataFactories, SyncContextFactory syncContextFactory ) - { - setFileProcessor( fileProcessor ); - setRepositoryEventDispatcher( repositoryEventDispatcher ); - setMetadataGeneratorFactories( metadataFactories ); - setSyncContextFactory( syncContextFactory ); + DefaultInstaller( + FileProcessor fileProcessor, + RepositoryEventDispatcher repositoryEventDispatcher, + Set metadataFactories, + SyncContextFactory syncContextFactory) { + setFileProcessor(fileProcessor); + setRepositoryEventDispatcher(repositoryEventDispatcher); + setMetadataGeneratorFactories(metadataFactories); + setSyncContextFactory(syncContextFactory); } - public void initService( ServiceLocator locator ) - { - setFileProcessor( locator.getService( FileProcessor.class ) ); - setRepositoryEventDispatcher( locator.getService( RepositoryEventDispatcher.class ) ); - setMetadataGeneratorFactories( locator.getServices( MetadataGeneratorFactory.class ) ); - setSyncContextFactory( locator.getService( SyncContextFactory.class ) ); + public void initService(ServiceLocator locator) { + setFileProcessor(locator.getService(FileProcessor.class)); + setRepositoryEventDispatcher(locator.getService(RepositoryEventDispatcher.class)); + setMetadataGeneratorFactories(locator.getServices(MetadataGeneratorFactory.class)); + setSyncContextFactory(locator.getService(SyncContextFactory.class)); } - public DefaultInstaller setFileProcessor( FileProcessor fileProcessor ) - { - this.fileProcessor = requireNonNull( fileProcessor, "file processor cannot be null" ); + public DefaultInstaller setFileProcessor(FileProcessor fileProcessor) { + this.fileProcessor = requireNonNull(fileProcessor, "file processor cannot be null"); return this; } - public DefaultInstaller setRepositoryEventDispatcher( RepositoryEventDispatcher repositoryEventDispatcher ) - { - this.repositoryEventDispatcher = requireNonNull( repositoryEventDispatcher, - "repository event dispatcher cannot be null" ); + public DefaultInstaller setRepositoryEventDispatcher(RepositoryEventDispatcher repositoryEventDispatcher) { + this.repositoryEventDispatcher = + requireNonNull(repositoryEventDispatcher, "repository event dispatcher cannot be null"); return this; } - public DefaultInstaller addMetadataGeneratorFactory( MetadataGeneratorFactory factory ) - { - metadataFactories.add( requireNonNull( factory, "metadata generator factory cannot be null" ) ); + public DefaultInstaller addMetadataGeneratorFactory(MetadataGeneratorFactory factory) { + metadataFactories.add(requireNonNull(factory, "metadata generator factory cannot be null")); return this; } - public DefaultInstaller setMetadataGeneratorFactories( Collection metadataFactories ) - { - if ( metadataFactories == null ) - { + public DefaultInstaller setMetadataGeneratorFactories(Collection metadataFactories) { + if (metadataFactories == null) { this.metadataFactories = new ArrayList<>(); - } - else - { + } else { this.metadataFactories = metadataFactories; } return this; } - public DefaultInstaller setSyncContextFactory( SyncContextFactory syncContextFactory ) - { - this.syncContextFactory = requireNonNull( syncContextFactory, "sync context factory cannot be null" ); + public DefaultInstaller setSyncContextFactory(SyncContextFactory syncContextFactory) { + this.syncContextFactory = requireNonNull(syncContextFactory, "sync context factory cannot be null"); return this; } - public InstallResult install( RepositorySystemSession session, InstallRequest request ) - throws InstallationException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); - try ( SyncContext syncContext = syncContextFactory.newInstance( session, false ) ) - { - return install( syncContext, session, request ); + public InstallResult install(RepositorySystemSession session, InstallRequest request) throws InstallationException { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); + try (SyncContext syncContext = syncContextFactory.newInstance(session, false)) { + return install(syncContext, session, request); } } - private InstallResult install( SyncContext syncContext, RepositorySystemSession session, InstallRequest request ) - throws InstallationException - { - InstallResult result = new InstallResult( request ); + private InstallResult install(SyncContext syncContext, RepositorySystemSession session, InstallRequest request) + throws InstallationException { + InstallResult result = new InstallResult(request); - RequestTrace trace = RequestTrace.newChild( request.getTrace(), request ); + RequestTrace trace = RequestTrace.newChild(request.getTrace(), request); - List generators = getMetadataGenerators( session, request ); + List generators = getMetadataGenerators(session, request); - List artifacts = new ArrayList<>( request.getArtifacts() ); + List artifacts = new ArrayList<>(request.getArtifacts()); IdentityHashMap processedMetadata = new IdentityHashMap<>(); - List metadatas = Utils.prepareMetadata( generators, artifacts ); + List metadatas = Utils.prepareMetadata(generators, artifacts); - syncContext.acquire( artifacts, Utils.combine( request.getMetadata(), metadatas ) ); + syncContext.acquire(artifacts, Utils.combine(request.getMetadata(), metadatas)); - for ( Metadata metadata : metadatas ) - { - install( session, trace, metadata ); - processedMetadata.put( metadata, null ); - result.addMetadata( metadata ); + for (Metadata metadata : metadatas) { + install(session, trace, metadata); + processedMetadata.put(metadata, null); + result.addMetadata(metadata); } - for ( ListIterator iterator = artifacts.listIterator(); iterator.hasNext(); ) - { + for (ListIterator iterator = artifacts.listIterator(); iterator.hasNext(); ) { Artifact artifact = iterator.next(); - for ( MetadataGenerator generator : generators ) - { - artifact = generator.transformArtifact( artifact ); + for (MetadataGenerator generator : generators) { + artifact = generator.transformArtifact(artifact); } - iterator.set( artifact ); + iterator.set(artifact); - install( session, trace, artifact ); - result.addArtifact( artifact ); + install(session, trace, artifact); + result.addArtifact(artifact); } - metadatas = Utils.finishMetadata( generators, artifacts ); + metadatas = Utils.finishMetadata(generators, artifacts); - syncContext.acquire( null, metadatas ); + syncContext.acquire(null, metadatas); - for ( Metadata metadata : metadatas ) - { - install( session, trace, metadata ); - processedMetadata.put( metadata, null ); - result.addMetadata( metadata ); + for (Metadata metadata : metadatas) { + install(session, trace, metadata); + processedMetadata.put(metadata, null); + result.addMetadata(metadata); } - for ( Metadata metadata : request.getMetadata() ) - { - if ( !processedMetadata.containsKey( metadata ) ) - { - install( session, trace, metadata ); - result.addMetadata( metadata ); + for (Metadata metadata : request.getMetadata()) { + if (!processedMetadata.containsKey(metadata)) { + install(session, trace, metadata); + result.addMetadata(metadata); } } return result; } - private List getMetadataGenerators( RepositorySystemSession session, - InstallRequest request ) - { + private List getMetadataGenerators( + RepositorySystemSession session, InstallRequest request) { PrioritizedComponents factories = - Utils.sortMetadataGeneratorFactories( session, this.metadataFactories ); + Utils.sortMetadataGeneratorFactories(session, this.metadataFactories); List generators = new ArrayList<>(); - for ( PrioritizedComponent factory : factories.getEnabled() ) - { - MetadataGenerator generator = factory.getComponent().newInstance( session, request ); - if ( generator != null ) - { - generators.add( generator ); + for (PrioritizedComponent factory : factories.getEnabled()) { + MetadataGenerator generator = factory.getComponent().newInstance(session, request); + if (generator != null) { + generators.add(generator); } } return generators; } - private void install( RepositorySystemSession session, RequestTrace trace, Artifact artifact ) - throws InstallationException - { + private void install(RepositorySystemSession session, RequestTrace trace, Artifact artifact) + throws InstallationException { LocalRepositoryManager lrm = session.getLocalRepositoryManager(); File srcFile = artifact.getFile(); - Collection fileTransformers = session.getFileTransformerManager() - .getTransformersForArtifact( artifact ); - if ( fileTransformers.isEmpty() ) - { - install( session, trace, artifact, lrm, srcFile, null ); - } - else - { - for ( FileTransformer fileTransformer : fileTransformers ) - { - install( session, trace, artifact, lrm, srcFile, fileTransformer ); + Collection fileTransformers = + session.getFileTransformerManager().getTransformersForArtifact(artifact); + if (fileTransformers.isEmpty()) { + install(session, trace, artifact, lrm, srcFile, null); + } else { + for (FileTransformer fileTransformer : fileTransformers) { + install(session, trace, artifact, lrm, srcFile, fileTransformer); } } } - private void install( RepositorySystemSession session, RequestTrace trace, Artifact artifact, - LocalRepositoryManager lrm, File srcFile, FileTransformer fileTransformer ) - throws InstallationException - { + private void install( + RepositorySystemSession session, + RequestTrace trace, + Artifact artifact, + LocalRepositoryManager lrm, + File srcFile, + FileTransformer fileTransformer) + throws InstallationException { final Artifact targetArtifact; - if ( fileTransformer != null ) - { - targetArtifact = fileTransformer.transformArtifact( artifact ); - } - else - { + if (fileTransformer != null) { + targetArtifact = fileTransformer.transformArtifact(artifact); + } else { targetArtifact = artifact; } - File dstFile = new File( lrm.getRepository().getBasedir(), lrm.getPathForLocalArtifact( targetArtifact ) ); + File dstFile = new File(lrm.getRepository().getBasedir(), lrm.getPathForLocalArtifact(targetArtifact)); - artifactInstalling( session, trace, targetArtifact, dstFile ); + artifactInstalling(session, trace, targetArtifact, dstFile); Exception exception = null; - try - { - if ( dstFile.equals( srcFile ) ) - { - throw new IllegalStateException( "cannot install " + dstFile + " to same path" ); + try { + if (dstFile.equals(srcFile)) { + throw new IllegalStateException("cannot install " + dstFile + " to same path"); } - boolean copy = - "pom".equals( targetArtifact.getExtension() ) || srcFile.lastModified() != dstFile.lastModified() - || srcFile.length() != dstFile.length() || !srcFile.exists(); - - if ( !copy ) - { - LOGGER.debug( "Skipped re-installing {} to {}, seems unchanged", srcFile, dstFile ); - } - else if ( fileTransformer != null ) - { - try ( InputStream is = fileTransformer.transformData( srcFile ) ) - { - fileProcessor.write( dstFile, is ); - dstFile.setLastModified( srcFile.lastModified() ); + boolean copy = "pom".equals(targetArtifact.getExtension()) + || srcFile.lastModified() != dstFile.lastModified() + || srcFile.length() != dstFile.length() + || !srcFile.exists(); + + if (!copy) { + LOGGER.debug("Skipped re-installing {} to {}, seems unchanged", srcFile, dstFile); + } else if (fileTransformer != null) { + try (InputStream is = fileTransformer.transformData(srcFile)) { + fileProcessor.write(dstFile, is); + dstFile.setLastModified(srcFile.lastModified()); } - } - else - { - fileProcessor.copy( srcFile, dstFile ); - dstFile.setLastModified( srcFile.lastModified() ); + } else { + fileProcessor.copy(srcFile, dstFile); + dstFile.setLastModified(srcFile.lastModified()); } - lrm.add( session, new LocalArtifactRegistration( targetArtifact ) ); - } - catch ( Exception e ) - { + lrm.add(session, new LocalArtifactRegistration(targetArtifact)); + } catch (Exception e) { exception = e; - throw new InstallationException( "Failed to install artifact " + targetArtifact + ": " + e.getMessage(), - e ); - } - finally - { - artifactInstalled( session, trace, targetArtifact, dstFile, exception ); + throw new InstallationException("Failed to install artifact " + targetArtifact + ": " + e.getMessage(), e); + } finally { + artifactInstalled(session, trace, targetArtifact, dstFile, exception); } } - private void install( RepositorySystemSession session, RequestTrace trace, Metadata metadata ) - throws InstallationException - { + private void install(RepositorySystemSession session, RequestTrace trace, Metadata metadata) + throws InstallationException { LocalRepositoryManager lrm = session.getLocalRepositoryManager(); - File dstFile = new File( lrm.getRepository().getBasedir(), lrm.getPathForLocalMetadata( metadata ) ); + File dstFile = new File(lrm.getRepository().getBasedir(), lrm.getPathForLocalMetadata(metadata)); - metadataInstalling( session, trace, metadata, dstFile ); + metadataInstalling(session, trace, metadata, dstFile); Exception exception = null; - try - { - if ( metadata instanceof MergeableMetadata ) - { - ( (MergeableMetadata) metadata ).merge( dstFile, dstFile ); - } - else - { - if ( dstFile.equals( metadata.getFile() ) ) - { - throw new IllegalStateException( "cannot install " + dstFile + " to same path" ); + try { + if (metadata instanceof MergeableMetadata) { + ((MergeableMetadata) metadata).merge(dstFile, dstFile); + } else { + if (dstFile.equals(metadata.getFile())) { + throw new IllegalStateException("cannot install " + dstFile + " to same path"); } - fileProcessor.copy( metadata.getFile(), dstFile ); + fileProcessor.copy(metadata.getFile(), dstFile); } - lrm.add( session, new LocalMetadataRegistration( metadata ) ); - } - catch ( Exception e ) - { + lrm.add(session, new LocalMetadataRegistration(metadata)); + } catch (Exception e) { exception = e; - throw new InstallationException( "Failed to install metadata " + metadata + ": " + e.getMessage(), e ); - } - finally - { - metadataInstalled( session, trace, metadata, dstFile, exception ); + throw new InstallationException("Failed to install metadata " + metadata + ": " + e.getMessage(), e); + } finally { + metadataInstalled(session, trace, metadata, dstFile, exception); } } - private void artifactInstalling( RepositorySystemSession session, RequestTrace trace, Artifact artifact, - File dstFile ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.ARTIFACT_INSTALLING ); - event.setTrace( trace ); - event.setArtifact( artifact ); - event.setRepository( session.getLocalRepositoryManager().getRepository() ); - event.setFile( dstFile ); + private void artifactInstalling( + RepositorySystemSession session, RequestTrace trace, Artifact artifact, File dstFile) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_INSTALLING); + event.setTrace(trace); + event.setArtifact(artifact); + event.setRepository(session.getLocalRepositoryManager().getRepository()); + event.setFile(dstFile); - repositoryEventDispatcher.dispatch( event.build() ); + repositoryEventDispatcher.dispatch(event.build()); } - private void artifactInstalled( RepositorySystemSession session, RequestTrace trace, Artifact artifact, - File dstFile, Exception exception ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.ARTIFACT_INSTALLED ); - event.setTrace( trace ); - event.setArtifact( artifact ); - event.setRepository( session.getLocalRepositoryManager().getRepository() ); - event.setFile( dstFile ); - event.setException( exception ); - - repositoryEventDispatcher.dispatch( event.build() ); + private void artifactInstalled( + RepositorySystemSession session, RequestTrace trace, Artifact artifact, File dstFile, Exception exception) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.ARTIFACT_INSTALLED); + event.setTrace(trace); + event.setArtifact(artifact); + event.setRepository(session.getLocalRepositoryManager().getRepository()); + event.setFile(dstFile); + event.setException(exception); + + repositoryEventDispatcher.dispatch(event.build()); } - private void metadataInstalling( RepositorySystemSession session, RequestTrace trace, Metadata metadata, - File dstFile ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.METADATA_INSTALLING ); - event.setTrace( trace ); - event.setMetadata( metadata ); - event.setRepository( session.getLocalRepositoryManager().getRepository() ); - event.setFile( dstFile ); + private void metadataInstalling( + RepositorySystemSession session, RequestTrace trace, Metadata metadata, File dstFile) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INSTALLING); + event.setTrace(trace); + event.setMetadata(metadata); + event.setRepository(session.getLocalRepositoryManager().getRepository()); + event.setFile(dstFile); - repositoryEventDispatcher.dispatch( event.build() ); + repositoryEventDispatcher.dispatch(event.build()); } - private void metadataInstalled( RepositorySystemSession session, RequestTrace trace, Metadata metadata, - File dstFile, Exception exception ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.METADATA_INSTALLED ); - event.setTrace( trace ); - event.setMetadata( metadata ); - event.setRepository( session.getLocalRepositoryManager().getRepository() ); - event.setFile( dstFile ); - event.setException( exception ); - - repositoryEventDispatcher.dispatch( event.build() ); - } + private void metadataInstalled( + RepositorySystemSession session, RequestTrace trace, Metadata metadata, File dstFile, Exception exception) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_INSTALLED); + event.setTrace(trace); + event.setMetadata(metadata); + event.setRepository(session.getLocalRepositoryManager().getRepository()); + event.setFile(dstFile); + event.setException(exception); + repositoryEventDispatcher.dispatch(event.build()); + } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalPathComposer.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalPathComposer.java index 548816073..dc55e1482 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalPathComposer.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalPathComposer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import javax.inject.Named; import javax.inject.Singleton; @@ -34,83 +33,68 @@ */ @Singleton @Named -public final class DefaultLocalPathComposer implements LocalPathComposer -{ +public final class DefaultLocalPathComposer implements LocalPathComposer { @Override - public String getPathForArtifact( Artifact artifact, boolean local ) - { - requireNonNull( artifact ); + public String getPathForArtifact(Artifact artifact, boolean local) { + requireNonNull(artifact); - StringBuilder path = new StringBuilder( 128 ); + StringBuilder path = new StringBuilder(128); - path.append( artifact.getGroupId().replace( '.', '/' ) ).append( '/' ); + path.append(artifact.getGroupId().replace('.', '/')).append('/'); - path.append( artifact.getArtifactId() ).append( '/' ); + path.append(artifact.getArtifactId()).append('/'); - path.append( artifact.getBaseVersion() ).append( '/' ); + path.append(artifact.getBaseVersion()).append('/'); - path.append( artifact.getArtifactId() ).append( '-' ); - if ( local ) - { - path.append( artifact.getBaseVersion() ); - } - else - { - path.append( artifact.getVersion() ); + path.append(artifact.getArtifactId()).append('-'); + if (local) { + path.append(artifact.getBaseVersion()); + } else { + path.append(artifact.getVersion()); } - if ( artifact.getClassifier().length() > 0 ) - { - path.append( '-' ).append( artifact.getClassifier() ); + if (artifact.getClassifier().length() > 0) { + path.append('-').append(artifact.getClassifier()); } - if ( artifact.getExtension().length() > 0 ) - { - path.append( '.' ).append( artifact.getExtension() ); + if (artifact.getExtension().length() > 0) { + path.append('.').append(artifact.getExtension()); } return path.toString(); } @Override - public String getPathForMetadata( Metadata metadata, String repositoryKey ) - { - requireNonNull( metadata ); - requireNonNull( repositoryKey ); + public String getPathForMetadata(Metadata metadata, String repositoryKey) { + requireNonNull(metadata); + requireNonNull(repositoryKey); - StringBuilder path = new StringBuilder( 128 ); + StringBuilder path = new StringBuilder(128); - if ( metadata.getGroupId().length() > 0 ) - { - path.append( metadata.getGroupId().replace( '.', '/' ) ).append( '/' ); + if (metadata.getGroupId().length() > 0) { + path.append(metadata.getGroupId().replace('.', '/')).append('/'); - if ( metadata.getArtifactId().length() > 0 ) - { - path.append( metadata.getArtifactId() ).append( '/' ); + if (metadata.getArtifactId().length() > 0) { + path.append(metadata.getArtifactId()).append('/'); - if ( metadata.getVersion().length() > 0 ) - { - path.append( metadata.getVersion() ).append( '/' ); + if (metadata.getVersion().length() > 0) { + path.append(metadata.getVersion()).append('/'); } } } - path.append( insertRepositoryKey( metadata.getType(), repositoryKey ) ); + path.append(insertRepositoryKey(metadata.getType(), repositoryKey)); return path.toString(); } - private String insertRepositoryKey( String metadataType, String repositoryKey ) - { + private String insertRepositoryKey(String metadataType, String repositoryKey) { String result; - int idx = metadataType.indexOf( '.' ); - if ( idx < 0 ) - { + int idx = metadataType.indexOf('.'); + if (idx < 0) { result = metadataType + '-' + repositoryKey; - } - else - { - result = metadataType.substring( 0, idx ) + '-' + repositoryKey + metadataType.substring( idx ); + } else { + result = metadataType.substring(0, idx) + '-' + repositoryKey + metadataType.substring(idx); } return result; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalPathPrefixComposerFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalPathPrefixComposerFactory.java index 7fce1a042..f5f335eff 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalPathPrefixComposerFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalPathPrefixComposerFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import javax.inject.Named; import javax.inject.Singleton; @@ -32,30 +31,46 @@ */ @Singleton @Named -public final class DefaultLocalPathPrefixComposerFactory extends LocalPathPrefixComposerFactorySupport -{ +public final class DefaultLocalPathPrefixComposerFactory extends LocalPathPrefixComposerFactorySupport { @Override - public LocalPathPrefixComposer createComposer( RepositorySystemSession session ) - { - return new DefaultLocalPathPrefixComposer( isSplit( session ), getLocalPrefix( session ), - isSplitLocal( session ), getRemotePrefix( session ), isSplitRemote( session ), - isSplitRemoteRepository( session ), isSplitRemoteRepositoryLast( session ), - getReleasesPrefix( session ), getSnapshotsPrefix( session ) ); + public LocalPathPrefixComposer createComposer(RepositorySystemSession session) { + return new DefaultLocalPathPrefixComposer( + isSplit(session), + getLocalPrefix(session), + isSplitLocal(session), + getRemotePrefix(session), + isSplitRemote(session), + isSplitRemoteRepository(session), + isSplitRemoteRepositoryLast(session), + getReleasesPrefix(session), + getSnapshotsPrefix(session)); } /** * {@link LocalPathPrefixComposer} implementation that fully reuses {@link LocalPathPrefixComposerSupport} class. */ - private static class DefaultLocalPathPrefixComposer extends LocalPathPrefixComposerSupport - { - @SuppressWarnings( "checkstyle:parameternumber" ) - private DefaultLocalPathPrefixComposer( boolean split, String localPrefix, boolean splitLocal, - String remotePrefix, boolean splitRemote, boolean splitRemoteRepository, - boolean splitRemoteRepositoryLast, - String releasesPrefix, String snapshotsPrefix ) - { - super( split, localPrefix, splitLocal, remotePrefix, splitRemote, splitRemoteRepository, - splitRemoteRepositoryLast, releasesPrefix, snapshotsPrefix ); + private static class DefaultLocalPathPrefixComposer extends LocalPathPrefixComposerSupport { + @SuppressWarnings("checkstyle:parameternumber") + private DefaultLocalPathPrefixComposer( + boolean split, + String localPrefix, + boolean splitLocal, + String remotePrefix, + boolean splitRemote, + boolean splitRemoteRepository, + boolean splitRemoteRepositoryLast, + String releasesPrefix, + String snapshotsPrefix) { + super( + split, + localPrefix, + splitLocal, + remotePrefix, + splitRemote, + splitRemoteRepository, + splitRemoteRepositoryLast, + releasesPrefix, + snapshotsPrefix); } } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalRepositoryProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalRepositoryProvider.java index 26110ec8a..201b79348 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalRepositoryProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultLocalRepositoryProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,17 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import static java.util.Objects.requireNonNull; import java.util.Set; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.impl.LocalRepositoryProvider; import org.eclipse.aether.repository.LocalRepository; @@ -40,115 +38,93 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; + /** */ @Singleton @Named -public class DefaultLocalRepositoryProvider - implements LocalRepositoryProvider, Service -{ +public class DefaultLocalRepositoryProvider implements LocalRepositoryProvider, Service { - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultLocalRepositoryProvider.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLocalRepositoryProvider.class); private Collection managerFactories = new ArrayList<>(); - public DefaultLocalRepositoryProvider() - { + public DefaultLocalRepositoryProvider() { // enables default constructor } @Inject - DefaultLocalRepositoryProvider( Set factories ) - { - setLocalRepositoryManagerFactories( factories ); + DefaultLocalRepositoryProvider(Set factories) { + setLocalRepositoryManagerFactories(factories); } - public void initService( ServiceLocator locator ) - { - setLocalRepositoryManagerFactories( locator.getServices( LocalRepositoryManagerFactory.class ) ); + public void initService(ServiceLocator locator) { + setLocalRepositoryManagerFactories(locator.getServices(LocalRepositoryManagerFactory.class)); } - public DefaultLocalRepositoryProvider addLocalRepositoryManagerFactory( LocalRepositoryManagerFactory factory ) - { - managerFactories.add( requireNonNull( factory, "local repository manager factory cannot be null" ) ); + public DefaultLocalRepositoryProvider addLocalRepositoryManagerFactory(LocalRepositoryManagerFactory factory) { + managerFactories.add(requireNonNull(factory, "local repository manager factory cannot be null")); return this; } public DefaultLocalRepositoryProvider setLocalRepositoryManagerFactories( - Collection factories ) - { - if ( factories == null ) - { - managerFactories = new ArrayList<>( 2 ); - } - else - { + Collection factories) { + if (factories == null) { + managerFactories = new ArrayList<>(2); + } else { managerFactories = factories; } return this; } - public LocalRepositoryManager newLocalRepositoryManager( RepositorySystemSession session, - LocalRepository repository ) - throws NoLocalRepositoryManagerException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); - PrioritizedComponents factories = new PrioritizedComponents<>( session ); - for ( LocalRepositoryManagerFactory factory : this.managerFactories ) - { - factories.add( factory, factory.getPriority() ); + public LocalRepositoryManager newLocalRepositoryManager(RepositorySystemSession session, LocalRepository repository) + throws NoLocalRepositoryManagerException { + requireNonNull(session, "session cannot be null"); + requireNonNull(repository, "repository cannot be null"); + PrioritizedComponents factories = new PrioritizedComponents<>(session); + for (LocalRepositoryManagerFactory factory : this.managerFactories) { + factories.add(factory, factory.getPriority()); } List errors = new ArrayList<>(); - for ( PrioritizedComponent factory : factories.getEnabled() ) - { - try - { - LocalRepositoryManager manager = factory.getComponent().newInstance( session, repository ); - - if ( LOGGER.isDebugEnabled() ) - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( "Using manager " ).append( manager.getClass().getSimpleName() ); - Utils.appendClassLoader( buffer, manager ); - buffer.append( " with priority " ).append( factory.getPriority() ); - buffer.append( " for " ).append( repository.getBasedir() ); - - LOGGER.debug( buffer.toString() ); + for (PrioritizedComponent factory : factories.getEnabled()) { + try { + LocalRepositoryManager manager = factory.getComponent().newInstance(session, repository); + + if (LOGGER.isDebugEnabled()) { + StringBuilder buffer = new StringBuilder(256); + buffer.append("Using manager ").append(manager.getClass().getSimpleName()); + Utils.appendClassLoader(buffer, manager); + buffer.append(" with priority ").append(factory.getPriority()); + buffer.append(" for ").append(repository.getBasedir()); + + LOGGER.debug(buffer.toString()); } return manager; - } - catch ( NoLocalRepositoryManagerException e ) - { + } catch (NoLocalRepositoryManagerException e) { // continue and try next factory - errors.add( e ); + errors.add(e); } } - if ( LOGGER.isDebugEnabled() && errors.size() > 1 ) - { - for ( Exception e : errors ) - { - LOGGER.debug( "Could not obtain local repository manager for {}", repository, e ); + if (LOGGER.isDebugEnabled() && errors.size() > 1) { + for (Exception e : errors) { + LOGGER.debug("Could not obtain local repository manager for {}", repository, e); } } - StringBuilder buffer = new StringBuilder( 256 ); - if ( factories.isEmpty() ) - { - buffer.append( "No local repository managers registered" ); - } - else - { - buffer.append( "Cannot access " ).append( repository.getBasedir() ); - buffer.append( " with type " ).append( repository.getContentType() ); - buffer.append( " using the available factories " ); - factories.list( buffer ); + StringBuilder buffer = new StringBuilder(256); + if (factories.isEmpty()) { + buffer.append("No local repository managers registered"); + } else { + buffer.append("Cannot access ").append(repository.getBasedir()); + buffer.append(" with type ").append(repository.getContentType()); + buffer.append(" using the available factories "); + factories.list(buffer); } - throw new NoLocalRepositoryManagerException( repository, buffer.toString(), errors.size() == 1 ? errors.get( 0 ) - : null ); + throw new NoLocalRepositoryManagerException( + repository, buffer.toString(), errors.size() == 1 ? errors.get(0) : null); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultMetadataResolver.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultMetadataResolver.java index 7585c73a7..a6743958a 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultMetadataResolver.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultMetadataResolver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import java.io.File; import java.util.ArrayList; @@ -26,13 +29,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static java.util.Objects.requireNonNull; import java.util.concurrent.Executor; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import org.eclipse.aether.RepositoryEvent; import org.eclipse.aether.RepositoryEvent.EventType; import org.eclipse.aether.RepositorySystemSession; @@ -44,8 +42,6 @@ import org.eclipse.aether.impl.RemoteRepositoryManager; import org.eclipse.aether.impl.RepositoryConnectorProvider; import org.eclipse.aether.impl.RepositoryEventDispatcher; -import org.eclipse.aether.spi.connector.filter.RemoteRepositoryFilter; -import org.eclipse.aether.spi.synccontext.SyncContextFactory; import org.eclipse.aether.impl.UpdateCheck; import org.eclipse.aether.impl.UpdateCheckManager; import org.eclipse.aether.metadata.Metadata; @@ -61,8 +57,10 @@ import org.eclipse.aether.resolution.MetadataResult; import org.eclipse.aether.spi.connector.MetadataDownload; import org.eclipse.aether.spi.connector.RepositoryConnector; +import org.eclipse.aether.spi.connector.filter.RemoteRepositoryFilter; import org.eclipse.aether.spi.locator.Service; import org.eclipse.aether.spi.locator.ServiceLocator; +import org.eclipse.aether.spi.synccontext.SyncContextFactory; import org.eclipse.aether.transfer.MetadataNotFoundException; import org.eclipse.aether.transfer.MetadataTransferException; import org.eclipse.aether.transfer.NoRepositoryConnectorException; @@ -70,13 +68,13 @@ import org.eclipse.aether.util.concurrency.ExecutorUtils; import org.eclipse.aether.util.concurrency.RunnableErrorForwarder; +import static java.util.Objects.requireNonNull; + /** */ @Singleton @Named -public class DefaultMetadataResolver - implements MetadataResolver, Service -{ +public class DefaultMetadataResolver implements MetadataResolver, Service { private static final String CONFIG_PROP_THREADS = "aether.metadataResolver.threads"; @@ -94,442 +92,396 @@ public class DefaultMetadataResolver private RemoteRepositoryFilterManager remoteRepositoryFilterManager; - public DefaultMetadataResolver() - { + public DefaultMetadataResolver() { // enables default constructor } @Inject - DefaultMetadataResolver( RepositoryEventDispatcher repositoryEventDispatcher, - UpdateCheckManager updateCheckManager, - RepositoryConnectorProvider repositoryConnectorProvider, - RemoteRepositoryManager remoteRepositoryManager, SyncContextFactory syncContextFactory, - OfflineController offlineController, - RemoteRepositoryFilterManager remoteRepositoryFilterManager ) - { - setRepositoryEventDispatcher( repositoryEventDispatcher ); - setUpdateCheckManager( updateCheckManager ); - setRepositoryConnectorProvider( repositoryConnectorProvider ); - setRemoteRepositoryManager( remoteRepositoryManager ); - setSyncContextFactory( syncContextFactory ); - setOfflineController( offlineController ); - setRemoteRepositoryFilterManager( remoteRepositoryFilterManager ); + DefaultMetadataResolver( + RepositoryEventDispatcher repositoryEventDispatcher, + UpdateCheckManager updateCheckManager, + RepositoryConnectorProvider repositoryConnectorProvider, + RemoteRepositoryManager remoteRepositoryManager, + SyncContextFactory syncContextFactory, + OfflineController offlineController, + RemoteRepositoryFilterManager remoteRepositoryFilterManager) { + setRepositoryEventDispatcher(repositoryEventDispatcher); + setUpdateCheckManager(updateCheckManager); + setRepositoryConnectorProvider(repositoryConnectorProvider); + setRemoteRepositoryManager(remoteRepositoryManager); + setSyncContextFactory(syncContextFactory); + setOfflineController(offlineController); + setRemoteRepositoryFilterManager(remoteRepositoryFilterManager); } - public void initService( ServiceLocator locator ) - { - setRepositoryEventDispatcher( locator.getService( RepositoryEventDispatcher.class ) ); - setUpdateCheckManager( locator.getService( UpdateCheckManager.class ) ); - setRepositoryConnectorProvider( locator.getService( RepositoryConnectorProvider.class ) ); - setRemoteRepositoryManager( locator.getService( RemoteRepositoryManager.class ) ); - setSyncContextFactory( locator.getService( SyncContextFactory.class ) ); - setOfflineController( locator.getService( OfflineController.class ) ); - setRemoteRepositoryFilterManager( locator.getService( RemoteRepositoryFilterManager.class ) ); + public void initService(ServiceLocator locator) { + setRepositoryEventDispatcher(locator.getService(RepositoryEventDispatcher.class)); + setUpdateCheckManager(locator.getService(UpdateCheckManager.class)); + setRepositoryConnectorProvider(locator.getService(RepositoryConnectorProvider.class)); + setRemoteRepositoryManager(locator.getService(RemoteRepositoryManager.class)); + setSyncContextFactory(locator.getService(SyncContextFactory.class)); + setOfflineController(locator.getService(OfflineController.class)); + setRemoteRepositoryFilterManager(locator.getService(RemoteRepositoryFilterManager.class)); } - public DefaultMetadataResolver setRepositoryEventDispatcher( RepositoryEventDispatcher repositoryEventDispatcher ) - { - this.repositoryEventDispatcher = requireNonNull( - repositoryEventDispatcher, "repository event dispatcher cannot be null" ); + public DefaultMetadataResolver setRepositoryEventDispatcher(RepositoryEventDispatcher repositoryEventDispatcher) { + this.repositoryEventDispatcher = + requireNonNull(repositoryEventDispatcher, "repository event dispatcher cannot be null"); return this; } - public DefaultMetadataResolver setUpdateCheckManager( UpdateCheckManager updateCheckManager ) - { - this.updateCheckManager = requireNonNull( updateCheckManager, "update check manager cannot be null" ); + public DefaultMetadataResolver setUpdateCheckManager(UpdateCheckManager updateCheckManager) { + this.updateCheckManager = requireNonNull(updateCheckManager, "update check manager cannot be null"); return this; } public DefaultMetadataResolver setRepositoryConnectorProvider( - RepositoryConnectorProvider repositoryConnectorProvider ) - { - this.repositoryConnectorProvider = requireNonNull( - repositoryConnectorProvider, "repository connector provider cannot be null" ); + RepositoryConnectorProvider repositoryConnectorProvider) { + this.repositoryConnectorProvider = + requireNonNull(repositoryConnectorProvider, "repository connector provider cannot be null"); return this; } - public DefaultMetadataResolver setRemoteRepositoryManager( RemoteRepositoryManager remoteRepositoryManager ) - { - this.remoteRepositoryManager = requireNonNull( - remoteRepositoryManager, "remote repository provider cannot be null" ); + public DefaultMetadataResolver setRemoteRepositoryManager(RemoteRepositoryManager remoteRepositoryManager) { + this.remoteRepositoryManager = + requireNonNull(remoteRepositoryManager, "remote repository provider cannot be null"); return this; } - public DefaultMetadataResolver setSyncContextFactory( SyncContextFactory syncContextFactory ) - { - this.syncContextFactory = requireNonNull( syncContextFactory, "sync context factory cannot be null" ); + public DefaultMetadataResolver setSyncContextFactory(SyncContextFactory syncContextFactory) { + this.syncContextFactory = requireNonNull(syncContextFactory, "sync context factory cannot be null"); return this; } - public DefaultMetadataResolver setOfflineController( OfflineController offlineController ) - { - this.offlineController = requireNonNull( offlineController, "offline controller cannot be null" ); + public DefaultMetadataResolver setOfflineController(OfflineController offlineController) { + this.offlineController = requireNonNull(offlineController, "offline controller cannot be null"); return this; } public DefaultMetadataResolver setRemoteRepositoryFilterManager( - RemoteRepositoryFilterManager remoteRepositoryFilterManager ) - { - this.remoteRepositoryFilterManager = requireNonNull( remoteRepositoryFilterManager, - "remote repository filter manager cannot be null" ); + RemoteRepositoryFilterManager remoteRepositoryFilterManager) { + this.remoteRepositoryFilterManager = + requireNonNull(remoteRepositoryFilterManager, "remote repository filter manager cannot be null"); return this; } - public List resolveMetadata( RepositorySystemSession session, - Collection requests ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( requests, "requests cannot be null" ); - try ( SyncContext syncContext = syncContextFactory.newInstance( session, false ) ) - { - Collection metadata = new ArrayList<>( requests.size() ); - for ( MetadataRequest request : requests ) - { - metadata.add( request.getMetadata() ); + public List resolveMetadata( + RepositorySystemSession session, Collection requests) { + requireNonNull(session, "session cannot be null"); + requireNonNull(requests, "requests cannot be null"); + try (SyncContext syncContext = syncContextFactory.newInstance(session, false)) { + Collection metadata = new ArrayList<>(requests.size()); + for (MetadataRequest request : requests) { + metadata.add(request.getMetadata()); } - syncContext.acquire( null, metadata ); + syncContext.acquire(null, metadata); - return resolve( session, requests ); + return resolve(session, requests); } } - @SuppressWarnings( "checkstyle:methodlength" ) - private List resolve( RepositorySystemSession session, - Collection requests ) - { - List results = new ArrayList<>( requests.size() ); + @SuppressWarnings("checkstyle:methodlength") + private List resolve( + RepositorySystemSession session, Collection requests) { + List results = new ArrayList<>(requests.size()); - List tasks = new ArrayList<>( requests.size() ); + List tasks = new ArrayList<>(requests.size()); Map localLastUpdates = new HashMap<>(); - RemoteRepositoryFilter remoteRepositoryFilter = remoteRepositoryFilterManager - .getRemoteRepositoryFilter( session ); + RemoteRepositoryFilter remoteRepositoryFilter = + remoteRepositoryFilterManager.getRemoteRepositoryFilter(session); - for ( MetadataRequest request : requests ) - { - RequestTrace trace = RequestTrace.newChild( request.getTrace(), request ); + for (MetadataRequest request : requests) { + RequestTrace trace = RequestTrace.newChild(request.getTrace(), request); - MetadataResult result = new MetadataResult( request ); - results.add( result ); + MetadataResult result = new MetadataResult(request); + results.add(result); Metadata metadata = request.getMetadata(); RemoteRepository repository = request.getRepository(); - if ( repository == null ) - { + if (repository == null) { LocalRepository localRepo = session.getLocalRepositoryManager().getRepository(); - metadataResolving( session, trace, metadata, localRepo ); + metadataResolving(session, trace, metadata, localRepo); - File localFile = getLocalFile( session, metadata ); + File localFile = getLocalFile(session, metadata); - if ( localFile != null ) - { - metadata = metadata.setFile( localFile ); - result.setMetadata( metadata ); - } - else - { - result.setException( new MetadataNotFoundException( metadata, localRepo ) ); + if (localFile != null) { + metadata = metadata.setFile(localFile); + result.setMetadata(metadata); + } else { + result.setException(new MetadataNotFoundException(metadata, localRepo)); } - metadataResolved( session, trace, metadata, localRepo, result.getException() ); + metadataResolved(session, trace, metadata, localRepo, result.getException()); continue; } - if ( remoteRepositoryFilter != null ) - { - RemoteRepositoryFilter.Result filterResult = remoteRepositoryFilter.acceptMetadata( - repository, metadata ); - if ( !filterResult.isAccepted() ) - { - result.setException( - new MetadataNotFoundException( metadata, repository, filterResult.reasoning() ) ); + if (remoteRepositoryFilter != null) { + RemoteRepositoryFilter.Result filterResult = + remoteRepositoryFilter.acceptMetadata(repository, metadata); + if (!filterResult.isAccepted()) { + result.setException(new MetadataNotFoundException(metadata, repository, filterResult.reasoning())); continue; } } - List repositories = getEnabledSourceRepositories( repository, metadata.getNature() ); + List repositories = getEnabledSourceRepositories(repository, metadata.getNature()); - if ( repositories.isEmpty() ) - { + if (repositories.isEmpty()) { continue; } - metadataResolving( session, trace, metadata, repository ); + metadataResolving(session, trace, metadata, repository); LocalRepositoryManager lrm = session.getLocalRepositoryManager(); LocalMetadataRequest localRequest = - new LocalMetadataRequest( metadata, repository, request.getRequestContext() ); - LocalMetadataResult lrmResult = lrm.find( session, localRequest ); + new LocalMetadataRequest(metadata, repository, request.getRequestContext()); + LocalMetadataResult lrmResult = lrm.find(session, localRequest); File metadataFile = lrmResult.getFile(); - try - { - Utils.checkOffline( session, offlineController, repository ); - } - catch ( RepositoryOfflineException e ) - { - if ( metadataFile != null ) - { - metadata = metadata.setFile( metadataFile ); - result.setMetadata( metadata ); - } - else - { - String msg = - "Cannot access " + repository.getId() + " (" + repository.getUrl() + try { + Utils.checkOffline(session, offlineController, repository); + } catch (RepositoryOfflineException e) { + if (metadataFile != null) { + metadata = metadata.setFile(metadataFile); + result.setMetadata(metadata); + } else { + String msg = "Cannot access " + repository.getId() + " (" + repository.getUrl() + ") in offline mode and the metadata " + metadata + " has not been downloaded from it before"; - result.setException( new MetadataNotFoundException( metadata, repository, msg, e ) ); + result.setException(new MetadataNotFoundException(metadata, repository, msg, e)); } - metadataResolved( session, trace, metadata, repository, result.getException() ); + metadataResolved(session, trace, metadata, repository, result.getException()); continue; } Long localLastUpdate = null; - if ( request.isFavorLocalRepository() ) - { - File localFile = getLocalFile( session, metadata ); - localLastUpdate = localLastUpdates.get( localFile ); - if ( localLastUpdate == null ) - { + if (request.isFavorLocalRepository()) { + File localFile = getLocalFile(session, metadata); + localLastUpdate = localLastUpdates.get(localFile); + if (localLastUpdate == null) { localLastUpdate = localFile != null ? localFile.lastModified() : 0; - localLastUpdates.put( localFile, localLastUpdate ); + localLastUpdates.put(localFile, localLastUpdate); } } List> checks = new ArrayList<>(); Exception exception = null; - for ( RemoteRepository repo : repositories ) - { + for (RemoteRepository repo : repositories) { UpdateCheck check = new UpdateCheck<>(); - check.setLocalLastUpdated( ( localLastUpdate != null ) ? localLastUpdate : 0 ); - check.setItem( metadata ); + check.setLocalLastUpdated((localLastUpdate != null) ? localLastUpdate : 0); + check.setItem(metadata); // use 'main' installation file for the check (-> use requested repository) File checkFile = new File( session.getLocalRepository().getBasedir(), session.getLocalRepositoryManager() - .getPathForRemoteMetadata( metadata, repository, request.getRequestContext() ) ); - check.setFile( checkFile ); - check.setRepository( repository ); - check.setAuthoritativeRepository( repo ); - check.setPolicy( getPolicy( session, repo, metadata.getNature() ).getUpdatePolicy() ); - - if ( lrmResult.isStale() ) - { - checks.add( check ); - } - else - { - updateCheckManager.checkMetadata( session, check ); - if ( check.isRequired() ) - { - checks.add( check ); - } - else if ( exception == null ) - { + .getPathForRemoteMetadata(metadata, repository, request.getRequestContext())); + check.setFile(checkFile); + check.setRepository(repository); + check.setAuthoritativeRepository(repo); + check.setPolicy(getPolicy(session, repo, metadata.getNature()).getUpdatePolicy()); + + if (lrmResult.isStale()) { + checks.add(check); + } else { + updateCheckManager.checkMetadata(session, check); + if (check.isRequired()) { + checks.add(check); + } else if (exception == null) { exception = check.getException(); } } } - if ( !checks.isEmpty() ) - { - RepositoryPolicy policy = getPolicy( session, repository, metadata.getNature() ); + if (!checks.isEmpty()) { + RepositoryPolicy policy = getPolicy(session, repository, metadata.getNature()); // install path may be different from lookup path File installFile = new File( session.getLocalRepository().getBasedir(), - session.getLocalRepositoryManager().getPathForRemoteMetadata( - metadata, request.getRepository(), request.getRequestContext() ) ); + session.getLocalRepositoryManager() + .getPathForRemoteMetadata( + metadata, request.getRepository(), request.getRequestContext())); metadataDownloading( - session, trace, result.getRequest().getMetadata(), result.getRequest().getRepository() ); + session, + trace, + result.getRequest().getMetadata(), + result.getRequest().getRepository()); ResolveTask task = - new ResolveTask( session, trace, result, installFile, checks, policy.getChecksumPolicy() ); - tasks.add( task ); - } - else - { - result.setException( exception ); - if ( metadataFile != null ) - { - metadata = metadata.setFile( metadataFile ); - result.setMetadata( metadata ); + new ResolveTask(session, trace, result, installFile, checks, policy.getChecksumPolicy()); + tasks.add(task); + } else { + result.setException(exception); + if (metadataFile != null) { + metadata = metadata.setFile(metadataFile); + result.setMetadata(metadata); } - metadataResolved( session, trace, metadata, repository, result.getException() ); + metadataResolved(session, trace, metadata, repository, result.getException()); } } - if ( !tasks.isEmpty() ) - { - int threads = ExecutorUtils.threadCount( session, 4, CONFIG_PROP_THREADS ); - Executor executor = ExecutorUtils.executor( - Math.min( tasks.size(), threads ), getClass().getSimpleName() + '-' ); - try - { + if (!tasks.isEmpty()) { + int threads = ExecutorUtils.threadCount(session, 4, CONFIG_PROP_THREADS); + Executor executor = ExecutorUtils.executor( + Math.min(tasks.size(), threads), getClass().getSimpleName() + '-'); + try { RunnableErrorForwarder errorForwarder = new RunnableErrorForwarder(); - for ( ResolveTask task : tasks ) - { - executor.execute( errorForwarder.wrap( task ) ); + for (ResolveTask task : tasks) { + executor.execute(errorForwarder.wrap(task)); } errorForwarder.await(); - for ( ResolveTask task : tasks ) - { + for (ResolveTask task : tasks) { /* * NOTE: Touch after registration with local repo to ensure concurrent resolution is not * rejected with "already updated" via session data when actual update to local repo is * still pending. */ - for ( UpdateCheck check : task.checks ) - { - updateCheckManager.touchMetadata( task.session, check.setException( task.exception ) ); + for (UpdateCheck check : task.checks) { + updateCheckManager.touchMetadata(task.session, check.setException(task.exception)); } - metadataDownloaded( session, task.trace, task.request.getMetadata(), task.request.getRepository(), - task.metadataFile, task.exception ); + metadataDownloaded( + session, + task.trace, + task.request.getMetadata(), + task.request.getRepository(), + task.metadataFile, + task.exception); - task.result.setException( task.exception ); + task.result.setException(task.exception); } + } finally { + ExecutorUtils.shutdown(executor); } - finally - { - ExecutorUtils.shutdown( executor ); - } - for ( ResolveTask task : tasks ) - { + for (ResolveTask task : tasks) { Metadata metadata = task.request.getMetadata(); // re-lookup metadata for resolve LocalMetadataRequest localRequest = new LocalMetadataRequest( - metadata, task.request.getRepository(), task.request.getRequestContext() ); - File metadataFile = session.getLocalRepositoryManager().find( session, localRequest ).getFile(); - if ( metadataFile != null ) - { - metadata = metadata.setFile( metadataFile ); - task.result.setMetadata( metadata ); + metadata, task.request.getRepository(), task.request.getRequestContext()); + File metadataFile = session.getLocalRepositoryManager() + .find(session, localRequest) + .getFile(); + if (metadataFile != null) { + metadata = metadata.setFile(metadataFile); + task.result.setMetadata(metadata); } - if ( task.result.getException() == null ) - { - task.result.setUpdated( true ); + if (task.result.getException() == null) { + task.result.setUpdated(true); } - metadataResolved( session, task.trace, metadata, task.request.getRepository(), - task.result.getException() ); + metadataResolved( + session, task.trace, metadata, task.request.getRepository(), task.result.getException()); } } return results; } - private File getLocalFile( RepositorySystemSession session, Metadata metadata ) - { + private File getLocalFile(RepositorySystemSession session, Metadata metadata) { LocalRepositoryManager lrm = session.getLocalRepositoryManager(); - LocalMetadataResult localResult = lrm.find( session, new LocalMetadataRequest( metadata, null, null ) ); + LocalMetadataResult localResult = lrm.find(session, new LocalMetadataRequest(metadata, null, null)); return localResult.getFile(); } - private List getEnabledSourceRepositories( RemoteRepository repository, Metadata.Nature nature ) - { + private List getEnabledSourceRepositories(RemoteRepository repository, Metadata.Nature nature) { List repositories = new ArrayList<>(); - if ( repository.isRepositoryManager() ) - { - for ( RemoteRepository repo : repository.getMirroredRepositories() ) - { - if ( isEnabled( repo, nature ) ) - { - repositories.add( repo ); + if (repository.isRepositoryManager()) { + for (RemoteRepository repo : repository.getMirroredRepositories()) { + if (isEnabled(repo, nature)) { + repositories.add(repo); } } - } - else if ( isEnabled( repository, nature ) ) - { - repositories.add( repository ); + } else if (isEnabled(repository, nature)) { + repositories.add(repository); } return repositories; } - private boolean isEnabled( RemoteRepository repository, Metadata.Nature nature ) - { - if ( !Metadata.Nature.SNAPSHOT.equals( nature ) && repository.getPolicy( false ).isEnabled() ) - { + private boolean isEnabled(RemoteRepository repository, Metadata.Nature nature) { + if (!Metadata.Nature.SNAPSHOT.equals(nature) + && repository.getPolicy(false).isEnabled()) { return true; } - if ( !Metadata.Nature.RELEASE.equals( nature ) && repository.getPolicy( true ).isEnabled() ) - { + if (!Metadata.Nature.RELEASE.equals(nature) + && repository.getPolicy(true).isEnabled()) { return true; } return false; } - private RepositoryPolicy getPolicy( RepositorySystemSession session, RemoteRepository repository, - Metadata.Nature nature ) - { - boolean releases = !Metadata.Nature.SNAPSHOT.equals( nature ); - boolean snapshots = !Metadata.Nature.RELEASE.equals( nature ); - return remoteRepositoryManager.getPolicy( session, repository, releases, snapshots ); + private RepositoryPolicy getPolicy( + RepositorySystemSession session, RemoteRepository repository, Metadata.Nature nature) { + boolean releases = !Metadata.Nature.SNAPSHOT.equals(nature); + boolean snapshots = !Metadata.Nature.RELEASE.equals(nature); + return remoteRepositoryManager.getPolicy(session, repository, releases, snapshots); } - private void metadataResolving( RepositorySystemSession session, RequestTrace trace, Metadata metadata, - ArtifactRepository repository ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.METADATA_RESOLVING ); - event.setTrace( trace ); - event.setMetadata( metadata ); - event.setRepository( repository ); + private void metadataResolving( + RepositorySystemSession session, RequestTrace trace, Metadata metadata, ArtifactRepository repository) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_RESOLVING); + event.setTrace(trace); + event.setMetadata(metadata); + event.setRepository(repository); - repositoryEventDispatcher.dispatch( event.build() ); + repositoryEventDispatcher.dispatch(event.build()); } - private void metadataResolved( RepositorySystemSession session, RequestTrace trace, Metadata metadata, - ArtifactRepository repository, Exception exception ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.METADATA_RESOLVED ); - event.setTrace( trace ); - event.setMetadata( metadata ); - event.setRepository( repository ); - event.setException( exception ); - event.setFile( metadata.getFile() ); - - repositoryEventDispatcher.dispatch( event.build() ); + private void metadataResolved( + RepositorySystemSession session, + RequestTrace trace, + Metadata metadata, + ArtifactRepository repository, + Exception exception) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_RESOLVED); + event.setTrace(trace); + event.setMetadata(metadata); + event.setRepository(repository); + event.setException(exception); + event.setFile(metadata.getFile()); + + repositoryEventDispatcher.dispatch(event.build()); } - private void metadataDownloading( RepositorySystemSession session, RequestTrace trace, Metadata metadata, - ArtifactRepository repository ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.METADATA_DOWNLOADING ); - event.setTrace( trace ); - event.setMetadata( metadata ); - event.setRepository( repository ); + private void metadataDownloading( + RepositorySystemSession session, RequestTrace trace, Metadata metadata, ArtifactRepository repository) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_DOWNLOADING); + event.setTrace(trace); + event.setMetadata(metadata); + event.setRepository(repository); - repositoryEventDispatcher.dispatch( event.build() ); + repositoryEventDispatcher.dispatch(event.build()); } - private void metadataDownloaded( RepositorySystemSession session, RequestTrace trace, Metadata metadata, - ArtifactRepository repository, File file, Exception exception ) - { - RepositoryEvent.Builder event = new RepositoryEvent.Builder( session, EventType.METADATA_DOWNLOADED ); - event.setTrace( trace ); - event.setMetadata( metadata ); - event.setRepository( repository ); - event.setException( exception ); - event.setFile( file ); - - repositoryEventDispatcher.dispatch( event.build() ); + private void metadataDownloaded( + RepositorySystemSession session, + RequestTrace trace, + Metadata metadata, + ArtifactRepository repository, + File file, + Exception exception) { + RepositoryEvent.Builder event = new RepositoryEvent.Builder(session, EventType.METADATA_DOWNLOADED); + event.setTrace(trace); + event.setMetadata(metadata); + event.setRepository(repository); + event.setException(exception); + event.setFile(file); + + repositoryEventDispatcher.dispatch(event.build()); } - class ResolveTask - implements Runnable - { + class ResolveTask implements Runnable { final RepositorySystemSession session; final RequestTrace trace; @@ -546,10 +498,13 @@ class ResolveTask volatile MetadataTransferException exception; - ResolveTask( RepositorySystemSession session, RequestTrace trace, MetadataResult result, - File metadataFile, List> checks, - String policy ) - { + ResolveTask( + RepositorySystemSession session, + RequestTrace trace, + MetadataResult result, + File metadataFile, + List> checks, + String policy) { this.session = session; this.trace = trace; this.result = result; @@ -559,53 +514,44 @@ class ResolveTask this.checks = checks; } - public void run() - { + public void run() { Metadata metadata = request.getMetadata(); RemoteRepository requestRepository = request.getRepository(); - try - { + try { List repositories = new ArrayList<>(); - for ( UpdateCheck check : checks ) - { - repositories.add( check.getAuthoritativeRepository() ); + for (UpdateCheck check : checks) { + repositories.add(check.getAuthoritativeRepository()); } MetadataDownload download = new MetadataDownload(); - download.setMetadata( metadata ); - download.setRequestContext( request.getRequestContext() ); - download.setFile( metadataFile ); - download.setChecksumPolicy( policy ); - download.setRepositories( repositories ); - download.setListener( SafeTransferListener.wrap( session ) ); - download.setTrace( trace ); - - try ( RepositoryConnector connector = - repositoryConnectorProvider.newRepositoryConnector( session, requestRepository ) ) - { - connector.get( null, Collections.singletonList( download ) ); + download.setMetadata(metadata); + download.setRequestContext(request.getRequestContext()); + download.setFile(metadataFile); + download.setChecksumPolicy(policy); + download.setRepositories(repositories); + download.setListener(SafeTransferListener.wrap(session)); + download.setTrace(trace); + + try (RepositoryConnector connector = + repositoryConnectorProvider.newRepositoryConnector(session, requestRepository)) { + connector.get(null, Collections.singletonList(download)); } exception = download.getException(); - if ( exception == null ) - { + if (exception == null) { - List contexts = Collections.singletonList( request.getRequestContext() ); + List contexts = Collections.singletonList(request.getRequestContext()); LocalMetadataRegistration registration = - new LocalMetadataRegistration( metadata, requestRepository, contexts ); + new LocalMetadataRegistration(metadata, requestRepository, contexts); - session.getLocalRepositoryManager().add( session, registration ); - } - else if ( request.isDeleteLocalCopyIfMissing() && exception instanceof MetadataNotFoundException ) - { + session.getLocalRepositoryManager().add(session, registration); + } else if (request.isDeleteLocalCopyIfMissing() && exception instanceof MetadataNotFoundException) { download.getFile().delete(); } - } - catch ( NoRepositoryConnectorException e ) - { - exception = new MetadataTransferException( metadata, requestRepository, e ); + } catch (NoRepositoryConnectorException e) { + exception = new MetadataTransferException(metadata, requestRepository, e); } } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultOfflineController.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultOfflineController.java index 464fd2752..dbf317643 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultOfflineController.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultOfflineController.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ - -import java.util.regex.Pattern; +package org.eclipse.aether.internal.impl; import javax.inject.Named; import javax.inject.Singleton; +import java.util.regex.Pattern; + import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.impl.OfflineController; import org.eclipse.aether.repository.RemoteRepository; @@ -33,50 +32,40 @@ import static java.util.Objects.requireNonNull; /** - * + * */ @Singleton @Named -public class DefaultOfflineController - implements OfflineController -{ +public class DefaultOfflineController implements OfflineController { static final String CONFIG_PROP_OFFLINE_PROTOCOLS = "aether.offline.protocols"; static final String CONFIG_PROP_OFFLINE_HOSTS = "aether.offline.hosts"; - private static final Pattern SEP = Pattern.compile( "\\s*,\\s*" ); + private static final Pattern SEP = Pattern.compile("\\s*,\\s*"); - public DefaultOfflineController() - { + public DefaultOfflineController() { // enables default constructor } - public void checkOffline( RepositorySystemSession session, RemoteRepository repository ) - throws RepositoryOfflineException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); - if ( isOfflineProtocol( session, repository ) || isOfflineHost( session, repository ) ) - { + public void checkOffline(RepositorySystemSession session, RemoteRepository repository) + throws RepositoryOfflineException { + requireNonNull(session, "session cannot be null"); + requireNonNull(repository, "repository cannot be null"); + if (isOfflineProtocol(session, repository) || isOfflineHost(session, repository)) { return; } - throw new RepositoryOfflineException( repository ); + throw new RepositoryOfflineException(repository); } - private boolean isOfflineProtocol( RepositorySystemSession session, RemoteRepository repository ) - { - String[] protocols = getConfig( session, CONFIG_PROP_OFFLINE_PROTOCOLS ); - if ( protocols != null ) - { + private boolean isOfflineProtocol(RepositorySystemSession session, RemoteRepository repository) { + String[] protocols = getConfig(session, CONFIG_PROP_OFFLINE_PROTOCOLS); + if (protocols != null) { String protocol = repository.getProtocol(); - if ( protocol.length() > 0 ) - { - for ( String p : protocols ) - { - if ( p.equalsIgnoreCase( protocol ) ) - { + if (protocol.length() > 0) { + for (String p : protocols) { + if (p.equalsIgnoreCase(protocol)) { return true; } } @@ -85,18 +74,13 @@ private boolean isOfflineProtocol( RepositorySystemSession session, RemoteReposi return false; } - private boolean isOfflineHost( RepositorySystemSession session, RemoteRepository repository ) - { - String[] hosts = getConfig( session, CONFIG_PROP_OFFLINE_HOSTS ); - if ( hosts != null ) - { + private boolean isOfflineHost(RepositorySystemSession session, RemoteRepository repository) { + String[] hosts = getConfig(session, CONFIG_PROP_OFFLINE_HOSTS); + if (hosts != null) { String host = repository.getHost(); - if ( host.length() > 0 ) - { - for ( String h : hosts ) - { - if ( h.equalsIgnoreCase( host ) ) - { + if (host.length() > 0) { + for (String h : hosts) { + if (h.equalsIgnoreCase(host)) { return true; } } @@ -105,14 +89,11 @@ private boolean isOfflineHost( RepositorySystemSession session, RemoteRepository return false; } - private String[] getConfig( RepositorySystemSession session, String key ) - { - String value = ConfigUtils.getString( session, "", key ).trim(); - if ( value.isEmpty() ) - { + private String[] getConfig(RepositorySystemSession session, String key) { + String value = ConfigUtils.getString(session, "", key).trim(); + if (value.isEmpty()) { return null; } - return SEP.split( value ); + return SEP.split(value); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRemoteRepositoryManager.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRemoteRepositoryManager.java index 6c71277a4..7cec323d2 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRemoteRepositoryManager.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRemoteRepositoryManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,16 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ListIterator; -import static java.util.Objects.requireNonNull; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; import org.apache.commons.lang3.StringUtils; import org.eclipse.aether.RepositoryCache; @@ -47,95 +45,80 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; + /** */ @Singleton @Named -public class DefaultRemoteRepositoryManager - implements RemoteRepositoryManager, Service -{ +public class DefaultRemoteRepositoryManager implements RemoteRepositoryManager, Service { - private static final class LoggedMirror - { + private static final class LoggedMirror { private final Object[] keys; - LoggedMirror( RemoteRepository original, RemoteRepository mirror ) - { - keys = new Object[] { mirror.getId(), mirror.getUrl(), original.getId(), original.getUrl() }; + LoggedMirror(RemoteRepository original, RemoteRepository mirror) { + keys = new Object[] {mirror.getId(), mirror.getUrl(), original.getId(), original.getUrl()}; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( !( obj instanceof LoggedMirror ) ) - { + } else if (!(obj instanceof LoggedMirror)) { return false; } LoggedMirror that = (LoggedMirror) obj; - return Arrays.equals( keys, that.keys ); + return Arrays.equals(keys, that.keys); } @Override - public int hashCode() - { - return Arrays.hashCode( keys ); + public int hashCode() { + return Arrays.hashCode(keys); } - } - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultRemoteRepositoryManager.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRemoteRepositoryManager.class); private UpdatePolicyAnalyzer updatePolicyAnalyzer; private ChecksumPolicyProvider checksumPolicyProvider; - public DefaultRemoteRepositoryManager() - { + public DefaultRemoteRepositoryManager() { // enables default constructor } @Inject - DefaultRemoteRepositoryManager( UpdatePolicyAnalyzer updatePolicyAnalyzer, - ChecksumPolicyProvider checksumPolicyProvider ) - { - setUpdatePolicyAnalyzer( updatePolicyAnalyzer ); - setChecksumPolicyProvider( checksumPolicyProvider ); + DefaultRemoteRepositoryManager( + UpdatePolicyAnalyzer updatePolicyAnalyzer, ChecksumPolicyProvider checksumPolicyProvider) { + setUpdatePolicyAnalyzer(updatePolicyAnalyzer); + setChecksumPolicyProvider(checksumPolicyProvider); } - public void initService( ServiceLocator locator ) - { - setUpdatePolicyAnalyzer( locator.getService( UpdatePolicyAnalyzer.class ) ); - setChecksumPolicyProvider( locator.getService( ChecksumPolicyProvider.class ) ); + public void initService(ServiceLocator locator) { + setUpdatePolicyAnalyzer(locator.getService(UpdatePolicyAnalyzer.class)); + setChecksumPolicyProvider(locator.getService(ChecksumPolicyProvider.class)); } - public DefaultRemoteRepositoryManager setUpdatePolicyAnalyzer( UpdatePolicyAnalyzer updatePolicyAnalyzer ) - { - this.updatePolicyAnalyzer = requireNonNull( updatePolicyAnalyzer, "update policy analyzer cannot be null" ); + public DefaultRemoteRepositoryManager setUpdatePolicyAnalyzer(UpdatePolicyAnalyzer updatePolicyAnalyzer) { + this.updatePolicyAnalyzer = requireNonNull(updatePolicyAnalyzer, "update policy analyzer cannot be null"); return this; } - public DefaultRemoteRepositoryManager setChecksumPolicyProvider( ChecksumPolicyProvider checksumPolicyProvider ) - { - this.checksumPolicyProvider = requireNonNull( - checksumPolicyProvider, "checksum policy provider cannot be null" ); + public DefaultRemoteRepositoryManager setChecksumPolicyProvider(ChecksumPolicyProvider checksumPolicyProvider) { + this.checksumPolicyProvider = requireNonNull(checksumPolicyProvider, "checksum policy provider cannot be null"); return this; } - public List aggregateRepositories( RepositorySystemSession session, - List dominantRepositories, - List recessiveRepositories, - boolean recessiveIsRaw ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( dominantRepositories, "dominantRepositories cannot be null" ); - requireNonNull( recessiveRepositories, "recessiveRepositories cannot be null" ); - if ( recessiveRepositories.isEmpty() ) - { + public List aggregateRepositories( + RepositorySystemSession session, + List dominantRepositories, + List recessiveRepositories, + boolean recessiveIsRaw) { + requireNonNull(session, "session cannot be null"); + requireNonNull(dominantRepositories, "dominantRepositories cannot be null"); + requireNonNull(recessiveRepositories, "recessiveRepositories cannot be null"); + if (recessiveRepositories.isEmpty()) { return dominantRepositories; } @@ -143,38 +126,32 @@ public List aggregateRepositories( RepositorySystemSession ses AuthenticationSelector authSelector = session.getAuthenticationSelector(); ProxySelector proxySelector = session.getProxySelector(); - List result = new ArrayList<>( dominantRepositories ); + List result = new ArrayList<>(dominantRepositories); - next: for ( RemoteRepository recessiveRepository : recessiveRepositories ) - { + next: + for (RemoteRepository recessiveRepository : recessiveRepositories) { RemoteRepository repository = recessiveRepository; - if ( recessiveIsRaw ) - { - RemoteRepository mirrorRepository = mirrorSelector.getMirror( recessiveRepository ); + if (recessiveIsRaw) { + RemoteRepository mirrorRepository = mirrorSelector.getMirror(recessiveRepository); - if ( mirrorRepository != null ) - { - logMirror( session, recessiveRepository, mirrorRepository ); + if (mirrorRepository != null) { + logMirror(session, recessiveRepository, mirrorRepository); repository = mirrorRepository; } } - String key = getKey( repository ); + String key = getKey(repository); - for ( ListIterator it = result.listIterator(); it.hasNext(); ) - { + for (ListIterator it = result.listIterator(); it.hasNext(); ) { RemoteRepository dominantRepository = it.next(); - if ( key.equals( getKey( dominantRepository ) ) ) - { - if ( !dominantRepository.getMirroredRepositories().isEmpty() - && !repository.getMirroredRepositories().isEmpty() ) - { - RemoteRepository mergedRepository = mergeMirrors( session, dominantRepository, repository ); - if ( mergedRepository != dominantRepository ) - { - it.set( mergedRepository ); + if (key.equals(getKey(dominantRepository))) { + if (!dominantRepository.getMirroredRepositories().isEmpty() + && !repository.getMirroredRepositories().isEmpty()) { + RemoteRepository mergedRepository = mergeMirrors(session, dominantRepository, repository); + if (mergedRepository != dominantRepository) { + it.set(mergedRepository); } } @@ -182,210 +159,163 @@ public List aggregateRepositories( RepositorySystemSession ses } } - if ( recessiveIsRaw ) - { + if (recessiveIsRaw) { RemoteRepository.Builder builder = null; - Authentication auth = authSelector.getAuthentication( repository ); - if ( auth != null ) - { - builder = new RemoteRepository.Builder( repository ); - builder.setAuthentication( auth ); + Authentication auth = authSelector.getAuthentication(repository); + if (auth != null) { + builder = new RemoteRepository.Builder(repository); + builder.setAuthentication(auth); } - Proxy proxy = proxySelector.getProxy( repository ); - if ( proxy != null ) - { - if ( builder == null ) - { - builder = new RemoteRepository.Builder( repository ); + Proxy proxy = proxySelector.getProxy(repository); + if (proxy != null) { + if (builder == null) { + builder = new RemoteRepository.Builder(repository); } - builder.setProxy( proxy ); + builder.setProxy(proxy); } - if ( builder != null ) - { + if (builder != null) { repository = builder.build(); } } - result.add( repository ); + result.add(repository); } return result; } - private void logMirror( RepositorySystemSession session, RemoteRepository original, RemoteRepository mirror ) - { - if ( !LOGGER.isDebugEnabled() ) - { + private void logMirror(RepositorySystemSession session, RemoteRepository original, RemoteRepository mirror) { + if (!LOGGER.isDebugEnabled()) { return; } RepositoryCache cache = session.getCache(); - if ( cache != null ) - { - Object key = new LoggedMirror( original, mirror ); - if ( cache.get( session, key ) != null ) - { + if (cache != null) { + Object key = new LoggedMirror(original, mirror); + if (cache.get(session, key) != null) { return; } - cache.put( session, key, Boolean.TRUE ); + cache.put(session, key, Boolean.TRUE); } - LOGGER.debug( "Using mirror {} ({}) for {} ({}).", - mirror.getId(), mirror.getUrl(), original.getId(), original.getUrl() ); + LOGGER.debug( + "Using mirror {} ({}) for {} ({}).", + mirror.getId(), + mirror.getUrl(), + original.getId(), + original.getUrl()); } - private String getKey( RemoteRepository repository ) - { + private String getKey(RemoteRepository repository) { return repository.getId(); } - private RemoteRepository mergeMirrors( RepositorySystemSession session, RemoteRepository dominant, - RemoteRepository recessive ) - { + private RemoteRepository mergeMirrors( + RepositorySystemSession session, RemoteRepository dominant, RemoteRepository recessive) { RemoteRepository.Builder merged = null; RepositoryPolicy releases = null, snapshots = null; - next: for ( RemoteRepository rec : recessive.getMirroredRepositories() ) - { - String recKey = getKey( rec ); + next: + for (RemoteRepository rec : recessive.getMirroredRepositories()) { + String recKey = getKey(rec); - for ( RemoteRepository dom : dominant.getMirroredRepositories() ) - { - if ( recKey.equals( getKey( dom ) ) ) - { + for (RemoteRepository dom : dominant.getMirroredRepositories()) { + if (recKey.equals(getKey(dom))) { continue next; } } - if ( merged == null ) - { - merged = new RemoteRepository.Builder( dominant ); - releases = dominant.getPolicy( false ); - snapshots = dominant.getPolicy( true ); + if (merged == null) { + merged = new RemoteRepository.Builder(dominant); + releases = dominant.getPolicy(false); + snapshots = dominant.getPolicy(true); } - releases = merge( session, releases, rec.getPolicy( false ), false ); - snapshots = merge( session, snapshots, rec.getPolicy( true ), false ); + releases = merge(session, releases, rec.getPolicy(false), false); + snapshots = merge(session, snapshots, rec.getPolicy(true), false); - merged.addMirroredRepository( rec ); + merged.addMirroredRepository(rec); } - if ( merged == null ) - { + if (merged == null) { return dominant; } - return merged.setReleasePolicy( releases ).setSnapshotPolicy( snapshots ).build(); + return merged.setReleasePolicy(releases).setSnapshotPolicy(snapshots).build(); } - public RepositoryPolicy getPolicy( RepositorySystemSession session, RemoteRepository repository, boolean releases, - boolean snapshots ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); - RepositoryPolicy policy1 = releases ? repository.getPolicy( false ) : null; - RepositoryPolicy policy2 = snapshots ? repository.getPolicy( true ) : null; - return merge( session, policy1, policy2, true ); + public RepositoryPolicy getPolicy( + RepositorySystemSession session, RemoteRepository repository, boolean releases, boolean snapshots) { + requireNonNull(session, "session cannot be null"); + requireNonNull(repository, "repository cannot be null"); + RepositoryPolicy policy1 = releases ? repository.getPolicy(false) : null; + RepositoryPolicy policy2 = snapshots ? repository.getPolicy(true) : null; + return merge(session, policy1, policy2, true); } - private RepositoryPolicy merge( RepositorySystemSession session, RepositoryPolicy policy1, - RepositoryPolicy policy2, boolean globalPolicy ) - { + private RepositoryPolicy merge( + RepositorySystemSession session, RepositoryPolicy policy1, RepositoryPolicy policy2, boolean globalPolicy) { RepositoryPolicy policy; - if ( policy2 == null ) - { - if ( globalPolicy ) - { - policy = merge( policy1, session.getUpdatePolicy(), session.getChecksumPolicy() ); - } - else - { + if (policy2 == null) { + if (globalPolicy) { + policy = merge(policy1, session.getUpdatePolicy(), session.getChecksumPolicy()); + } else { policy = policy1; } - } - else if ( policy1 == null ) - { - if ( globalPolicy ) - { - policy = merge( policy2, session.getUpdatePolicy(), session.getChecksumPolicy() ); - } - else - { + } else if (policy1 == null) { + if (globalPolicy) { + policy = merge(policy2, session.getUpdatePolicy(), session.getChecksumPolicy()); + } else { policy = policy2; } - } - else if ( !policy2.isEnabled() ) - { - if ( globalPolicy ) - { - policy = merge( policy1, session.getUpdatePolicy(), session.getChecksumPolicy() ); - } - else - { + } else if (!policy2.isEnabled()) { + if (globalPolicy) { + policy = merge(policy1, session.getUpdatePolicy(), session.getChecksumPolicy()); + } else { policy = policy1; } - } - else if ( !policy1.isEnabled() ) - { - if ( globalPolicy ) - { - policy = merge( policy2, session.getUpdatePolicy(), session.getChecksumPolicy() ); - } - else - { + } else if (!policy1.isEnabled()) { + if (globalPolicy) { + policy = merge(policy2, session.getUpdatePolicy(), session.getChecksumPolicy()); + } else { policy = policy2; } - } - else - { + } else { String checksums = session.getChecksumPolicy(); //noinspection StatementWithEmptyBody - if ( globalPolicy && !StringUtils.isEmpty( checksums ) ) - { + if (globalPolicy && !StringUtils.isEmpty(checksums)) { // use global override - } - else - { - checksums = - checksumPolicyProvider.getEffectiveChecksumPolicy( session, policy1.getChecksumPolicy(), - policy2.getChecksumPolicy() ); + } else { + checksums = checksumPolicyProvider.getEffectiveChecksumPolicy( + session, policy1.getChecksumPolicy(), policy2.getChecksumPolicy()); } String updates = session.getUpdatePolicy(); //noinspection StatementWithEmptyBody - if ( globalPolicy && !StringUtils.isEmpty( updates ) ) - { + if (globalPolicy && !StringUtils.isEmpty(updates)) { // use global override - } - else - { - updates = - updatePolicyAnalyzer.getEffectiveUpdatePolicy( session, policy1.getUpdatePolicy(), - policy2.getUpdatePolicy() ); + } else { + updates = updatePolicyAnalyzer.getEffectiveUpdatePolicy( + session, policy1.getUpdatePolicy(), policy2.getUpdatePolicy()); } - policy = new RepositoryPolicy( true, updates, checksums ); + policy = new RepositoryPolicy(true, updates, checksums); } return policy; } - private RepositoryPolicy merge( RepositoryPolicy policy, String updates, String checksums ) - { - if ( policy != null ) - { - if ( StringUtils.isEmpty( updates ) ) - { + private RepositoryPolicy merge(RepositoryPolicy policy, String updates, String checksums) { + if (policy != null) { + if (StringUtils.isEmpty(updates)) { updates = policy.getUpdatePolicy(); } - if ( StringUtils.isEmpty( checksums ) ) - { + if (StringUtils.isEmpty(checksums)) { checksums = policy.getChecksumPolicy(); } - if ( !policy.getUpdatePolicy().equals( updates ) || !policy.getChecksumPolicy().equals( checksums ) ) - { - policy = new RepositoryPolicy( policy.isEnabled(), updates, checksums ); + if (!policy.getUpdatePolicy().equals(updates) + || !policy.getChecksumPolicy().equals(checksums)) { + policy = new RepositoryPolicy(policy.isEnabled(), updates, checksums); } } return policy; } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryConnectorProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryConnectorProvider.java index c148983c6..1f94cb2ef 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryConnectorProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryConnectorProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,17 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import static java.util.Objects.requireNonNull; import java.util.Set; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.impl.RemoteRepositoryFilterManager; import org.eclipse.aether.impl.RepositoryConnectorProvider; @@ -45,170 +43,139 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; + /** */ @Singleton @Named -public class DefaultRepositoryConnectorProvider - implements RepositoryConnectorProvider, Service -{ +public class DefaultRepositoryConnectorProvider implements RepositoryConnectorProvider, Service { - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultRepositoryConnectorProvider.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRepositoryConnectorProvider.class); private Collection connectorFactories = new ArrayList<>(); private RemoteRepositoryFilterManager remoteRepositoryFilterManager; - public DefaultRepositoryConnectorProvider() - { + public DefaultRepositoryConnectorProvider() { // enables default constructor } @Inject - DefaultRepositoryConnectorProvider( Set connectorFactories, - RemoteRepositoryFilterManager remoteRepositoryFilterManager ) - { - setRepositoryConnectorFactories( connectorFactories ); - setRemoteRepositoryFilterManager( remoteRepositoryFilterManager ); + DefaultRepositoryConnectorProvider( + Set connectorFactories, + RemoteRepositoryFilterManager remoteRepositoryFilterManager) { + setRepositoryConnectorFactories(connectorFactories); + setRemoteRepositoryFilterManager(remoteRepositoryFilterManager); } - public void initService( ServiceLocator locator ) - { - setRepositoryConnectorFactories( locator.getServices( RepositoryConnectorFactory.class ) ); - setRemoteRepositoryFilterManager( locator.getService( RemoteRepositoryFilterManager.class ) ); + public void initService(ServiceLocator locator) { + setRepositoryConnectorFactories(locator.getServices(RepositoryConnectorFactory.class)); + setRemoteRepositoryFilterManager(locator.getService(RemoteRepositoryFilterManager.class)); } - public DefaultRepositoryConnectorProvider addRepositoryConnectorFactory( RepositoryConnectorFactory factory ) - { - connectorFactories.add( requireNonNull( factory, "repository connector factory cannot be null" ) ); + public DefaultRepositoryConnectorProvider addRepositoryConnectorFactory(RepositoryConnectorFactory factory) { + connectorFactories.add(requireNonNull(factory, "repository connector factory cannot be null")); return this; } public DefaultRepositoryConnectorProvider setRepositoryConnectorFactories( - Collection factories ) - { - if ( factories == null ) - { + Collection factories) { + if (factories == null) { this.connectorFactories = new ArrayList<>(); - } - else - { + } else { this.connectorFactories = factories; } return this; } public DefaultRepositoryConnectorProvider setRemoteRepositoryFilterManager( - RemoteRepositoryFilterManager remoteRepositoryFilterManager ) - { - this.remoteRepositoryFilterManager = requireNonNull( remoteRepositoryFilterManager ); + RemoteRepositoryFilterManager remoteRepositoryFilterManager) { + this.remoteRepositoryFilterManager = requireNonNull(remoteRepositoryFilterManager); return this; } - public RepositoryConnector newRepositoryConnector( RepositorySystemSession session, RemoteRepository repository ) - throws NoRepositoryConnectorException - { - requireNonNull( repository, "remote repository cannot be null" ); + public RepositoryConnector newRepositoryConnector(RepositorySystemSession session, RemoteRepository repository) + throws NoRepositoryConnectorException { + requireNonNull(repository, "remote repository cannot be null"); - if ( repository.isBlocked() ) - { - if ( repository.getMirroredRepositories().isEmpty() ) - { - throw new NoRepositoryConnectorException( repository, "Blocked repository: " + repository ); - } - else - { - throw new NoRepositoryConnectorException( repository, "Blocked mirror for repositories: " - + repository.getMirroredRepositories() ); + if (repository.isBlocked()) { + if (repository.getMirroredRepositories().isEmpty()) { + throw new NoRepositoryConnectorException(repository, "Blocked repository: " + repository); + } else { + throw new NoRepositoryConnectorException( + repository, "Blocked mirror for repositories: " + repository.getMirroredRepositories()); } } - RemoteRepositoryFilter filter = remoteRepositoryFilterManager.getRemoteRepositoryFilter( session ); + RemoteRepositoryFilter filter = remoteRepositoryFilterManager.getRemoteRepositoryFilter(session); - PrioritizedComponents factories = new PrioritizedComponents<>( session ); - for ( RepositoryConnectorFactory factory : this.connectorFactories ) - { - factories.add( factory, factory.getPriority() ); + PrioritizedComponents factories = new PrioritizedComponents<>(session); + for (RepositoryConnectorFactory factory : this.connectorFactories) { + factories.add(factory, factory.getPriority()); } List errors = new ArrayList<>(); - for ( PrioritizedComponent factory : factories.getEnabled() ) - { - try - { - RepositoryConnector connector = factory.getComponent().newInstance( session, repository ); - - if ( LOGGER.isDebugEnabled() ) - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( "Using connector " ).append( connector.getClass().getSimpleName() ); - Utils.appendClassLoader( buffer, connector ); - buffer.append( " with priority " ).append( factory.getPriority() ); - buffer.append( " for " ).append( repository.getUrl() ); + for (PrioritizedComponent factory : factories.getEnabled()) { + try { + RepositoryConnector connector = factory.getComponent().newInstance(session, repository); + + if (LOGGER.isDebugEnabled()) { + StringBuilder buffer = new StringBuilder(256); + buffer.append("Using connector ") + .append(connector.getClass().getSimpleName()); + Utils.appendClassLoader(buffer, connector); + buffer.append(" with priority ").append(factory.getPriority()); + buffer.append(" for ").append(repository.getUrl()); Authentication auth = repository.getAuthentication(); - if ( auth != null ) - { - buffer.append( " with " ).append( auth ); + if (auth != null) { + buffer.append(" with ").append(auth); } Proxy proxy = repository.getProxy(); - if ( proxy != null ) - { - buffer.append( " via " ).append( proxy.getHost() ).append( ':' ).append( proxy.getPort() ); + if (proxy != null) { + buffer.append(" via ") + .append(proxy.getHost()) + .append(':') + .append(proxy.getPort()); auth = proxy.getAuthentication(); - if ( auth != null ) - { - buffer.append( " with " ).append( auth ); + if (auth != null) { + buffer.append(" with ").append(auth); } } - LOGGER.debug( buffer.toString() ); + LOGGER.debug(buffer.toString()); } - if ( filter != null ) - { - return new FilteringRepositoryConnector( - repository, - connector, - filter - ); - } - else - { + if (filter != null) { + return new FilteringRepositoryConnector(repository, connector, filter); + } else { return connector; } - } - catch ( NoRepositoryConnectorException e ) - { + } catch (NoRepositoryConnectorException e) { // continue and try next factory - errors.add( e ); + errors.add(e); } } - if ( LOGGER.isDebugEnabled() && errors.size() > 1 ) - { - for ( Exception e : errors ) - { - LOGGER.debug( "Could not obtain connector factory for {}", repository, e ); + if (LOGGER.isDebugEnabled() && errors.size() > 1) { + for (Exception e : errors) { + LOGGER.debug("Could not obtain connector factory for {}", repository, e); } } - StringBuilder buffer = new StringBuilder( 256 ); - if ( factories.isEmpty() ) - { - buffer.append( "No connector factories available" ); - } - else - { - buffer.append( "Cannot access " ).append( repository.getUrl() ); - buffer.append( " with type " ).append( repository.getContentType() ); - buffer.append( " using the available connector factories: " ); - factories.list( buffer ); + StringBuilder buffer = new StringBuilder(256); + if (factories.isEmpty()) { + buffer.append("No connector factories available"); + } else { + buffer.append("Cannot access ").append(repository.getUrl()); + buffer.append(" with type ").append(repository.getContentType()); + buffer.append(" using the available connector factories: "); + factories.list(buffer); } - throw new NoRepositoryConnectorException( repository, buffer.toString(), errors.size() == 1 ? errors.get( 0 ) - : null ); + throw new NoRepositoryConnectorException( + repository, buffer.toString(), errors.size() == 1 ? errors.get(0) : null); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryEventDispatcher.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryEventDispatcher.java index 864b1b29c..31b15292d 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryEventDispatcher.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryEventDispatcher.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,16 +16,16 @@ * specific language governing permissions and limitations * under the License. */ - -import java.util.ArrayList; -import java.util.Collection; -import static java.util.Objects.requireNonNull; -import java.util.Set; +package org.eclipse.aether.internal.impl; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Set; + import org.eclipse.aether.RepositoryEvent; import org.eclipse.aether.RepositoryListener; import org.eclipse.aether.impl.RepositoryEventDispatcher; @@ -36,148 +34,130 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; + /** */ @Singleton @Named -public class DefaultRepositoryEventDispatcher - implements RepositoryEventDispatcher, Service -{ +public class DefaultRepositoryEventDispatcher implements RepositoryEventDispatcher, Service { - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultRepositoryEventDispatcher.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRepositoryEventDispatcher.class); private Collection listeners = new ArrayList<>(); - public DefaultRepositoryEventDispatcher() - { + public DefaultRepositoryEventDispatcher() { // enables no-arg constructor } @Inject - DefaultRepositoryEventDispatcher( Set listeners ) - { - setRepositoryListeners( listeners ); + DefaultRepositoryEventDispatcher(Set listeners) { + setRepositoryListeners(listeners); } - public DefaultRepositoryEventDispatcher addRepositoryListener( RepositoryListener listener ) - { - this.listeners.add( requireNonNull( listener, "repository listener cannot be null" ) ); + public DefaultRepositoryEventDispatcher addRepositoryListener(RepositoryListener listener) { + this.listeners.add(requireNonNull(listener, "repository listener cannot be null")); return this; } - public DefaultRepositoryEventDispatcher setRepositoryListeners( Collection listeners ) - { - if ( listeners == null ) - { + public DefaultRepositoryEventDispatcher setRepositoryListeners(Collection listeners) { + if (listeners == null) { this.listeners = new ArrayList<>(); - } - else - { + } else { this.listeners = listeners; } return this; } - public void initService( ServiceLocator locator ) - { - setRepositoryListeners( locator.getServices( RepositoryListener.class ) ); + public void initService(ServiceLocator locator) { + setRepositoryListeners(locator.getServices(RepositoryListener.class)); } - public void dispatch( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - if ( !listeners.isEmpty() ) - { - for ( RepositoryListener listener : listeners ) - { - dispatch( event, listener ); + public void dispatch(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + if (!listeners.isEmpty()) { + for (RepositoryListener listener : listeners) { + dispatch(event, listener); } } RepositoryListener listener = event.getSession().getRepositoryListener(); - if ( listener != null ) - { - dispatch( event, listener ); + if (listener != null) { + dispatch(event, listener); } } - private void dispatch( RepositoryEvent event, RepositoryListener listener ) - { - try - { - switch ( event.getType() ) - { + private void dispatch(RepositoryEvent event, RepositoryListener listener) { + try { + switch (event.getType()) { case ARTIFACT_DEPLOYED: - listener.artifactDeployed( event ); + listener.artifactDeployed(event); break; case ARTIFACT_DEPLOYING: - listener.artifactDeploying( event ); + listener.artifactDeploying(event); break; case ARTIFACT_DESCRIPTOR_INVALID: - listener.artifactDescriptorInvalid( event ); + listener.artifactDescriptorInvalid(event); break; case ARTIFACT_DESCRIPTOR_MISSING: - listener.artifactDescriptorMissing( event ); + listener.artifactDescriptorMissing(event); break; case ARTIFACT_DOWNLOADED: - listener.artifactDownloaded( event ); + listener.artifactDownloaded(event); break; case ARTIFACT_DOWNLOADING: - listener.artifactDownloading( event ); + listener.artifactDownloading(event); break; case ARTIFACT_INSTALLED: - listener.artifactInstalled( event ); + listener.artifactInstalled(event); break; case ARTIFACT_INSTALLING: - listener.artifactInstalling( event ); + listener.artifactInstalling(event); break; case ARTIFACT_RESOLVED: - listener.artifactResolved( event ); + listener.artifactResolved(event); break; case ARTIFACT_RESOLVING: - listener.artifactResolving( event ); + listener.artifactResolving(event); break; case METADATA_DEPLOYED: - listener.metadataDeployed( event ); + listener.metadataDeployed(event); break; case METADATA_DEPLOYING: - listener.metadataDeploying( event ); + listener.metadataDeploying(event); break; case METADATA_DOWNLOADED: - listener.metadataDownloaded( event ); + listener.metadataDownloaded(event); break; case METADATA_DOWNLOADING: - listener.metadataDownloading( event ); + listener.metadataDownloading(event); break; case METADATA_INSTALLED: - listener.metadataInstalled( event ); + listener.metadataInstalled(event); break; case METADATA_INSTALLING: - listener.metadataInstalling( event ); + listener.metadataInstalling(event); break; case METADATA_INVALID: - listener.metadataInvalid( event ); + listener.metadataInvalid(event); break; case METADATA_RESOLVED: - listener.metadataResolved( event ); + listener.metadataResolved(event); break; case METADATA_RESOLVING: - listener.metadataResolving( event ); + listener.metadataResolving(event); break; default: - throw new IllegalStateException( "unknown repository event type " + event.getType() ); + throw new IllegalStateException("unknown repository event type " + event.getType()); } - } - catch ( Exception | LinkageError e ) - { - logError( e, listener ); + } catch (Exception | LinkageError e) { + logError(e, listener); } } - private void logError( Throwable e, Object listener ) - { - LOGGER.warn( "Failed to dispatch repository event to {}", listener.getClass().getCanonicalName(), e ); + private void logError(Throwable e, Object listener) { + LOGGER.warn( + "Failed to dispatch repository event to {}", listener.getClass().getCanonicalName(), e); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryLayoutProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryLayoutProvider.java index 2dcfd083c..f555c684f 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryLayoutProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositoryLayoutProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,17 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import static java.util.Objects.requireNonNull; import java.util.Set; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.spi.connector.layout.RepositoryLayout; @@ -40,101 +38,80 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; + /** */ @Singleton @Named -public final class DefaultRepositoryLayoutProvider - implements RepositoryLayoutProvider, Service -{ +public final class DefaultRepositoryLayoutProvider implements RepositoryLayoutProvider, Service { - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultRepositoryLayoutProvider.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRepositoryLayoutProvider.class); private Collection factories = new ArrayList<>(); - public DefaultRepositoryLayoutProvider() - { + public DefaultRepositoryLayoutProvider() { // enables default constructor } @Inject - DefaultRepositoryLayoutProvider( Set layoutFactories ) - { - setRepositoryLayoutFactories( layoutFactories ); + DefaultRepositoryLayoutProvider(Set layoutFactories) { + setRepositoryLayoutFactories(layoutFactories); } - public void initService( ServiceLocator locator ) - { - setRepositoryLayoutFactories( locator.getServices( RepositoryLayoutFactory.class ) ); + public void initService(ServiceLocator locator) { + setRepositoryLayoutFactories(locator.getServices(RepositoryLayoutFactory.class)); } - public DefaultRepositoryLayoutProvider addRepositoryLayoutFactory( RepositoryLayoutFactory factory ) - { - factories.add( requireNonNull( factory, "layout factory cannot be null" ) ); + public DefaultRepositoryLayoutProvider addRepositoryLayoutFactory(RepositoryLayoutFactory factory) { + factories.add(requireNonNull(factory, "layout factory cannot be null")); return this; } - public DefaultRepositoryLayoutProvider setRepositoryLayoutFactories( Collection factories ) - { - if ( factories == null ) - { + public DefaultRepositoryLayoutProvider setRepositoryLayoutFactories(Collection factories) { + if (factories == null) { this.factories = new ArrayList<>(); - } - else - { + } else { this.factories = factories; } return this; } - public RepositoryLayout newRepositoryLayout( RepositorySystemSession session, RemoteRepository repository ) - throws NoRepositoryLayoutException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( repository, "remote repository cannot be null" ); + public RepositoryLayout newRepositoryLayout(RepositorySystemSession session, RemoteRepository repository) + throws NoRepositoryLayoutException { + requireNonNull(session, "session cannot be null"); + requireNonNull(repository, "remote repository cannot be null"); - PrioritizedComponents factories = new PrioritizedComponents<>( session ); - for ( RepositoryLayoutFactory factory : this.factories ) - { - factories.add( factory, factory.getPriority() ); + PrioritizedComponents factories = new PrioritizedComponents<>(session); + for (RepositoryLayoutFactory factory : this.factories) { + factories.add(factory, factory.getPriority()); } List errors = new ArrayList<>(); - for ( PrioritizedComponent factory : factories.getEnabled() ) - { - try - { - return factory.getComponent().newInstance( session, repository ); - } - catch ( NoRepositoryLayoutException e ) - { + for (PrioritizedComponent factory : factories.getEnabled()) { + try { + return factory.getComponent().newInstance(session, repository); + } catch (NoRepositoryLayoutException e) { // continue and try next factory - errors.add( e ); + errors.add(e); } } - if ( LOGGER.isDebugEnabled() && errors.size() > 1 ) - { - for ( Exception e : errors ) - { - LOGGER.debug( "Could not obtain layout factory for {}", repository, e ); + if (LOGGER.isDebugEnabled() && errors.size() > 1) { + for (Exception e : errors) { + LOGGER.debug("Could not obtain layout factory for {}", repository, e); } } - StringBuilder buffer = new StringBuilder( 256 ); - if ( factories.isEmpty() ) - { - buffer.append( "No layout factories registered" ); - } - else - { - buffer.append( "Cannot access " ).append( repository.getUrl() ); - buffer.append( " with type " ).append( repository.getContentType() ); - buffer.append( " using the available layout factories: " ); - factories.list( buffer ); + StringBuilder buffer = new StringBuilder(256); + if (factories.isEmpty()) { + buffer.append("No layout factories registered"); + } else { + buffer.append("Cannot access ").append(repository.getUrl()); + buffer.append(" with type ").append(repository.getContentType()); + buffer.append(" using the available layout factories: "); + factories.list(buffer); } - throw new NoRepositoryLayoutException( repository, buffer.toString(), errors.size() == 1 ? errors.get( 0 ) - : null ); + throw new NoRepositoryLayoutException(repository, buffer.toString(), errors.size() == 1 ? errors.get(0) : null); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositorySystem.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositorySystem.java index 7a383bf59..025351a46 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositorySystem.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositorySystem.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import javax.inject.Inject; import javax.inject.Named; @@ -91,9 +90,7 @@ */ @Singleton @Named -public class DefaultRepositorySystem - implements RepositorySystem, Service -{ +public class DefaultRepositorySystem implements RepositorySystem, Service { private final AtomicBoolean shutdown; private VersionResolver versionResolver; @@ -120,418 +117,360 @@ public class DefaultRepositorySystem private RepositorySystemLifecycle repositorySystemLifecycle; - public DefaultRepositorySystem() - { + public DefaultRepositorySystem() { // enables default constructor - this.shutdown = new AtomicBoolean( false ); + this.shutdown = new AtomicBoolean(false); } - @SuppressWarnings( "checkstyle:parameternumber" ) + @SuppressWarnings("checkstyle:parameternumber") @Inject - DefaultRepositorySystem( VersionResolver versionResolver, VersionRangeResolver versionRangeResolver, - ArtifactResolver artifactResolver, MetadataResolver metadataResolver, - ArtifactDescriptorReader artifactDescriptorReader, - DependencyCollector dependencyCollector, Installer installer, Deployer deployer, - LocalRepositoryProvider localRepositoryProvider, SyncContextFactory syncContextFactory, - RemoteRepositoryManager remoteRepositoryManager, - RepositorySystemLifecycle repositorySystemLifecycle ) - { - this.shutdown = new AtomicBoolean( false ); - setVersionResolver( versionResolver ); - setVersionRangeResolver( versionRangeResolver ); - setArtifactResolver( artifactResolver ); - setMetadataResolver( metadataResolver ); - setArtifactDescriptorReader( artifactDescriptorReader ); - setDependencyCollector( dependencyCollector ); - setInstaller( installer ); - setDeployer( deployer ); - setLocalRepositoryProvider( localRepositoryProvider ); - setSyncContextFactory( syncContextFactory ); - setRemoteRepositoryManager( remoteRepositoryManager ); - setRepositorySystemLifecycle( repositorySystemLifecycle ); + DefaultRepositorySystem( + VersionResolver versionResolver, + VersionRangeResolver versionRangeResolver, + ArtifactResolver artifactResolver, + MetadataResolver metadataResolver, + ArtifactDescriptorReader artifactDescriptorReader, + DependencyCollector dependencyCollector, + Installer installer, + Deployer deployer, + LocalRepositoryProvider localRepositoryProvider, + SyncContextFactory syncContextFactory, + RemoteRepositoryManager remoteRepositoryManager, + RepositorySystemLifecycle repositorySystemLifecycle) { + this.shutdown = new AtomicBoolean(false); + setVersionResolver(versionResolver); + setVersionRangeResolver(versionRangeResolver); + setArtifactResolver(artifactResolver); + setMetadataResolver(metadataResolver); + setArtifactDescriptorReader(artifactDescriptorReader); + setDependencyCollector(dependencyCollector); + setInstaller(installer); + setDeployer(deployer); + setLocalRepositoryProvider(localRepositoryProvider); + setSyncContextFactory(syncContextFactory); + setRemoteRepositoryManager(remoteRepositoryManager); + setRepositorySystemLifecycle(repositorySystemLifecycle); } @Override - public void initService( ServiceLocator locator ) - { - setVersionResolver( locator.getService( VersionResolver.class ) ); - setVersionRangeResolver( locator.getService( VersionRangeResolver.class ) ); - setArtifactResolver( locator.getService( ArtifactResolver.class ) ); - setMetadataResolver( locator.getService( MetadataResolver.class ) ); - setArtifactDescriptorReader( locator.getService( ArtifactDescriptorReader.class ) ); - setDependencyCollector( locator.getService( DependencyCollector.class ) ); - setInstaller( locator.getService( Installer.class ) ); - setDeployer( locator.getService( Deployer.class ) ); - setLocalRepositoryProvider( locator.getService( LocalRepositoryProvider.class ) ); - setRemoteRepositoryManager( locator.getService( RemoteRepositoryManager.class ) ); - setSyncContextFactory( locator.getService( SyncContextFactory.class ) ); - setRepositorySystemLifecycle( locator.getService( RepositorySystemLifecycle.class ) ); + public void initService(ServiceLocator locator) { + setVersionResolver(locator.getService(VersionResolver.class)); + setVersionRangeResolver(locator.getService(VersionRangeResolver.class)); + setArtifactResolver(locator.getService(ArtifactResolver.class)); + setMetadataResolver(locator.getService(MetadataResolver.class)); + setArtifactDescriptorReader(locator.getService(ArtifactDescriptorReader.class)); + setDependencyCollector(locator.getService(DependencyCollector.class)); + setInstaller(locator.getService(Installer.class)); + setDeployer(locator.getService(Deployer.class)); + setLocalRepositoryProvider(locator.getService(LocalRepositoryProvider.class)); + setRemoteRepositoryManager(locator.getService(RemoteRepositoryManager.class)); + setSyncContextFactory(locator.getService(SyncContextFactory.class)); + setRepositorySystemLifecycle(locator.getService(RepositorySystemLifecycle.class)); } /** * @deprecated not used any more since MRESOLVER-36 move to slf4j, added back in MRESOLVER-64 for compatibility */ @Deprecated - public DefaultRepositorySystem setLoggerFactory( org.eclipse.aether.spi.log.LoggerFactory loggerFactory ) - { + public DefaultRepositorySystem setLoggerFactory(org.eclipse.aether.spi.log.LoggerFactory loggerFactory) { // this.logger = NullLoggerFactory.getSafeLogger( loggerFactory, getClass() ); return this; } - public DefaultRepositorySystem setVersionResolver( VersionResolver versionResolver ) - { - this.versionResolver = requireNonNull( versionResolver, "version resolver cannot be null" ); + public DefaultRepositorySystem setVersionResolver(VersionResolver versionResolver) { + this.versionResolver = requireNonNull(versionResolver, "version resolver cannot be null"); return this; } - public DefaultRepositorySystem setVersionRangeResolver( VersionRangeResolver versionRangeResolver ) - { - this.versionRangeResolver = requireNonNull( - versionRangeResolver, "version range resolver cannot be null" ); + public DefaultRepositorySystem setVersionRangeResolver(VersionRangeResolver versionRangeResolver) { + this.versionRangeResolver = requireNonNull(versionRangeResolver, "version range resolver cannot be null"); return this; } - public DefaultRepositorySystem setArtifactResolver( ArtifactResolver artifactResolver ) - { - this.artifactResolver = requireNonNull( artifactResolver, "artifact resolver cannot be null" ); + public DefaultRepositorySystem setArtifactResolver(ArtifactResolver artifactResolver) { + this.artifactResolver = requireNonNull(artifactResolver, "artifact resolver cannot be null"); return this; } - public DefaultRepositorySystem setMetadataResolver( MetadataResolver metadataResolver ) - { - this.metadataResolver = requireNonNull( metadataResolver, "metadata resolver cannot be null" ); + public DefaultRepositorySystem setMetadataResolver(MetadataResolver metadataResolver) { + this.metadataResolver = requireNonNull(metadataResolver, "metadata resolver cannot be null"); return this; } - public DefaultRepositorySystem setArtifactDescriptorReader( ArtifactDescriptorReader artifactDescriptorReader ) - { - this.artifactDescriptorReader = requireNonNull( - artifactDescriptorReader, "artifact descriptor reader cannot be null" ); + public DefaultRepositorySystem setArtifactDescriptorReader(ArtifactDescriptorReader artifactDescriptorReader) { + this.artifactDescriptorReader = + requireNonNull(artifactDescriptorReader, "artifact descriptor reader cannot be null"); return this; } - public DefaultRepositorySystem setDependencyCollector( DependencyCollector dependencyCollector ) - { - this.dependencyCollector = requireNonNull( dependencyCollector, "dependency collector cannot be null" ); + public DefaultRepositorySystem setDependencyCollector(DependencyCollector dependencyCollector) { + this.dependencyCollector = requireNonNull(dependencyCollector, "dependency collector cannot be null"); return this; } - public DefaultRepositorySystem setInstaller( Installer installer ) - { - this.installer = requireNonNull( installer, "installer cannot be null" ); + public DefaultRepositorySystem setInstaller(Installer installer) { + this.installer = requireNonNull(installer, "installer cannot be null"); return this; } - public DefaultRepositorySystem setDeployer( Deployer deployer ) - { - this.deployer = requireNonNull( deployer, "deployer cannot be null" ); + public DefaultRepositorySystem setDeployer(Deployer deployer) { + this.deployer = requireNonNull(deployer, "deployer cannot be null"); return this; } - public DefaultRepositorySystem setLocalRepositoryProvider( LocalRepositoryProvider localRepositoryProvider ) - { - this.localRepositoryProvider = requireNonNull( - localRepositoryProvider, "local repository provider cannot be null" ); + public DefaultRepositorySystem setLocalRepositoryProvider(LocalRepositoryProvider localRepositoryProvider) { + this.localRepositoryProvider = + requireNonNull(localRepositoryProvider, "local repository provider cannot be null"); return this; } - public DefaultRepositorySystem setSyncContextFactory( SyncContextFactory syncContextFactory ) - { - this.syncContextFactory = requireNonNull( syncContextFactory, "sync context factory cannot be null" ); + public DefaultRepositorySystem setSyncContextFactory(SyncContextFactory syncContextFactory) { + this.syncContextFactory = requireNonNull(syncContextFactory, "sync context factory cannot be null"); return this; } - public DefaultRepositorySystem setRemoteRepositoryManager( RemoteRepositoryManager remoteRepositoryManager ) - { - this.remoteRepositoryManager = requireNonNull( - remoteRepositoryManager, "remote repository provider cannot be null" ); + public DefaultRepositorySystem setRemoteRepositoryManager(RemoteRepositoryManager remoteRepositoryManager) { + this.remoteRepositoryManager = + requireNonNull(remoteRepositoryManager, "remote repository provider cannot be null"); return this; } - public DefaultRepositorySystem setRepositorySystemLifecycle( RepositorySystemLifecycle repositorySystemLifecycle ) - { - this.repositorySystemLifecycle = requireNonNull( - repositorySystemLifecycle, "repository system lifecycle cannot be null" ); + public DefaultRepositorySystem setRepositorySystemLifecycle(RepositorySystemLifecycle repositorySystemLifecycle) { + this.repositorySystemLifecycle = + requireNonNull(repositorySystemLifecycle, "repository system lifecycle cannot be null"); return this; } @Override - public VersionResult resolveVersion( RepositorySystemSession session, VersionRequest request ) - throws VersionResolutionException - { - validateSession( session ); - requireNonNull( request, "request cannot be null" ); + public VersionResult resolveVersion(RepositorySystemSession session, VersionRequest request) + throws VersionResolutionException { + validateSession(session); + requireNonNull(request, "request cannot be null"); - return versionResolver.resolveVersion( session, request ); + return versionResolver.resolveVersion(session, request); } @Override - public VersionRangeResult resolveVersionRange( RepositorySystemSession session, VersionRangeRequest request ) - throws VersionRangeResolutionException - { - validateSession( session ); - requireNonNull( request, "request cannot be null" ); + public VersionRangeResult resolveVersionRange(RepositorySystemSession session, VersionRangeRequest request) + throws VersionRangeResolutionException { + validateSession(session); + requireNonNull(request, "request cannot be null"); - return versionRangeResolver.resolveVersionRange( session, request ); + return versionRangeResolver.resolveVersionRange(session, request); } @Override - public ArtifactDescriptorResult readArtifactDescriptor( RepositorySystemSession session, - ArtifactDescriptorRequest request ) - throws ArtifactDescriptorException - { - validateSession( session ); - requireNonNull( request, "request cannot be null" ); + public ArtifactDescriptorResult readArtifactDescriptor( + RepositorySystemSession session, ArtifactDescriptorRequest request) throws ArtifactDescriptorException { + validateSession(session); + requireNonNull(request, "request cannot be null"); - return artifactDescriptorReader.readArtifactDescriptor( session, request ); + return artifactDescriptorReader.readArtifactDescriptor(session, request); } @Override - public ArtifactResult resolveArtifact( RepositorySystemSession session, ArtifactRequest request ) - throws ArtifactResolutionException - { - validateSession( session ); - requireNonNull( session, "session cannot be null" ); + public ArtifactResult resolveArtifact(RepositorySystemSession session, ArtifactRequest request) + throws ArtifactResolutionException { + validateSession(session); + requireNonNull(session, "session cannot be null"); - return artifactResolver.resolveArtifact( session, request ); + return artifactResolver.resolveArtifact(session, request); } @Override - public List resolveArtifacts( RepositorySystemSession session, - Collection requests ) - throws ArtifactResolutionException - { - validateSession( session ); - requireNonNull( requests, "requests cannot be null" ); + public List resolveArtifacts( + RepositorySystemSession session, Collection requests) + throws ArtifactResolutionException { + validateSession(session); + requireNonNull(requests, "requests cannot be null"); - return artifactResolver.resolveArtifacts( session, requests ); + return artifactResolver.resolveArtifacts(session, requests); } @Override - public List resolveMetadata( RepositorySystemSession session, - Collection requests ) - { - validateSession( session ); - requireNonNull( requests, "requests cannot be null" ); + public List resolveMetadata( + RepositorySystemSession session, Collection requests) { + validateSession(session); + requireNonNull(requests, "requests cannot be null"); - return metadataResolver.resolveMetadata( session, requests ); + return metadataResolver.resolveMetadata(session, requests); } @Override - public CollectResult collectDependencies( RepositorySystemSession session, CollectRequest request ) - throws DependencyCollectionException - { - validateSession( session ); - requireNonNull( request, "request cannot be null" ); + public CollectResult collectDependencies(RepositorySystemSession session, CollectRequest request) + throws DependencyCollectionException { + validateSession(session); + requireNonNull(request, "request cannot be null"); - return dependencyCollector.collectDependencies( session, request ); + return dependencyCollector.collectDependencies(session, request); } @Override - public DependencyResult resolveDependencies( RepositorySystemSession session, DependencyRequest request ) - throws DependencyResolutionException - { - validateSession( session ); - requireNonNull( request, "request cannot be null" ); + public DependencyResult resolveDependencies(RepositorySystemSession session, DependencyRequest request) + throws DependencyResolutionException { + validateSession(session); + requireNonNull(request, "request cannot be null"); - RequestTrace trace = RequestTrace.newChild( request.getTrace(), request ); + RequestTrace trace = RequestTrace.newChild(request.getTrace(), request); - DependencyResult result = new DependencyResult( request ); + DependencyResult result = new DependencyResult(request); DependencyCollectionException dce = null; ArtifactResolutionException are = null; - if ( request.getRoot() != null ) - { - result.setRoot( request.getRoot() ); - } - else if ( request.getCollectRequest() != null ) - { + if (request.getRoot() != null) { + result.setRoot(request.getRoot()); + } else if (request.getCollectRequest() != null) { CollectResult collectResult; - try - { - request.getCollectRequest().setTrace( trace ); - collectResult = dependencyCollector.collectDependencies( session, request.getCollectRequest() ); - } - catch ( DependencyCollectionException e ) - { + try { + request.getCollectRequest().setTrace(trace); + collectResult = dependencyCollector.collectDependencies(session, request.getCollectRequest()); + } catch (DependencyCollectionException e) { dce = e; collectResult = e.getResult(); } - result.setRoot( collectResult.getRoot() ); - result.setCycles( collectResult.getCycles() ); - result.setCollectExceptions( collectResult.getExceptions() ); - } - else - { - throw new NullPointerException( "dependency node and collect request cannot be null" ); + result.setRoot(collectResult.getRoot()); + result.setCycles(collectResult.getCycles()); + result.setCollectExceptions(collectResult.getExceptions()); + } else { + throw new NullPointerException("dependency node and collect request cannot be null"); } - ArtifactRequestBuilder builder = new ArtifactRequestBuilder( trace ); + ArtifactRequestBuilder builder = new ArtifactRequestBuilder(trace); DependencyFilter filter = request.getFilter(); - DependencyVisitor visitor = ( filter != null ) ? new FilteringDependencyVisitor( builder, filter ) : builder; - visitor = new TreeDependencyVisitor( visitor ); + DependencyVisitor visitor = (filter != null) ? new FilteringDependencyVisitor(builder, filter) : builder; + visitor = new TreeDependencyVisitor(visitor); - if ( result.getRoot() != null ) - { - result.getRoot().accept( visitor ); + if (result.getRoot() != null) { + result.getRoot().accept(visitor); } List requests = builder.getRequests(); List results; - try - { - results = artifactResolver.resolveArtifacts( session, requests ); - } - catch ( ArtifactResolutionException e ) - { + try { + results = artifactResolver.resolveArtifacts(session, requests); + } catch (ArtifactResolutionException e) { are = e; results = e.getResults(); } - result.setArtifactResults( results ); + result.setArtifactResults(results); - updateNodesWithResolvedArtifacts( results ); + updateNodesWithResolvedArtifacts(results); - if ( dce != null ) - { - throw new DependencyResolutionException( result, dce ); - } - else if ( are != null ) - { - throw new DependencyResolutionException( result, are ); + if (dce != null) { + throw new DependencyResolutionException(result, dce); + } else if (are != null) { + throw new DependencyResolutionException(result, are); } return result; } - private void updateNodesWithResolvedArtifacts( List results ) - { - for ( ArtifactResult result : results ) - { + private void updateNodesWithResolvedArtifacts(List results) { + for (ArtifactResult result : results) { Artifact artifact = result.getArtifact(); - if ( artifact != null ) - { - result.getRequest().getDependencyNode().setArtifact( artifact ); + if (artifact != null) { + result.getRequest().getDependencyNode().setArtifact(artifact); } } } @Override - public InstallResult install( RepositorySystemSession session, InstallRequest request ) - throws InstallationException - { - validateSession( session ); - requireNonNull( request, "request cannot be null" ); + public InstallResult install(RepositorySystemSession session, InstallRequest request) throws InstallationException { + validateSession(session); + requireNonNull(request, "request cannot be null"); - return installer.install( session, request ); + return installer.install(session, request); } @Override - public DeployResult deploy( RepositorySystemSession session, DeployRequest request ) - throws DeploymentException - { - validateSession( session ); - requireNonNull( request, "request cannot be null" ); + public DeployResult deploy(RepositorySystemSession session, DeployRequest request) throws DeploymentException { + validateSession(session); + requireNonNull(request, "request cannot be null"); - return deployer.deploy( session, request ); + return deployer.deploy(session, request); } @Override - public LocalRepositoryManager newLocalRepositoryManager( RepositorySystemSession session, - LocalRepository localRepository ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( localRepository, "localRepository cannot be null" ); - - try - { - return localRepositoryProvider.newLocalRepositoryManager( session, localRepository ); - } - catch ( NoLocalRepositoryManagerException e ) - { - throw new IllegalArgumentException( e.getMessage(), e ); + public LocalRepositoryManager newLocalRepositoryManager( + RepositorySystemSession session, LocalRepository localRepository) { + requireNonNull(session, "session cannot be null"); + requireNonNull(localRepository, "localRepository cannot be null"); + + try { + return localRepositoryProvider.newLocalRepositoryManager(session, localRepository); + } catch (NoLocalRepositoryManagerException e) { + throw new IllegalArgumentException(e.getMessage(), e); } } @Override - public SyncContext newSyncContext( RepositorySystemSession session, boolean shared ) - { - validateSession( session ); - return syncContextFactory.newInstance( session, shared ); + public SyncContext newSyncContext(RepositorySystemSession session, boolean shared) { + validateSession(session); + return syncContextFactory.newInstance(session, shared); } @Override - public List newResolutionRepositories( RepositorySystemSession session, - List repositories ) - { - validateSession( session ); - validateRepositories( repositories ); - - repositories = - remoteRepositoryManager.aggregateRepositories( session, new ArrayList(), repositories, - true ); + public List newResolutionRepositories( + RepositorySystemSession session, List repositories) { + validateSession(session); + validateRepositories(repositories); + + repositories = remoteRepositoryManager.aggregateRepositories( + session, new ArrayList(), repositories, true); return repositories; } @Override - public RemoteRepository newDeploymentRepository( RepositorySystemSession session, RemoteRepository repository ) - { - validateSession( session ); - requireNonNull( repository, "repository cannot be null" ); - - RemoteRepository.Builder builder = new RemoteRepository.Builder( repository ); - Authentication auth = session.getAuthenticationSelector().getAuthentication( repository ); - builder.setAuthentication( auth ); - Proxy proxy = session.getProxySelector().getProxy( repository ); - builder.setProxy( proxy ); + public RemoteRepository newDeploymentRepository(RepositorySystemSession session, RemoteRepository repository) { + validateSession(session); + requireNonNull(repository, "repository cannot be null"); + + RemoteRepository.Builder builder = new RemoteRepository.Builder(repository); + Authentication auth = session.getAuthenticationSelector().getAuthentication(repository); + builder.setAuthentication(auth); + Proxy proxy = session.getProxySelector().getProxy(repository); + builder.setProxy(proxy); return builder.build(); } @Override - public void addOnSystemEndedHandler( Runnable handler ) - { - repositorySystemLifecycle.addOnSystemEndedHandler( handler ); + public void addOnSystemEndedHandler(Runnable handler) { + repositorySystemLifecycle.addOnSystemEndedHandler(handler); } @Override - public void shutdown() - { - if ( shutdown.compareAndSet( false, true ) ) - { + public void shutdown() { + if (shutdown.compareAndSet(false, true)) { repositorySystemLifecycle.systemEnded(); } } - private void validateSession( RepositorySystemSession session ) - { - requireNonNull( session, "repository system session cannot be null" ); - invalidSession( session.getLocalRepositoryManager(), "local repository manager" ); - invalidSession( session.getSystemProperties(), "system properties" ); - invalidSession( session.getUserProperties(), "user properties" ); - invalidSession( session.getConfigProperties(), "config properties" ); - invalidSession( session.getMirrorSelector(), "mirror selector" ); - invalidSession( session.getProxySelector(), "proxy selector" ); - invalidSession( session.getAuthenticationSelector(), "authentication selector" ); - invalidSession( session.getArtifactTypeRegistry(), "artifact type registry" ); - invalidSession( session.getData(), "data" ); - if ( shutdown.get() ) - { - throw new IllegalStateException( "repository system is already shut down" ); + private void validateSession(RepositorySystemSession session) { + requireNonNull(session, "repository system session cannot be null"); + invalidSession(session.getLocalRepositoryManager(), "local repository manager"); + invalidSession(session.getSystemProperties(), "system properties"); + invalidSession(session.getUserProperties(), "user properties"); + invalidSession(session.getConfigProperties(), "config properties"); + invalidSession(session.getMirrorSelector(), "mirror selector"); + invalidSession(session.getProxySelector(), "proxy selector"); + invalidSession(session.getAuthenticationSelector(), "authentication selector"); + invalidSession(session.getArtifactTypeRegistry(), "artifact type registry"); + invalidSession(session.getData(), "data"); + if (shutdown.get()) { + throw new IllegalStateException("repository system is already shut down"); } } - private void validateRepositories( List repositories ) - { - requireNonNull( repositories, "repositories cannot be null" ); - for ( RemoteRepository repository : repositories ) - { - requireNonNull( repository, "repository cannot be null" ); + private void validateRepositories(List repositories) { + requireNonNull(repositories, "repositories cannot be null"); + for (RemoteRepository repository : repositories) { + requireNonNull(repository, "repository cannot be null"); } } - private void invalidSession( Object obj, String name ) - { - requireNonNull( obj, "repository system session's " + name + " cannot be null" ); + private void invalidSession(Object obj, String name) { + requireNonNull(obj, "repository system session's " + name + " cannot be null"); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositorySystemLifecycle.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositorySystemLifecycle.java index 6aef7c0bc..0d462aa8c 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositorySystemLifecycle.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultRepositorySystemLifecycle.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import javax.inject.Inject; import javax.inject.Named; @@ -37,54 +36,42 @@ */ @Singleton @Named -public class DefaultRepositorySystemLifecycle - implements RepositorySystemLifecycle -{ +public class DefaultRepositorySystemLifecycle implements RepositorySystemLifecycle { private final AtomicBoolean shutdown; private final CopyOnWriteArrayList onSystemEndedHandlers; @Inject - public DefaultRepositorySystemLifecycle() - { - this.shutdown = new AtomicBoolean( false ); + public DefaultRepositorySystemLifecycle() { + this.shutdown = new AtomicBoolean(false); this.onSystemEndedHandlers = new CopyOnWriteArrayList<>(); } @Override - public void systemEnded() - { - if ( shutdown.compareAndSet( false, true ) ) - { + public void systemEnded() { + if (shutdown.compareAndSet(false, true)) { final ArrayList exceptions = new ArrayList<>(); - for ( Runnable onCloseHandler : onSystemEndedHandlers ) - { - try - { + for (Runnable onCloseHandler : onSystemEndedHandlers) { + try { onCloseHandler.run(); - } - catch ( Exception e ) - { - exceptions.add( e ); + } catch (Exception e) { + exceptions.add(e); } } - MultiRuntimeException.mayThrow( "system on-close handler failures", exceptions ); + MultiRuntimeException.mayThrow("system on-close handler failures", exceptions); } } @Override - public void addOnSystemEndedHandler( Runnable handler ) - { - requireNonNull( handler, "handler cannot be null" ); + public void addOnSystemEndedHandler(Runnable handler) { + requireNonNull(handler, "handler cannot be null"); requireNotShutdown(); - onSystemEndedHandlers.add( 0, handler ); + onSystemEndedHandlers.add(0, handler); } - private void requireNotShutdown() - { - if ( shutdown.get() ) - { - throw new IllegalStateException( "repository system is already shut down" ); + private void requireNotShutdown() { + if (shutdown.get()) { + throw new IllegalStateException("repository system is already shut down"); } } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultTrackingFileManager.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultTrackingFileManager.java index 4269ce987..793ece141 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultTrackingFileManager.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultTrackingFileManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import javax.inject.Named; import javax.inject.Singleton; @@ -41,84 +40,64 @@ */ @Singleton @Named -public final class DefaultTrackingFileManager - implements TrackingFileManager -{ - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultTrackingFileManager.class ); +public final class DefaultTrackingFileManager implements TrackingFileManager { + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTrackingFileManager.class); @Override - public Properties read( File file ) - { + public Properties read(File file) { Path filePath = file.toPath(); - if ( Files.isRegularFile( filePath ) ) - { - try ( InputStream stream = Files.newInputStream( filePath ) ) - { + if (Files.isRegularFile(filePath)) { + try (InputStream stream = Files.newInputStream(filePath)) { Properties props = new Properties(); - props.load( stream ); + props.load(stream); return props; - } - catch ( IOException e ) - { - LOGGER.warn( "Failed to read tracking file '{}'", file, e ); - throw new UncheckedIOException( e ); + } catch (IOException e) { + LOGGER.warn("Failed to read tracking file '{}'", file, e); + throw new UncheckedIOException(e); } } return null; } @Override - public Properties update( File file, Map updates ) - { + public Properties update(File file, Map updates) { Path filePath = file.toPath(); Properties props = new Properties(); - try - { - Files.createDirectories( filePath.getParent() ); - } - catch ( IOException e ) - { - LOGGER.warn( "Failed to create tracking file parent '{}'", file, e ); - throw new UncheckedIOException( e ); + try { + Files.createDirectories(filePath.getParent()); + } catch (IOException e) { + LOGGER.warn("Failed to create tracking file parent '{}'", file, e); + throw new UncheckedIOException(e); } - try - { - if ( Files.isReadable( filePath ) ) - { - try ( InputStream stream = Files.newInputStream( filePath ) ) - { - props.load( stream ); + try { + if (Files.isReadable(filePath)) { + try (InputStream stream = Files.newInputStream(filePath)) { + props.load(stream); } } - for ( Map.Entry update : updates.entrySet() ) - { - if ( update.getValue() == null ) - { - props.remove( update.getKey() ); - } - else - { - props.setProperty( update.getKey(), update.getValue() ); + for (Map.Entry update : updates.entrySet()) { + if (update.getValue() == null) { + props.remove(update.getKey()); + } else { + props.setProperty(update.getKey(), update.getValue()); } } - FileUtils.writeFile( filePath, p -> - { - try ( OutputStream stream = Files.newOutputStream( p ) ) - { - LOGGER.debug( "Writing tracking file '{}'", file ); - props.store( stream, "NOTE: This is a Maven Resolver internal implementation file" - + ", its format can be changed without prior notice." ); + FileUtils.writeFile(filePath, p -> { + try (OutputStream stream = Files.newOutputStream(p)) { + LOGGER.debug("Writing tracking file '{}'", file); + props.store( + stream, + "NOTE: This is a Maven Resolver internal implementation file" + + ", its format can be changed without prior notice."); } - } ); - } - catch ( IOException e ) - { - LOGGER.warn( "Failed to write tracking file '{}'", file, e ); - throw new UncheckedIOException( e ); + }); + } catch (IOException e) { + LOGGER.warn("Failed to write tracking file '{}'", file, e); + throw new UncheckedIOException(e); } return props; diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultTransporterProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultTransporterProvider.java index 07ba82035..f7d10b19d 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultTransporterProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultTransporterProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,17 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import static java.util.Objects.requireNonNull; import java.util.Set; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.spi.connector.transport.Transporter; @@ -40,111 +38,91 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; + /** */ @Singleton @Named -public final class DefaultTransporterProvider - implements TransporterProvider, Service -{ +public final class DefaultTransporterProvider implements TransporterProvider, Service { - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultTransporterProvider.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTransporterProvider.class); private Collection factories = new ArrayList<>(); - public DefaultTransporterProvider() - { + public DefaultTransporterProvider() { // enables default constructor } @Inject - DefaultTransporterProvider( Set transporterFactories ) - { - setTransporterFactories( transporterFactories ); + DefaultTransporterProvider(Set transporterFactories) { + setTransporterFactories(transporterFactories); } - public void initService( ServiceLocator locator ) - { - setTransporterFactories( locator.getServices( TransporterFactory.class ) ); + public void initService(ServiceLocator locator) { + setTransporterFactories(locator.getServices(TransporterFactory.class)); } - public DefaultTransporterProvider addTransporterFactory( TransporterFactory factory ) - { - factories.add( requireNonNull( factory, "transporter factory cannot be null" ) ); + public DefaultTransporterProvider addTransporterFactory(TransporterFactory factory) { + factories.add(requireNonNull(factory, "transporter factory cannot be null")); return this; } - public DefaultTransporterProvider setTransporterFactories( Collection factories ) - { - if ( factories == null ) - { + public DefaultTransporterProvider setTransporterFactories(Collection factories) { + if (factories == null) { this.factories = new ArrayList<>(); - } - else - { + } else { this.factories = factories; } return this; } - public Transporter newTransporter( RepositorySystemSession session, RemoteRepository repository ) - throws NoTransporterException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); + public Transporter newTransporter(RepositorySystemSession session, RemoteRepository repository) + throws NoTransporterException { + requireNonNull(session, "session cannot be null"); + requireNonNull(repository, "repository cannot be null"); - PrioritizedComponents factories = new PrioritizedComponents<>( session ); - for ( TransporterFactory factory : this.factories ) - { - factories.add( factory, factory.getPriority() ); + PrioritizedComponents factories = new PrioritizedComponents<>(session); + for (TransporterFactory factory : this.factories) { + factories.add(factory, factory.getPriority()); } List errors = new ArrayList<>(); - for ( PrioritizedComponent factory : factories.getEnabled() ) - { - try - { - Transporter transporter = factory.getComponent().newInstance( session, repository ); - - if ( LOGGER.isDebugEnabled() ) - { - StringBuilder buffer = new StringBuilder( 256 ); - buffer.append( "Using transporter " ).append( transporter.getClass().getSimpleName() ); - Utils.appendClassLoader( buffer, transporter ); - buffer.append( " with priority " ).append( factory.getPriority() ); - buffer.append( " for " ).append( repository.getUrl() ); - LOGGER.debug( buffer.toString() ); + for (PrioritizedComponent factory : factories.getEnabled()) { + try { + Transporter transporter = factory.getComponent().newInstance(session, repository); + + if (LOGGER.isDebugEnabled()) { + StringBuilder buffer = new StringBuilder(256); + buffer.append("Using transporter ") + .append(transporter.getClass().getSimpleName()); + Utils.appendClassLoader(buffer, transporter); + buffer.append(" with priority ").append(factory.getPriority()); + buffer.append(" for ").append(repository.getUrl()); + LOGGER.debug(buffer.toString()); } return transporter; - } - catch ( NoTransporterException e ) - { + } catch (NoTransporterException e) { // continue and try next factory - errors.add( e ); + errors.add(e); } } - if ( LOGGER.isDebugEnabled() && errors.size() > 1 ) - { - for ( Exception e : errors ) - { - LOGGER.debug( "Could not obtain transporter factory for {}", repository, e ); + if (LOGGER.isDebugEnabled() && errors.size() > 1) { + for (Exception e : errors) { + LOGGER.debug("Could not obtain transporter factory for {}", repository, e); } } - StringBuilder buffer = new StringBuilder( 256 ); - if ( factories.isEmpty() ) - { - buffer.append( "No transporter factories registered" ); - } - else - { - buffer.append( "Cannot access " ).append( repository.getUrl() ); - buffer.append( " using the registered transporter factories: " ); - factories.list( buffer ); + StringBuilder buffer = new StringBuilder(256); + if (factories.isEmpty()) { + buffer.append("No transporter factories registered"); + } else { + buffer.append("Cannot access ").append(repository.getUrl()); + buffer.append(" using the registered transporter factories: "); + factories.list(buffer); } - throw new NoTransporterException( repository, buffer.toString(), errors.size() == 1 ? errors.get( 0 ) : null ); + throw new NoTransporterException(repository, buffer.toString(), errors.size() == 1 ? errors.get(0) : null); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultUpdateCheckManager.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultUpdateCheckManager.java index 188d849ed..9d2df9505 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultUpdateCheckManager.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultUpdateCheckManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,21 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import static java.util.Objects.requireNonNull; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.SessionData; import org.eclipse.aether.artifact.Artifact; @@ -54,15 +52,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static java.util.Objects.requireNonNull; + /** */ @Singleton @Named -public class DefaultUpdateCheckManager - implements UpdateCheckManager, Service -{ +public class DefaultUpdateCheckManager implements UpdateCheckManager, Service { - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultUpdatePolicyAnalyzer.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultUpdatePolicyAnalyzer.class); private TrackingFileManager trackingFileManager; @@ -74,11 +72,9 @@ public class DefaultUpdateCheckManager private static final String NOT_FOUND = ""; - static final Object SESSION_CHECKS = new Object() - { + static final Object SESSION_CHECKS = new Object() { @Override - public String toString() - { + public String toString() { return "updateCheckManager.checks"; } }; @@ -91,517 +87,424 @@ public String toString() private static final int STATE_DISABLED = 2; - public DefaultUpdateCheckManager() - { + public DefaultUpdateCheckManager() { // default ctor for ServiceLocator } @Inject - DefaultUpdateCheckManager( TrackingFileManager trackingFileManager, UpdatePolicyAnalyzer updatePolicyAnalyzer ) - { - setTrackingFileManager( trackingFileManager ); - setUpdatePolicyAnalyzer( updatePolicyAnalyzer ); + DefaultUpdateCheckManager(TrackingFileManager trackingFileManager, UpdatePolicyAnalyzer updatePolicyAnalyzer) { + setTrackingFileManager(trackingFileManager); + setUpdatePolicyAnalyzer(updatePolicyAnalyzer); } - public void initService( ServiceLocator locator ) - { - setTrackingFileManager( locator.getService( TrackingFileManager.class ) ); - setUpdatePolicyAnalyzer( locator.getService( UpdatePolicyAnalyzer.class ) ); + public void initService(ServiceLocator locator) { + setTrackingFileManager(locator.getService(TrackingFileManager.class)); + setUpdatePolicyAnalyzer(locator.getService(UpdatePolicyAnalyzer.class)); } - public DefaultUpdateCheckManager setTrackingFileManager( TrackingFileManager trackingFileManager ) - { - this.trackingFileManager = requireNonNull( trackingFileManager ); + public DefaultUpdateCheckManager setTrackingFileManager(TrackingFileManager trackingFileManager) { + this.trackingFileManager = requireNonNull(trackingFileManager); return this; } - public DefaultUpdateCheckManager setUpdatePolicyAnalyzer( UpdatePolicyAnalyzer updatePolicyAnalyzer ) - { - this.updatePolicyAnalyzer = requireNonNull( updatePolicyAnalyzer, "update policy analyzer cannot be null" ); + public DefaultUpdateCheckManager setUpdatePolicyAnalyzer(UpdatePolicyAnalyzer updatePolicyAnalyzer) { + this.updatePolicyAnalyzer = requireNonNull(updatePolicyAnalyzer, "update policy analyzer cannot be null"); return this; } - public void checkArtifact( RepositorySystemSession session, UpdateCheck check ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( check, "check cannot be null" ); - if ( check.getLocalLastUpdated() != 0 - && !isUpdatedRequired( session, check.getLocalLastUpdated(), check.getPolicy() ) ) - { - LOGGER.debug( "Skipped remote request for {}, locally installed artifact up-to-date", check.getItem() ); + public void checkArtifact(RepositorySystemSession session, UpdateCheck check) { + requireNonNull(session, "session cannot be null"); + requireNonNull(check, "check cannot be null"); + if (check.getLocalLastUpdated() != 0 + && !isUpdatedRequired(session, check.getLocalLastUpdated(), check.getPolicy())) { + LOGGER.debug("Skipped remote request for {}, locally installed artifact up-to-date", check.getItem()); - check.setRequired( false ); + check.setRequired(false); return; } Artifact artifact = check.getItem(); RemoteRepository repository = check.getRepository(); - File artifactFile = requireNonNull( check.getFile(), String.format( "The artifact '%s' has no file attached", - artifact ) ); + File artifactFile = + requireNonNull(check.getFile(), String.format("The artifact '%s' has no file attached", artifact)); boolean fileExists = check.isFileValid() && artifactFile.exists(); - File touchFile = getArtifactTouchFile( artifactFile ); - Properties props = read( touchFile ); + File touchFile = getArtifactTouchFile(artifactFile); + Properties props = read(touchFile); - String updateKey = getUpdateKey( session, artifactFile, repository ); - String dataKey = getDataKey( repository ); + String updateKey = getUpdateKey(session, artifactFile, repository); + String dataKey = getDataKey(repository); - String error = getError( props, dataKey ); + String error = getError(props, dataKey); long lastUpdated; - if ( error == null ) - { - if ( fileExists ) - { + if (error == null) { + if (fileExists) { // last update was successful lastUpdated = artifactFile.lastModified(); - } - else - { + } else { // this is the first attempt ever lastUpdated = 0L; } - } - else if ( error.isEmpty() ) - { + } else if (error.isEmpty()) { // artifact did not exist - lastUpdated = getLastUpdated( props, dataKey ); - } - else - { + lastUpdated = getLastUpdated(props, dataKey); + } else { // artifact could not be transferred - String transferKey = getTransferKey( session, repository ); - lastUpdated = getLastUpdated( props, transferKey ); + String transferKey = getTransferKey(session, repository); + lastUpdated = getLastUpdated(props, transferKey); } - if ( lastUpdated == 0L ) - { - check.setRequired( true ); - } - else if ( isAlreadyUpdated( session, updateKey ) ) - { - LOGGER.debug( "Skipped remote request for {}, already updated during this session", check.getItem() ); - - check.setRequired( false ); - if ( error != null ) - { - check.setException( newException( error, artifact, repository ) ); - } - } - else if ( isUpdatedRequired( session, lastUpdated, check.getPolicy() ) ) - { - check.setRequired( true ); - } - else if ( fileExists ) - { - LOGGER.debug( "Skipped remote request for {}, locally cached artifact up-to-date", check.getItem() ); + if (lastUpdated == 0L) { + check.setRequired(true); + } else if (isAlreadyUpdated(session, updateKey)) { + LOGGER.debug("Skipped remote request for {}, already updated during this session", check.getItem()); - check.setRequired( false ); - } - else - { - int errorPolicy = Utils.getPolicy( session, artifact, repository ); - int cacheFlag = getCacheFlag( error ); - if ( ( errorPolicy & cacheFlag ) != 0 ) - { - check.setRequired( false ); - check.setException( newException( error, artifact, repository ) ); + check.setRequired(false); + if (error != null) { + check.setException(newException(error, artifact, repository)); } - else - { - check.setRequired( true ); + } else if (isUpdatedRequired(session, lastUpdated, check.getPolicy())) { + check.setRequired(true); + } else if (fileExists) { + LOGGER.debug("Skipped remote request for {}, locally cached artifact up-to-date", check.getItem()); + + check.setRequired(false); + } else { + int errorPolicy = Utils.getPolicy(session, artifact, repository); + int cacheFlag = getCacheFlag(error); + if ((errorPolicy & cacheFlag) != 0) { + check.setRequired(false); + check.setException(newException(error, artifact, repository)); + } else { + check.setRequired(true); } } } - private static int getCacheFlag( String error ) - { - if ( error == null || error.isEmpty() ) - { + private static int getCacheFlag(String error) { + if (error == null || error.isEmpty()) { return ResolutionErrorPolicy.CACHE_NOT_FOUND; - } - else - { + } else { return ResolutionErrorPolicy.CACHE_TRANSFER_ERROR; } } - private ArtifactTransferException newException( String error, Artifact artifact, RemoteRepository repository ) - { - if ( error == null || error.isEmpty() ) - { - return new ArtifactNotFoundException( artifact, repository, artifact - + " was not found in " + repository.getUrl() + " during a previous attempt. This failure was" - + " cached in the local repository and" - + " resolution is not reattempted until the update interval of " + repository.getId() - + " has elapsed or updates are forced", true ); - } - else - { - return new ArtifactTransferException( artifact, repository, artifact + " failed to transfer from " - + repository.getUrl() + " during a previous attempt. This failure" - + " was cached in the local repository and" - + " resolution is not reattempted until the update interval of " + repository.getId() - + " has elapsed or updates are forced. Original error: " + error, true ); + private ArtifactTransferException newException(String error, Artifact artifact, RemoteRepository repository) { + if (error == null || error.isEmpty()) { + return new ArtifactNotFoundException( + artifact, + repository, + artifact + + " was not found in " + repository.getUrl() + + " during a previous attempt. This failure was" + + " cached in the local repository and" + + " resolution is not reattempted until the update interval of " + repository.getId() + + " has elapsed or updates are forced", + true); + } else { + return new ArtifactTransferException( + artifact, + repository, + artifact + " failed to transfer from " + + repository.getUrl() + " during a previous attempt. This failure" + + " was cached in the local repository and" + + " resolution is not reattempted until the update interval of " + repository.getId() + + " has elapsed or updates are forced. Original error: " + error, + true); } } - public void checkMetadata( RepositorySystemSession session, UpdateCheck check ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( check, "check cannot be null" ); - if ( check.getLocalLastUpdated() != 0 - && !isUpdatedRequired( session, check.getLocalLastUpdated(), check.getPolicy() ) ) - { - LOGGER.debug( "Skipped remote request for {} locally installed metadata up-to-date", check.getItem() ); + public void checkMetadata(RepositorySystemSession session, UpdateCheck check) { + requireNonNull(session, "session cannot be null"); + requireNonNull(check, "check cannot be null"); + if (check.getLocalLastUpdated() != 0 + && !isUpdatedRequired(session, check.getLocalLastUpdated(), check.getPolicy())) { + LOGGER.debug("Skipped remote request for {} locally installed metadata up-to-date", check.getItem()); - check.setRequired( false ); + check.setRequired(false); return; } Metadata metadata = check.getItem(); RemoteRepository repository = check.getRepository(); - File metadataFile = requireNonNull( check.getFile(), String.format( "The metadata '%s' has no file attached", - metadata ) ); + File metadataFile = + requireNonNull(check.getFile(), String.format("The metadata '%s' has no file attached", metadata)); boolean fileExists = check.isFileValid() && metadataFile.exists(); - File touchFile = getMetadataTouchFile( metadataFile ); - Properties props = read( touchFile ); + File touchFile = getMetadataTouchFile(metadataFile); + Properties props = read(touchFile); - String updateKey = getUpdateKey( session, metadataFile, repository ); - String dataKey = getDataKey( metadataFile ); + String updateKey = getUpdateKey(session, metadataFile, repository); + String dataKey = getDataKey(metadataFile); - String error = getError( props, dataKey ); + String error = getError(props, dataKey); long lastUpdated; - if ( error == null ) - { - if ( fileExists ) - { + if (error == null) { + if (fileExists) { // last update was successful - lastUpdated = getLastUpdated( props, dataKey ); - } - else - { + lastUpdated = getLastUpdated(props, dataKey); + } else { // this is the first attempt ever lastUpdated = 0L; } - } - else if ( error.isEmpty() ) - { + } else if (error.isEmpty()) { // metadata did not exist - lastUpdated = getLastUpdated( props, dataKey ); - } - else - { + lastUpdated = getLastUpdated(props, dataKey); + } else { // metadata could not be transferred - String transferKey = getTransferKey( session, metadataFile, repository ); - lastUpdated = getLastUpdated( props, transferKey ); + String transferKey = getTransferKey(session, metadataFile, repository); + lastUpdated = getLastUpdated(props, transferKey); } - if ( lastUpdated == 0L ) - { - check.setRequired( true ); - } - else if ( isAlreadyUpdated( session, updateKey ) ) - { - LOGGER.debug( "Skipped remote request for {}, already updated during this session", check.getItem() ); - - check.setRequired( false ); - if ( error != null ) - { - check.setException( newException( error, metadata, repository ) ); - } - } - else if ( isUpdatedRequired( session, lastUpdated, check.getPolicy() ) ) - { - check.setRequired( true ); - } - else if ( fileExists ) - { - LOGGER.debug( "Skipped remote request for {}, locally cached metadata up-to-date", check.getItem() ); + if (lastUpdated == 0L) { + check.setRequired(true); + } else if (isAlreadyUpdated(session, updateKey)) { + LOGGER.debug("Skipped remote request for {}, already updated during this session", check.getItem()); - check.setRequired( false ); - } - else - { - int errorPolicy = Utils.getPolicy( session, metadata, repository ); - int cacheFlag = getCacheFlag( error ); - if ( ( errorPolicy & cacheFlag ) != 0 ) - { - check.setRequired( false ); - check.setException( newException( error, metadata, repository ) ); + check.setRequired(false); + if (error != null) { + check.setException(newException(error, metadata, repository)); } - else - { - check.setRequired( true ); + } else if (isUpdatedRequired(session, lastUpdated, check.getPolicy())) { + check.setRequired(true); + } else if (fileExists) { + LOGGER.debug("Skipped remote request for {}, locally cached metadata up-to-date", check.getItem()); + + check.setRequired(false); + } else { + int errorPolicy = Utils.getPolicy(session, metadata, repository); + int cacheFlag = getCacheFlag(error); + if ((errorPolicy & cacheFlag) != 0) { + check.setRequired(false); + check.setException(newException(error, metadata, repository)); + } else { + check.setRequired(true); } } } - private MetadataTransferException newException( String error, Metadata metadata, RemoteRepository repository ) - { - if ( error == null || error.isEmpty() ) - { - return new MetadataNotFoundException( metadata, repository, metadata + " was not found in " - + repository.getUrl() + " during a previous attempt." - + " This failure was cached in the local repository and" - + " resolution is not be reattempted until the update interval of " + repository.getId() - + " has elapsed or updates are forced", true ); - } - else - { - return new MetadataTransferException( metadata, repository, metadata + " failed to transfer from " - + repository.getUrl() + " during a previous attempt." - + " This failure was cached in the local repository and" - + " resolution will not be reattempted until the update interval of " + repository.getId() - + " has elapsed or updates are forced. Original error: " + error, true ); + private MetadataTransferException newException(String error, Metadata metadata, RemoteRepository repository) { + if (error == null || error.isEmpty()) { + return new MetadataNotFoundException( + metadata, + repository, + metadata + " was not found in " + + repository.getUrl() + " during a previous attempt." + + " This failure was cached in the local repository and" + + " resolution is not be reattempted until the update interval of " + repository.getId() + + " has elapsed or updates are forced", + true); + } else { + return new MetadataTransferException( + metadata, + repository, + metadata + " failed to transfer from " + + repository.getUrl() + " during a previous attempt." + + " This failure was cached in the local repository and" + + " resolution will not be reattempted until the update interval of " + repository.getId() + + " has elapsed or updates are forced. Original error: " + error, + true); } } - private long getLastUpdated( Properties props, String key ) - { - String value = props.getProperty( key + UPDATED_KEY_SUFFIX, "" ); - try - { - return ( value.length() > 0 ) ? Long.parseLong( value ) : 1; - } - catch ( NumberFormatException e ) - { - LOGGER.debug( "Cannot parse last updated date {}, ignoring it", value, e ); + private long getLastUpdated(Properties props, String key) { + String value = props.getProperty(key + UPDATED_KEY_SUFFIX, ""); + try { + return (value.length() > 0) ? Long.parseLong(value) : 1; + } catch (NumberFormatException e) { + LOGGER.debug("Cannot parse last updated date {}, ignoring it", value, e); return 1; } } - private String getError( Properties props, String key ) - { - return props.getProperty( key + ERROR_KEY_SUFFIX ); + private String getError(Properties props, String key) { + return props.getProperty(key + ERROR_KEY_SUFFIX); } - private File getArtifactTouchFile( File artifactFile ) - { - return new File( artifactFile.getPath() + UPDATED_KEY_SUFFIX ); + private File getArtifactTouchFile(File artifactFile) { + return new File(artifactFile.getPath() + UPDATED_KEY_SUFFIX); } - private File getMetadataTouchFile( File metadataFile ) - { - return new File( metadataFile.getParent(), "resolver-status.properties" ); + private File getMetadataTouchFile(File metadataFile) { + return new File(metadataFile.getParent(), "resolver-status.properties"); } - private String getDataKey( RemoteRepository repository ) - { + private String getDataKey(RemoteRepository repository) { Set mirroredUrls = Collections.emptySet(); - if ( repository.isRepositoryManager() ) - { + if (repository.isRepositoryManager()) { mirroredUrls = new TreeSet<>(); - for ( RemoteRepository mirroredRepository : repository.getMirroredRepositories() ) - { - mirroredUrls.add( normalizeRepoUrl( mirroredRepository.getUrl() ) ); + for (RemoteRepository mirroredRepository : repository.getMirroredRepositories()) { + mirroredUrls.add(normalizeRepoUrl(mirroredRepository.getUrl())); } } - StringBuilder buffer = new StringBuilder( 1024 ); + StringBuilder buffer = new StringBuilder(1024); - buffer.append( normalizeRepoUrl( repository.getUrl() ) ); - for ( String mirroredUrl : mirroredUrls ) - { - buffer.append( '+' ).append( mirroredUrl ); + buffer.append(normalizeRepoUrl(repository.getUrl())); + for (String mirroredUrl : mirroredUrls) { + buffer.append('+').append(mirroredUrl); } return buffer.toString(); } - private String getTransferKey( RepositorySystemSession session, RemoteRepository repository ) - { - return getRepoKey( session, repository ); + private String getTransferKey(RepositorySystemSession session, RemoteRepository repository) { + return getRepoKey(session, repository); } - private String getDataKey( File metadataFile ) - { + private String getDataKey(File metadataFile) { return metadataFile.getName(); } - private String getTransferKey( RepositorySystemSession session, File metadataFile, - RemoteRepository repository ) - { - return metadataFile.getName() + '/' + getRepoKey( session, repository ); + private String getTransferKey(RepositorySystemSession session, File metadataFile, RemoteRepository repository) { + return metadataFile.getName() + '/' + getRepoKey(session, repository); } - private String getRepoKey( RepositorySystemSession session, RemoteRepository repository ) - { - StringBuilder buffer = new StringBuilder( 128 ); + private String getRepoKey(RepositorySystemSession session, RemoteRepository repository) { + StringBuilder buffer = new StringBuilder(128); Proxy proxy = repository.getProxy(); - if ( proxy != null ) - { - buffer.append( AuthenticationDigest.forProxy( session, repository ) ).append( '@' ); - buffer.append( proxy.getHost() ).append( ':' ).append( proxy.getPort() ).append( '>' ); + if (proxy != null) { + buffer.append(AuthenticationDigest.forProxy(session, repository)).append('@'); + buffer.append(proxy.getHost()).append(':').append(proxy.getPort()).append('>'); } - buffer.append( AuthenticationDigest.forRepository( session, repository ) ).append( '@' ); + buffer.append(AuthenticationDigest.forRepository(session, repository)).append('@'); - buffer.append( repository.getContentType() ).append( '-' ); - buffer.append( repository.getId() ).append( '-' ); - buffer.append( normalizeRepoUrl( repository.getUrl() ) ); + buffer.append(repository.getContentType()).append('-'); + buffer.append(repository.getId()).append('-'); + buffer.append(normalizeRepoUrl(repository.getUrl())); return buffer.toString(); } - private String normalizeRepoUrl( String url ) - { + private String normalizeRepoUrl(String url) { String result = url; - if ( url != null && url.length() > 0 && !url.endsWith( "/" ) ) - { + if (url != null && url.length() > 0 && !url.endsWith("/")) { result = url + '/'; } return result; } - private String getUpdateKey( RepositorySystemSession session, File file, RemoteRepository repository ) - { - return file.getAbsolutePath() + '|' + getRepoKey( session, repository ); + private String getUpdateKey(RepositorySystemSession session, File file, RemoteRepository repository) { + return file.getAbsolutePath() + '|' + getRepoKey(session, repository); } - private int getSessionState( RepositorySystemSession session ) - { - String mode = ConfigUtils.getString( session, "enabled", CONFIG_PROP_SESSION_STATE ); - if ( Boolean.parseBoolean( mode ) || "enabled".equalsIgnoreCase( mode ) ) - { + private int getSessionState(RepositorySystemSession session) { + String mode = ConfigUtils.getString(session, "enabled", CONFIG_PROP_SESSION_STATE); + if (Boolean.parseBoolean(mode) || "enabled".equalsIgnoreCase(mode)) { // perform update check at most once per session, regardless of update policy return STATE_ENABLED; - } - else if ( "bypass".equalsIgnoreCase( mode ) ) - { + } else if ("bypass".equalsIgnoreCase(mode)) { // evaluate update policy but record update in session to prevent potential future checks return STATE_BYPASS; - } - else - { + } else { // no session state at all, always evaluate update policy return STATE_DISABLED; } } - private boolean isAlreadyUpdated( RepositorySystemSession session, Object updateKey ) - { - if ( getSessionState( session ) >= STATE_BYPASS ) - { + private boolean isAlreadyUpdated(RepositorySystemSession session, Object updateKey) { + if (getSessionState(session) >= STATE_BYPASS) { return false; } SessionData data = session.getData(); - Object checkedFiles = data.get( SESSION_CHECKS ); - if ( !( checkedFiles instanceof Map ) ) - { + Object checkedFiles = data.get(SESSION_CHECKS); + if (!(checkedFiles instanceof Map)) { return false; } - return ( (Map) checkedFiles ).containsKey( updateKey ); + return ((Map) checkedFiles).containsKey(updateKey); } - @SuppressWarnings( "unchecked" ) - private void setUpdated( RepositorySystemSession session, Object updateKey ) - { - if ( getSessionState( session ) >= STATE_DISABLED ) - { + @SuppressWarnings("unchecked") + private void setUpdated(RepositorySystemSession session, Object updateKey) { + if (getSessionState(session) >= STATE_DISABLED) { return; } SessionData data = session.getData(); - Object checkedFiles = data.computeIfAbsent( SESSION_CHECKS, () -> new ConcurrentHashMap<>( 256 ) ); - ( (Map) checkedFiles ).put( updateKey, Boolean.TRUE ); + Object checkedFiles = data.computeIfAbsent(SESSION_CHECKS, () -> new ConcurrentHashMap<>(256)); + ((Map) checkedFiles).put(updateKey, Boolean.TRUE); } - private boolean isUpdatedRequired( RepositorySystemSession session, long lastModified, String policy ) - { - return updatePolicyAnalyzer.isUpdatedRequired( session, lastModified, policy ); + private boolean isUpdatedRequired(RepositorySystemSession session, long lastModified, String policy) { + return updatePolicyAnalyzer.isUpdatedRequired(session, lastModified, policy); } - private Properties read( File touchFile ) - { - Properties props = trackingFileManager.read( touchFile ); - return ( props != null ) ? props : new Properties(); + private Properties read(File touchFile) { + Properties props = trackingFileManager.read(touchFile); + return (props != null) ? props : new Properties(); } - public void touchArtifact( RepositorySystemSession session, UpdateCheck check ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( check, "check cannot be null" ); + public void touchArtifact(RepositorySystemSession session, UpdateCheck check) { + requireNonNull(session, "session cannot be null"); + requireNonNull(check, "check cannot be null"); File artifactFile = check.getFile(); - File touchFile = getArtifactTouchFile( artifactFile ); + File touchFile = getArtifactTouchFile(artifactFile); - String updateKey = getUpdateKey( session, artifactFile, check.getRepository() ); - String dataKey = getDataKey( check.getAuthoritativeRepository() ); - String transferKey = getTransferKey( session, check.getRepository() ); + String updateKey = getUpdateKey(session, artifactFile, check.getRepository()); + String dataKey = getDataKey(check.getAuthoritativeRepository()); + String transferKey = getTransferKey(session, check.getRepository()); - setUpdated( session, updateKey ); - Properties props = write( touchFile, dataKey, transferKey, check.getException() ); + setUpdated(session, updateKey); + Properties props = write(touchFile, dataKey, transferKey, check.getException()); - if ( artifactFile.exists() && !hasErrors( props ) ) - { + if (artifactFile.exists() && !hasErrors(props)) { touchFile.delete(); } } - private boolean hasErrors( Properties props ) - { - for ( Object key : props.keySet() ) - { - if ( key.toString().endsWith( ERROR_KEY_SUFFIX ) ) - { + private boolean hasErrors(Properties props) { + for (Object key : props.keySet()) { + if (key.toString().endsWith(ERROR_KEY_SUFFIX)) { return true; } } return false; } - public void touchMetadata( RepositorySystemSession session, UpdateCheck check ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( check, "check cannot be null" ); + public void touchMetadata(RepositorySystemSession session, UpdateCheck check) { + requireNonNull(session, "session cannot be null"); + requireNonNull(check, "check cannot be null"); File metadataFile = check.getFile(); - File touchFile = getMetadataTouchFile( metadataFile ); + File touchFile = getMetadataTouchFile(metadataFile); - String updateKey = getUpdateKey( session, metadataFile, check.getRepository() ); - String dataKey = getDataKey( metadataFile ); - String transferKey = getTransferKey( session, metadataFile, check.getRepository() ); + String updateKey = getUpdateKey(session, metadataFile, check.getRepository()); + String dataKey = getDataKey(metadataFile); + String transferKey = getTransferKey(session, metadataFile, check.getRepository()); - setUpdated( session, updateKey ); - write( touchFile, dataKey, transferKey, check.getException() ); + setUpdated(session, updateKey); + write(touchFile, dataKey, transferKey, check.getException()); } - private Properties write( File touchFile, String dataKey, String transferKey, Exception error ) - { + private Properties write(File touchFile, String dataKey, String transferKey, Exception error) { Map updates = new HashMap<>(); - String timestamp = Long.toString( System.currentTimeMillis() ); - - if ( error == null ) - { - updates.put( dataKey + ERROR_KEY_SUFFIX, null ); - updates.put( dataKey + UPDATED_KEY_SUFFIX, timestamp ); - updates.put( transferKey + UPDATED_KEY_SUFFIX, null ); - } - else if ( error instanceof ArtifactNotFoundException || error instanceof MetadataNotFoundException ) - { - updates.put( dataKey + ERROR_KEY_SUFFIX, NOT_FOUND ); - updates.put( dataKey + UPDATED_KEY_SUFFIX, timestamp ); - updates.put( transferKey + UPDATED_KEY_SUFFIX, null ); - } - else - { + String timestamp = Long.toString(System.currentTimeMillis()); + + if (error == null) { + updates.put(dataKey + ERROR_KEY_SUFFIX, null); + updates.put(dataKey + UPDATED_KEY_SUFFIX, timestamp); + updates.put(transferKey + UPDATED_KEY_SUFFIX, null); + } else if (error instanceof ArtifactNotFoundException || error instanceof MetadataNotFoundException) { + updates.put(dataKey + ERROR_KEY_SUFFIX, NOT_FOUND); + updates.put(dataKey + UPDATED_KEY_SUFFIX, timestamp); + updates.put(transferKey + UPDATED_KEY_SUFFIX, null); + } else { String msg = error.getMessage(); - if ( msg == null || msg.isEmpty() ) - { + if (msg == null || msg.isEmpty()) { msg = error.getClass().getSimpleName(); } - updates.put( dataKey + ERROR_KEY_SUFFIX, msg ); - updates.put( dataKey + UPDATED_KEY_SUFFIX, null ); - updates.put( transferKey + UPDATED_KEY_SUFFIX, timestamp ); + updates.put(dataKey + ERROR_KEY_SUFFIX, msg); + updates.put(dataKey + UPDATED_KEY_SUFFIX, null); + updates.put(transferKey + UPDATED_KEY_SUFFIX, timestamp); } - return trackingFileManager.update( touchFile, updates ); + return trackingFileManager.update(touchFile, updates); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultUpdatePolicyAnalyzer.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultUpdatePolicyAnalyzer.java index 253ac594b..3e3df2bac 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultUpdatePolicyAnalyzer.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/DefaultUpdatePolicyAnalyzer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ - -import java.util.Calendar; +package org.eclipse.aether.internal.impl; import javax.inject.Named; import javax.inject.Singleton; +import java.util.Calendar; + import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.impl.UpdatePolicyAnalyzer; import org.eclipse.aether.repository.RepositoryPolicy; @@ -36,110 +35,87 @@ */ @Singleton @Named -public class DefaultUpdatePolicyAnalyzer - implements UpdatePolicyAnalyzer -{ +public class DefaultUpdatePolicyAnalyzer implements UpdatePolicyAnalyzer { - private static final Logger LOGGER = LoggerFactory.getLogger( DefaultUpdatePolicyAnalyzer.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultUpdatePolicyAnalyzer.class); - public DefaultUpdatePolicyAnalyzer() - { + public DefaultUpdatePolicyAnalyzer() { // enables default constructor } - public String getEffectiveUpdatePolicy( RepositorySystemSession session, String policy1, String policy2 ) - { - requireNonNull( session, "session cannot be null" ); - return ordinalOfUpdatePolicy( policy1 ) < ordinalOfUpdatePolicy( policy2 ) ? policy1 : policy2; + public String getEffectiveUpdatePolicy(RepositorySystemSession session, String policy1, String policy2) { + requireNonNull(session, "session cannot be null"); + return ordinalOfUpdatePolicy(policy1) < ordinalOfUpdatePolicy(policy2) ? policy1 : policy2; } - @SuppressWarnings( { "checkstyle:magicnumber" } ) - private int ordinalOfUpdatePolicy( String policy ) - { - if ( RepositoryPolicy.UPDATE_POLICY_DAILY.equals( policy ) ) - { + @SuppressWarnings({"checkstyle:magicnumber"}) + private int ordinalOfUpdatePolicy(String policy) { + if (RepositoryPolicy.UPDATE_POLICY_DAILY.equals(policy)) { return 1440; - } - else if ( RepositoryPolicy.UPDATE_POLICY_ALWAYS.equals( policy ) ) - { + } else if (RepositoryPolicy.UPDATE_POLICY_ALWAYS.equals(policy)) { return 0; - } - else if ( policy != null && policy.startsWith( RepositoryPolicy.UPDATE_POLICY_INTERVAL ) ) - { - return getMinutes( policy ); - } - else - { + } else if (policy != null && policy.startsWith(RepositoryPolicy.UPDATE_POLICY_INTERVAL)) { + return getMinutes(policy); + } else { // assume "never" return Integer.MAX_VALUE; } } - public boolean isUpdatedRequired( RepositorySystemSession session, long lastModified, String policy ) - { - requireNonNull( session, "session cannot be null" ); + public boolean isUpdatedRequired(RepositorySystemSession session, long lastModified, String policy) { + requireNonNull(session, "session cannot be null"); boolean checkForUpdates; - if ( policy == null ) - { + if (policy == null) { policy = ""; } - if ( RepositoryPolicy.UPDATE_POLICY_ALWAYS.equals( policy ) ) - { + if (RepositoryPolicy.UPDATE_POLICY_ALWAYS.equals(policy)) { checkForUpdates = true; - } - else if ( RepositoryPolicy.UPDATE_POLICY_DAILY.equals( policy ) ) - { + } else if (RepositoryPolicy.UPDATE_POLICY_DAILY.equals(policy)) { Calendar cal = Calendar.getInstance(); - cal.set( Calendar.HOUR_OF_DAY, 0 ); - cal.set( Calendar.MINUTE, 0 ); - cal.set( Calendar.SECOND, 0 ); - cal.set( Calendar.MILLISECOND, 0 ); + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); checkForUpdates = cal.getTimeInMillis() > lastModified; - } - else if ( policy.startsWith( RepositoryPolicy.UPDATE_POLICY_INTERVAL ) ) - { - int minutes = getMinutes( policy ); + } else if (policy.startsWith(RepositoryPolicy.UPDATE_POLICY_INTERVAL)) { + int minutes = getMinutes(policy); Calendar cal = Calendar.getInstance(); - cal.add( Calendar.MINUTE, -minutes ); + cal.add(Calendar.MINUTE, -minutes); checkForUpdates = cal.getTimeInMillis() > lastModified; - } - else - { + } else { // assume "never" checkForUpdates = false; - if ( !RepositoryPolicy.UPDATE_POLICY_NEVER.equals( policy ) ) - { - LOGGER.warn( "Unknown repository update policy '{}', assuming '{}'", - policy, RepositoryPolicy.UPDATE_POLICY_NEVER ); + if (!RepositoryPolicy.UPDATE_POLICY_NEVER.equals(policy)) { + LOGGER.warn( + "Unknown repository update policy '{}', assuming '{}'", + policy, + RepositoryPolicy.UPDATE_POLICY_NEVER); } } return checkForUpdates; } - @SuppressWarnings( { "checkstyle:magicnumber" } ) - private int getMinutes( String policy ) - { + @SuppressWarnings({"checkstyle:magicnumber"}) + private int getMinutes(String policy) { int minutes; - try - { - String s = policy.substring( RepositoryPolicy.UPDATE_POLICY_INTERVAL.length() + 1 ); - minutes = Integer.parseInt( s ); - } - catch ( RuntimeException e ) - { + try { + String s = policy.substring(RepositoryPolicy.UPDATE_POLICY_INTERVAL.length() + 1); + minutes = Integer.parseInt(s); + } catch (RuntimeException e) { minutes = 24 * 60; - LOGGER.warn( "Non-parseable repository update policy '{}', assuming '{}:1440'", - policy, RepositoryPolicy.UPDATE_POLICY_INTERVAL ); + LOGGER.warn( + "Non-parseable repository update policy '{}', assuming '{}:1440'", + policy, + RepositoryPolicy.UPDATE_POLICY_INTERVAL); } return minutes; } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManager.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManager.java index 0b0e398a5..8191f0b09 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManager.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import java.io.File; import java.util.Collection; @@ -25,9 +24,6 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; - -import static java.util.Objects.requireNonNull; - import java.util.Objects; import java.util.Properties; @@ -39,6 +35,8 @@ import org.eclipse.aether.repository.LocalArtifactResult; import org.eclipse.aether.repository.RemoteRepository; +import static java.util.Objects.requireNonNull; + /** * These are implementation details for enhanced local repository manager, subject to change without prior notice. * Repositories from which a cached artifact was resolved are tracked in a properties file named @@ -58,9 +56,7 @@ * * @see EnhancedLocalRepositoryManagerFactory */ -class EnhancedLocalRepositoryManager - extends SimpleLocalRepositoryManager -{ +class EnhancedLocalRepositoryManager extends SimpleLocalRepositoryManager { private static final String LOCAL_REPO_ID = ""; @@ -70,91 +66,76 @@ class EnhancedLocalRepositoryManager private final LocalPathPrefixComposer localPathPrefixComposer; - EnhancedLocalRepositoryManager( File basedir, - LocalPathComposer localPathComposer, - String trackingFilename, - TrackingFileManager trackingFileManager, - LocalPathPrefixComposer localPathPrefixComposer ) - { - super( basedir, "enhanced", localPathComposer ); - this.trackingFilename = requireNonNull( trackingFilename ); - this.trackingFileManager = requireNonNull( trackingFileManager ); - this.localPathPrefixComposer = requireNonNull( localPathPrefixComposer ); + EnhancedLocalRepositoryManager( + File basedir, + LocalPathComposer localPathComposer, + String trackingFilename, + TrackingFileManager trackingFileManager, + LocalPathPrefixComposer localPathPrefixComposer) { + super(basedir, "enhanced", localPathComposer); + this.trackingFilename = requireNonNull(trackingFilename); + this.trackingFileManager = requireNonNull(trackingFileManager); + this.localPathPrefixComposer = requireNonNull(localPathPrefixComposer); } - private String concatPaths( String prefix, String artifactPath ) - { - if ( prefix == null || prefix.isEmpty() ) - { + private String concatPaths(String prefix, String artifactPath) { + if (prefix == null || prefix.isEmpty()) { return artifactPath; } return prefix + '/' + artifactPath; } @Override - public String getPathForLocalArtifact( Artifact artifact ) - { + public String getPathForLocalArtifact(Artifact artifact) { return concatPaths( - localPathPrefixComposer.getPathPrefixForLocalArtifact( artifact ), - super.getPathForLocalArtifact( artifact ) - ); + localPathPrefixComposer.getPathPrefixForLocalArtifact(artifact), + super.getPathForLocalArtifact(artifact)); } @Override - public String getPathForRemoteArtifact( Artifact artifact, RemoteRepository repository, String context ) - { + public String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context) { return concatPaths( - localPathPrefixComposer.getPathPrefixForRemoteArtifact( artifact, repository ), - super.getPathForRemoteArtifact( artifact, repository, context ) - ); + localPathPrefixComposer.getPathPrefixForRemoteArtifact(artifact, repository), + super.getPathForRemoteArtifact(artifact, repository, context)); } @Override - public String getPathForLocalMetadata( Metadata metadata ) - { + public String getPathForLocalMetadata(Metadata metadata) { return concatPaths( - localPathPrefixComposer.getPathPrefixForLocalMetadata( metadata ), - super.getPathForLocalMetadata( metadata ) - ); + localPathPrefixComposer.getPathPrefixForLocalMetadata(metadata), + super.getPathForLocalMetadata(metadata)); } @Override - public String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repository, String context ) - { + public String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context) { return concatPaths( - localPathPrefixComposer.getPathPrefixForRemoteMetadata( metadata, repository ), - super.getPathForRemoteMetadata( metadata, repository, context ) - ); + localPathPrefixComposer.getPathPrefixForRemoteMetadata(metadata, repository), + super.getPathForRemoteMetadata(metadata, repository, context)); } @Override - public LocalArtifactResult find( RepositorySystemSession session, LocalArtifactRequest request ) - { + public LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request) { Artifact artifact = request.getArtifact(); - LocalArtifactResult result = new LocalArtifactResult( request ); + LocalArtifactResult result = new LocalArtifactResult(request); String path; File file; // Local repository CANNOT have timestamped installed, they are created only during deploy - if ( Objects.equals( artifact.getVersion(), artifact.getBaseVersion() ) ) - { - path = getPathForLocalArtifact( artifact ); - file = new File( getRepository().getBasedir(), path ); - checkFind( file, result ); + if (Objects.equals(artifact.getVersion(), artifact.getBaseVersion())) { + path = getPathForLocalArtifact(artifact); + file = new File(getRepository().getBasedir(), path); + checkFind(file, result); } - if ( !result.isAvailable() ) - { - for ( RemoteRepository repository : request.getRepositories() ) - { - path = getPathForRemoteArtifact( artifact, repository, request.getContext() ); - file = new File( getRepository().getBasedir(), path ); + if (!result.isAvailable()) { + for (RemoteRepository repository : request.getRepositories()) { + path = getPathForRemoteArtifact(artifact, repository, request.getContext()); + file = new File(getRepository().getBasedir(), path); - checkFind( file, result ); + checkFind(file, result); - if ( result.isAvailable() ) - { + if (result.isAvailable()) { break; } } @@ -163,141 +144,112 @@ public LocalArtifactResult find( RepositorySystemSession session, LocalArtifactR return result; } - private void checkFind( File file, LocalArtifactResult result ) - { - if ( file.isFile() ) - { - result.setFile( file ); + private void checkFind(File file, LocalArtifactResult result) { + if (file.isFile()) { + result.setFile(file); - Properties props = readRepos( file ); + Properties props = readRepos(file); - if ( props.get( getKey( file, LOCAL_REPO_ID ) ) != null ) - { + if (props.get(getKey(file, LOCAL_REPO_ID)) != null) { // artifact installed into the local repo is always accepted - result.setAvailable( true ); - } - else - { + result.setAvailable(true); + } else { String context = result.getRequest().getContext(); - for ( RemoteRepository repository : result.getRequest().getRepositories() ) - { - if ( props.get( getKey( file, getRepositoryKey( repository, context ) ) ) != null ) - { + for (RemoteRepository repository : result.getRequest().getRepositories()) { + if (props.get(getKey(file, getRepositoryKey(repository, context))) != null) { // artifact downloaded from remote repository is accepted only downloaded from request // repositories - result.setAvailable( true ); - result.setRepository( repository ); + result.setAvailable(true); + result.setRepository(repository); break; } } - if ( !result.isAvailable() && !isTracked( props, file ) ) - { + if (!result.isAvailable() && !isTracked(props, file)) { /* * NOTE: The artifact is present but not tracked at all, for inter-op with simple local repo, assume * the artifact was locally installed. */ - result.setAvailable( true ); + result.setAvailable(true); } } } } @Override - public void add( RepositorySystemSession session, LocalArtifactRegistration request ) - { + public void add(RepositorySystemSession session, LocalArtifactRegistration request) { Collection repositories; - if ( request.getRepository() == null ) - { - repositories = Collections.singleton( LOCAL_REPO_ID ); + if (request.getRepository() == null) { + repositories = Collections.singleton(LOCAL_REPO_ID); + } else { + repositories = getRepositoryKeys(request.getRepository(), request.getContexts()); } - else - { - repositories = getRepositoryKeys( request.getRepository(), request.getContexts() ); - } - if ( request.getRepository() == null ) - { - addArtifact( request.getArtifact(), repositories, null, null ); - } - else - { - for ( String context : request.getContexts() ) - { - addArtifact( request.getArtifact(), repositories, request.getRepository(), context ); + if (request.getRepository() == null) { + addArtifact(request.getArtifact(), repositories, null, null); + } else { + for (String context : request.getContexts()) { + addArtifact(request.getArtifact(), repositories, request.getRepository(), context); } } } - private Collection getRepositoryKeys( RemoteRepository repository, Collection contexts ) - { + private Collection getRepositoryKeys(RemoteRepository repository, Collection contexts) { Collection keys = new HashSet<>(); - if ( contexts != null ) - { - for ( String context : contexts ) - { - keys.add( getRepositoryKey( repository, context ) ); + if (contexts != null) { + for (String context : contexts) { + keys.add(getRepositoryKey(repository, context)); } } return keys; } - private void addArtifact( Artifact artifact, Collection repositories, RemoteRepository repository, - String context ) - { - requireNonNull( artifact, "artifact cannot be null" ); - String path = repository == null ? getPathForLocalArtifact( artifact ) - : getPathForRemoteArtifact( artifact, repository, context ); - File file = new File( getRepository().getBasedir(), path ); - addRepo( file, repositories ); + private void addArtifact( + Artifact artifact, Collection repositories, RemoteRepository repository, String context) { + requireNonNull(artifact, "artifact cannot be null"); + String path = repository == null + ? getPathForLocalArtifact(artifact) + : getPathForRemoteArtifact(artifact, repository, context); + File file = new File(getRepository().getBasedir(), path); + addRepo(file, repositories); } - private Properties readRepos( File artifactFile ) - { - File trackingFile = getTrackingFile( artifactFile ); + private Properties readRepos(File artifactFile) { + File trackingFile = getTrackingFile(artifactFile); - Properties props = trackingFileManager.read( trackingFile ); + Properties props = trackingFileManager.read(trackingFile); - return ( props != null ) ? props : new Properties(); + return (props != null) ? props : new Properties(); } - private void addRepo( File artifactFile, Collection repositories ) - { + private void addRepo(File artifactFile, Collection repositories) { Map updates = new HashMap<>(); - for ( String repository : repositories ) - { - updates.put( getKey( artifactFile, repository ), "" ); + for (String repository : repositories) { + updates.put(getKey(artifactFile, repository), ""); } - File trackingFile = getTrackingFile( artifactFile ); + File trackingFile = getTrackingFile(artifactFile); - trackingFileManager.update( trackingFile, updates ); + trackingFileManager.update(trackingFile, updates); } - private File getTrackingFile( File artifactFile ) - { - return new File( artifactFile.getParentFile(), trackingFilename ); + private File getTrackingFile(File artifactFile) { + return new File(artifactFile.getParentFile(), trackingFilename); } - private String getKey( File file, String repository ) - { + private String getKey(File file, String repository) { return file.getName() + '>' + repository; } - private boolean isTracked( Properties props, File file ) - { - if ( props != null ) - { + private boolean isTracked(Properties props, File file) { + if (props != null) { String keyPrefix = file.getName() + '>'; - for ( Object key : props.keySet() ) - { - if ( key.toString().startsWith( keyPrefix ) ) - { + for (Object key : props.keySet()) { + if (key.toString().startsWith(keyPrefix)) { return true; } } } return false; } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManagerFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManagerFactory.java index 98fcddb55..44b7f6ba4 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManagerFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManagerFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import javax.inject.Inject; import javax.inject.Named; @@ -42,10 +41,8 @@ * emulating physically separated artifact caches per remote repository. */ @Singleton -@Named( "enhanced" ) -public class EnhancedLocalRepositoryManagerFactory - implements LocalRepositoryManagerFactory, Service -{ +@Named("enhanced") +public class EnhancedLocalRepositoryManagerFactory implements LocalRepositoryManagerFactory, Service { private static final String CONFIG_PROP_TRACKING_FILENAME = "aether.enhancedLocalRepository.trackingFilename"; private static final String DEFAULT_TRACKING_FILENAME = "_remote.repositories"; @@ -58,62 +55,55 @@ public class EnhancedLocalRepositoryManagerFactory private LocalPathPrefixComposerFactory localPathPrefixComposerFactory; - public EnhancedLocalRepositoryManagerFactory() - { + public EnhancedLocalRepositoryManagerFactory() { // no arg ctor for ServiceLocator } @Inject - public EnhancedLocalRepositoryManagerFactory( final LocalPathComposer localPathComposer, - final TrackingFileManager trackingFileManager, - final LocalPathPrefixComposerFactory localPathPrefixComposerFactory ) - { - this.localPathComposer = requireNonNull( localPathComposer ); - this.trackingFileManager = requireNonNull( trackingFileManager ); - this.localPathPrefixComposerFactory = requireNonNull( localPathPrefixComposerFactory ); + public EnhancedLocalRepositoryManagerFactory( + final LocalPathComposer localPathComposer, + final TrackingFileManager trackingFileManager, + final LocalPathPrefixComposerFactory localPathPrefixComposerFactory) { + this.localPathComposer = requireNonNull(localPathComposer); + this.trackingFileManager = requireNonNull(trackingFileManager); + this.localPathPrefixComposerFactory = requireNonNull(localPathPrefixComposerFactory); } @Override - public void initService( final ServiceLocator locator ) - { - this.localPathComposer = requireNonNull( locator.getService( LocalPathComposer.class ) ); - this.trackingFileManager = requireNonNull( locator.getService( TrackingFileManager.class ) ); + public void initService(final ServiceLocator locator) { + this.localPathComposer = requireNonNull(locator.getService(LocalPathComposer.class)); + this.trackingFileManager = requireNonNull(locator.getService(TrackingFileManager.class)); this.localPathPrefixComposerFactory = new DefaultLocalPathPrefixComposerFactory(); } @Override - public LocalRepositoryManager newInstance( RepositorySystemSession session, LocalRepository repository ) - throws NoLocalRepositoryManagerException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); - - String trackingFilename = ConfigUtils.getString( session, "", CONFIG_PROP_TRACKING_FILENAME ); - if ( trackingFilename.isEmpty() || trackingFilename.contains( "/" ) || trackingFilename.contains( "\\" ) - || trackingFilename.contains( ".." ) ) - { + public LocalRepositoryManager newInstance(RepositorySystemSession session, LocalRepository repository) + throws NoLocalRepositoryManagerException { + requireNonNull(session, "session cannot be null"); + requireNonNull(repository, "repository cannot be null"); + + String trackingFilename = ConfigUtils.getString(session, "", CONFIG_PROP_TRACKING_FILENAME); + if (trackingFilename.isEmpty() + || trackingFilename.contains("/") + || trackingFilename.contains("\\") + || trackingFilename.contains("..")) { trackingFilename = DEFAULT_TRACKING_FILENAME; } - if ( "".equals( repository.getContentType() ) || "default".equals( repository.getContentType() ) ) - { + if ("".equals(repository.getContentType()) || "default".equals(repository.getContentType())) { return new EnhancedLocalRepositoryManager( repository.getBasedir(), localPathComposer, trackingFilename, trackingFileManager, - localPathPrefixComposerFactory.createComposer( session ) - ); - } - else - { - throw new NoLocalRepositoryManagerException( repository ); + localPathPrefixComposerFactory.createComposer(session)); + } else { + throw new NoLocalRepositoryManagerException(repository); } } @Override - public float getPriority() - { + public float getPriority() { return priority; } @@ -123,10 +113,8 @@ public float getPriority() * @param priority The priority. * @return This component for chaining, never {@code null}. */ - public EnhancedLocalRepositoryManagerFactory setPriority( float priority ) - { + public EnhancedLocalRepositoryManagerFactory setPriority(float priority) { this.priority = priority; return this; } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/FailChecksumPolicy.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/FailChecksumPolicy.java index 70d36c6ca..33249ba70 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/FailChecksumPolicy.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/FailChecksumPolicy.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.transfer.ChecksumFailureException; import org.eclipse.aether.transfer.TransferResource; @@ -25,19 +24,14 @@ /** * Implements {@link org.eclipse.aether.repository.RepositoryPolicy#CHECKSUM_POLICY_FAIL}. */ -final class FailChecksumPolicy - extends AbstractChecksumPolicy -{ +final class FailChecksumPolicy extends AbstractChecksumPolicy { - FailChecksumPolicy( TransferResource resource ) - { - super( resource ); + FailChecksumPolicy(TransferResource resource) { + super(resource); } @Override - public boolean onTransferChecksumFailure( ChecksumFailureException error ) - { + public boolean onTransferChecksumFailure(ChecksumFailureException error) { return false; } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathComposer.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathComposer.java index e4c842154..1da7d8498 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathComposer.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathComposer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.metadata.Metadata; @@ -28,8 +27,7 @@ * * @since 1.8.1 */ -public interface LocalPathComposer -{ +public interface LocalPathComposer { /** * Gets the relative path for a locally installed (local=true) or remotely cached (local=false) artifact. * @@ -37,7 +35,7 @@ public interface LocalPathComposer * @param local {@code true} if artifact is locally installed or {@code false} if artifact is remotely cached. * @return A relative path representing artifact path. */ - String getPathForArtifact( Artifact artifact, boolean local ); + String getPathForArtifact(Artifact artifact, boolean local); /** * Gets the relative path for locally installed (repositoryKey=local) or remotely cached metadata. The @@ -49,5 +47,5 @@ public interface LocalPathComposer * @param repositoryKey The repository key, never {@code null}. * @return A relative path representing metadata path. */ - String getPathForMetadata( Metadata metadata, String repositoryKey ); + String getPathForMetadata(Metadata metadata, String repositoryKey); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposer.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposer.java index 4b7d3fa0d..36774f3d9 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposer.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.metadata.Metadata; @@ -28,15 +27,14 @@ * * @since 1.8.1 */ -public interface LocalPathPrefixComposer -{ +public interface LocalPathPrefixComposer { /** * Gets the path prefix for a locally installed artifact. * * @param artifact The artifact for which to determine the prefix, must not be {@code null}. * @return The prefix, may be {@code null} (note: {@code null}s and empty strings are treated equally). */ - String getPathPrefixForLocalArtifact( Artifact artifact ); + String getPathPrefixForLocalArtifact(Artifact artifact); /** * Gets the path prefix for an artifact cached from a remote repository. @@ -45,7 +43,7 @@ public interface LocalPathPrefixComposer * @param repository The remote repository, never {@code null}. * @return The prefix, may be {@code null} (note: {@code null}s and empty strings are treated equally). */ - String getPathPrefixForRemoteArtifact( Artifact artifact, RemoteRepository repository ); + String getPathPrefixForRemoteArtifact(Artifact artifact, RemoteRepository repository); /** * Gets the path prefix for locally installed metadata. @@ -53,7 +51,7 @@ public interface LocalPathPrefixComposer * @param metadata The metadata for which to determine the prefix, must not be {@code null}. * @return The prefix, may be {@code null} (note: {@code null}s and empty strings are treated equally). */ - String getPathPrefixForLocalMetadata( Metadata metadata ); + String getPathPrefixForLocalMetadata(Metadata metadata); /** * Gets the path prefix for metadata cached from a remote repository. @@ -62,5 +60,5 @@ public interface LocalPathPrefixComposer * @param repository The remote repository, never {@code null}. * @return The prefix, may be {@code null} (note: {@code null}s and empty strings are treated equally). */ - String getPathPrefixForRemoteMetadata( Metadata metadata, RemoteRepository repository ); + String getPathPrefixForRemoteMetadata(Metadata metadata, RemoteRepository repository); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposerFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposerFactory.java index 2ef76937e..240e876ee 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposerFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposerFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.RepositorySystemSession; @@ -26,13 +25,12 @@ * * @since 1.8.1 */ -public interface LocalPathPrefixComposerFactory -{ +public interface LocalPathPrefixComposerFactory { /** * Creates {@link LocalPathPrefixComposer} instance out of whatever configuration it finds in passed in session. * * @param session The repository session, never {@code null}. * @return The created instance, never {@code null}. */ - LocalPathPrefixComposer createComposer( RepositorySystemSession session ); + LocalPathPrefixComposer createComposer(RepositorySystemSession session); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposerFactorySupport.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposerFactorySupport.java index eff360ebb..cf1587bda 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposerFactorySupport.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LocalPathPrefixComposerFactorySupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -36,8 +35,7 @@ * @see DefaultLocalPathPrefixComposerFactory * @since 1.8.1 */ -public abstract class LocalPathPrefixComposerFactorySupport implements LocalPathPrefixComposerFactory -{ +public abstract class LocalPathPrefixComposerFactorySupport implements LocalPathPrefixComposerFactory { protected static final String CONF_PROP_SPLIT = "aether.enhancedLocalRepository.split"; protected static final boolean DEFAULT_SPLIT = false; @@ -76,67 +74,49 @@ public abstract class LocalPathPrefixComposerFactorySupport implements LocalPath protected static final String DEFAULT_SNAPSHOTS_PREFIX = "snapshots"; - protected boolean isSplit( RepositorySystemSession session ) - { - return ConfigUtils.getBoolean( - session, DEFAULT_SPLIT, CONF_PROP_SPLIT ); + protected boolean isSplit(RepositorySystemSession session) { + return ConfigUtils.getBoolean(session, DEFAULT_SPLIT, CONF_PROP_SPLIT); } - protected String getLocalPrefix( RepositorySystemSession session ) - { - return ConfigUtils.getString( - session, DEFAULT_LOCAL_PREFIX, CONF_PROP_LOCAL_PREFIX ); + protected String getLocalPrefix(RepositorySystemSession session) { + return ConfigUtils.getString(session, DEFAULT_LOCAL_PREFIX, CONF_PROP_LOCAL_PREFIX); } - protected boolean isSplitLocal( RepositorySystemSession session ) - { - return ConfigUtils.getBoolean( - session, DEFAULT_SPLIT_LOCAL, CONF_PROP_SPLIT_LOCAL ); + protected boolean isSplitLocal(RepositorySystemSession session) { + return ConfigUtils.getBoolean(session, DEFAULT_SPLIT_LOCAL, CONF_PROP_SPLIT_LOCAL); } - protected String getRemotePrefix( RepositorySystemSession session ) - { - return ConfigUtils.getString( - session, DEFAULT_REMOTE_PREFIX, CONF_PROP_REMOTE_PREFIX ); + protected String getRemotePrefix(RepositorySystemSession session) { + return ConfigUtils.getString(session, DEFAULT_REMOTE_PREFIX, CONF_PROP_REMOTE_PREFIX); } - protected boolean isSplitRemote( RepositorySystemSession session ) - { - return ConfigUtils.getBoolean( - session, DEFAULT_SPLIT_REMOTE, CONF_PROP_SPLIT_REMOTE ); + protected boolean isSplitRemote(RepositorySystemSession session) { + return ConfigUtils.getBoolean(session, DEFAULT_SPLIT_REMOTE, CONF_PROP_SPLIT_REMOTE); } - protected boolean isSplitRemoteRepository( RepositorySystemSession session ) - { - return ConfigUtils.getBoolean( - session, DEFAULT_SPLIT_REMOTE_REPOSITORY, CONF_PROP_SPLIT_REMOTE_REPOSITORY ); + protected boolean isSplitRemoteRepository(RepositorySystemSession session) { + return ConfigUtils.getBoolean(session, DEFAULT_SPLIT_REMOTE_REPOSITORY, CONF_PROP_SPLIT_REMOTE_REPOSITORY); } - protected boolean isSplitRemoteRepositoryLast( RepositorySystemSession session ) - { + protected boolean isSplitRemoteRepositoryLast(RepositorySystemSession session) { return ConfigUtils.getBoolean( - session, DEFAULT_SPLIT_REMOTE_REPOSITORY_LAST, CONF_PROP_SPLIT_REMOTE_REPOSITORY_LAST ); + session, DEFAULT_SPLIT_REMOTE_REPOSITORY_LAST, CONF_PROP_SPLIT_REMOTE_REPOSITORY_LAST); } - protected String getReleasesPrefix( RepositorySystemSession session ) - { - return ConfigUtils.getString( - session, DEFAULT_RELEASES_PREFIX, CONF_PROP_RELEASES_PREFIX ); + protected String getReleasesPrefix(RepositorySystemSession session) { + return ConfigUtils.getString(session, DEFAULT_RELEASES_PREFIX, CONF_PROP_RELEASES_PREFIX); } - protected String getSnapshotsPrefix( RepositorySystemSession session ) - { - return ConfigUtils.getString( - session, DEFAULT_SNAPSHOTS_PREFIX, CONF_PROP_SNAPSHOTS_PREFIX ); + protected String getSnapshotsPrefix(RepositorySystemSession session) { + return ConfigUtils.getString(session, DEFAULT_SNAPSHOTS_PREFIX, CONF_PROP_SNAPSHOTS_PREFIX); } /** * Support class for composers: it defines protected members for all the predefined configuration values and * provides default implementation for methods. Implementors may change it's behaviour by overriding methods. */ - @SuppressWarnings( "checkstyle:parameternumber" ) - protected abstract static class LocalPathPrefixComposerSupport implements LocalPathPrefixComposer - { + @SuppressWarnings("checkstyle:parameternumber") + protected abstract static class LocalPathPrefixComposerSupport implements LocalPathPrefixComposer { protected final boolean split; protected final String localPrefix; @@ -155,16 +135,16 @@ protected abstract static class LocalPathPrefixComposerSupport implements LocalP protected final String snapshotsPrefix; - protected LocalPathPrefixComposerSupport( boolean split, - String localPrefix, - boolean splitLocal, - String remotePrefix, - boolean splitRemote, - boolean splitRemoteRepository, - boolean splitRemoteRepositoryLast, - String releasesPrefix, - String snapshotsPrefix ) - { + protected LocalPathPrefixComposerSupport( + boolean split, + String localPrefix, + boolean splitLocal, + String remotePrefix, + boolean splitRemote, + boolean splitRemoteRepository, + boolean splitRemoteRepositoryLast, + String releasesPrefix, + String snapshotsPrefix) { this.split = split; this.localPrefix = localPrefix; this.splitLocal = splitLocal; @@ -177,85 +157,67 @@ protected LocalPathPrefixComposerSupport( boolean split, } @Override - public String getPathPrefixForLocalArtifact( Artifact artifact ) - { - if ( !split ) - { + public String getPathPrefixForLocalArtifact(Artifact artifact) { + if (!split) { return null; } String result = localPrefix; - if ( splitLocal ) - { - result += "/" + ( artifact.isSnapshot() ? snapshotsPrefix : releasesPrefix ); + if (splitLocal) { + result += "/" + (artifact.isSnapshot() ? snapshotsPrefix : releasesPrefix); } return result; } @Override - public String getPathPrefixForRemoteArtifact( Artifact artifact, RemoteRepository repository ) - { - if ( !split ) - { + public String getPathPrefixForRemoteArtifact(Artifact artifact, RemoteRepository repository) { + if (!split) { return null; } String result = remotePrefix; - if ( !splitRemoteRepositoryLast && splitRemoteRepository ) - { + if (!splitRemoteRepositoryLast && splitRemoteRepository) { result += "/" + repository.getId(); } - if ( splitRemote ) - { - result += "/" + ( artifact.isSnapshot() ? snapshotsPrefix : releasesPrefix ); + if (splitRemote) { + result += "/" + (artifact.isSnapshot() ? snapshotsPrefix : releasesPrefix); } - if ( splitRemoteRepositoryLast && splitRemoteRepository ) - { + if (splitRemoteRepositoryLast && splitRemoteRepository) { result += "/" + repository.getId(); } return result; } @Override - public String getPathPrefixForLocalMetadata( Metadata metadata ) - { - if ( !split ) - { + public String getPathPrefixForLocalMetadata(Metadata metadata) { + if (!split) { return null; } String result = localPrefix; - if ( splitLocal ) - { - result += "/" + ( isSnapshot( metadata ) ? snapshotsPrefix : releasesPrefix ); + if (splitLocal) { + result += "/" + (isSnapshot(metadata) ? snapshotsPrefix : releasesPrefix); } return result; } @Override - public String getPathPrefixForRemoteMetadata( Metadata metadata, RemoteRepository repository ) - { - if ( !split ) - { + public String getPathPrefixForRemoteMetadata(Metadata metadata, RemoteRepository repository) { + if (!split) { return null; } String result = remotePrefix; - if ( !splitRemoteRepositoryLast && splitRemoteRepository ) - { + if (!splitRemoteRepositoryLast && splitRemoteRepository) { result += "/" + repository.getId(); } - if ( splitRemote ) - { - result += "/" + ( isSnapshot( metadata ) ? snapshotsPrefix : releasesPrefix ); + if (splitRemote) { + result += "/" + (isSnapshot(metadata) ? snapshotsPrefix : releasesPrefix); } - if ( splitRemoteRepositoryLast && splitRemoteRepository ) - { + if (splitRemoteRepositoryLast && splitRemoteRepository) { result += "/" + repository.getId(); } return result; } - protected boolean isSnapshot( Metadata metadata ) - { - return !metadata.getVersion().isEmpty() - && metadata.getVersion().endsWith( "-SNAPSHOT" ); + protected boolean isSnapshot(Metadata metadata) { + return !metadata.getVersion().isEmpty() && metadata.getVersion().endsWith("-SNAPSHOT"); } } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LoggerFactoryProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LoggerFactoryProvider.java index 4a532e26c..10dcb4594 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LoggerFactoryProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/LoggerFactoryProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import javax.inject.Inject; import javax.inject.Named; @@ -31,17 +30,13 @@ */ @Named @Singleton -public class LoggerFactoryProvider - implements Provider -{ +public class LoggerFactoryProvider implements Provider { @Inject - @Named( "slf4j" ) + @Named("slf4j") private Provider slf4j; - public LoggerFactory get() - { - return slf4j.get(); + public LoggerFactory get() { + return slf4j.get(); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/Maven2RepositoryLayoutFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/Maven2RepositoryLayoutFactory.java index 46d2501f9..086991947 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/Maven2RepositoryLayoutFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/Maven2RepositoryLayoutFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import java.net.URI; import java.net.URISyntaxException; @@ -28,10 +31,6 @@ import java.util.Set; import java.util.stream.Collectors; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.internal.impl.checksum.DefaultChecksumAlgorithmFactorySelector; @@ -50,10 +49,8 @@ * Provides a Maven-2 repository layout for repositories with content type {@code "default"}. */ @Singleton -@Named( "maven2" ) -public final class Maven2RepositoryLayoutFactory - implements RepositoryLayoutFactory -{ +@Named("maven2") +public final class Maven2RepositoryLayoutFactory implements RepositoryLayoutFactory { public static final String CONFIG_PROP_CHECKSUMS_ALGORITHMS = "aether.checksums.algorithms"; @@ -68,8 +65,7 @@ public final class Maven2RepositoryLayoutFactory private final ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector; - public float getPriority() - { + public float getPriority() { return priority; } @@ -77,15 +73,13 @@ public float getPriority() * Service locator ctor. */ @Deprecated - public Maven2RepositoryLayoutFactory() - { - this( new DefaultChecksumAlgorithmFactorySelector() ); + public Maven2RepositoryLayoutFactory() { + this(new DefaultChecksumAlgorithmFactorySelector()); } @Inject - public Maven2RepositoryLayoutFactory( ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector ) - { - this.checksumAlgorithmFactorySelector = requireNonNull( checksumAlgorithmFactorySelector ); + public Maven2RepositoryLayoutFactory(ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector) { + this.checksumAlgorithmFactorySelector = requireNonNull(checksumAlgorithmFactorySelector); } /** @@ -94,96 +88,77 @@ public Maven2RepositoryLayoutFactory( ChecksumAlgorithmFactorySelector checksumA * @param priority The priority. * @return This component for chaining, never {@code null}. */ - public Maven2RepositoryLayoutFactory setPriority( float priority ) - { + public Maven2RepositoryLayoutFactory setPriority(float priority) { this.priority = priority; return this; } - public RepositoryLayout newInstance( RepositorySystemSession session, RemoteRepository repository ) - throws NoRepositoryLayoutException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); - if ( !"default".equals( repository.getContentType() ) ) - { - throw new NoRepositoryLayoutException( repository ); + public RepositoryLayout newInstance(RepositorySystemSession session, RemoteRepository repository) + throws NoRepositoryLayoutException { + requireNonNull(session, "session cannot be null"); + requireNonNull(repository, "repository cannot be null"); + if (!"default".equals(repository.getContentType())) { + throw new NoRepositoryLayoutException(repository); } List checksumsAlgorithms = checksumAlgorithmFactorySelector.selectList( - ConfigUtils.parseCommaSeparatedUniqueNames( ConfigUtils.getString( - session, DEFAULT_CHECKSUMS_ALGORITHMS, CONFIG_PROP_CHECKSUMS_ALGORITHMS ) ) - ); + ConfigUtils.parseCommaSeparatedUniqueNames(ConfigUtils.getString( + session, DEFAULT_CHECKSUMS_ALGORITHMS, CONFIG_PROP_CHECKSUMS_ALGORITHMS))); // ensure uniqueness of (potentially user set) extension list - Set omitChecksumsForExtensions = Arrays.stream( ConfigUtils.getString( - session, DEFAULT_OMIT_CHECKSUMS_FOR_EXTENSIONS, CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS ) - .split( "," ) - ).filter( s -> s != null && !s.trim().isEmpty() ).collect( Collectors.toSet() ); + Set omitChecksumsForExtensions = Arrays.stream(ConfigUtils.getString( + session, + DEFAULT_OMIT_CHECKSUMS_FOR_EXTENSIONS, + CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS) + .split(",")) + .filter(s -> s != null && !s.trim().isEmpty()) + .collect(Collectors.toSet()); // validation: enforce that all strings in this set are having leading dot - if ( omitChecksumsForExtensions.stream().anyMatch( s -> !s.startsWith( "." ) ) ) - { - throw new IllegalArgumentException( - String.format( - "The configuration %s contains illegal values: %s (all entries must start with '.' (dot))", - CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS, - omitChecksumsForExtensions - ) - ); + if (omitChecksumsForExtensions.stream().anyMatch(s -> !s.startsWith("."))) { + throw new IllegalArgumentException(String.format( + "The configuration %s contains illegal values: %s (all entries must start with '.' (dot))", + CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS, omitChecksumsForExtensions)); } return new Maven2RepositoryLayout( - checksumAlgorithmFactorySelector, - checksumsAlgorithms, - omitChecksumsForExtensions - ); + checksumAlgorithmFactorySelector, checksumsAlgorithms, omitChecksumsForExtensions); } - private static class Maven2RepositoryLayout - implements RepositoryLayout - { + private static class Maven2RepositoryLayout implements RepositoryLayout { private final ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector; private final List configuredChecksumAlgorithms; private final Set extensionsWithoutChecksums; - private Maven2RepositoryLayout( ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector, - List configuredChecksumAlgorithms, - Set extensionsWithoutChecksums ) - { - this.checksumAlgorithmFactorySelector = requireNonNull( checksumAlgorithmFactorySelector ); - this.configuredChecksumAlgorithms = Collections.unmodifiableList( configuredChecksumAlgorithms ); - this.extensionsWithoutChecksums = requireNonNull( extensionsWithoutChecksums ); + private Maven2RepositoryLayout( + ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector, + List configuredChecksumAlgorithms, + Set extensionsWithoutChecksums) { + this.checksumAlgorithmFactorySelector = requireNonNull(checksumAlgorithmFactorySelector); + this.configuredChecksumAlgorithms = Collections.unmodifiableList(configuredChecksumAlgorithms); + this.extensionsWithoutChecksums = requireNonNull(extensionsWithoutChecksums); } - private URI toUri( String path ) - { - try - { - return new URI( null, null, path, null ); - } - catch ( URISyntaxException e ) - { - throw new IllegalStateException( e ); + private URI toUri(String path) { + try { + return new URI(null, null, path, null); + } catch (URISyntaxException e) { + throw new IllegalStateException(e); } } @Override - public List getChecksumAlgorithmFactories() - { + public List getChecksumAlgorithmFactories() { return configuredChecksumAlgorithms; } @Override - public boolean hasChecksums( Artifact artifact ) - { + public boolean hasChecksums(Artifact artifact) { String artifactExtension = artifact.getExtension(); // ie. pom.asc - for ( String extensionWithoutChecksums : extensionsWithoutChecksums ) - { - if ( artifactExtension.endsWith( extensionWithoutChecksums ) ) - { + for (String extensionWithoutChecksums : extensionsWithoutChecksums) { + if (artifactExtension.endsWith(extensionWithoutChecksums)) { return false; } } @@ -191,85 +166,72 @@ public boolean hasChecksums( Artifact artifact ) } @Override - public URI getLocation( Artifact artifact, boolean upload ) - { - StringBuilder path = new StringBuilder( 128 ); + public URI getLocation(Artifact artifact, boolean upload) { + StringBuilder path = new StringBuilder(128); - path.append( artifact.getGroupId().replace( '.', '/' ) ).append( '/' ); + path.append(artifact.getGroupId().replace('.', '/')).append('/'); - path.append( artifact.getArtifactId() ).append( '/' ); + path.append(artifact.getArtifactId()).append('/'); - path.append( artifact.getBaseVersion() ).append( '/' ); + path.append(artifact.getBaseVersion()).append('/'); - path.append( artifact.getArtifactId() ).append( '-' ).append( artifact.getVersion() ); + path.append(artifact.getArtifactId()).append('-').append(artifact.getVersion()); - if ( artifact.getClassifier().length() > 0 ) - { - path.append( '-' ).append( artifact.getClassifier() ); + if (artifact.getClassifier().length() > 0) { + path.append('-').append(artifact.getClassifier()); } - if ( artifact.getExtension().length() > 0 ) - { - path.append( '.' ).append( artifact.getExtension() ); + if (artifact.getExtension().length() > 0) { + path.append('.').append(artifact.getExtension()); } - return toUri( path.toString() ); + return toUri(path.toString()); } @Override - public URI getLocation( Metadata metadata, boolean upload ) - { - StringBuilder path = new StringBuilder( 128 ); + public URI getLocation(Metadata metadata, boolean upload) { + StringBuilder path = new StringBuilder(128); - if ( metadata.getGroupId().length() > 0 ) - { - path.append( metadata.getGroupId().replace( '.', '/' ) ).append( '/' ); + if (metadata.getGroupId().length() > 0) { + path.append(metadata.getGroupId().replace('.', '/')).append('/'); - if ( metadata.getArtifactId().length() > 0 ) - { - path.append( metadata.getArtifactId() ).append( '/' ); + if (metadata.getArtifactId().length() > 0) { + path.append(metadata.getArtifactId()).append('/'); - if ( metadata.getVersion().length() > 0 ) - { - path.append( metadata.getVersion() ).append( '/' ); + if (metadata.getVersion().length() > 0) { + path.append(metadata.getVersion()).append('/'); } } } - path.append( metadata.getType() ); + path.append(metadata.getType()); - return toUri( path.toString() ); + return toUri(path.toString()); } @Override - public List getChecksumLocations( Artifact artifact, boolean upload, URI location ) - { - if ( !hasChecksums( artifact ) || isChecksum( artifact.getExtension() ) ) - { + public List getChecksumLocations(Artifact artifact, boolean upload, URI location) { + if (!hasChecksums(artifact) || isChecksum(artifact.getExtension())) { return Collections.emptyList(); } - return getChecksumLocations( location ); + return getChecksumLocations(location); } @Override - public List getChecksumLocations( Metadata metadata, boolean upload, URI location ) - { - return getChecksumLocations( location ); + public List getChecksumLocations(Metadata metadata, boolean upload, URI location) { + return getChecksumLocations(location); } - private List getChecksumLocations( URI location ) - { - List checksumLocations = new ArrayList<>( configuredChecksumAlgorithms.size() ); - for ( ChecksumAlgorithmFactory checksumAlgorithmFactory : configuredChecksumAlgorithms ) - { - checksumLocations.add( ChecksumLocation.forLocation( location, checksumAlgorithmFactory ) ); + private List getChecksumLocations(URI location) { + List checksumLocations = new ArrayList<>(configuredChecksumAlgorithms.size()); + for (ChecksumAlgorithmFactory checksumAlgorithmFactory : configuredChecksumAlgorithms) { + checksumLocations.add(ChecksumLocation.forLocation(location, checksumAlgorithmFactory)); } return checksumLocations; } - private boolean isChecksum( String extension ) - { - return checksumAlgorithmFactorySelector.isChecksumExtension( extension ); + private boolean isChecksum(String extension) { + return checksumAlgorithmFactorySelector.isChecksumExtension(extension); } } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/PrioritizedComponent.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/PrioritizedComponent.java index 5bbf9fe23..8bc258a87 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/PrioritizedComponent.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/PrioritizedComponent.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,10 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; -final class PrioritizedComponent - implements Comparable> -{ +final class PrioritizedComponent implements Comparable> { private final T component; @@ -31,42 +28,34 @@ final class PrioritizedComponent private final int index; - PrioritizedComponent( T component, Class type, float priority, int index ) - { + PrioritizedComponent(T component, Class type, float priority, int index) { this.component = component; this.type = type; this.priority = priority; this.index = index; } - public T getComponent() - { + public T getComponent() { return component; } - public Class getType() - { + public Class getType() { return type; } - public float getPriority() - { + public float getPriority() { return priority; } - public boolean isDisabled() - { - return Float.isNaN( priority ); + public boolean isDisabled() { + return Float.isNaN(priority); } - public int compareTo( PrioritizedComponent o ) - { - int rel = ( isDisabled() ? 1 : 0 ) - ( o.isDisabled() ? 1 : 0 ); - if ( rel == 0 ) - { - rel = Float.compare( o.priority, priority ); - if ( rel == 0 ) - { + public int compareTo(PrioritizedComponent o) { + int rel = (isDisabled() ? 1 : 0) - (o.isDisabled() ? 1 : 0); + if (rel == 0) { + rel = Float.compare(o.priority, priority); + if (rel == 0) { rel = index - o.index; } } @@ -74,9 +63,7 @@ public int compareTo( PrioritizedComponent o ) } @Override - public String toString() - { + public String toString() { return priority + " (#" + index + "): " + component; } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/PrioritizedComponents.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/PrioritizedComponents.java index bec493fc5..87b65b82a 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/PrioritizedComponents.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/PrioritizedComponents.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import java.util.ArrayList; import java.util.Collections; @@ -31,8 +30,7 @@ /** * Helps to sort pluggable components by their priority. */ -final class PrioritizedComponents -{ +final class PrioritizedComponents { private static final String FACTORY_SUFFIX = "Factory"; @@ -44,114 +42,92 @@ final class PrioritizedComponents private int firstDisabled; - PrioritizedComponents( RepositorySystemSession session ) - { - this( session.getConfigProperties() ); + PrioritizedComponents(RepositorySystemSession session) { + this(session.getConfigProperties()); } - PrioritizedComponents( Map configurationProperties ) - { + PrioritizedComponents(Map configurationProperties) { configProps = configurationProperties; - useInsertionOrder = - ConfigUtils.getBoolean( configProps, ConfigurationProperties.DEFAULT_IMPLICIT_PRIORITIES, - ConfigurationProperties.IMPLICIT_PRIORITIES ); + useInsertionOrder = ConfigUtils.getBoolean( + configProps, + ConfigurationProperties.DEFAULT_IMPLICIT_PRIORITIES, + ConfigurationProperties.IMPLICIT_PRIORITIES); components = new ArrayList<>(); firstDisabled = 0; } - public void add( T component, float priority ) - { - Class type = getImplClass( component ); + public void add(T component, float priority) { + Class type = getImplClass(component); int index = components.size(); - priority = useInsertionOrder ? -index : ConfigUtils.getFloat( configProps, priority, getConfigKeys( type ) ); - PrioritizedComponent pc = new PrioritizedComponent<>( component, type, priority, index ); - - if ( !useInsertionOrder ) - { - index = Collections.binarySearch( components, pc ); - if ( index < 0 ) - { + priority = useInsertionOrder ? -index : ConfigUtils.getFloat(configProps, priority, getConfigKeys(type)); + PrioritizedComponent pc = new PrioritizedComponent<>(component, type, priority, index); + + if (!useInsertionOrder) { + index = Collections.binarySearch(components, pc); + if (index < 0) { index = -index - 1; - } - else - { + } else { index++; } } - components.add( index, pc ); + components.add(index, pc); - if ( index <= firstDisabled && !pc.isDisabled() ) - { + if (index <= firstDisabled && !pc.isDisabled()) { firstDisabled++; } } - private static Class getImplClass( Object component ) - { + private static Class getImplClass(Object component) { Class type = component.getClass(); // detect and ignore CGLIB-based proxy classes employed by Guice for AOP (cf. BytecodeGen.newEnhancer) - int idx = type.getName().indexOf( "$$" ); - if ( idx >= 0 ) - { + int idx = type.getName().indexOf("$$"); + if (idx >= 0) { Class base = type.getSuperclass(); - if ( base != null && idx == base.getName().length() && type.getName().startsWith( base.getName() ) ) - { + if (base != null && idx == base.getName().length() && type.getName().startsWith(base.getName())) { type = base; } } return type; } - static String[] getConfigKeys( Class type ) - { + static String[] getConfigKeys(Class type) { List keys = new ArrayList<>(); - keys.add( ConfigurationProperties.PREFIX_PRIORITY + type.getName() ); + keys.add(ConfigurationProperties.PREFIX_PRIORITY + type.getName()); String sn = type.getSimpleName(); - keys.add( ConfigurationProperties.PREFIX_PRIORITY + sn ); - if ( sn.endsWith( FACTORY_SUFFIX ) ) - { - keys.add( - ConfigurationProperties.PREFIX_PRIORITY + sn.substring( 0, sn.length() - FACTORY_SUFFIX.length() ) ); + keys.add(ConfigurationProperties.PREFIX_PRIORITY + sn); + if (sn.endsWith(FACTORY_SUFFIX)) { + keys.add(ConfigurationProperties.PREFIX_PRIORITY + sn.substring(0, sn.length() - FACTORY_SUFFIX.length())); } - return keys.toArray( new String[0] ); + return keys.toArray(new String[0]); } - public boolean isEmpty() - { + public boolean isEmpty() { return components.isEmpty(); } - public List> getAll() - { + public List> getAll() { return components; } - public List> getEnabled() - { - return components.subList( 0, firstDisabled ); + public List> getEnabled() { + return components.subList(0, firstDisabled); } - public void list( StringBuilder buffer ) - { + public void list(StringBuilder buffer) { int i = 0; - for ( PrioritizedComponent component : components ) - { - if ( i++ > 0 ) - { - buffer.append( ", " ); + for (PrioritizedComponent component : components) { + if (i++ > 0) { + buffer.append(", "); } - buffer.append( component.getType().getSimpleName() ); - if ( component.isDisabled() ) - { - buffer.append( " (disabled)" ); + buffer.append(component.getType().getSimpleName()); + if (component.isDisabled()) { + buffer.append(" (disabled)"); } } } @Override - public String toString() - { + public String toString() { return components.toString(); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SafeTransferListener.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SafeTransferListener.java index c690fd1c6..2788e9378 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SafeTransferListener.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SafeTransferListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.transfer.AbstractTransferListener; @@ -29,144 +28,105 @@ import static java.util.Objects.requireNonNull; -class SafeTransferListener - extends AbstractTransferListener -{ +class SafeTransferListener extends AbstractTransferListener { - private static final Logger LOGGER = LoggerFactory.getLogger( SafeTransferListener.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(SafeTransferListener.class); private final TransferListener listener; - public static TransferListener wrap( RepositorySystemSession session ) - { + public static TransferListener wrap(RepositorySystemSession session) { TransferListener listener = session.getTransferListener(); - if ( listener == null ) - { + if (listener == null) { return null; } - return new SafeTransferListener( listener ); + return new SafeTransferListener(listener); } - protected SafeTransferListener( RepositorySystemSession session ) - { - this( session.getTransferListener() ); + protected SafeTransferListener(RepositorySystemSession session) { + this(session.getTransferListener()); } - private SafeTransferListener( TransferListener listener ) - { + private SafeTransferListener(TransferListener listener) { this.listener = listener; } - private void logError( TransferEvent event, Throwable e ) - { - LOGGER.debug( "Failed to dispatch transfer event '{}' to {}", event, listener.getClass().getCanonicalName(), - e ); + private void logError(TransferEvent event, Throwable e) { + LOGGER.debug( + "Failed to dispatch transfer event '{}' to {}", + event, + listener.getClass().getCanonicalName(), + e); } @Override - public void transferInitiated( TransferEvent event ) - throws TransferCancelledException - { - requireNonNull( event, "event cannot be null" ); - if ( listener != null ) - { - try - { - listener.transferInitiated( event ); - } - catch ( RuntimeException | LinkageError e ) - { - logError( event, e ); + public void transferInitiated(TransferEvent event) throws TransferCancelledException { + requireNonNull(event, "event cannot be null"); + if (listener != null) { + try { + listener.transferInitiated(event); + } catch (RuntimeException | LinkageError e) { + logError(event, e); } } } @Override - public void transferStarted( TransferEvent event ) - throws TransferCancelledException - { - requireNonNull( event, "event cannot be null" ); - if ( listener != null ) - { - try - { - listener.transferStarted( event ); - } - catch ( RuntimeException | LinkageError e ) - { - logError( event, e ); + public void transferStarted(TransferEvent event) throws TransferCancelledException { + requireNonNull(event, "event cannot be null"); + if (listener != null) { + try { + listener.transferStarted(event); + } catch (RuntimeException | LinkageError e) { + logError(event, e); } } } @Override - public void transferProgressed( TransferEvent event ) - throws TransferCancelledException - { - requireNonNull( event, "event cannot be null" ); - if ( listener != null ) - { - try - { - listener.transferProgressed( event ); - } - catch ( RuntimeException | LinkageError e ) - { - logError( event, e ); + public void transferProgressed(TransferEvent event) throws TransferCancelledException { + requireNonNull(event, "event cannot be null"); + if (listener != null) { + try { + listener.transferProgressed(event); + } catch (RuntimeException | LinkageError e) { + logError(event, e); } } } @Override - public void transferCorrupted( TransferEvent event ) - throws TransferCancelledException - { - requireNonNull( event, "event cannot be null" ); - if ( listener != null ) - { - try - { - listener.transferCorrupted( event ); - } - catch ( RuntimeException | LinkageError e ) - { - logError( event, e ); + public void transferCorrupted(TransferEvent event) throws TransferCancelledException { + requireNonNull(event, "event cannot be null"); + if (listener != null) { + try { + listener.transferCorrupted(event); + } catch (RuntimeException | LinkageError e) { + logError(event, e); } } } @Override - public void transferSucceeded( TransferEvent event ) - { - requireNonNull( event, "event cannot be null" ); - if ( listener != null ) - { - try - { - listener.transferSucceeded( event ); - } - catch ( RuntimeException | LinkageError e ) - { - logError( event, e ); + public void transferSucceeded(TransferEvent event) { + requireNonNull(event, "event cannot be null"); + if (listener != null) { + try { + listener.transferSucceeded(event); + } catch (RuntimeException | LinkageError e) { + logError(event, e); } } } @Override - public void transferFailed( TransferEvent event ) - { - requireNonNull( event, "event cannot be null" ); - if ( listener != null ) - { - try - { - listener.transferFailed( event ); - } - catch ( RuntimeException | LinkageError e ) - { - logError( event, e ); + public void transferFailed(TransferEvent event) { + requireNonNull(event, "event cannot be null"); + if (listener != null) { + try { + listener.transferFailed(event); + } catch (RuntimeException | LinkageError e) { + logError(event, e); } } } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManager.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManager.java index 6758ca005..82f6ddfe2 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManager.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import java.io.File; - -import static java.util.Objects.requireNonNull; - import java.util.Objects; import java.util.SortedSet; import java.util.TreeSet; @@ -41,58 +37,52 @@ import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.util.StringDigestUtil; +import static java.util.Objects.requireNonNull; + /** * A local repository manager that realizes the classical Maven 2.0 local repository. */ -class SimpleLocalRepositoryManager - implements LocalRepositoryManager -{ +class SimpleLocalRepositoryManager implements LocalRepositoryManager { private final LocalRepository repository; private final LocalPathComposer localPathComposer; - SimpleLocalRepositoryManager( File basedir, String type, LocalPathComposer localPathComposer ) - { - requireNonNull( basedir, "base directory cannot be null" ); - repository = new LocalRepository( basedir.getAbsoluteFile(), type ); - this.localPathComposer = requireNonNull( localPathComposer ); + SimpleLocalRepositoryManager(File basedir, String type, LocalPathComposer localPathComposer) { + requireNonNull(basedir, "base directory cannot be null"); + repository = new LocalRepository(basedir.getAbsoluteFile(), type); + this.localPathComposer = requireNonNull(localPathComposer); } @Override - public LocalRepository getRepository() - { + public LocalRepository getRepository() { return repository; } @Override - public String getPathForLocalArtifact( Artifact artifact ) - { - requireNonNull( artifact, "artifact cannot be null" ); - return localPathComposer.getPathForArtifact( artifact, true ); + public String getPathForLocalArtifact(Artifact artifact) { + requireNonNull(artifact, "artifact cannot be null"); + return localPathComposer.getPathForArtifact(artifact, true); } @Override - public String getPathForRemoteArtifact( Artifact artifact, RemoteRepository repository, String context ) - { - requireNonNull( artifact, "artifact cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); - return localPathComposer.getPathForArtifact( artifact, false ); + public String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context) { + requireNonNull(artifact, "artifact cannot be null"); + requireNonNull(repository, "repository cannot be null"); + return localPathComposer.getPathForArtifact(artifact, false); } @Override - public String getPathForLocalMetadata( Metadata metadata ) - { - requireNonNull( metadata, "metadata cannot be null" ); - return localPathComposer.getPathForMetadata( metadata, "local" ); + public String getPathForLocalMetadata(Metadata metadata) { + requireNonNull(metadata, "metadata cannot be null"); + return localPathComposer.getPathForMetadata(metadata, "local"); } @Override - public String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repository, String context ) - { - requireNonNull( metadata, "metadata cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); - return localPathComposer.getPathForMetadata( metadata, getRepositoryKey( repository, context ) ); + public String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context) { + requireNonNull(metadata, "metadata cannot be null"); + requireNonNull(repository, "repository cannot be null"); + return localPathComposer.getPathForMetadata(metadata, getRepositoryKey(repository, context)); } /** @@ -100,38 +90,32 @@ public String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repo * {@code true}, in which case this method creates unique identifier based on ID and current configuration * of the remote repository (as it may change). */ - protected String getRepositoryKey( RemoteRepository repository, String context ) - { + protected String getRepositoryKey(RemoteRepository repository, String context) { String key; - if ( repository.isRepositoryManager() ) - { + if (repository.isRepositoryManager()) { // repository serves dynamic contents, take request parameters into account for key - StringBuilder buffer = new StringBuilder( 128 ); + StringBuilder buffer = new StringBuilder(128); - buffer.append( repository.getId() ); + buffer.append(repository.getId()); - buffer.append( '-' ); + buffer.append('-'); SortedSet subKeys = new TreeSet<>(); - for ( RemoteRepository mirroredRepo : repository.getMirroredRepositories() ) - { - subKeys.add( mirroredRepo.getId() ); + for (RemoteRepository mirroredRepo : repository.getMirroredRepositories()) { + subKeys.add(mirroredRepo.getId()); } StringDigestUtil sha1 = StringDigestUtil.sha1(); - sha1.update( context ); - for ( String subKey : subKeys ) - { - sha1.update( subKey ); + sha1.update(context); + for (String subKey : subKeys) { + sha1.update(subKey); } - buffer.append( sha1.digest() ); + buffer.append(sha1.digest()); key = buffer.toString(); - } - else - { + } else { // repository serves static contents, its id is sufficient as key key = repository.getId(); @@ -141,61 +125,52 @@ protected String getRepositoryKey( RemoteRepository repository, String context ) } @Override - public LocalArtifactResult find( RepositorySystemSession session, LocalArtifactRequest request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); + public LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); Artifact artifact = request.getArtifact(); - LocalArtifactResult result = new LocalArtifactResult( request ); + LocalArtifactResult result = new LocalArtifactResult(request); String path; File file; // Local repository CANNOT have timestamped installed, they are created only during deploy - if ( Objects.equals( artifact.getVersion(), artifact.getBaseVersion() ) ) - { - path = getPathForLocalArtifact( artifact ); - file = new File( getRepository().getBasedir(), path ); - if ( file.isFile() ) - { - result.setFile( file ); - result.setAvailable( true ); + if (Objects.equals(artifact.getVersion(), artifact.getBaseVersion())) { + path = getPathForLocalArtifact(artifact); + file = new File(getRepository().getBasedir(), path); + if (file.isFile()) { + result.setFile(file); + result.setAvailable(true); } } - if ( !result.isAvailable() ) - { - for ( RemoteRepository repository : request.getRepositories() ) - { - path = getPathForRemoteArtifact( artifact, repository, request.getContext() ); - file = new File( getRepository().getBasedir(), path ); - if ( file.isFile() ) - { - result.setFile( file ); - result.setAvailable( true ); + if (!result.isAvailable()) { + for (RemoteRepository repository : request.getRepositories()) { + path = getPathForRemoteArtifact(artifact, repository, request.getContext()); + file = new File(getRepository().getBasedir(), path); + if (file.isFile()) { + result.setFile(file); + result.setAvailable(true); break; } } - } return result; } @Override - public void add( RepositorySystemSession session, LocalArtifactRegistration request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); + public void add(RepositorySystemSession session, LocalArtifactRegistration request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); // noop } @Override - public LocalMetadataResult find( RepositorySystemSession session, LocalMetadataRequest request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); - LocalMetadataResult result = new LocalMetadataResult( request ); + public LocalMetadataResult find(RepositorySystemSession session, LocalMetadataRequest request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); + LocalMetadataResult result = new LocalMetadataResult(request); String path; @@ -203,35 +178,29 @@ public LocalMetadataResult find( RepositorySystemSession session, LocalMetadataR String context = request.getContext(); RemoteRepository remote = request.getRepository(); - if ( remote != null ) - { - path = getPathForRemoteMetadata( metadata, remote, context ); - } - else - { - path = getPathForLocalMetadata( metadata ); + if (remote != null) { + path = getPathForRemoteMetadata(metadata, remote, context); + } else { + path = getPathForLocalMetadata(metadata); } - File file = new File( getRepository().getBasedir(), path ); - if ( file.isFile() ) - { - result.setFile( file ); + File file = new File(getRepository().getBasedir(), path); + if (file.isFile()) { + result.setFile(file); } return result; } @Override - public void add( RepositorySystemSession session, LocalMetadataRegistration request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); + public void add(RepositorySystemSession session, LocalMetadataRegistration request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); // noop } @Override - public String toString() - { - return String.valueOf( getRepository() ); + public String toString() { + return String.valueOf(getRepository()); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManagerFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManagerFactory.java index 9f428a3dc..a71673a05 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManagerFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManagerFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import javax.inject.Inject; import javax.inject.Named; @@ -39,52 +38,42 @@ * Creates local repository managers for repository type {@code "simple"}. */ @Singleton -@Named( "simple" ) -public class SimpleLocalRepositoryManagerFactory - implements LocalRepositoryManagerFactory, Service -{ +@Named("simple") +public class SimpleLocalRepositoryManagerFactory implements LocalRepositoryManagerFactory, Service { private float priority; private LocalPathComposer localPathComposer; - public SimpleLocalRepositoryManagerFactory() - { + public SimpleLocalRepositoryManagerFactory() { // enable no-arg constructor this.localPathComposer = new DefaultLocalPathComposer(); // maven UTs needs this } @Inject - public SimpleLocalRepositoryManagerFactory( final LocalPathComposer localPathComposer ) - { - this.localPathComposer = requireNonNull( localPathComposer ); + public SimpleLocalRepositoryManagerFactory(final LocalPathComposer localPathComposer) { + this.localPathComposer = requireNonNull(localPathComposer); } @Override - public void initService( final ServiceLocator locator ) - { - this.localPathComposer = Objects.requireNonNull( locator.getService( LocalPathComposer.class ) ); + public void initService(final ServiceLocator locator) { + this.localPathComposer = Objects.requireNonNull(locator.getService(LocalPathComposer.class)); } @Override - public LocalRepositoryManager newInstance( RepositorySystemSession session, LocalRepository repository ) - throws NoLocalRepositoryManagerException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); + public LocalRepositoryManager newInstance(RepositorySystemSession session, LocalRepository repository) + throws NoLocalRepositoryManagerException { + requireNonNull(session, "session cannot be null"); + requireNonNull(repository, "repository cannot be null"); - if ( "".equals( repository.getContentType() ) || "simple".equals( repository.getContentType() ) ) - { - return new SimpleLocalRepositoryManager( repository.getBasedir(), "simple", localPathComposer ); - } - else - { - throw new NoLocalRepositoryManagerException( repository ); + if ("".equals(repository.getContentType()) || "simple".equals(repository.getContentType())) { + return new SimpleLocalRepositoryManager(repository.getBasedir(), "simple", localPathComposer); + } else { + throw new NoLocalRepositoryManagerException(repository); } } @Override - public float getPriority() - { + public float getPriority() { return priority; } @@ -94,10 +83,8 @@ public float getPriority() * @param priority The priority. * @return This component for chaining, never {@code null}. */ - public SimpleLocalRepositoryManagerFactory setPriority( float priority ) - { + public SimpleLocalRepositoryManagerFactory setPriority(float priority) { this.priority = priority; return this; } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/TrackingFileManager.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/TrackingFileManager.java index c719d13bb..5e922bf58 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/TrackingFileManager.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/TrackingFileManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import java.io.File; import java.util.Map; @@ -26,16 +25,15 @@ /** * Manages access to a properties file. */ -public interface TrackingFileManager -{ +public interface TrackingFileManager { /** * Reads up the specified properties file into {@link Properties}, if exists, otherwise {@code null} is returned. */ - Properties read( File file ); + Properties read(File file); /** * Applies updates to specified properties file and returns resulting {@link Properties} with contents same * as in updated file, never {@code null}. */ - Properties update( File file, Map updates ); + Properties update(File file, Map updates); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/Utils.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/Utils.java index 480906f61..0c16abfcf 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/Utils.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/Utils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import java.util.ArrayList; import java.util.Collection; @@ -37,91 +36,74 @@ /** * Internal utility methods. */ -final class Utils -{ +final class Utils { public static PrioritizedComponents sortMetadataGeneratorFactories( - RepositorySystemSession session, Collection factories ) - { - PrioritizedComponents result = new PrioritizedComponents<>( session ); - for ( MetadataGeneratorFactory factory : factories ) - { - result.add( factory, factory.getPriority() ); + RepositorySystemSession session, Collection factories) { + PrioritizedComponents result = new PrioritizedComponents<>(session); + for (MetadataGeneratorFactory factory : factories) { + result.add(factory, factory.getPriority()); } return result; } - public static List prepareMetadata( List generators, - List artifacts ) - { + public static List prepareMetadata( + List generators, List artifacts) { List metadatas = new ArrayList<>(); - for ( MetadataGenerator generator : generators ) - { - metadatas.addAll( generator.prepare( artifacts ) ); + for (MetadataGenerator generator : generators) { + metadatas.addAll(generator.prepare(artifacts)); } return metadatas; } - public static List finishMetadata( List generators, - List artifacts ) - { + public static List finishMetadata( + List generators, List artifacts) { List metadatas = new ArrayList<>(); - for ( MetadataGenerator generator : generators ) - { - metadatas.addAll( generator.finish( artifacts ) ); + for (MetadataGenerator generator : generators) { + metadatas.addAll(generator.finish(artifacts)); } return metadatas; } - public static List combine( Collection first, Collection second ) - { - List result = new ArrayList<>( first.size() + second.size() ); - result.addAll( first ); - result.addAll( second ); + public static List combine(Collection first, Collection second) { + List result = new ArrayList<>(first.size() + second.size()); + result.addAll(first); + result.addAll(second); return result; } - public static int getPolicy( RepositorySystemSession session, Artifact artifact, RemoteRepository repository ) - { + public static int getPolicy(RepositorySystemSession session, Artifact artifact, RemoteRepository repository) { ResolutionErrorPolicy rep = session.getResolutionErrorPolicy(); - if ( rep == null ) - { + if (rep == null) { return ResolutionErrorPolicy.CACHE_DISABLED; } - return rep.getArtifactPolicy( session, new ResolutionErrorPolicyRequest<>( artifact, repository ) ); + return rep.getArtifactPolicy(session, new ResolutionErrorPolicyRequest<>(artifact, repository)); } - public static int getPolicy( RepositorySystemSession session, Metadata metadata, RemoteRepository repository ) - { + public static int getPolicy(RepositorySystemSession session, Metadata metadata, RemoteRepository repository) { ResolutionErrorPolicy rep = session.getResolutionErrorPolicy(); - if ( rep == null ) - { + if (rep == null) { return ResolutionErrorPolicy.CACHE_DISABLED; } - return rep.getMetadataPolicy( session, new ResolutionErrorPolicyRequest<>( metadata, repository ) ); + return rep.getMetadataPolicy(session, new ResolutionErrorPolicyRequest<>(metadata, repository)); } - public static void appendClassLoader( StringBuilder buffer, Object component ) - { + public static void appendClassLoader(StringBuilder buffer, Object component) { ClassLoader loader = component.getClass().getClassLoader(); - if ( loader != null && !loader.equals( Utils.class.getClassLoader() ) ) - { - buffer.append( " from " ).append( loader ); + if (loader != null && !loader.equals(Utils.class.getClassLoader())) { + buffer.append(" from ").append(loader); } } - public static void checkOffline( RepositorySystemSession session, OfflineController offlineController, - RemoteRepository repository ) - throws RepositoryOfflineException - { - if ( session.isOffline() ) - { - offlineController.checkOffline( session, repository ); + public static void checkOffline( + RepositorySystemSession session, OfflineController offlineController, RemoteRepository repository) + throws RepositoryOfflineException { + if (session.isOffline()) { + offlineController.checkOffline(session, repository); } } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/WarnChecksumPolicy.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/WarnChecksumPolicy.java index ff8ac4f46..0670254d1 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/WarnChecksumPolicy.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/WarnChecksumPolicy.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.transfer.ChecksumFailureException; import org.eclipse.aether.transfer.TransferResource; @@ -25,21 +24,19 @@ /** * Implements {@link org.eclipse.aether.repository.RepositoryPolicy#CHECKSUM_POLICY_WARN}. */ -final class WarnChecksumPolicy - extends AbstractChecksumPolicy -{ +final class WarnChecksumPolicy extends AbstractChecksumPolicy { - WarnChecksumPolicy( TransferResource resource ) - { - super( resource ); + WarnChecksumPolicy(TransferResource resource) { + super(resource); } @Override - public boolean onTransferChecksumFailure( ChecksumFailureException exception ) - { - logger.warn( "Could not validate integrity of download from {}{}", resource.getRepositoryUrl(), - resource.getResourceName(), exception ); + public boolean onTransferChecksumFailure(ChecksumFailureException exception) { + logger.warn( + "Could not validate integrity of download from {}{}", + resource.getRepositoryUrl(), + resource.getResourceName(), + exception); return true; } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/DefaultChecksumAlgorithmFactorySelector.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/DefaultChecksumAlgorithmFactorySelector.java index da353add8..4f37d0dad 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/DefaultChecksumAlgorithmFactorySelector.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/DefaultChecksumAlgorithmFactorySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import javax.inject.Inject; import javax.inject.Named; @@ -42,74 +41,58 @@ */ @Singleton @Named -public class DefaultChecksumAlgorithmFactorySelector - implements ChecksumAlgorithmFactorySelector -{ +public class DefaultChecksumAlgorithmFactorySelector implements ChecksumAlgorithmFactorySelector { private final Map factories; /** * Default ctor for SL. */ @Deprecated - public DefaultChecksumAlgorithmFactorySelector() - { + public DefaultChecksumAlgorithmFactorySelector() { this.factories = new HashMap<>(); - this.factories.put( Sha512ChecksumAlgorithmFactory.NAME, new Sha512ChecksumAlgorithmFactory() ); - this.factories.put( Sha256ChecksumAlgorithmFactory.NAME, new Sha256ChecksumAlgorithmFactory() ); - this.factories.put( Sha1ChecksumAlgorithmFactory.NAME, new Sha1ChecksumAlgorithmFactory() ); - this.factories.put( Md5ChecksumAlgorithmFactory.NAME, new Md5ChecksumAlgorithmFactory() ); + this.factories.put(Sha512ChecksumAlgorithmFactory.NAME, new Sha512ChecksumAlgorithmFactory()); + this.factories.put(Sha256ChecksumAlgorithmFactory.NAME, new Sha256ChecksumAlgorithmFactory()); + this.factories.put(Sha1ChecksumAlgorithmFactory.NAME, new Sha1ChecksumAlgorithmFactory()); + this.factories.put(Md5ChecksumAlgorithmFactory.NAME, new Md5ChecksumAlgorithmFactory()); } @Inject - public DefaultChecksumAlgorithmFactorySelector( Map factories ) - { - this.factories = requireNonNull( factories ); + public DefaultChecksumAlgorithmFactorySelector(Map factories) { + this.factories = requireNonNull(factories); } @Override - public ChecksumAlgorithmFactory select( String algorithmName ) - { - requireNonNull( algorithmName, "algorithmMame must not be null" ); - ChecksumAlgorithmFactory factory = factories.get( algorithmName ); - if ( factory == null ) - { - throw new IllegalArgumentException( - String.format( "Unsupported checksum algorithm %s, supported ones are %s", - algorithmName, - getChecksumAlgorithmFactories().stream() - .map( ChecksumAlgorithmFactory::getName ) - .collect( toList() ) - ) - ); + public ChecksumAlgorithmFactory select(String algorithmName) { + requireNonNull(algorithmName, "algorithmMame must not be null"); + ChecksumAlgorithmFactory factory = factories.get(algorithmName); + if (factory == null) { + throw new IllegalArgumentException(String.format( + "Unsupported checksum algorithm %s, supported ones are %s", + algorithmName, + getChecksumAlgorithmFactories().stream() + .map(ChecksumAlgorithmFactory::getName) + .collect(toList()))); } return factory; } @Override - public List selectList( Collection algorithmNames ) - { - return algorithmNames.stream() - .map( this::select ) - .collect( toList() ); + public List selectList(Collection algorithmNames) { + return algorithmNames.stream().map(this::select).collect(toList()); } @Override - public Collection getChecksumAlgorithmFactories() - { - return Collections.unmodifiableCollection( factories.values() ); + public Collection getChecksumAlgorithmFactories() { + return Collections.unmodifiableCollection(factories.values()); } @Override - public boolean isChecksumExtension( String extension ) - { - requireNonNull( extension ); - if ( extension.contains( "." ) ) - { - return factories.values().stream().anyMatch( a -> extension.endsWith( "." + a.getFileExtension() ) ); - } - else - { - return factories.values().stream().anyMatch( a -> extension.equals( a.getFileExtension() ) ); + public boolean isChecksumExtension(String extension) { + requireNonNull(extension); + if (extension.contains(".")) { + return factories.values().stream().anyMatch(a -> extension.endsWith("." + a.getFileExtension())); + } else { + return factories.values().stream().anyMatch(a -> extension.equals(a.getFileExtension())); } } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/FileTrustedChecksumsSourceSupport.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/FileTrustedChecksumsSourceSupport.java index f970c645a..caf314d1c 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/FileTrustedChecksumsSourceSupport.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/FileTrustedChecksumsSourceSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import java.io.IOException; import java.io.UncheckedIOException; @@ -54,9 +53,7 @@ * * @since 1.9.0 */ -abstract class FileTrustedChecksumsSourceSupport - implements TrustedChecksumsSource -{ +abstract class FileTrustedChecksumsSourceSupport implements TrustedChecksumsSource { private static final String CONFIG_PROP_PREFIX = "aether.trustedChecksumsSource."; private static final String CONF_NAME_BASEDIR = "basedir"; @@ -70,9 +67,8 @@ abstract class FileTrustedChecksumsSourceSupport private final String name; - FileTrustedChecksumsSourceSupport( String name ) - { - this.name = requireNonNull( name ); + FileTrustedChecksumsSourceSupport(String name) { + this.name = requireNonNull(name); } /** @@ -80,20 +76,18 @@ abstract class FileTrustedChecksumsSourceSupport * value. In worst case, empty map should be returned, meaning "no trusted checksums available". */ @Override - public Map getTrustedArtifactChecksums( RepositorySystemSession session, - Artifact artifact, - ArtifactRepository artifactRepository, - List checksumAlgorithmFactories ) - { - requireNonNull( session, "session is null" ); - requireNonNull( artifact, "artifact is null" ); - requireNonNull( artifactRepository, "artifactRepository is null" ); - requireNonNull( checksumAlgorithmFactories, "checksumAlgorithmFactories is null" ); - if ( isEnabled( session ) ) - { + public Map getTrustedArtifactChecksums( + RepositorySystemSession session, + Artifact artifact, + ArtifactRepository artifactRepository, + List checksumAlgorithmFactories) { + requireNonNull(session, "session is null"); + requireNonNull(artifact, "artifact is null"); + requireNonNull(artifactRepository, "artifactRepository is null"); + requireNonNull(checksumAlgorithmFactories, "checksumAlgorithmFactories is null"); + if (isEnabled(session)) { return requireNonNull( - doGetTrustedArtifactChecksums( session, artifact, artifactRepository, checksumAlgorithmFactories ) - ); + doGetTrustedArtifactChecksums(session, artifact, artifactRepository, checksumAlgorithmFactories)); } return null; } @@ -103,12 +97,10 @@ public Map getTrustedArtifactChecksums( RepositorySystemSession * to return {@code null}. */ @Override - public Writer getTrustedArtifactChecksumsWriter( RepositorySystemSession session ) - { - requireNonNull( session, "session is null" ); - if ( isEnabled( session ) ) - { - return doGetTrustedArtifactChecksumsWriter( session ); + public Writer getTrustedArtifactChecksumsWriter(RepositorySystemSession session) { + requireNonNull(session, "session is null"); + if (isEnabled(session)) { + return doGetTrustedArtifactChecksumsWriter(session); } return null; } @@ -117,23 +109,23 @@ public Writer getTrustedArtifactChecksumsWriter( RepositorySystemSession session * Implementors MUST NOT return {@code null} at this point, as this source is enabled. */ protected abstract Map doGetTrustedArtifactChecksums( - RepositorySystemSession session, Artifact artifact, ArtifactRepository artifactRepository, - List checksumAlgorithmFactories ); + RepositorySystemSession session, + Artifact artifact, + ArtifactRepository artifactRepository, + List checksumAlgorithmFactories); /** * Implementors may override this method and return {@link Writer} instance. */ - protected Writer doGetTrustedArtifactChecksumsWriter( RepositorySystemSession session ) - { + protected Writer doGetTrustedArtifactChecksumsWriter(RepositorySystemSession session) { return null; } /** * To be used by underlying implementations to form configuration property keys properly scoped. */ - protected String configPropKey( String name ) - { - requireNonNull( name ); + protected String configPropKey(String name) { + requireNonNull(name); return CONFIG_PROP_PREFIX + this.name + "." + name; } @@ -142,9 +134,8 @@ protected String configPropKey( String name ) *

    * Default value is {@code false}. */ - protected boolean isEnabled( RepositorySystemSession session ) - { - return ConfigUtils.getBoolean( session, false, CONFIG_PROP_PREFIX + this.name ); + protected boolean isEnabled(RepositorySystemSession session) { + return ConfigUtils.getBoolean(session, false, CONFIG_PROP_PREFIX + this.name); } /** @@ -152,9 +143,8 @@ protected boolean isEnabled( RepositorySystemSession session ) *

    * Default value is {@code true}. */ - protected boolean isOriginAware( RepositorySystemSession session ) - { - return ConfigUtils.getBoolean( session, true, configPropKey( CONF_NAME_ORIGIN_AWARE ) ); + protected boolean isOriginAware(RepositorySystemSession session) { + return ConfigUtils.getBoolean(session, true, configPropKey(CONF_NAME_ORIGIN_AWARE)); } /** @@ -166,16 +156,12 @@ protected boolean isOriginAware( RepositorySystemSession session ) * * @return The {@link Path} of basedir, never {@code null}. */ - protected Path getBasedir( RepositorySystemSession session, boolean mayCreate ) - { - try - { + protected Path getBasedir(RepositorySystemSession session, boolean mayCreate) { + try { return DirectoryUtils.resolveDirectory( - session, LOCAL_REPO_PREFIX_DIR, configPropKey( CONF_NAME_BASEDIR ), mayCreate ); - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + session, LOCAL_REPO_PREFIX_DIR, configPropKey(CONF_NAME_BASEDIR), mayCreate); + } catch (IOException e) { + throw new UncheckedIOException(e); } } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Md5ChecksumAlgorithmFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Md5ChecksumAlgorithmFactory.java index 4c6faf8ae..f3f914f12 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Md5ChecksumAlgorithmFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Md5ChecksumAlgorithmFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import javax.inject.Inject; import javax.inject.Named; @@ -29,15 +28,12 @@ * @since 1.8.0 */ @Singleton -@Named( Md5ChecksumAlgorithmFactory.NAME ) -public class Md5ChecksumAlgorithmFactory - extends MessageDigestChecksumAlgorithmFactorySupport -{ +@Named(Md5ChecksumAlgorithmFactory.NAME) +public class Md5ChecksumAlgorithmFactory extends MessageDigestChecksumAlgorithmFactorySupport { public static final String NAME = "MD5"; @Inject - public Md5ChecksumAlgorithmFactory() - { - super( NAME, "md5" ); + public Md5ChecksumAlgorithmFactory() { + super(NAME, "md5"); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/MessageDigestChecksumAlgorithmFactorySupport.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/MessageDigestChecksumAlgorithmFactorySupport.java index a285f5e52..e335fec16 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/MessageDigestChecksumAlgorithmFactorySupport.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/MessageDigestChecksumAlgorithmFactorySupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,54 +16,45 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; + +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithm; import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactory; import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactorySupport; import org.eclipse.aether.util.ChecksumUtils; -import java.nio.ByteBuffer; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - /** * Support class to implement {@link ChecksumAlgorithmFactory} based on Java {@link MessageDigest}. * * @since 1.8.0 */ -public abstract class MessageDigestChecksumAlgorithmFactorySupport - extends ChecksumAlgorithmFactorySupport -{ - public MessageDigestChecksumAlgorithmFactorySupport( String name, String extension ) - { - super( name, extension ); +public abstract class MessageDigestChecksumAlgorithmFactorySupport extends ChecksumAlgorithmFactorySupport { + public MessageDigestChecksumAlgorithmFactorySupport(String name, String extension) { + super(name, extension); } @Override - public ChecksumAlgorithm getAlgorithm() - { - try - { - MessageDigest messageDigest = MessageDigest.getInstance( getName() ); - return new ChecksumAlgorithm() - { + public ChecksumAlgorithm getAlgorithm() { + try { + MessageDigest messageDigest = MessageDigest.getInstance(getName()); + return new ChecksumAlgorithm() { @Override - public void update( final ByteBuffer input ) - { - messageDigest.update( input ); + public void update(final ByteBuffer input) { + messageDigest.update(input); } @Override - public String checksum() - { - return ChecksumUtils.toHexString( messageDigest.digest() ); + public String checksum() { + return ChecksumUtils.toHexString(messageDigest.digest()); } }; - } - catch ( NoSuchAlgorithmException e ) - { + } catch (NoSuchAlgorithmException e) { throw new IllegalStateException( - "MessageDigest algorithm " + getName() + " not supported, but is required by resolver.", e ); + "MessageDigest algorithm " + getName() + " not supported, but is required by resolver.", e); } } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha1ChecksumAlgorithmFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha1ChecksumAlgorithmFactory.java index aef57fe4f..224e7d8c2 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha1ChecksumAlgorithmFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha1ChecksumAlgorithmFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import javax.inject.Inject; import javax.inject.Named; @@ -29,15 +28,12 @@ * @since 1.8.0 */ @Singleton -@Named( Sha1ChecksumAlgorithmFactory.NAME ) -public class Sha1ChecksumAlgorithmFactory - extends MessageDigestChecksumAlgorithmFactorySupport -{ +@Named(Sha1ChecksumAlgorithmFactory.NAME) +public class Sha1ChecksumAlgorithmFactory extends MessageDigestChecksumAlgorithmFactorySupport { public static final String NAME = "SHA-1"; @Inject - public Sha1ChecksumAlgorithmFactory() - { - super( NAME, "sha1" ); + public Sha1ChecksumAlgorithmFactory() { + super(NAME, "sha1"); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha256ChecksumAlgorithmFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha256ChecksumAlgorithmFactory.java index 35d00cfcd..e76d58706 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha256ChecksumAlgorithmFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha256ChecksumAlgorithmFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import javax.inject.Inject; import javax.inject.Named; @@ -29,15 +28,12 @@ * @since 1.8.0 */ @Singleton -@Named( Sha256ChecksumAlgorithmFactory.NAME ) -public class Sha256ChecksumAlgorithmFactory - extends MessageDigestChecksumAlgorithmFactorySupport -{ +@Named(Sha256ChecksumAlgorithmFactory.NAME) +public class Sha256ChecksumAlgorithmFactory extends MessageDigestChecksumAlgorithmFactorySupport { public static final String NAME = "SHA-256"; @Inject - public Sha256ChecksumAlgorithmFactory() - { - super( NAME, "sha256" ); + public Sha256ChecksumAlgorithmFactory() { + super(NAME, "sha256"); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha512ChecksumAlgorithmFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha512ChecksumAlgorithmFactory.java index 0c60862ed..36bc01fec 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha512ChecksumAlgorithmFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/Sha512ChecksumAlgorithmFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import javax.inject.Inject; import javax.inject.Named; @@ -29,15 +28,12 @@ * @since 1.8.0 */ @Singleton -@Named( Sha512ChecksumAlgorithmFactory.NAME ) -public class Sha512ChecksumAlgorithmFactory - extends MessageDigestChecksumAlgorithmFactorySupport -{ +@Named(Sha512ChecksumAlgorithmFactory.NAME) +public class Sha512ChecksumAlgorithmFactory extends MessageDigestChecksumAlgorithmFactorySupport { public static final String NAME = "SHA-512"; @Inject - public Sha512ChecksumAlgorithmFactory() - { - super( NAME, "sha512" ); + public Sha512ChecksumAlgorithmFactory() { + super(NAME, "sha512"); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/SparseDirectoryTrustedChecksumsSource.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/SparseDirectoryTrustedChecksumsSource.java index 0d6307bf2..039d2d2f2 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/SparseDirectoryTrustedChecksumsSource.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/SparseDirectoryTrustedChecksumsSource.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import javax.inject.Inject; import javax.inject.Named; @@ -60,62 +59,56 @@ * @since 1.9.0 */ @Singleton -@Named( SparseDirectoryTrustedChecksumsSource.NAME ) -public final class SparseDirectoryTrustedChecksumsSource - extends FileTrustedChecksumsSourceSupport -{ +@Named(SparseDirectoryTrustedChecksumsSource.NAME) +public final class SparseDirectoryTrustedChecksumsSource extends FileTrustedChecksumsSourceSupport { public static final String NAME = "sparseDirectory"; - private static final Logger LOGGER = LoggerFactory.getLogger( SparseDirectoryTrustedChecksumsSource.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(SparseDirectoryTrustedChecksumsSource.class); private final FileProcessor fileProcessor; private final LocalPathComposer localPathComposer; @Inject - public SparseDirectoryTrustedChecksumsSource( FileProcessor fileProcessor, LocalPathComposer localPathComposer ) - { - super( NAME ); - this.fileProcessor = requireNonNull( fileProcessor ); - this.localPathComposer = requireNonNull( localPathComposer ); + public SparseDirectoryTrustedChecksumsSource(FileProcessor fileProcessor, LocalPathComposer localPathComposer) { + super(NAME); + this.fileProcessor = requireNonNull(fileProcessor); + this.localPathComposer = requireNonNull(localPathComposer); } @Override protected Map doGetTrustedArtifactChecksums( - RepositorySystemSession session, Artifact artifact, ArtifactRepository artifactRepository, - List checksumAlgorithmFactories ) - { - final boolean originAware = isOriginAware( session ); + RepositorySystemSession session, + Artifact artifact, + ArtifactRepository artifactRepository, + List checksumAlgorithmFactories) { + final boolean originAware = isOriginAware(session); final HashMap checksums = new HashMap<>(); - Path basedir = getBasedir( session, false ); - if ( Files.isDirectory( basedir ) ) - { - for ( ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories ) - { + Path basedir = getBasedir(session, false); + if (Files.isDirectory(basedir)) { + for (ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories) { Path checksumPath = basedir.resolve( - calculateArtifactPath( originAware, artifact, artifactRepository, checksumAlgorithmFactory ) ); - - if ( !Files.isRegularFile( checksumPath ) ) - { - LOGGER.debug( "Artifact '{}' trusted checksum '{}' not found on path '{}'", - artifact, checksumAlgorithmFactory.getName(), checksumPath ); + calculateArtifactPath(originAware, artifact, artifactRepository, checksumAlgorithmFactory)); + + if (!Files.isRegularFile(checksumPath)) { + LOGGER.debug( + "Artifact '{}' trusted checksum '{}' not found on path '{}'", + artifact, + checksumAlgorithmFactory.getName(), + checksumPath); continue; } - try - { - String checksum = fileProcessor.readChecksum( checksumPath.toFile() ); - if ( checksum != null ) - { - checksums.put( checksumAlgorithmFactory.getName(), checksum ); + try { + String checksum = fileProcessor.readChecksum(checksumPath.toFile()); + if (checksum != null) { + checksums.put(checksumAlgorithmFactory.getName(), checksum); } - } - catch ( IOException e ) - { + } catch (IOException e) { // unexpected, log - LOGGER.warn( "Could not read artifact '{}' trusted checksum on path '{}'", artifact, checksumPath, - e ); - throw new UncheckedIOException( e ); + LOGGER.warn( + "Could not read artifact '{}' trusted checksum on path '{}'", artifact, checksumPath, e); + throw new UncheckedIOException(e); } } } @@ -123,51 +116,46 @@ protected Map doGetTrustedArtifactChecksums( } @Override - protected SparseDirectoryWriter doGetTrustedArtifactChecksumsWriter( RepositorySystemSession session ) - { - return new SparseDirectoryWriter( getBasedir( session, true ), isOriginAware( session ) ); + protected SparseDirectoryWriter doGetTrustedArtifactChecksumsWriter(RepositorySystemSession session) { + return new SparseDirectoryWriter(getBasedir(session, true), isOriginAware(session)); } - private String calculateArtifactPath( boolean originAware, - Artifact artifact, - ArtifactRepository artifactRepository, - ChecksumAlgorithmFactory checksumAlgorithmFactory ) - { - String path = localPathComposer.getPathForArtifact( artifact, false ) - + "." + checksumAlgorithmFactory.getFileExtension(); - if ( originAware ) - { + private String calculateArtifactPath( + boolean originAware, + Artifact artifact, + ArtifactRepository artifactRepository, + ChecksumAlgorithmFactory checksumAlgorithmFactory) { + String path = localPathComposer.getPathForArtifact(artifact, false) + "." + + checksumAlgorithmFactory.getFileExtension(); + if (originAware) { path = artifactRepository.getId() + "/" + path; } return path; } - private class SparseDirectoryWriter implements Writer - { + private class SparseDirectoryWriter implements Writer { private final Path basedir; private final boolean originAware; - private SparseDirectoryWriter( Path basedir, boolean originAware ) - { + private SparseDirectoryWriter(Path basedir, boolean originAware) { this.basedir = basedir; this.originAware = originAware; } @Override - public void addTrustedArtifactChecksums( Artifact artifact, - ArtifactRepository artifactRepository, - List checksumAlgorithmFactories, - Map trustedArtifactChecksums ) throws IOException - { - for ( ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories ) - { - Path checksumPath = basedir.resolve( calculateArtifactPath( - originAware, artifact, artifactRepository, checksumAlgorithmFactory ) ); - String checksum = requireNonNull( - trustedArtifactChecksums.get( checksumAlgorithmFactory.getName() ) ); - fileProcessor.writeChecksum( checksumPath.toFile(), checksum ); + public void addTrustedArtifactChecksums( + Artifact artifact, + ArtifactRepository artifactRepository, + List checksumAlgorithmFactories, + Map trustedArtifactChecksums) + throws IOException { + for (ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories) { + Path checksumPath = basedir.resolve( + calculateArtifactPath(originAware, artifact, artifactRepository, checksumAlgorithmFactory)); + String checksum = requireNonNull(trustedArtifactChecksums.get(checksumAlgorithmFactory.getName())); + fileProcessor.writeChecksum(checksumPath.toFile(), checksum); } } - } + } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/SummaryFileTrustedChecksumsSource.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/SummaryFileTrustedChecksumsSource.java index 2bfb722f8..f00f82887 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/SummaryFileTrustedChecksumsSource.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/SummaryFileTrustedChecksumsSource.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import javax.inject.Inject; import javax.inject.Named; @@ -86,15 +85,13 @@ * @since 1.9.0 */ @Singleton -@Named( SummaryFileTrustedChecksumsSource.NAME ) -public final class SummaryFileTrustedChecksumsSource - extends FileTrustedChecksumsSourceSupport -{ +@Named(SummaryFileTrustedChecksumsSource.NAME) +public final class SummaryFileTrustedChecksumsSource extends FileTrustedChecksumsSourceSupport { public static final String NAME = "summaryFile"; private static final String CHECKSUMS_FILE_PREFIX = "checksums"; - private static final Logger LOGGER = LoggerFactory.getLogger( SummaryFileTrustedChecksumsSource.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(SummaryFileTrustedChecksumsSource.class); private final LocalPathComposer localPathComposer; @@ -106,49 +103,45 @@ public final class SummaryFileTrustedChecksumsSource private final AtomicBoolean onShutdownHandlerRegistered; - @Inject - public SummaryFileTrustedChecksumsSource( LocalPathComposer localPathComposer, - RepositorySystemLifecycle repositorySystemLifecycle ) - { - super( NAME ); - this.localPathComposer = requireNonNull( localPathComposer ); - this.repositorySystemLifecycle = requireNonNull( repositorySystemLifecycle ); + public SummaryFileTrustedChecksumsSource( + LocalPathComposer localPathComposer, RepositorySystemLifecycle repositorySystemLifecycle) { + super(NAME); + this.localPathComposer = requireNonNull(localPathComposer); + this.repositorySystemLifecycle = requireNonNull(repositorySystemLifecycle); this.checksums = new ConcurrentHashMap<>(); this.changedChecksums = new ConcurrentHashMap<>(); - this.onShutdownHandlerRegistered = new AtomicBoolean( false ); + this.onShutdownHandlerRegistered = new AtomicBoolean(false); } @Override protected Map doGetTrustedArtifactChecksums( - RepositorySystemSession session, Artifact artifact, ArtifactRepository artifactRepository, - List checksumAlgorithmFactories ) - { + RepositorySystemSession session, + Artifact artifact, + ArtifactRepository artifactRepository, + List checksumAlgorithmFactories) { final HashMap result = new HashMap<>(); - final Path basedir = getBasedir( session, false ); - if ( Files.isDirectory( basedir ) ) - { - final String artifactPath = localPathComposer.getPathForArtifact( artifact, false ); - final boolean originAware = isOriginAware( session ); - for ( ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories ) - { - Path summaryFile = summaryFile( basedir, originAware, artifactRepository.getId(), - checksumAlgorithmFactory.getFileExtension() ); - ConcurrentHashMap algorithmChecksums = checksums.computeIfAbsent( summaryFile, f -> - { - ConcurrentHashMap loaded = loadProvidedChecksums( summaryFile ); - if ( Files.isRegularFile( summaryFile ) ) - { - LOGGER.info( "Loaded {} {} trusted checksums for remote repository {}", - loaded.size(), checksumAlgorithmFactory.getName(), artifactRepository.getId() ); - } - return loaded; - } - ); - String checksum = algorithmChecksums.get( artifactPath ); - if ( checksum != null ) - { - result.put( checksumAlgorithmFactory.getName(), checksum ); + final Path basedir = getBasedir(session, false); + if (Files.isDirectory(basedir)) { + final String artifactPath = localPathComposer.getPathForArtifact(artifact, false); + final boolean originAware = isOriginAware(session); + for (ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories) { + Path summaryFile = summaryFile( + basedir, originAware, artifactRepository.getId(), checksumAlgorithmFactory.getFileExtension()); + ConcurrentHashMap algorithmChecksums = checksums.computeIfAbsent(summaryFile, f -> { + ConcurrentHashMap loaded = loadProvidedChecksums(summaryFile); + if (Files.isRegularFile(summaryFile)) { + LOGGER.info( + "Loaded {} {} trusted checksums for remote repository {}", + loaded.size(), + checksumAlgorithmFactory.getName(), + artifactRepository.getId()); + } + return loaded; + }); + String checksum = algorithmChecksums.get(artifactPath); + if (checksum != null) { + result.put(checksumAlgorithmFactory.getName(), checksum); } } } @@ -156,122 +149,104 @@ protected Map doGetTrustedArtifactChecksums( } @Override - protected SummaryFileWriter doGetTrustedArtifactChecksumsWriter( RepositorySystemSession session ) - { - if ( onShutdownHandlerRegistered.compareAndSet( false, true ) ) - { - repositorySystemLifecycle.addOnSystemEndedHandler( this::saveRecordedLines ); + protected SummaryFileWriter doGetTrustedArtifactChecksumsWriter(RepositorySystemSession session) { + if (onShutdownHandlerRegistered.compareAndSet(false, true)) { + repositorySystemLifecycle.addOnSystemEndedHandler(this::saveRecordedLines); } - return new SummaryFileWriter( checksums, getBasedir( session, true ), isOriginAware( session ) ); + return new SummaryFileWriter(checksums, getBasedir(session, true), isOriginAware(session)); } /** * Returns the summary file path. The file itself and its parent directories may not exist, this method merely * calculate the path. */ - private Path summaryFile( Path basedir, boolean originAware, String repositoryId, String checksumExtension ) - { + private Path summaryFile(Path basedir, boolean originAware, String repositoryId, String checksumExtension) { String fileName = CHECKSUMS_FILE_PREFIX; - if ( originAware ) - { + if (originAware) { fileName += "-" + repositoryId; } - return basedir.resolve( fileName + "." + checksumExtension ); + return basedir.resolve(fileName + "." + checksumExtension); } - private ConcurrentHashMap loadProvidedChecksums( Path summaryFile ) - { + private ConcurrentHashMap loadProvidedChecksums(Path summaryFile) { ConcurrentHashMap result = new ConcurrentHashMap<>(); - if ( Files.isRegularFile( summaryFile ) ) - { - try ( BufferedReader reader = Files.newBufferedReader( summaryFile, StandardCharsets.UTF_8 ) ) - { + if (Files.isRegularFile(summaryFile)) { + try (BufferedReader reader = Files.newBufferedReader(summaryFile, StandardCharsets.UTF_8)) { String line; - while ( ( line = reader.readLine() ) != null ) - { - if ( !line.startsWith( "#" ) && !line.isEmpty() ) - { - String[] parts = line.split( " ", 2 ); - if ( parts.length == 2 ) - { + while ((line = reader.readLine()) != null) { + if (!line.startsWith("#") && !line.isEmpty()) { + String[] parts = line.split(" ", 2); + if (parts.length == 2) { String newChecksum = parts[0]; String artifactPath = parts[1]; - String oldChecksum = result.put( artifactPath, newChecksum ); - if ( oldChecksum != null ) - { - if ( Objects.equals( oldChecksum, newChecksum ) ) - { + String oldChecksum = result.put(artifactPath, newChecksum); + if (oldChecksum != null) { + if (Objects.equals(oldChecksum, newChecksum)) { LOGGER.warn( "Checksums file '{}' contains duplicate checksums for artifact {}: {}", - summaryFile, artifactPath, oldChecksum ); - } - else - { + summaryFile, + artifactPath, + oldChecksum); + } else { LOGGER.warn( "Checksums file '{}' contains different checksums for artifact {}: " - + "old '{}' replaced by new '{}'", summaryFile, artifactPath, - oldChecksum, newChecksum ); + + "old '{}' replaced by new '{}'", + summaryFile, + artifactPath, + oldChecksum, + newChecksum); } } - } - else - { - LOGGER.warn( "Checksums file '{}' ignored malformed line '{}'", summaryFile, line ); + } else { + LOGGER.warn("Checksums file '{}' ignored malformed line '{}'", summaryFile, line); } } } - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + } catch (IOException e) { + throw new UncheckedIOException(e); } } return result; } - private class SummaryFileWriter implements Writer - { + private class SummaryFileWriter implements Writer { private final ConcurrentHashMap> cache; private final Path basedir; private final boolean originAware; - private SummaryFileWriter( ConcurrentHashMap> cache, - Path basedir, - boolean originAware ) - { + private SummaryFileWriter( + ConcurrentHashMap> cache, Path basedir, boolean originAware) { this.cache = cache; this.basedir = basedir; this.originAware = originAware; } @Override - public void addTrustedArtifactChecksums( Artifact artifact, - ArtifactRepository artifactRepository, - List checksumAlgorithmFactories, - Map trustedArtifactChecksums ) - { - String artifactPath = localPathComposer.getPathForArtifact( artifact, false ); - for ( ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories ) - { - Path summaryFile = summaryFile( basedir, originAware, artifactRepository.getId(), - checksumAlgorithmFactory.getFileExtension() ); - String checksum = requireNonNull( - trustedArtifactChecksums.get( checksumAlgorithmFactory.getName() ) ); + public void addTrustedArtifactChecksums( + Artifact artifact, + ArtifactRepository artifactRepository, + List checksumAlgorithmFactories, + Map trustedArtifactChecksums) { + String artifactPath = localPathComposer.getPathForArtifact(artifact, false); + for (ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories) { + Path summaryFile = summaryFile( + basedir, originAware, artifactRepository.getId(), checksumAlgorithmFactory.getFileExtension()); + String checksum = requireNonNull(trustedArtifactChecksums.get(checksumAlgorithmFactory.getName())); - String oldChecksum = cache.computeIfAbsent( summaryFile, k -> loadProvidedChecksums( summaryFile ) ) - .put( artifactPath, checksum ); + String oldChecksum = cache.computeIfAbsent(summaryFile, k -> loadProvidedChecksums(summaryFile)) + .put(artifactPath, checksum); - if ( oldChecksum == null ) - { - changedChecksums.put( summaryFile, Boolean.TRUE ); // new - } - else if ( !Objects.equals( oldChecksum, checksum ) ) - { - changedChecksums.put( summaryFile, Boolean.TRUE ); // replaced - LOGGER.info( "Trusted checksum for artifact {} replaced: old {}, new {}", - artifact, oldChecksum, checksum ); + if (oldChecksum == null) { + changedChecksums.put(summaryFile, Boolean.TRUE); // new + } else if (!Objects.equals(oldChecksum, checksum)) { + changedChecksums.put(summaryFile, Boolean.TRUE); // replaced + LOGGER.info( + "Trusted checksum for artifact {} replaced: old {}, new {}", + artifact, + oldChecksum, + checksum); } } } @@ -280,47 +255,38 @@ else if ( !Objects.equals( oldChecksum, checksum ) ) /** * On-close handler that saves recorded checksums, if any. */ - private void saveRecordedLines() - { - if ( changedChecksums.isEmpty() ) - { + private void saveRecordedLines() { + if (changedChecksums.isEmpty()) { return; } ArrayList exceptions = new ArrayList<>(); - for ( Map.Entry> entry : checksums.entrySet() ) - { + for (Map.Entry> entry : checksums.entrySet()) { Path summaryFile = entry.getKey(); - if ( changedChecksums.get( summaryFile ) != Boolean.TRUE ) - { + if (changedChecksums.get(summaryFile) != Boolean.TRUE) { continue; } ConcurrentHashMap recordedLines = entry.getValue(); - if ( !recordedLines.isEmpty() ) - { - try - { + if (!recordedLines.isEmpty()) { + try { ConcurrentHashMap result = new ConcurrentHashMap<>(); - result.putAll( loadProvidedChecksums( summaryFile ) ); - result.putAll( recordedLines ); + result.putAll(loadProvidedChecksums(summaryFile)); + result.putAll(recordedLines); - LOGGER.info( "Saving {} checksums to '{}'", result.size(), summaryFile ); + LOGGER.info("Saving {} checksums to '{}'", result.size(), summaryFile); FileUtils.writeFileWithBackup( summaryFile, - p -> Files.write( p, + p -> Files.write( + p, result.entrySet().stream() - .sorted( Map.Entry.comparingByValue() ) - .map( e -> e.getValue() + " " + e.getKey() ) - .collect( toList() ) - ) - ); - } - catch ( IOException e ) - { - exceptions.add( e ); + .sorted(Map.Entry.comparingByValue()) + .map(e -> e.getValue() + " " + e.getKey()) + .collect(toList()))); + } catch (IOException e) { + exceptions.add(e); } } } - MultiRuntimeException.mayThrow( "session save checksums failure", exceptions ); + MultiRuntimeException.mayThrow("session save checksums failure", exceptions); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/TrustedToProvidedChecksumsSourceAdapter.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/TrustedToProvidedChecksumsSourceAdapter.java index e91da3a0b..711cd12f5 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/TrustedToProvidedChecksumsSourceAdapter.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/checksum/TrustedToProvidedChecksumsSourceAdapter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import javax.inject.Inject; import javax.inject.Named; @@ -43,34 +42,28 @@ * @since 1.9.0 */ @Singleton -@Named( TrustedToProvidedChecksumsSourceAdapter.NAME ) -public final class TrustedToProvidedChecksumsSourceAdapter - implements ProvidedChecksumsSource -{ +@Named(TrustedToProvidedChecksumsSourceAdapter.NAME) +public final class TrustedToProvidedChecksumsSourceAdapter implements ProvidedChecksumsSource { public static final String NAME = "trusted2provided"; private final Map trustedChecksumsSources; @Inject - public TrustedToProvidedChecksumsSourceAdapter( Map trustedChecksumsSources ) - { - this.trustedChecksumsSources = requireNonNull( trustedChecksumsSources ); + public TrustedToProvidedChecksumsSourceAdapter(Map trustedChecksumsSources) { + this.trustedChecksumsSources = requireNonNull(trustedChecksumsSources); } @Override - public Map getProvidedArtifactChecksums( RepositorySystemSession session, - ArtifactDownload transfer, - List checksumAlgorithmFactories ) - { + public Map getProvidedArtifactChecksums( + RepositorySystemSession session, + ArtifactDownload transfer, + List checksumAlgorithmFactories) { Artifact artifact = transfer.getArtifact(); - for ( RemoteRepository remoteRepository : transfer.getRepositories() ) - { - for ( TrustedChecksumsSource trustedChecksumsSource : trustedChecksumsSources.values() ) - { - Map trustedChecksums = trustedChecksumsSource - .getTrustedArtifactChecksums( session, artifact, remoteRepository, checksumAlgorithmFactories ); - if ( trustedChecksums != null && !trustedChecksums.isEmpty() ) - { + for (RemoteRepository remoteRepository : transfer.getRepositories()) { + for (TrustedChecksumsSource trustedChecksumsSource : trustedChecksumsSources.values()) { + Map trustedChecksums = trustedChecksumsSource.getTrustedArtifactChecksums( + session, artifact, remoteRepository, checksumAlgorithmFactories); + if (trustedChecksums != null && !trustedChecksums.isEmpty()) { return trustedChecksums; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/CachingArtifactTypeRegistry.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/CachingArtifactTypeRegistry.java index 1a9a98f5b..0ba77e1f2 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/CachingArtifactTypeRegistry.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/CachingArtifactTypeRegistry.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; import java.util.HashMap; import java.util.Map; @@ -30,41 +29,33 @@ * A short-lived artifact type registry that caches results from a presumably slower type registry. * Internal helper class for collector implementations. */ -public class CachingArtifactTypeRegistry - implements ArtifactTypeRegistry -{ +public class CachingArtifactTypeRegistry implements ArtifactTypeRegistry { private final ArtifactTypeRegistry delegate; private final Map types; - public static ArtifactTypeRegistry newInstance( RepositorySystemSession session ) - { - return newInstance( session.getArtifactTypeRegistry() ); + public static ArtifactTypeRegistry newInstance(RepositorySystemSession session) { + return newInstance(session.getArtifactTypeRegistry()); } - public static ArtifactTypeRegistry newInstance( ArtifactTypeRegistry delegate ) - { - return ( delegate != null ) ? new CachingArtifactTypeRegistry( delegate ) : null; + public static ArtifactTypeRegistry newInstance(ArtifactTypeRegistry delegate) { + return (delegate != null) ? new CachingArtifactTypeRegistry(delegate) : null; } - private CachingArtifactTypeRegistry( ArtifactTypeRegistry delegate ) - { + private CachingArtifactTypeRegistry(ArtifactTypeRegistry delegate) { this.delegate = delegate; types = new HashMap<>(); } - public ArtifactType get( String typeId ) - { - ArtifactType type = types.get( typeId ); + public ArtifactType get(String typeId) { + ArtifactType type = types.get(typeId); - if ( type == null ) - { - type = delegate.get( typeId ); - types.put( typeId, type ); + if (type == null) { + type = delegate.get(typeId); + types.put(typeId, type); } return type; } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/CollectStepDataImpl.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/CollectStepDataImpl.java index eb1df324c..6bc9192d0 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/CollectStepDataImpl.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/CollectStepDataImpl.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; import java.util.List; @@ -32,36 +31,31 @@ * * @since 1.8.1 */ -public final class CollectStepDataImpl implements CollectStepData -{ +public final class CollectStepDataImpl implements CollectStepData { private final String context; private final List path; private final Dependency node; - public CollectStepDataImpl( final String context, final List path, final Dependency node ) - { - this.context = requireNonNull( context ); - this.path = requireNonNull( path ); - this.node = requireNonNull( node ); + public CollectStepDataImpl(final String context, final List path, final Dependency node) { + this.context = requireNonNull(context); + this.path = requireNonNull(path); + this.node = requireNonNull(node); } @Override - public String getContext() - { + public String getContext() { return context; } @Override - public List getPath() - { + public List getPath() { return path; } @Override - public Dependency getNode() - { + public Dependency getNode() { return node; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DataPool.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DataPool.java index a531b3ff2..c86f3527d 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DataPool.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DataPool.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; import java.lang.ref.WeakReference; import java.util.Collection; @@ -52,8 +51,7 @@ /** * Internal helper class for collector implementations. */ -public final class DataPool -{ +public final class DataPool { private static final String CONFIG_PROP_COLLECTOR_POOL_ARTIFACT = "aether.dependencyCollector.pool.artifact"; private static final String CONFIG_PROP_COLLECTOR_POOL_DEPENDENCY = "aether.dependencyCollector.pool.dependency"; @@ -67,7 +65,7 @@ public final class DataPool private static final String DESCRIPTORS = DataPool.class.getName() + "$Descriptors"; public static final ArtifactDescriptorResult NO_DESCRIPTOR = - new ArtifactDescriptorResult( new ArtifactDescriptorRequest() ); + new ArtifactDescriptorResult(new ArtifactDescriptorRequest()); /** * Artifact interning pool, lives across session (if session carries non-null {@link RepositoryCache}). @@ -94,51 +92,43 @@ public final class DataPool */ private final ConcurrentHashMap> nodes; - @SuppressWarnings( "unchecked" ) - public DataPool( RepositorySystemSession session ) - { + @SuppressWarnings("unchecked") + public DataPool(RepositorySystemSession session) { final RepositoryCache cache = session.getCache(); InternPool artifactsPool = null; InternPool dependenciesPool = null; InternPool descriptorsPool = null; - if ( cache != null ) - { - artifactsPool = (InternPool) cache.get( session, ARTIFACT_POOL ); - dependenciesPool = (InternPool) cache.get( session, DEPENDENCY_POOL ); - descriptorsPool = (InternPool) cache.get( session, DESCRIPTORS ); + if (cache != null) { + artifactsPool = (InternPool) cache.get(session, ARTIFACT_POOL); + dependenciesPool = (InternPool) cache.get(session, DEPENDENCY_POOL); + descriptorsPool = (InternPool) cache.get(session, DESCRIPTORS); } - if ( artifactsPool == null ) - { - String artifactPoolType = ConfigUtils.getString( session, WEAK, CONFIG_PROP_COLLECTOR_POOL_ARTIFACT ); + if (artifactsPool == null) { + String artifactPoolType = ConfigUtils.getString(session, WEAK, CONFIG_PROP_COLLECTOR_POOL_ARTIFACT); - artifactsPool = createPool( artifactPoolType ); - if ( cache != null ) - { - cache.put( session, ARTIFACT_POOL, artifactsPool ); + artifactsPool = createPool(artifactPoolType); + if (cache != null) { + cache.put(session, ARTIFACT_POOL, artifactsPool); } } - if ( dependenciesPool == null ) - { - String dependencyPoolType = ConfigUtils.getString( session, WEAK, CONFIG_PROP_COLLECTOR_POOL_DEPENDENCY ); + if (dependenciesPool == null) { + String dependencyPoolType = ConfigUtils.getString(session, WEAK, CONFIG_PROP_COLLECTOR_POOL_DEPENDENCY); - dependenciesPool = createPool( dependencyPoolType ); - if ( cache != null ) - { - cache.put( session, DEPENDENCY_POOL, dependenciesPool ); + dependenciesPool = createPool(dependencyPoolType); + if (cache != null) { + cache.put(session, DEPENDENCY_POOL, dependenciesPool); } } - if ( descriptorsPool == null ) - { - String descriptorPoolType = ConfigUtils.getString( session, HARD, CONFIG_PROP_COLLECTOR_POOL_DESCRIPTOR ); + if (descriptorsPool == null) { + String descriptorPoolType = ConfigUtils.getString(session, HARD, CONFIG_PROP_COLLECTOR_POOL_DESCRIPTOR); - descriptorsPool = createPool( descriptorPoolType ); - if ( cache != null ) - { - cache.put( session, DESCRIPTORS, descriptorsPool ); + descriptorsPool = createPool(descriptorPoolType); + if (cache != null) { + cache.put(session, DESCRIPTORS, descriptorsPool); } } @@ -146,91 +136,78 @@ public DataPool( RepositorySystemSession session ) this.dependencies = dependenciesPool; this.descriptors = descriptorsPool; - this.constraints = new ConcurrentHashMap<>( 256 ); - this.nodes = new ConcurrentHashMap<>( 256 ); + this.constraints = new ConcurrentHashMap<>(256); + this.nodes = new ConcurrentHashMap<>(256); } - public Artifact intern( Artifact artifact ) - { - return artifacts.intern( artifact, artifact ); + public Artifact intern(Artifact artifact) { + return artifacts.intern(artifact, artifact); } - public Dependency intern( Dependency dependency ) - { - return dependencies.intern( dependency, dependency ); + public Dependency intern(Dependency dependency) { + return dependencies.intern(dependency, dependency); } - public Object toKey( ArtifactDescriptorRequest request ) - { + public Object toKey(ArtifactDescriptorRequest request) { return request.getArtifact(); } - public ArtifactDescriptorResult getDescriptor( Object key, ArtifactDescriptorRequest request ) - { - Descriptor descriptor = descriptors.get( key ); - if ( descriptor != null ) - { - return descriptor.toResult( request ); + public ArtifactDescriptorResult getDescriptor(Object key, ArtifactDescriptorRequest request) { + Descriptor descriptor = descriptors.get(key); + if (descriptor != null) { + return descriptor.toResult(request); } return null; } - public void putDescriptor( Object key, ArtifactDescriptorResult result ) - { - descriptors.intern( key, new GoodDescriptor( result ) ); + public void putDescriptor(Object key, ArtifactDescriptorResult result) { + descriptors.intern(key, new GoodDescriptor(result)); } - public void putDescriptor( Object key, ArtifactDescriptorException e ) - { - descriptors.intern( key, BadDescriptor.INSTANCE ); + public void putDescriptor(Object key, ArtifactDescriptorException e) { + descriptors.intern(key, BadDescriptor.INSTANCE); } - public Object toKey( VersionRangeRequest request ) - { - return new ConstraintKey( request ); + public Object toKey(VersionRangeRequest request) { + return new ConstraintKey(request); } - public VersionRangeResult getConstraint( Object key, VersionRangeRequest request ) - { - Constraint constraint = constraints.get( key ); - if ( constraint != null ) - { - return constraint.toResult( request ); + public VersionRangeResult getConstraint(Object key, VersionRangeRequest request) { + Constraint constraint = constraints.get(key); + if (constraint != null) { + return constraint.toResult(request); } return null; } - public void putConstraint( Object key, VersionRangeResult result ) - { - constraints.put( key, new Constraint( result ) ); + public void putConstraint(Object key, VersionRangeResult result) { + constraints.put(key, new Constraint(result)); } - public Object toKey( Artifact artifact, List repositories, DependencySelector selector, - DependencyManager manager, DependencyTraverser traverser, VersionFilter filter ) - { - return new GraphKey( artifact, repositories, selector, manager, traverser, filter ); + public Object toKey( + Artifact artifact, + List repositories, + DependencySelector selector, + DependencyManager manager, + DependencyTraverser traverser, + VersionFilter filter) { + return new GraphKey(artifact, repositories, selector, manager, traverser, filter); } - public List getChildren( Object key ) - { - return nodes.get( key ); + public List getChildren(Object key) { + return nodes.get(key); } - public void putChildren( Object key, List children ) - { - nodes.put( key, children ); + public void putChildren(Object key, List children) { + nodes.put(key, children); } - abstract static class Descriptor - { - - public abstract ArtifactDescriptorResult toResult( ArtifactDescriptorRequest request ); + abstract static class Descriptor { + public abstract ArtifactDescriptorResult toResult(ArtifactDescriptorRequest request); } - static final class GoodDescriptor - extends Descriptor - { + static final class GoodDescriptor extends Descriptor { final Artifact artifact; @@ -244,8 +221,7 @@ static final class GoodDescriptor final List managedDependencies; - GoodDescriptor( ArtifactDescriptorResult result ) - { + GoodDescriptor(ArtifactDescriptorResult result) { artifact = result.getArtifact(); relocations = result.getRelocations(); aliases = result.getAliases(); @@ -254,138 +230,110 @@ static final class GoodDescriptor repositories = result.getRepositories(); } - public ArtifactDescriptorResult toResult( ArtifactDescriptorRequest request ) - { - ArtifactDescriptorResult result = new ArtifactDescriptorResult( request ); - result.setArtifact( artifact ); - result.setRelocations( relocations ); - result.setAliases( aliases ); - result.setDependencies( dependencies ); - result.setManagedDependencies( managedDependencies ); - result.setRepositories( repositories ); + public ArtifactDescriptorResult toResult(ArtifactDescriptorRequest request) { + ArtifactDescriptorResult result = new ArtifactDescriptorResult(request); + result.setArtifact(artifact); + result.setRelocations(relocations); + result.setAliases(aliases); + result.setDependencies(dependencies); + result.setManagedDependencies(managedDependencies); + result.setRepositories(repositories); return result; } - } - static final class BadDescriptor - extends Descriptor - { + static final class BadDescriptor extends Descriptor { static final BadDescriptor INSTANCE = new BadDescriptor(); - public ArtifactDescriptorResult toResult( ArtifactDescriptorRequest request ) - { + public ArtifactDescriptorResult toResult(ArtifactDescriptorRequest request) { return NO_DESCRIPTOR; } } - private static final class Constraint - { + private static final class Constraint { final VersionRepo[] repositories; final VersionConstraint versionConstraint; - Constraint( VersionRangeResult result ) - { + Constraint(VersionRangeResult result) { versionConstraint = result.getVersionConstraint(); List versions = result.getVersions(); repositories = new VersionRepo[versions.size()]; int i = 0; - for ( Version version : versions ) - { - repositories[i++] = new VersionRepo( version, result.getRepository( version ) ); + for (Version version : versions) { + repositories[i++] = new VersionRepo(version, result.getRepository(version)); } } - VersionRangeResult toResult( VersionRangeRequest request ) - { - VersionRangeResult result = new VersionRangeResult( request ); - for ( VersionRepo vr : repositories ) - { - result.addVersion( vr.version ); - result.setRepository( vr.version, vr.repo ); + VersionRangeResult toResult(VersionRangeRequest request) { + VersionRangeResult result = new VersionRangeResult(request); + for (VersionRepo vr : repositories) { + result.addVersion(vr.version); + result.setRepository(vr.version, vr.repo); } - result.setVersionConstraint( versionConstraint ); + result.setVersionConstraint(versionConstraint); return result; } - static final class VersionRepo - { + static final class VersionRepo { final Version version; final ArtifactRepository repo; - VersionRepo( Version version, ArtifactRepository repo ) - { + VersionRepo(Version version, ArtifactRepository repo) { this.version = version; this.repo = repo; } } } - static final class ConstraintKey - { + static final class ConstraintKey { private final Artifact artifact; private final List repositories; private final int hashCode; - ConstraintKey( VersionRangeRequest request ) - { + ConstraintKey(VersionRangeRequest request) { artifact = request.getArtifact(); repositories = request.getRepositories(); hashCode = artifact.hashCode(); } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( !( obj instanceof ConstraintKey ) ) - { + } else if (!(obj instanceof ConstraintKey)) { return false; } ConstraintKey that = (ConstraintKey) obj; - return artifact.equals( that.artifact ) && equals( repositories, that.repositories ); + return artifact.equals(that.artifact) && equals(repositories, that.repositories); } - private static boolean equals( List repos1, List repos2 ) - { - if ( repos1.size() != repos2.size() ) - { + private static boolean equals(List repos1, List repos2) { + if (repos1.size() != repos2.size()) { return false; } - for ( Iterator it1 = repos1.iterator(), it2 = repos2.iterator(); - it1.hasNext() && it2.hasNext(); ) - { + for (Iterator it1 = repos1.iterator(), it2 = repos2.iterator(); + it1.hasNext() && it2.hasNext(); ) { RemoteRepository repo1 = it1.next(); RemoteRepository repo2 = it2.next(); - if ( repo1.isRepositoryManager() != repo2.isRepositoryManager() ) - { + if (repo1.isRepositoryManager() != repo2.isRepositoryManager()) { return false; } - if ( repo1.isRepositoryManager() ) - { - if ( !equals( repo1.getMirroredRepositories(), repo2.getMirroredRepositories() ) ) - { + if (repo1.isRepositoryManager()) { + if (!equals(repo1.getMirroredRepositories(), repo2.getMirroredRepositories())) { return false; } - } - else if ( !repo1.getUrl().equals( repo2.getUrl() ) ) - { + } else if (!repo1.getUrl().equals(repo2.getUrl())) { return false; - } - else if ( repo1.getPolicy( true ).isEnabled() != repo2.getPolicy( true ).isEnabled() ) - { + } else if (repo1.getPolicy(true).isEnabled() + != repo2.getPolicy(true).isEnabled()) { return false; - } - else if ( repo1.getPolicy( false ).isEnabled() != repo2.getPolicy( false ).isEnabled() ) - { + } else if (repo1.getPolicy(false).isEnabled() + != repo2.getPolicy(false).isEnabled()) { return false; } } @@ -393,14 +341,12 @@ else if ( repo1.getPolicy( false ).isEnabled() != repo2.getPolicy( false ).isEna } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } } - static final class GraphKey - { + static final class GraphKey { private final Artifact artifact; private final List repositories; @@ -415,9 +361,13 @@ static final class GraphKey private final int hashCode; - GraphKey( Artifact artifact, List repositories, DependencySelector selector, - DependencyManager manager, DependencyTraverser traverser, VersionFilter filter ) - { + GraphKey( + Artifact artifact, + List repositories, + DependencySelector selector, + DependencyManager manager, + DependencyTraverser traverser, + VersionFilter filter) { this.artifact = artifact; this.repositories = repositories; this.selector = selector; @@ -425,46 +375,38 @@ static final class GraphKey this.traverser = traverser; this.filter = filter; - hashCode = Objects.hash( artifact, repositories, selector, manager, traverser, filter ); + hashCode = Objects.hash(artifact, repositories, selector, manager, traverser, filter); } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( !( obj instanceof GraphKey ) ) - { + } else if (!(obj instanceof GraphKey)) { return false; } GraphKey that = (GraphKey) obj; - return Objects.equals( artifact, that.artifact ) && Objects.equals( repositories, that.repositories ) - && Objects.equals( selector, that.selector ) && Objects.equals( manager, that.manager ) - && Objects.equals( traverser, that.traverser ) && Objects.equals( filter, that.filter ); + return Objects.equals(artifact, that.artifact) + && Objects.equals(repositories, that.repositories) + && Objects.equals(selector, that.selector) + && Objects.equals(manager, that.manager) + && Objects.equals(traverser, that.traverser) + && Objects.equals(filter, that.filter); } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } } - private static InternPool createPool( String type ) - { - if ( HARD.equals( type ) ) - { + private static InternPool createPool(String type) { + if (HARD.equals(type)) { return new HardInternPool<>(); - } - else if ( WEAK.equals( type ) ) - { + } else if (WEAK.equals(type)) { return new WeakInternPool<>(); - } - else - { - throw new IllegalArgumentException( "Unknown object pool type: '" + type + "'" ); + } else { + throw new IllegalArgumentException("Unknown object pool type: '" + type + "'"); } } @@ -472,54 +414,45 @@ else if ( WEAK.equals( type ) ) private static final String WEAK = "weak"; - private interface InternPool - { - V get( K key ); + private interface InternPool { + V get(K key); - V intern( K key, V value ); + V intern(K key, V value); } - private static class HardInternPool implements InternPool - { - private final ConcurrentHashMap map = new ConcurrentHashMap<>( 256 ); + private static class HardInternPool implements InternPool { + private final ConcurrentHashMap map = new ConcurrentHashMap<>(256); @Override - public V get( K key ) - { - return map.get( key ); + public V get(K key) { + return map.get(key); } @Override - public V intern( K key, V value ) - { - return map.computeIfAbsent( key, k -> value ); + public V intern(K key, V value) { + return map.computeIfAbsent(key, k -> value); } } - private static class WeakInternPool implements InternPool - { - private final Map> map = Collections.synchronizedMap( new WeakHashMap<>( 256 ) ); + private static class WeakInternPool implements InternPool { + private final Map> map = Collections.synchronizedMap(new WeakHashMap<>(256)); @Override - public V get( K key ) - { - WeakReference ref = map.get( key ); + public V get(K key) { + WeakReference ref = map.get(key); return ref != null ? ref.get() : null; } @Override - public V intern( K key, V value ) - { - WeakReference pooledRef = map.get( key ); - if ( pooledRef != null ) - { + public V intern(K key, V value) { + WeakReference pooledRef = map.get(key); + if (pooledRef != null) { V pooled = pooledRef.get(); - if ( pooled != null ) - { + if (pooled != null) { return pooled; } } - map.put( key, new WeakReference<>( value ) ); + map.put(key, new WeakReference<>(value)); return value; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCollectionContext.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCollectionContext.java index 117af8804..6874d4aae 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCollectionContext.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCollectionContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; import java.util.List; @@ -29,9 +28,7 @@ /** * Internal helper class for collector implementations. */ -public final class DefaultDependencyCollectionContext - implements DependencyCollectionContext -{ +public final class DefaultDependencyCollectionContext implements DependencyCollectionContext { private final RepositorySystemSession session; @@ -41,46 +38,41 @@ public final class DefaultDependencyCollectionContext private List managedDependencies; - public DefaultDependencyCollectionContext( RepositorySystemSession session, Artifact artifact, - Dependency dependency, List managedDependencies ) - { + public DefaultDependencyCollectionContext( + RepositorySystemSession session, + Artifact artifact, + Dependency dependency, + List managedDependencies) { this.session = session; - this.artifact = ( dependency != null ) ? dependency.getArtifact() : artifact; + this.artifact = (dependency != null) ? dependency.getArtifact() : artifact; this.dependency = dependency; this.managedDependencies = managedDependencies; } - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } - public Dependency getDependency() - { + public Dependency getDependency() { return dependency; } - public List getManagedDependencies() - { + public List getManagedDependencies() { return managedDependencies; } - public void set( Dependency dependency, List managedDependencies ) - { + public void set(Dependency dependency, List managedDependencies) { artifact = dependency.getArtifact(); this.dependency = dependency; this.managedDependencies = managedDependencies; } @Override - public String toString() - { - return String.valueOf( getDependency() ); + public String toString() { + return String.valueOf(getDependency()); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCollector.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCollector.java index 2ffe7b090..b468e7faa 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCollector.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCollector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; import javax.inject.Inject; import javax.inject.Named; @@ -44,9 +43,7 @@ */ @Singleton @Named -public class DefaultDependencyCollector - implements DependencyCollector, Service -{ +public class DefaultDependencyCollector implements DependencyCollector, Service { private static final String CONFIG_PROP_COLLECTOR_IMPL = "aether.dependencyCollector.impl"; private static final String DEFAULT_COLLECTOR_IMPL = DfDependencyCollector.NAME; @@ -59,39 +56,34 @@ public class DefaultDependencyCollector * @deprecated SL is to be removed. */ @Deprecated - public DefaultDependencyCollector() - { + public DefaultDependencyCollector() { this.delegates = new HashMap<>(); } @Inject - public DefaultDependencyCollector( Map delegates ) - { - this.delegates = requireNonNull( delegates ); + public DefaultDependencyCollector(Map delegates) { + this.delegates = requireNonNull(delegates); } @Override - public void initService( ServiceLocator locator ) - { + public void initService(ServiceLocator locator) { BfDependencyCollector bf = new BfDependencyCollector(); - bf.initService( locator ); + bf.initService(locator); DfDependencyCollector df = new DfDependencyCollector(); - df.initService( locator ); - this.delegates.put( BfDependencyCollector.NAME, bf ); - this.delegates.put( DfDependencyCollector.NAME, df ); + df.initService(locator); + this.delegates.put(BfDependencyCollector.NAME, bf); + this.delegates.put(DfDependencyCollector.NAME, df); } @Override - public CollectResult collectDependencies( RepositorySystemSession session, CollectRequest request ) - throws DependencyCollectionException - { - String delegateName = ConfigUtils.getString( session, DEFAULT_COLLECTOR_IMPL, CONFIG_PROP_COLLECTOR_IMPL ); - DependencyCollectorDelegate delegate = delegates.get( delegateName ); - if ( delegate == null ) - { - throw new IllegalArgumentException( "Unknown collector impl: '" + delegateName - + "', known implementations are " + delegates.keySet() ); + public CollectResult collectDependencies(RepositorySystemSession session, CollectRequest request) + throws DependencyCollectionException { + String delegateName = ConfigUtils.getString(session, DEFAULT_COLLECTOR_IMPL, CONFIG_PROP_COLLECTOR_IMPL); + DependencyCollectorDelegate delegate = delegates.get(delegateName); + if (delegate == null) { + throw new IllegalArgumentException( + "Unknown collector impl: '" + delegateName + "', known implementations are " + delegates.keySet()); } - return delegate.collectDependencies( session, request ); + return delegate.collectDependencies(session, request); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCycle.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCycle.java index d417b70e2..bd0f7f8c3 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCycle.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCycle.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; import java.util.Arrays; import java.util.Collections; @@ -33,43 +32,36 @@ * Default implementation of {@link DependencyCycle}. * Internal helper class for collector implementations. */ -public final class DefaultDependencyCycle - implements DependencyCycle -{ +public final class DefaultDependencyCycle implements DependencyCycle { private final List dependencies; private final int cycleEntry; - public DefaultDependencyCycle( List nodes, int cycleEntry, Dependency dependency ) - { + public DefaultDependencyCycle(List nodes, int cycleEntry, Dependency dependency) { // skip root node unless it actually has a dependency or is considered the cycle entry (due to its label) - int offset = ( cycleEntry > 0 && nodes.get( 0 ).getDependency() == null ) ? 1 : 0; + int offset = (cycleEntry > 0 && nodes.get(0).getDependency() == null) ? 1 : 0; Dependency[] dependencies = new Dependency[nodes.size() - offset + 1]; - for ( int i = 0, n = dependencies.length - 1; i < n; i++ ) - { - DependencyNode node = nodes.get( i + offset ); + for (int i = 0, n = dependencies.length - 1; i < n; i++) { + DependencyNode node = nodes.get(i + offset); dependencies[i] = node.getDependency(); // when cycle starts at root artifact as opposed to root dependency, synthesize a dependency - if ( dependencies[i] == null ) - { - dependencies[i] = new Dependency( node.getArtifact(), null ); + if (dependencies[i] == null) { + dependencies[i] = new Dependency(node.getArtifact(), null); } } dependencies[dependencies.length - 1] = dependency; - this.dependencies = Collections.unmodifiableList( Arrays.asList( dependencies ) ); + this.dependencies = Collections.unmodifiableList(Arrays.asList(dependencies)); this.cycleEntry = cycleEntry; } @Override - public List getPrecedingDependencies() - { - return dependencies.subList( 0, cycleEntry ); + public List getPrecedingDependencies() { + return dependencies.subList(0, cycleEntry); } @Override - public List getCyclicDependencies() - { - return dependencies.subList( cycleEntry, dependencies.size() ); + public List getCyclicDependencies() { + return dependencies.subList(cycleEntry, dependencies.size()); } /** @@ -81,33 +73,26 @@ public List getCyclicDependencies() * @return the index of the node furthest from the root and associated with the given artifact, or {@literal -1} if * there is no such node. */ - public static int find( List nodes, Artifact artifact ) - { + public static int find(List nodes, Artifact artifact) { - for ( int i = nodes.size() - 1; i >= 0; i-- ) - { - DependencyNode node = nodes.get( i ); + for (int i = nodes.size() - 1; i >= 0; i--) { + DependencyNode node = nodes.get(i); Artifact a = node.getArtifact(); - if ( a == null ) - { + if (a == null) { break; } - if ( !a.getArtifactId().equals( artifact.getArtifactId() ) ) - { + if (!a.getArtifactId().equals(artifact.getArtifactId())) { continue; } - if ( !a.getGroupId().equals( artifact.getGroupId() ) ) - { + if (!a.getGroupId().equals(artifact.getGroupId())) { continue; } - if ( !a.getExtension().equals( artifact.getExtension() ) ) - { + if (!a.getExtension().equals(artifact.getExtension())) { continue; } - if ( !a.getClassifier().equals( artifact.getClassifier() ) ) - { + if (!a.getClassifier().equals(artifact.getClassifier())) { continue; } /* @@ -125,19 +110,15 @@ public static int find( List nodes, Artifact artifact ) } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 256 ); + public String toString() { + StringBuilder buffer = new StringBuilder(256); int i = 0; - for ( Dependency dependency : dependencies ) - { - if ( i++ > 0 ) - { - buffer.append( " -> " ); + for (Dependency dependency : dependencies) { + if (i++ > 0) { + buffer.append(" -> "); } - buffer.append( ArtifactIdUtils.toVersionlessId( dependency.getArtifact() ) ); + buffer.append(ArtifactIdUtils.toVersionlessId(dependency.getArtifact())); } return buffer.toString(); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyGraphTransformationContext.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyGraphTransformationContext.java index 721eab5e2..04b85fa68 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyGraphTransformationContext.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyGraphTransformationContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,62 +16,53 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; import java.util.HashMap; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.collection.DependencyGraphTransformationContext; +import static java.util.Objects.requireNonNull; + /** * Default implementation of {@link DependencyGraphTransformationContext}. * Internal helper class for collector implementations. */ -public class DefaultDependencyGraphTransformationContext - implements DependencyGraphTransformationContext -{ +public class DefaultDependencyGraphTransformationContext implements DependencyGraphTransformationContext { private final RepositorySystemSession session; private final Map map; - public DefaultDependencyGraphTransformationContext( RepositorySystemSession session ) - { + public DefaultDependencyGraphTransformationContext(RepositorySystemSession session) { this.session = session; this.map = new HashMap<>(); } @Override - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } @Override - public Object get( Object key ) - { - return map.get( requireNonNull( key, "key cannot be null" ) ); + public Object get(Object key) { + return map.get(requireNonNull(key, "key cannot be null")); } @Override - public Object put( Object key, Object value ) - { - requireNonNull( key, "key cannot be null" ); - if ( value != null ) - { - return map.put( key, value ); - } - else - { - return map.remove( key ); + public Object put(Object key, Object value) { + requireNonNull(key, "key cannot be null"); + if (value != null) { + return map.put(key, value); + } else { + return map.remove(key); } } @Override - public String toString() - { - return String.valueOf( map ); + public String toString() { + return String.valueOf(map); } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultVersionFilterContext.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultVersionFilterContext.java index 97c16c63b..703b91016 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultVersionFilterContext.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DefaultVersionFilterContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; import java.util.ArrayList; import java.util.Collections; @@ -37,9 +36,7 @@ * Default implementation of {@link VersionFilter.VersionFilterContext}. * Internal helper class for collector implementations. */ -public final class DefaultVersionFilterContext - implements VersionFilter.VersionFilterContext -{ +public final class DefaultVersionFilterContext implements VersionFilter.VersionFilterContext { private final RepositorySystemSession session; private Dependency dependency; @@ -48,68 +45,57 @@ public final class DefaultVersionFilterContext private List versions; - public DefaultVersionFilterContext( RepositorySystemSession session ) - { + public DefaultVersionFilterContext(RepositorySystemSession session) { this.session = session; } - public void set( Dependency dependency, VersionRangeResult result ) - { + public void set(Dependency dependency, VersionRangeResult result) { this.dependency = dependency; this.result = result; - this.versions = new ArrayList<>( result.getVersions() ); + this.versions = new ArrayList<>(result.getVersions()); } - public List get() - { - return new ArrayList<>( versions ); + public List get() { + return new ArrayList<>(versions); } @Override - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } @Override - public Dependency getDependency() - { + public Dependency getDependency() { return dependency; } @Override - public VersionConstraint getVersionConstraint() - { + public VersionConstraint getVersionConstraint() { return result.getVersionConstraint(); } @Override - public int getCount() - { + public int getCount() { return versions.size(); } @Override - public ArtifactRepository getRepository( Version version ) - { - return result.getRepository( version ); + public ArtifactRepository getRepository(Version version) { + return result.getRepository(version); } @Override - public List getRepositories() - { - return Collections.unmodifiableList( result.getRequest().getRepositories() ); + public List getRepositories() { + return Collections.unmodifiableList(result.getRequest().getRepositories()); } @Override - public Iterator iterator() - { + public Iterator iterator() { return versions.iterator(); } @Override - public String toString() - { + public String toString() { return dependency + " " + result.getVersions(); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DependencyCollectorDelegate.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DependencyCollectorDelegate.java index d54fc4d8b..601e083bb 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DependencyCollectorDelegate.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/DependencyCollectorDelegate.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; import java.util.ArrayList; import java.util.Collection; @@ -68,8 +67,7 @@ * * @since 1.8.0 */ -public abstract class DependencyCollectorDelegate implements DependencyCollector -{ +public abstract class DependencyCollectorDelegate implements DependencyCollector { protected static final String CONFIG_PROP_MAX_EXCEPTIONS = "aether.dependencyCollector.maxExceptions"; protected static final int CONFIG_PROP_MAX_EXCEPTIONS_DEFAULT = 50; @@ -78,7 +76,7 @@ public abstract class DependencyCollectorDelegate implements DependencyCollector protected static final int CONFIG_PROP_MAX_CYCLES_DEFAULT = 10; - protected final Logger logger = LoggerFactory.getLogger( getClass() ); + protected final Logger logger = LoggerFactory.getLogger(getClass()); protected RemoteRepositoryManager remoteRepositoryManager; @@ -92,59 +90,52 @@ public abstract class DependencyCollectorDelegate implements DependencyCollector * @deprecated Will be dropped once SL gone. */ @Deprecated - protected DependencyCollectorDelegate() - { + protected DependencyCollectorDelegate() { // enables default constructor } - protected DependencyCollectorDelegate( RemoteRepositoryManager remoteRepositoryManager, - ArtifactDescriptorReader artifactDescriptorReader, - VersionRangeResolver versionRangeResolver ) - { - setRemoteRepositoryManager( remoteRepositoryManager ); - setArtifactDescriptorReader( artifactDescriptorReader ); - setVersionRangeResolver( versionRangeResolver ); + protected DependencyCollectorDelegate( + RemoteRepositoryManager remoteRepositoryManager, + ArtifactDescriptorReader artifactDescriptorReader, + VersionRangeResolver versionRangeResolver) { + setRemoteRepositoryManager(remoteRepositoryManager); + setArtifactDescriptorReader(artifactDescriptorReader); + setVersionRangeResolver(versionRangeResolver); } - public void initService( ServiceLocator locator ) - { - setRemoteRepositoryManager( locator.getService( RemoteRepositoryManager.class ) ); - setArtifactDescriptorReader( locator.getService( ArtifactDescriptorReader.class ) ); - setVersionRangeResolver( locator.getService( VersionRangeResolver.class ) ); + public void initService(ServiceLocator locator) { + setRemoteRepositoryManager(locator.getService(RemoteRepositoryManager.class)); + setArtifactDescriptorReader(locator.getService(ArtifactDescriptorReader.class)); + setVersionRangeResolver(locator.getService(VersionRangeResolver.class)); } - public DependencyCollector setRemoteRepositoryManager( RemoteRepositoryManager remoteRepositoryManager ) - { + public DependencyCollector setRemoteRepositoryManager(RemoteRepositoryManager remoteRepositoryManager) { this.remoteRepositoryManager = - requireNonNull( remoteRepositoryManager, "remote repository manager cannot be null" ); + requireNonNull(remoteRepositoryManager, "remote repository manager cannot be null"); return this; } - public DependencyCollector setArtifactDescriptorReader( ArtifactDescriptorReader artifactDescriptorReader ) - { - descriptorReader = requireNonNull( artifactDescriptorReader, "artifact descriptor reader cannot be null" ); + public DependencyCollector setArtifactDescriptorReader(ArtifactDescriptorReader artifactDescriptorReader) { + descriptorReader = requireNonNull(artifactDescriptorReader, "artifact descriptor reader cannot be null"); return this; } - public DependencyCollector setVersionRangeResolver( VersionRangeResolver versionRangeResolver ) - { - this.versionRangeResolver = - requireNonNull( versionRangeResolver, "version range resolver cannot be null" ); + public DependencyCollector setVersionRangeResolver(VersionRangeResolver versionRangeResolver) { + this.versionRangeResolver = requireNonNull(versionRangeResolver, "version range resolver cannot be null"); return this; } - @SuppressWarnings( "checkstyle:methodlength" ) + @SuppressWarnings("checkstyle:methodlength") @Override - public final CollectResult collectDependencies( RepositorySystemSession session, CollectRequest request ) - throws DependencyCollectionException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); - session = optimizeSession( session ); + public final CollectResult collectDependencies(RepositorySystemSession session, CollectRequest request) + throws DependencyCollectionException { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); + session = optimizeSession(session); - RequestTrace trace = RequestTrace.newChild( request.getTrace(), request ); + RequestTrace trace = RequestTrace.newChild(request.getTrace(), request); - CollectResult result = new CollectResult( request ); + CollectResult result = new CollectResult(request); DependencyTraverser depTraverser = session.getDependencyTraverser(); VersionFilter verFilter = session.getVersionFilter(); @@ -158,96 +149,88 @@ public final CollectResult collectDependencies( RepositorySystemSession session, long time1 = System.nanoTime(); DefaultDependencyNode node; - if ( root != null ) - { + if (root != null) { List versions; VersionRangeResult rangeResult; - try - { - VersionRangeRequest rangeRequest = - new VersionRangeRequest( root.getArtifact(), request.getRepositories(), - request.getRequestContext() ); - rangeRequest.setTrace( trace ); - rangeResult = versionRangeResolver.resolveVersionRange( session, rangeRequest ); - versions = filterVersions( root, rangeResult, verFilter, new DefaultVersionFilterContext( session ) ); - } - catch ( VersionRangeResolutionException e ) - { - result.addException( e ); - throw new DependencyCollectionException( result, e.getMessage() ); + try { + VersionRangeRequest rangeRequest = new VersionRangeRequest( + root.getArtifact(), request.getRepositories(), request.getRequestContext()); + rangeRequest.setTrace(trace); + rangeResult = versionRangeResolver.resolveVersionRange(session, rangeRequest); + versions = filterVersions(root, rangeResult, verFilter, new DefaultVersionFilterContext(session)); + } catch (VersionRangeResolutionException e) { + result.addException(e); + throw new DependencyCollectionException(result, e.getMessage()); } - Version version = versions.get( versions.size() - 1 ); - root = root.setArtifact( root.getArtifact().setVersion( version.toString() ) ); + Version version = versions.get(versions.size() - 1); + root = root.setArtifact(root.getArtifact().setVersion(version.toString())); ArtifactDescriptorResult descriptorResult; - try - { + try { ArtifactDescriptorRequest descriptorRequest = new ArtifactDescriptorRequest(); - descriptorRequest.setArtifact( root.getArtifact() ); - descriptorRequest.setRepositories( request.getRepositories() ); - descriptorRequest.setRequestContext( request.getRequestContext() ); - descriptorRequest.setTrace( trace ); - if ( isLackingDescriptor( root.getArtifact() ) ) - { - descriptorResult = new ArtifactDescriptorResult( descriptorRequest ); + descriptorRequest.setArtifact(root.getArtifact()); + descriptorRequest.setRepositories(request.getRepositories()); + descriptorRequest.setRequestContext(request.getRequestContext()); + descriptorRequest.setTrace(trace); + if (isLackingDescriptor(root.getArtifact())) { + descriptorResult = new ArtifactDescriptorResult(descriptorRequest); + } else { + descriptorResult = descriptorReader.readArtifactDescriptor(session, descriptorRequest); } - else - { - descriptorResult = descriptorReader.readArtifactDescriptor( session, descriptorRequest ); - } - } - catch ( ArtifactDescriptorException e ) - { - result.addException( e ); - throw new DependencyCollectionException( result, e.getMessage() ); + } catch (ArtifactDescriptorException e) { + result.addException(e); + throw new DependencyCollectionException(result, e.getMessage()); } - root = root.setArtifact( descriptorResult.getArtifact() ); + root = root.setArtifact(descriptorResult.getArtifact()); - if ( !session.isIgnoreArtifactDescriptorRepositories() ) - { - repositories = remoteRepositoryManager.aggregateRepositories( session, repositories, - descriptorResult.getRepositories(), - true ); + if (!session.isIgnoreArtifactDescriptorRepositories()) { + repositories = remoteRepositoryManager.aggregateRepositories( + session, repositories, descriptorResult.getRepositories(), true); } - dependencies = mergeDeps( dependencies, descriptorResult.getDependencies() ); - managedDependencies = mergeDeps( managedDependencies, descriptorResult.getManagedDependencies() ); - - node = new DefaultDependencyNode( root ); - node.setRequestContext( request.getRequestContext() ); - node.setRelocations( descriptorResult.getRelocations() ); - node.setVersionConstraint( rangeResult.getVersionConstraint() ); - node.setVersion( version ); - node.setAliases( descriptorResult.getAliases() ); - node.setRepositories( request.getRepositories() ); - } - else - { - node = new DefaultDependencyNode( request.getRootArtifact() ); - node.setRequestContext( request.getRequestContext() ); - node.setRepositories( request.getRepositories() ); + dependencies = mergeDeps(dependencies, descriptorResult.getDependencies()); + managedDependencies = mergeDeps(managedDependencies, descriptorResult.getManagedDependencies()); + + node = new DefaultDependencyNode(root); + node.setRequestContext(request.getRequestContext()); + node.setRelocations(descriptorResult.getRelocations()); + node.setVersionConstraint(rangeResult.getVersionConstraint()); + node.setVersion(version); + node.setAliases(descriptorResult.getAliases()); + node.setRepositories(request.getRepositories()); + } else { + node = new DefaultDependencyNode(request.getRootArtifact()); + node.setRequestContext(request.getRequestContext()); + node.setRepositories(request.getRepositories()); } - result.setRoot( node ); + result.setRoot(node); - boolean traverse = root == null || depTraverser == null || depTraverser.traverseDependency( root ); + boolean traverse = root == null || depTraverser == null || depTraverser.traverseDependency(root); String errorPath = null; - if ( traverse && !dependencies.isEmpty() ) - { - DataPool pool = new DataPool( session ); + if (traverse && !dependencies.isEmpty()) { + DataPool pool = new DataPool(session); DefaultDependencyCollectionContext context = new DefaultDependencyCollectionContext( - session, request.getRootArtifact(), root, managedDependencies ); + session, request.getRootArtifact(), root, managedDependencies); - DefaultVersionFilterContext versionContext = new DefaultVersionFilterContext( session ); + DefaultVersionFilterContext versionContext = new DefaultVersionFilterContext(session); - Results results = new Results( result, session ); + Results results = new Results(result, session); doCollectDependencies( - session, trace, pool, context, versionContext, request, node, repositories, dependencies, - managedDependencies, results - ); + session, + trace, + pool, + context, + versionContext, + request, + node, + repositories, + dependencies, + managedDependencies, + results); errorPath = results.getErrorPath(); } @@ -255,36 +238,29 @@ public final CollectResult collectDependencies( RepositorySystemSession session, long time2 = System.nanoTime(); DependencyGraphTransformer transformer = session.getDependencyGraphTransformer(); - if ( transformer != null ) - { - try - { + if (transformer != null) { + try { DefaultDependencyGraphTransformationContext context = - new DefaultDependencyGraphTransformationContext( session ); - context.put( TransformationContextKeys.STATS, stats ); - result.setRoot( transformer.transformGraph( node, context ) ); - } - catch ( RepositoryException e ) - { - result.addException( e ); + new DefaultDependencyGraphTransformationContext(session); + context.put(TransformationContextKeys.STATS, stats); + result.setRoot(transformer.transformGraph(node, context)); + } catch (RepositoryException e) { + result.addException(e); } } long time3 = System.nanoTime(); - if ( logger.isDebugEnabled() ) - { - stats.put( getClass().getSimpleName() + ".collectTime", time2 - time1 ); - stats.put( getClass().getSimpleName() + ".transformTime", time3 - time2 ); - logger.debug( "Dependency collection stats {}", stats ); + if (logger.isDebugEnabled()) { + stats.put(getClass().getSimpleName() + ".collectTime", time2 - time1); + stats.put(getClass().getSimpleName() + ".transformTime", time3 - time2); + logger.debug("Dependency collection stats {}", stats); } - if ( errorPath != null ) - { - throw new DependencyCollectionException( result, "Failed to collect dependencies at " + errorPath ); + if (errorPath != null) { + throw new DependencyCollectionException(result, "Failed to collect dependencies at " + errorPath); } - if ( !result.getExceptions().isEmpty() ) - { - throw new DependencyCollectionException( result ); + if (!result.getExceptions().isEmpty()) { + throw new DependencyCollectionException(result); } return result; @@ -304,196 +280,177 @@ public final CollectResult collectDependencies( RepositorySystemSession session, * @param node Currently collected node, that collector came by following the passed in path. * @return A child request trance instance, never {@code null}. */ - protected RequestTrace collectStepTrace( RequestTrace trace, String context, List path, - Dependency node ) - { - return RequestTrace.newChild( - trace, - new CollectStepDataImpl( - context, - path, - node - ) - ); + protected RequestTrace collectStepTrace( + RequestTrace trace, String context, List path, Dependency node) { + return RequestTrace.newChild(trace, new CollectStepDataImpl(context, path, node)); } - @SuppressWarnings( "checkstyle:parameternumber" ) - protected abstract void doCollectDependencies( RepositorySystemSession session, RequestTrace trace, DataPool pool, - DefaultDependencyCollectionContext context, - DefaultVersionFilterContext versionContext, - CollectRequest request, DependencyNode node, - List repositories, List dependencies, - List managedDependencies, Results results ); - - protected RepositorySystemSession optimizeSession( RepositorySystemSession session ) - { - DefaultRepositorySystemSession optimized = new DefaultRepositorySystemSession( session ); - optimized.setArtifactTypeRegistry( CachingArtifactTypeRegistry.newInstance( session ) ); + @SuppressWarnings("checkstyle:parameternumber") + protected abstract void doCollectDependencies( + RepositorySystemSession session, + RequestTrace trace, + DataPool pool, + DefaultDependencyCollectionContext context, + DefaultVersionFilterContext versionContext, + CollectRequest request, + DependencyNode node, + List repositories, + List dependencies, + List managedDependencies, + Results results); + + protected RepositorySystemSession optimizeSession(RepositorySystemSession session) { + DefaultRepositorySystemSession optimized = new DefaultRepositorySystemSession(session); + optimized.setArtifactTypeRegistry(CachingArtifactTypeRegistry.newInstance(session)); return optimized; } - protected List mergeDeps( List dominant, List recessive ) - { + protected List mergeDeps(List dominant, List recessive) { List result; - if ( dominant == null || dominant.isEmpty() ) - { + if (dominant == null || dominant.isEmpty()) { result = recessive; - } - else if ( recessive == null || recessive.isEmpty() ) - { + } else if (recessive == null || recessive.isEmpty()) { result = dominant; - } - else - { + } else { int initialCapacity = dominant.size() + recessive.size(); - result = new ArrayList<>( initialCapacity ); - Collection ids = new HashSet<>( initialCapacity, 1.0f ); - for ( Dependency dependency : dominant ) - { - ids.add( getId( dependency.getArtifact() ) ); - result.add( dependency ); + result = new ArrayList<>(initialCapacity); + Collection ids = new HashSet<>(initialCapacity, 1.0f); + for (Dependency dependency : dominant) { + ids.add(getId(dependency.getArtifact())); + result.add(dependency); } - for ( Dependency dependency : recessive ) - { - if ( !ids.contains( getId( dependency.getArtifact() ) ) ) - { - result.add( dependency ); + for (Dependency dependency : recessive) { + if (!ids.contains(getId(dependency.getArtifact()))) { + result.add(dependency); } } } return result; } - protected static String getId( Artifact a ) - { + protected static String getId(Artifact a) { return a.getGroupId() + ':' + a.getArtifactId() + ':' + a.getClassifier() + ':' + a.getExtension(); } - @SuppressWarnings( "checkstyle:parameternumber" ) - protected static DefaultDependencyNode createDependencyNode( List relocations, - PremanagedDependency preManaged, - VersionRangeResult rangeResult, Version version, - Dependency d, Collection aliases, - List repos, String requestContext ) - { - DefaultDependencyNode child = new DefaultDependencyNode( d ); - preManaged.applyTo( child ); - child.setRelocations( relocations ); - child.setVersionConstraint( rangeResult.getVersionConstraint() ); - child.setVersion( version ); - child.setAliases( aliases ); - child.setRepositories( repos ); - child.setRequestContext( requestContext ); + @SuppressWarnings("checkstyle:parameternumber") + protected static DefaultDependencyNode createDependencyNode( + List relocations, + PremanagedDependency preManaged, + VersionRangeResult rangeResult, + Version version, + Dependency d, + Collection aliases, + List repos, + String requestContext) { + DefaultDependencyNode child = new DefaultDependencyNode(d); + preManaged.applyTo(child); + child.setRelocations(relocations); + child.setVersionConstraint(rangeResult.getVersionConstraint()); + child.setVersion(version); + child.setAliases(aliases); + child.setRepositories(repos); + child.setRequestContext(requestContext); return child; } - protected static DefaultDependencyNode createDependencyNode( List relocations, - PremanagedDependency preManaged, - VersionRangeResult rangeResult, Version version, - Dependency d, - ArtifactDescriptorResult descriptorResult, - DependencyNode cycleNode ) - { - DefaultDependencyNode child = - createDependencyNode( relocations, preManaged, rangeResult, version, d, descriptorResult.getAliases(), - cycleNode.getRepositories(), cycleNode.getRequestContext() ); - child.setChildren( cycleNode.getChildren() ); + protected static DefaultDependencyNode createDependencyNode( + List relocations, + PremanagedDependency preManaged, + VersionRangeResult rangeResult, + Version version, + Dependency d, + ArtifactDescriptorResult descriptorResult, + DependencyNode cycleNode) { + DefaultDependencyNode child = createDependencyNode( + relocations, + preManaged, + rangeResult, + version, + d, + descriptorResult.getAliases(), + cycleNode.getRepositories(), + cycleNode.getRequestContext()); + child.setChildren(cycleNode.getChildren()); return child; } - protected static ArtifactDescriptorRequest createArtifactDescriptorRequest( String requestContext, - RequestTrace requestTrace, - List repositories, - Dependency d ) - { + protected static ArtifactDescriptorRequest createArtifactDescriptorRequest( + String requestContext, RequestTrace requestTrace, List repositories, Dependency d) { ArtifactDescriptorRequest descriptorRequest = new ArtifactDescriptorRequest(); - descriptorRequest.setArtifact( d.getArtifact() ); - descriptorRequest.setRepositories( repositories ); - descriptorRequest.setRequestContext( requestContext ); - descriptorRequest.setTrace( requestTrace ); + descriptorRequest.setArtifact(d.getArtifact()); + descriptorRequest.setRepositories(repositories); + descriptorRequest.setRequestContext(requestContext); + descriptorRequest.setTrace(requestTrace); return descriptorRequest; } - protected static VersionRangeRequest createVersionRangeRequest( String requestContext, - RequestTrace requestTrace, - List repositories, - Dependency dependency ) - { + protected static VersionRangeRequest createVersionRangeRequest( + String requestContext, + RequestTrace requestTrace, + List repositories, + Dependency dependency) { VersionRangeRequest rangeRequest = new VersionRangeRequest(); - rangeRequest.setArtifact( dependency.getArtifact() ); - rangeRequest.setRepositories( repositories ); - rangeRequest.setRequestContext( requestContext ); - rangeRequest.setTrace( requestTrace ); + rangeRequest.setArtifact(dependency.getArtifact()); + rangeRequest.setRepositories(repositories); + rangeRequest.setRequestContext(requestContext); + rangeRequest.setTrace(requestTrace); return rangeRequest; } - protected VersionRangeResult cachedResolveRangeResult( VersionRangeRequest rangeRequest, DataPool pool, - RepositorySystemSession session ) - throws VersionRangeResolutionException - { - Object key = pool.toKey( rangeRequest ); - VersionRangeResult rangeResult = pool.getConstraint( key, rangeRequest ); - if ( rangeResult == null ) - { - rangeResult = versionRangeResolver.resolveVersionRange( session, rangeRequest ); - pool.putConstraint( key, rangeResult ); + protected VersionRangeResult cachedResolveRangeResult( + VersionRangeRequest rangeRequest, DataPool pool, RepositorySystemSession session) + throws VersionRangeResolutionException { + Object key = pool.toKey(rangeRequest); + VersionRangeResult rangeResult = pool.getConstraint(key, rangeRequest); + if (rangeResult == null) { + rangeResult = versionRangeResolver.resolveVersionRange(session, rangeRequest); + pool.putConstraint(key, rangeResult); } return rangeResult; } - protected static boolean isLackingDescriptor( Artifact artifact ) - { - return artifact.getProperty( ArtifactProperties.LOCAL_PATH, null ) != null; + protected static boolean isLackingDescriptor(Artifact artifact) { + return artifact.getProperty(ArtifactProperties.LOCAL_PATH, null) != null; } - protected static List getRemoteRepositories( ArtifactRepository repository, - List repositories ) - { - if ( repository instanceof RemoteRepository ) - { - return Collections.singletonList( (RemoteRepository) repository ); + protected static List getRemoteRepositories( + ArtifactRepository repository, List repositories) { + if (repository instanceof RemoteRepository) { + return Collections.singletonList((RemoteRepository) repository); } - if ( repository != null ) - { + if (repository != null) { return Collections.emptyList(); } return repositories; } - protected static List filterVersions( Dependency dependency, VersionRangeResult rangeResult, - VersionFilter verFilter, - DefaultVersionFilterContext verContext ) - throws VersionRangeResolutionException - { - if ( rangeResult.getVersions().isEmpty() ) - { - throw new VersionRangeResolutionException( rangeResult, - "No versions available for " + dependency.getArtifact() - + " within specified range" ); + protected static List filterVersions( + Dependency dependency, + VersionRangeResult rangeResult, + VersionFilter verFilter, + DefaultVersionFilterContext verContext) + throws VersionRangeResolutionException { + if (rangeResult.getVersions().isEmpty()) { + throw new VersionRangeResolutionException( + rangeResult, "No versions available for " + dependency.getArtifact() + " within specified range"); } List versions; - if ( verFilter != null && rangeResult.getVersionConstraint().getRange() != null ) - { - verContext.set( dependency, rangeResult ); - try - { - verFilter.filterVersions( verContext ); - } - catch ( RepositoryException e ) - { - throw new VersionRangeResolutionException( rangeResult, - "Failed to filter versions for " + dependency.getArtifact(), e ); + if (verFilter != null && rangeResult.getVersionConstraint().getRange() != null) { + verContext.set(dependency, rangeResult); + try { + verFilter.filterVersions(verContext); + } catch (RepositoryException e) { + throw new VersionRangeResolutionException( + rangeResult, "Failed to filter versions for " + dependency.getArtifact(), e); } versions = verContext.get(); - if ( versions.isEmpty() ) - { - throw new VersionRangeResolutionException( rangeResult, - "No acceptable versions for " + dependency.getArtifact() + ": " + rangeResult.getVersions() ); + if (versions.isEmpty()) { + throw new VersionRangeResolutionException( + rangeResult, + "No acceptable versions for " + dependency.getArtifact() + ": " + rangeResult.getVersions()); } - } - else - { + } else { versions = rangeResult.getVersions(); } return versions; @@ -502,8 +459,7 @@ protected static List filterVersions( Dependency dependency, /** * Helper class used during collection. */ - protected static class Results - { + protected static class Results { private final CollectResult result; @@ -513,58 +469,46 @@ protected static class Results String errorPath; - public Results( CollectResult result, RepositorySystemSession session ) - { + public Results(CollectResult result, RepositorySystemSession session) { this.result = result; maxExceptions = - ConfigUtils.getInteger( session, CONFIG_PROP_MAX_EXCEPTIONS_DEFAULT, CONFIG_PROP_MAX_EXCEPTIONS ); + ConfigUtils.getInteger(session, CONFIG_PROP_MAX_EXCEPTIONS_DEFAULT, CONFIG_PROP_MAX_EXCEPTIONS); - maxCycles = ConfigUtils.getInteger( session, CONFIG_PROP_MAX_CYCLES_DEFAULT, CONFIG_PROP_MAX_CYCLES ); + maxCycles = ConfigUtils.getInteger(session, CONFIG_PROP_MAX_CYCLES_DEFAULT, CONFIG_PROP_MAX_CYCLES); } - public String getErrorPath() - { + public String getErrorPath() { return errorPath; } - public void addException( Dependency dependency, Exception e, List nodes ) - { - if ( maxExceptions < 0 || result.getExceptions().size() < maxExceptions ) - { - result.addException( e ); - if ( errorPath == null ) - { - StringBuilder buffer = new StringBuilder( 256 ); - for ( DependencyNode node : nodes ) - { - if ( buffer.length() > 0 ) - { - buffer.append( " -> " ); + public void addException(Dependency dependency, Exception e, List nodes) { + if (maxExceptions < 0 || result.getExceptions().size() < maxExceptions) { + result.addException(e); + if (errorPath == null) { + StringBuilder buffer = new StringBuilder(256); + for (DependencyNode node : nodes) { + if (buffer.length() > 0) { + buffer.append(" -> "); } Dependency dep = node.getDependency(); - if ( dep != null ) - { - buffer.append( dep.getArtifact() ); + if (dep != null) { + buffer.append(dep.getArtifact()); } } - if ( buffer.length() > 0 ) - { - buffer.append( " -> " ); + if (buffer.length() > 0) { + buffer.append(" -> "); } - buffer.append( dependency.getArtifact() ); + buffer.append(dependency.getArtifact()); errorPath = buffer.toString(); } } } - public void addCycle( List nodes, int cycleEntry, Dependency dependency ) - { - if ( maxCycles < 0 || result.getCycles().size() < maxCycles ) - { - result.addCycle( new DefaultDependencyCycle( nodes, cycleEntry, dependency ) ); + public void addCycle(List nodes, int cycleEntry, Dependency dependency) { + if (maxCycles < 0 || result.getCycles().size() < maxCycles) { + result.addCycle(new DefaultDependencyCycle(nodes, cycleEntry, dependency)); } } } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/PremanagedDependency.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/PremanagedDependency.java index 2d259c632..c0a6ef3bb 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/PremanagedDependency.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/PremanagedDependency.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.collection.DependencyManagement; @@ -28,17 +33,10 @@ import org.eclipse.aether.graph.Exclusion; import org.eclipse.aether.util.graph.manager.DependencyManagerUtils; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - /** * Helper class used during collection. */ -public class PremanagedDependency -{ +public class PremanagedDependency { final String premanagedVersion; @@ -62,33 +60,37 @@ public class PremanagedDependency final boolean premanagedState; - @SuppressWarnings( "checkstyle:parameternumber" ) - PremanagedDependency( String premanagedVersion, String premanagedScope, Boolean premanagedOptional, - Collection premanagedExclusions, Map premanagedProperties, - int managedBits, Dependency managedDependency, boolean premanagedState ) - { + @SuppressWarnings("checkstyle:parameternumber") + PremanagedDependency( + String premanagedVersion, + String premanagedScope, + Boolean premanagedOptional, + Collection premanagedExclusions, + Map premanagedProperties, + int managedBits, + Dependency managedDependency, + boolean premanagedState) { this.premanagedVersion = premanagedVersion; this.premanagedScope = premanagedScope; this.premanagedOptional = premanagedOptional; - this.premanagedExclusions = - premanagedExclusions != null - ? Collections.unmodifiableCollection( new ArrayList<>( premanagedExclusions ) ) - : null; + this.premanagedExclusions = premanagedExclusions != null + ? Collections.unmodifiableCollection(new ArrayList<>(premanagedExclusions)) + : null; this.premanagedProperties = - premanagedProperties != null - ? Collections.unmodifiableMap( new HashMap<>( premanagedProperties ) ) - : null; + premanagedProperties != null ? Collections.unmodifiableMap(new HashMap<>(premanagedProperties)) : null; this.managedBits = managedBits; this.managedDependency = managedDependency; this.premanagedState = premanagedState; } - public static PremanagedDependency create( DependencyManager depManager, Dependency dependency, - boolean disableVersionManagement, boolean premanagedState ) - { - DependencyManagement depMngt = depManager != null ? depManager.manageDependency( dependency ) : null; + public static PremanagedDependency create( + DependencyManager depManager, + Dependency dependency, + boolean disableVersionManagement, + boolean premanagedState) { + DependencyManagement depMngt = depManager != null ? depManager.manageDependency(dependency) : null; int managedBits = 0; String premanagedVersion = null; @@ -97,63 +99,58 @@ public static PremanagedDependency create( DependencyManager depManager, Depende Collection premanagedExclusions = null; Map premanagedProperties = null; - if ( depMngt != null ) - { - if ( depMngt.getVersion() != null && !disableVersionManagement ) - { + if (depMngt != null) { + if (depMngt.getVersion() != null && !disableVersionManagement) { Artifact artifact = dependency.getArtifact(); premanagedVersion = artifact.getVersion(); - dependency = dependency.setArtifact( artifact.setVersion( depMngt.getVersion() ) ); + dependency = dependency.setArtifact(artifact.setVersion(depMngt.getVersion())); managedBits |= DependencyNode.MANAGED_VERSION; } - if ( depMngt.getProperties() != null ) - { + if (depMngt.getProperties() != null) { Artifact artifact = dependency.getArtifact(); premanagedProperties = artifact.getProperties(); - dependency = dependency.setArtifact( artifact.setProperties( depMngt.getProperties() ) ); + dependency = dependency.setArtifact(artifact.setProperties(depMngt.getProperties())); managedBits |= DependencyNode.MANAGED_PROPERTIES; } - if ( depMngt.getScope() != null ) - { + if (depMngt.getScope() != null) { premanagedScope = dependency.getScope(); - dependency = dependency.setScope( depMngt.getScope() ); + dependency = dependency.setScope(depMngt.getScope()); managedBits |= DependencyNode.MANAGED_SCOPE; } - if ( depMngt.getOptional() != null ) - { + if (depMngt.getOptional() != null) { premanagedOptional = dependency.isOptional(); - dependency = dependency.setOptional( depMngt.getOptional() ); + dependency = dependency.setOptional(depMngt.getOptional()); managedBits |= DependencyNode.MANAGED_OPTIONAL; } - if ( depMngt.getExclusions() != null ) - { + if (depMngt.getExclusions() != null) { premanagedExclusions = dependency.getExclusions(); - dependency = dependency.setExclusions( depMngt.getExclusions() ); + dependency = dependency.setExclusions(depMngt.getExclusions()); managedBits |= DependencyNode.MANAGED_EXCLUSIONS; } } - return new PremanagedDependency( premanagedVersion, premanagedScope, premanagedOptional, - premanagedExclusions, premanagedProperties, managedBits, dependency, - premanagedState ); - + return new PremanagedDependency( + premanagedVersion, + premanagedScope, + premanagedOptional, + premanagedExclusions, + premanagedProperties, + managedBits, + dependency, + premanagedState); } - public Dependency getManagedDependency() - { + public Dependency getManagedDependency() { return managedDependency; } - public void applyTo( DefaultDependencyNode child ) - { - child.setManagedBits( managedBits ); - if ( premanagedState ) - { - child.setData( DependencyManagerUtils.NODE_DATA_PREMANAGED_VERSION, premanagedVersion ); - child.setData( DependencyManagerUtils.NODE_DATA_PREMANAGED_SCOPE, premanagedScope ); - child.setData( DependencyManagerUtils.NODE_DATA_PREMANAGED_OPTIONAL, premanagedOptional ); - child.setData( DependencyManagerUtils.NODE_DATA_PREMANAGED_EXCLUSIONS, premanagedExclusions ); - child.setData( DependencyManagerUtils.NODE_DATA_PREMANAGED_PROPERTIES, premanagedProperties ); + public void applyTo(DefaultDependencyNode child) { + child.setManagedBits(managedBits); + if (premanagedState) { + child.setData(DependencyManagerUtils.NODE_DATA_PREMANAGED_VERSION, premanagedVersion); + child.setData(DependencyManagerUtils.NODE_DATA_PREMANAGED_SCOPE, premanagedScope); + child.setData(DependencyManagerUtils.NODE_DATA_PREMANAGED_OPTIONAL, premanagedOptional); + child.setData(DependencyManagerUtils.NODE_DATA_PREMANAGED_EXCLUSIONS, premanagedExclusions); + child.setData(DependencyManagerUtils.NODE_DATA_PREMANAGED_PROPERTIES, premanagedProperties); } } - -} \ No newline at end of file +} diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/BfDependencyCollector.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/BfDependencyCollector.java index 209de1971..250dce77a 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/BfDependencyCollector.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/BfDependencyCollector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect.bf; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect.bf; import javax.inject.Inject; import javax.inject.Named; @@ -83,10 +82,8 @@ * @since 1.8.0 */ @Singleton -@Named( BfDependencyCollector.NAME ) -public class BfDependencyCollector - extends DependencyCollectorDelegate implements Service -{ +@Named(BfDependencyCollector.NAME) +public class BfDependencyCollector extends DependencyCollectorDelegate implements Service { public static final String NAME = "bf"; /** @@ -117,438 +114,428 @@ public class BfDependencyCollector * @deprecated Will be dropped once SL gone. */ @Deprecated - public BfDependencyCollector() - { + public BfDependencyCollector() { // enables default constructor } @Inject - BfDependencyCollector( RemoteRepositoryManager remoteRepositoryManager, - ArtifactDescriptorReader artifactDescriptorReader, - VersionRangeResolver versionRangeResolver ) - { - super( remoteRepositoryManager, artifactDescriptorReader, versionRangeResolver ); + BfDependencyCollector( + RemoteRepositoryManager remoteRepositoryManager, + ArtifactDescriptorReader artifactDescriptorReader, + VersionRangeResolver versionRangeResolver) { + super(remoteRepositoryManager, artifactDescriptorReader, versionRangeResolver); } - @SuppressWarnings( "checkstyle:parameternumber" ) + @SuppressWarnings("checkstyle:parameternumber") @Override - protected void doCollectDependencies( RepositorySystemSession session, RequestTrace trace, DataPool pool, - DefaultDependencyCollectionContext context, - DefaultVersionFilterContext versionContext, - CollectRequest request, DependencyNode node, - List repositories, List dependencies, - List managedDependencies, Results results ) - { - boolean useSkip = ConfigUtils.getBoolean( - session, CONFIG_PROP_SKIPPER_DEFAULT, CONFIG_PROP_SKIPPER - ); - int nThreads = ExecutorUtils.threadCount( - session, 5, CONFIG_PROP_THREADS, "maven.artifact.threads" ); - logger.debug( "Using thread pool with {} threads to resolve descriptors.", nThreads ); - - if ( useSkip ) - { - logger.debug( "Collector skip mode enabled" ); + protected void doCollectDependencies( + RepositorySystemSession session, + RequestTrace trace, + DataPool pool, + DefaultDependencyCollectionContext context, + DefaultVersionFilterContext versionContext, + CollectRequest request, + DependencyNode node, + List repositories, + List dependencies, + List managedDependencies, + Results results) { + boolean useSkip = ConfigUtils.getBoolean(session, CONFIG_PROP_SKIPPER_DEFAULT, CONFIG_PROP_SKIPPER); + int nThreads = ExecutorUtils.threadCount(session, 5, CONFIG_PROP_THREADS, "maven.artifact.threads"); + logger.debug("Using thread pool with {} threads to resolve descriptors.", nThreads); + + if (useSkip) { + logger.debug("Collector skip mode enabled"); } - try ( DependencyResolutionSkipper skipper = useSkip - ? DependencyResolutionSkipper.defaultSkipper() : DependencyResolutionSkipper.neverSkipper(); - ParallelDescriptorResolver parallelDescriptorResolver = new ParallelDescriptorResolver( nThreads ) ) - { - Args args = new Args( - session, pool, context, versionContext, request, skipper, parallelDescriptorResolver ); + try (DependencyResolutionSkipper skipper = useSkip + ? DependencyResolutionSkipper.defaultSkipper() + : DependencyResolutionSkipper.neverSkipper(); + ParallelDescriptorResolver parallelDescriptorResolver = new ParallelDescriptorResolver(nThreads)) { + Args args = new Args(session, pool, context, versionContext, request, skipper, parallelDescriptorResolver); DependencySelector rootDepSelector = session.getDependencySelector() != null - ? session.getDependencySelector().deriveChildSelector( context ) : null; + ? session.getDependencySelector().deriveChildSelector(context) + : null; DependencyManager rootDepManager = session.getDependencyManager() != null - ? session.getDependencyManager().deriveChildManager( context ) : null; + ? session.getDependencyManager().deriveChildManager(context) + : null; DependencyTraverser rootDepTraverser = session.getDependencyTraverser() != null - ? session.getDependencyTraverser().deriveChildTraverser( context ) : null; + ? session.getDependencyTraverser().deriveChildTraverser(context) + : null; VersionFilter rootVerFilter = session.getVersionFilter() != null - ? session.getVersionFilter().deriveChildFilter( context ) : null; - - List parents = Collections.singletonList( node ); - for ( Dependency dependency : dependencies ) - { - RequestTrace childTrace = collectStepTrace( trace, args.request.getRequestContext(), parents, - dependency ); - DependencyProcessingContext processingContext = - new DependencyProcessingContext( rootDepSelector, rootDepManager, rootDepTraverser, - rootVerFilter, childTrace, repositories, managedDependencies, parents, dependency, - PremanagedDependency.create( rootDepManager, dependency, - false, args.premanagedState ) ); - if ( !filter( processingContext ) ) - { - processingContext.withDependency( processingContext.premanagedDependency.getManagedDependency() ); - resolveArtifactDescriptorAsync( args, processingContext, results ); - args.dependencyProcessingQueue.add( processingContext ); + ? session.getVersionFilter().deriveChildFilter(context) + : null; + + List parents = Collections.singletonList(node); + for (Dependency dependency : dependencies) { + RequestTrace childTrace = + collectStepTrace(trace, args.request.getRequestContext(), parents, dependency); + DependencyProcessingContext processingContext = new DependencyProcessingContext( + rootDepSelector, + rootDepManager, + rootDepTraverser, + rootVerFilter, + childTrace, + repositories, + managedDependencies, + parents, + dependency, + PremanagedDependency.create(rootDepManager, dependency, false, args.premanagedState)); + if (!filter(processingContext)) { + processingContext.withDependency(processingContext.premanagedDependency.getManagedDependency()); + resolveArtifactDescriptorAsync(args, processingContext, results); + args.dependencyProcessingQueue.add(processingContext); } } - while ( !args.dependencyProcessingQueue.isEmpty() ) - { - processDependency( args, results, args.dependencyProcessingQueue.remove(), Collections.emptyList(), - false ); + while (!args.dependencyProcessingQueue.isEmpty()) { + processDependency( + args, results, args.dependencyProcessingQueue.remove(), Collections.emptyList(), false); } } } - @SuppressWarnings( "checkstyle:parameternumber" ) - private void processDependency( Args args, Results results, - DependencyProcessingContext context, List relocations, - boolean disableVersionManagement ) - { + @SuppressWarnings("checkstyle:parameternumber") + private void processDependency( + Args args, + Results results, + DependencyProcessingContext context, + List relocations, + boolean disableVersionManagement) { Dependency dependency = context.dependency; PremanagedDependency preManaged = context.premanagedDependency; - boolean noDescriptor = isLackingDescriptor( dependency.getArtifact() ); + boolean noDescriptor = isLackingDescriptor(dependency.getArtifact()); boolean traverse = - !noDescriptor && ( context.depTraverser == null || context.depTraverser.traverseDependency( - dependency ) ); + !noDescriptor && (context.depTraverser == null || context.depTraverser.traverseDependency(dependency)); - Future resolutionResultFuture = args.resolver.find( dependency.getArtifact() ); + Future resolutionResultFuture = args.resolver.find(dependency.getArtifact()); DescriptorResolutionResult resolutionResult; VersionRangeResult rangeResult; - try - { + try { resolutionResult = resolutionResultFuture.get(); rangeResult = resolutionResult.rangeResult; - } - catch ( Exception e ) - { - results.addException( dependency, e, context.parents ); + } catch (Exception e) { + results.addException(dependency, e, context.parents); return; } Set versions = resolutionResult.descriptors.keySet(); - for ( Version version : versions ) - { - Artifact originalArtifact = dependency.getArtifact().setVersion( version.toString() ); - Dependency d = dependency.setArtifact( originalArtifact ); - - final ArtifactDescriptorResult descriptorResult = resolutionResult.descriptors.get( version ); - if ( descriptorResult != null ) - { - d = d.setArtifact( descriptorResult.getArtifact() ); - - int cycleEntry = find( context.parents, d.getArtifact() ); - if ( cycleEntry >= 0 ) - { - results.addCycle( context.parents, cycleEntry, d ); - DependencyNode cycleNode = context.parents.get( cycleEntry ); - if ( cycleNode.getDependency() != null ) - { - DefaultDependencyNode child = - createDependencyNode( relocations, preManaged, rangeResult, version, d, - descriptorResult, cycleNode ); - context.getParent().getChildren().add( child ); + for (Version version : versions) { + Artifact originalArtifact = dependency.getArtifact().setVersion(version.toString()); + Dependency d = dependency.setArtifact(originalArtifact); + + final ArtifactDescriptorResult descriptorResult = resolutionResult.descriptors.get(version); + if (descriptorResult != null) { + d = d.setArtifact(descriptorResult.getArtifact()); + + int cycleEntry = find(context.parents, d.getArtifact()); + if (cycleEntry >= 0) { + results.addCycle(context.parents, cycleEntry, d); + DependencyNode cycleNode = context.parents.get(cycleEntry); + if (cycleNode.getDependency() != null) { + DefaultDependencyNode child = createDependencyNode( + relocations, preManaged, rangeResult, version, d, descriptorResult, cycleNode); + context.getParent().getChildren().add(child); continue; } } - if ( !descriptorResult.getRelocations().isEmpty() ) - { + if (!descriptorResult.getRelocations().isEmpty()) { boolean disableVersionManagementSubsequently = - originalArtifact.getGroupId().equals( d.getArtifact().getGroupId() ) - && originalArtifact.getArtifactId().equals( d.getArtifact().getArtifactId() ); - - PremanagedDependency premanagedDependency = - PremanagedDependency.create( context.depManager, d, disableVersionManagementSubsequently, - args.premanagedState ); - DependencyProcessingContext relocatedContext = - new DependencyProcessingContext( context.depSelector, context.depManager, - context.depTraverser, context.verFilter, - context.trace, context.repositories, descriptorResult.getManagedDependencies(), - context.parents, - d, premanagedDependency ); - - if ( !filter( relocatedContext ) ) - { - relocatedContext.withDependency( premanagedDependency.getManagedDependency() ); - resolveArtifactDescriptorAsync( args, relocatedContext, results ); - processDependency( args, results, relocatedContext, descriptorResult.getRelocations(), - disableVersionManagementSubsequently ); + originalArtifact.getGroupId().equals(d.getArtifact().getGroupId()) + && originalArtifact + .getArtifactId() + .equals(d.getArtifact().getArtifactId()); + + PremanagedDependency premanagedDependency = PremanagedDependency.create( + context.depManager, d, disableVersionManagementSubsequently, args.premanagedState); + DependencyProcessingContext relocatedContext = new DependencyProcessingContext( + context.depSelector, + context.depManager, + context.depTraverser, + context.verFilter, + context.trace, + context.repositories, + descriptorResult.getManagedDependencies(), + context.parents, + d, + premanagedDependency); + + if (!filter(relocatedContext)) { + relocatedContext.withDependency(premanagedDependency.getManagedDependency()); + resolveArtifactDescriptorAsync(args, relocatedContext, results); + processDependency( + args, + results, + relocatedContext, + descriptorResult.getRelocations(), + disableVersionManagementSubsequently); } return; - } - else - { - d = args.pool.intern( d.setArtifact( args.pool.intern( d.getArtifact() ) ) ); + } else { + d = args.pool.intern(d.setArtifact(args.pool.intern(d.getArtifact()))); List repos = - getRemoteRepositories( rangeResult.getRepository( version ), context.repositories ); - - DefaultDependencyNode child = - createDependencyNode( relocations, preManaged, rangeResult, version, d, - descriptorResult.getAliases(), repos, args.request.getRequestContext() ); - - context.getParent().getChildren().add( child ); - - boolean recurse = traverse && !descriptorResult.getDependencies().isEmpty(); - DependencyProcessingContext parentContext = context.withDependency( d ); - if ( recurse ) - { - doRecurse( args, parentContext, descriptorResult, child, results, - disableVersionManagement ); - } - else if ( !args.skipper.skipResolution( child, parentContext.parents ) ) - { - List parents = new ArrayList<>( parentContext.parents.size() + 1 ); - parents.addAll( parentContext.parents ); - parents.add( child ); - args.skipper.cache( child, parents ); + getRemoteRepositories(rangeResult.getRepository(version), context.repositories); + + DefaultDependencyNode child = createDependencyNode( + relocations, + preManaged, + rangeResult, + version, + d, + descriptorResult.getAliases(), + repos, + args.request.getRequestContext()); + + context.getParent().getChildren().add(child); + + boolean recurse = + traverse && !descriptorResult.getDependencies().isEmpty(); + DependencyProcessingContext parentContext = context.withDependency(d); + if (recurse) { + doRecurse(args, parentContext, descriptorResult, child, results, disableVersionManagement); + } else if (!args.skipper.skipResolution(child, parentContext.parents)) { + List parents = new ArrayList<>(parentContext.parents.size() + 1); + parents.addAll(parentContext.parents); + parents.add(child); + args.skipper.cache(child, parents); } } - } - else - { + } else { List repos = - getRemoteRepositories( rangeResult.getRepository( version ), context.repositories ); - DefaultDependencyNode child = - createDependencyNode( relocations, preManaged, rangeResult, version, d, null, repos, - args.request.getRequestContext() ); - context.getParent().getChildren().add( child ); + getRemoteRepositories(rangeResult.getRepository(version), context.repositories); + DefaultDependencyNode child = createDependencyNode( + relocations, + preManaged, + rangeResult, + version, + d, + null, + repos, + args.request.getRequestContext()); + context.getParent().getChildren().add(child); } } } - @SuppressWarnings( "checkstyle:parameternumber" ) - private void doRecurse( Args args, DependencyProcessingContext parentContext, - ArtifactDescriptorResult descriptorResult, DefaultDependencyNode child, Results results, - boolean disableVersionManagement ) - { + @SuppressWarnings("checkstyle:parameternumber") + private void doRecurse( + Args args, + DependencyProcessingContext parentContext, + ArtifactDescriptorResult descriptorResult, + DefaultDependencyNode child, + Results results, + boolean disableVersionManagement) { DefaultDependencyCollectionContext context = args.collectionContext; - context.set( parentContext.dependency, descriptorResult.getManagedDependencies() ); + context.set(parentContext.dependency, descriptorResult.getManagedDependencies()); DependencySelector childSelector = - parentContext.depSelector != null ? parentContext.depSelector.deriveChildSelector( context ) : null; + parentContext.depSelector != null ? parentContext.depSelector.deriveChildSelector(context) : null; DependencyManager childManager = - parentContext.depManager != null ? parentContext.depManager.deriveChildManager( context ) : null; + parentContext.depManager != null ? parentContext.depManager.deriveChildManager(context) : null; DependencyTraverser childTraverser = - parentContext.depTraverser != null ? parentContext.depTraverser.deriveChildTraverser( context ) : null; + parentContext.depTraverser != null ? parentContext.depTraverser.deriveChildTraverser(context) : null; VersionFilter childFilter = - parentContext.verFilter != null ? parentContext.verFilter.deriveChildFilter( context ) : null; - - final List childRepos = - args.ignoreRepos - ? parentContext.repositories - : remoteRepositoryManager.aggregateRepositories( args.session, parentContext.repositories, - descriptorResult.getRepositories(), true ); - - Object key = - args.pool.toKey( parentContext.dependency.getArtifact(), childRepos, childSelector, childManager, - childTraverser, childFilter ); - - List children = args.pool.getChildren( key ); - if ( children == null ) - { - boolean skipResolution = args.skipper.skipResolution( child, parentContext.parents ); - if ( !skipResolution ) - { - List parents = new ArrayList<>( parentContext.parents.size() + 1 ); - parents.addAll( parentContext.parents ); - parents.add( child ); - for ( Dependency dependency : descriptorResult.getDependencies() ) - { - RequestTrace childTrace = - collectStepTrace( parentContext.trace, args.request.getRequestContext(), parents, - dependency ); - PremanagedDependency premanagedDependency = - PremanagedDependency.create( childManager, dependency, disableVersionManagement, - args.premanagedState ); - DependencyProcessingContext processingContext = - new DependencyProcessingContext( childSelector, childManager, childTraverser, childFilter, - childTrace, childRepos, descriptorResult.getManagedDependencies(), parents, - dependency, premanagedDependency ); - if ( !filter( processingContext ) ) - { - //resolve descriptors ahead for managed dependency - processingContext.withDependency( - processingContext.premanagedDependency.getManagedDependency() ); - resolveArtifactDescriptorAsync( args, processingContext, results ); - args.dependencyProcessingQueue.add( processingContext ); + parentContext.verFilter != null ? parentContext.verFilter.deriveChildFilter(context) : null; + + final List childRepos = args.ignoreRepos + ? parentContext.repositories + : remoteRepositoryManager.aggregateRepositories( + args.session, parentContext.repositories, descriptorResult.getRepositories(), true); + + Object key = args.pool.toKey( + parentContext.dependency.getArtifact(), + childRepos, + childSelector, + childManager, + childTraverser, + childFilter); + + List children = args.pool.getChildren(key); + if (children == null) { + boolean skipResolution = args.skipper.skipResolution(child, parentContext.parents); + if (!skipResolution) { + List parents = new ArrayList<>(parentContext.parents.size() + 1); + parents.addAll(parentContext.parents); + parents.add(child); + for (Dependency dependency : descriptorResult.getDependencies()) { + RequestTrace childTrace = collectStepTrace( + parentContext.trace, args.request.getRequestContext(), parents, dependency); + PremanagedDependency premanagedDependency = PremanagedDependency.create( + childManager, dependency, disableVersionManagement, args.premanagedState); + DependencyProcessingContext processingContext = new DependencyProcessingContext( + childSelector, + childManager, + childTraverser, + childFilter, + childTrace, + childRepos, + descriptorResult.getManagedDependencies(), + parents, + dependency, + premanagedDependency); + if (!filter(processingContext)) { + // resolve descriptors ahead for managed dependency + processingContext.withDependency(processingContext.premanagedDependency.getManagedDependency()); + resolveArtifactDescriptorAsync(args, processingContext, results); + args.dependencyProcessingQueue.add(processingContext); } } - args.pool.putChildren( key, child.getChildren() ); - args.skipper.cache( child, parents ); + args.pool.putChildren(key, child.getChildren()); + args.skipper.cache(child, parents); } - } - else - { - child.setChildren( children ); + } else { + child.setChildren(children); } } - private boolean filter( DependencyProcessingContext context ) - { - return context.depSelector != null && !context.depSelector.selectDependency( context.dependency ); + private boolean filter(DependencyProcessingContext context) { + return context.depSelector != null && !context.depSelector.selectDependency(context.dependency); } - - private void resolveArtifactDescriptorAsync( Args args, DependencyProcessingContext context, - Results results ) - { + private void resolveArtifactDescriptorAsync(Args args, DependencyProcessingContext context, Results results) { Dependency dependency = context.dependency; - args.resolver.resolveDescriptors( dependency.getArtifact(), () -> - { - VersionRangeRequest rangeRequest = - createVersionRangeRequest( args.request.getRequestContext(), context.trace, context.repositories, - dependency ); - VersionRangeResult rangeResult = cachedResolveRangeResult( rangeRequest, args.pool, args.session ); - List versions = filterVersions( dependency, rangeResult, context.verFilter, - args.versionContext ); - - //resolve newer version first to maximize benefits of skipper - Collections.reverse( versions ); - - Map descriptors = new ConcurrentHashMap<>( versions.size() ); + args.resolver.resolveDescriptors(dependency.getArtifact(), () -> { + VersionRangeRequest rangeRequest = createVersionRangeRequest( + args.request.getRequestContext(), context.trace, context.repositories, dependency); + VersionRangeResult rangeResult = cachedResolveRangeResult(rangeRequest, args.pool, args.session); + List versions = + filterVersions(dependency, rangeResult, context.verFilter, args.versionContext); + + // resolve newer version first to maximize benefits of skipper + Collections.reverse(versions); + + Map descriptors = new ConcurrentHashMap<>(versions.size()); Stream stream = versions.size() > 1 ? versions.parallelStream() : versions.stream(); - stream.forEach( version -> - Optional.ofNullable( resolveDescriptorForVersion( args, context, results, dependency, version ) ) - .ifPresent( r -> descriptors.put( version, r ) ) - ); + stream.forEach(version -> Optional.ofNullable( + resolveDescriptorForVersion(args, context, results, dependency, version)) + .ifPresent(r -> descriptors.put(version, r))); DescriptorResolutionResult resolutionResult = - new DescriptorResolutionResult( dependency.getArtifact(), rangeResult ); - //keep original sequence - versions.forEach( version -> resolutionResult.descriptors.put( version, descriptors.get( version ) ) ); - //populate for versions in version range - resolutionResult.flatten().forEach( dr -> args.resolver.cacheVersionRangeDescriptor( dr.artifact, dr ) ); + new DescriptorResolutionResult(dependency.getArtifact(), rangeResult); + // keep original sequence + versions.forEach(version -> resolutionResult.descriptors.put(version, descriptors.get(version))); + // populate for versions in version range + resolutionResult.flatten().forEach(dr -> args.resolver.cacheVersionRangeDescriptor(dr.artifact, dr)); return resolutionResult; - } ); + }); } - private ArtifactDescriptorResult resolveDescriptorForVersion( Args args, DependencyProcessingContext context, - Results results, Dependency dependency, - Version version ) - { + private ArtifactDescriptorResult resolveDescriptorForVersion( + Args args, DependencyProcessingContext context, Results results, Dependency dependency, Version version) { Artifact original = dependency.getArtifact(); - Artifact newArtifact = new DefaultArtifact( original.getGroupId(), - original.getArtifactId(), original.getClassifier(), original.getExtension(), - version.toString(), original.getProperties(), (ArtifactType) null ); - Dependency newDependency = new Dependency( newArtifact, dependency.getScope(), dependency.isOptional(), - dependency.getExclusions() ); + Artifact newArtifact = new DefaultArtifact( + original.getGroupId(), + original.getArtifactId(), + original.getClassifier(), + original.getExtension(), + version.toString(), + original.getProperties(), + (ArtifactType) null); + Dependency newDependency = + new Dependency(newArtifact, dependency.getScope(), dependency.isOptional(), dependency.getExclusions()); DependencyProcessingContext newContext = context.copy(); - ArtifactDescriptorRequest descriptorRequest = - createArtifactDescriptorRequest( args.request.getRequestContext(), context.trace, - newContext.repositories, newDependency ); - return isLackingDescriptor( newArtifact ) - ? new ArtifactDescriptorResult( descriptorRequest ) - : resolveCachedArtifactDescriptor( args.pool, descriptorRequest, args.session, - newContext.withDependency( newDependency ), results ); + ArtifactDescriptorRequest descriptorRequest = createArtifactDescriptorRequest( + args.request.getRequestContext(), context.trace, newContext.repositories, newDependency); + return isLackingDescriptor(newArtifact) + ? new ArtifactDescriptorResult(descriptorRequest) + : resolveCachedArtifactDescriptor( + args.pool, descriptorRequest, args.session, newContext.withDependency(newDependency), results); } - private ArtifactDescriptorResult resolveCachedArtifactDescriptor( DataPool pool, - ArtifactDescriptorRequest descriptorRequest, - RepositorySystemSession session, - DependencyProcessingContext context, - Results results ) - { - Object key = pool.toKey( descriptorRequest ); - ArtifactDescriptorResult descriptorResult = pool.getDescriptor( key, descriptorRequest ); - if ( descriptorResult == null ) - { - try - { - descriptorResult = descriptorReader.readArtifactDescriptor( session, descriptorRequest ); - pool.putDescriptor( key, descriptorResult ); - } - catch ( ArtifactDescriptorException e ) - { - results.addException( context.dependency, e, context.parents ); - pool.putDescriptor( key, e ); + private ArtifactDescriptorResult resolveCachedArtifactDescriptor( + DataPool pool, + ArtifactDescriptorRequest descriptorRequest, + RepositorySystemSession session, + DependencyProcessingContext context, + Results results) { + Object key = pool.toKey(descriptorRequest); + ArtifactDescriptorResult descriptorResult = pool.getDescriptor(key, descriptorRequest); + if (descriptorResult == null) { + try { + descriptorResult = descriptorReader.readArtifactDescriptor(session, descriptorRequest); + pool.putDescriptor(key, descriptorResult); + } catch (ArtifactDescriptorException e) { + results.addException(context.dependency, e, context.parents); + pool.putDescriptor(key, e); return null; } - } - else if ( descriptorResult == DataPool.NO_DESCRIPTOR ) - { + } else if (descriptorResult == DataPool.NO_DESCRIPTOR) { return null; } return descriptorResult; } - static class ParallelDescriptorResolver implements Closeable - { + static class ParallelDescriptorResolver implements Closeable { private final ExecutorService executorService; /** * Artifact ID -> Future of DescriptorResolutionResult */ - private final Map> results = new ConcurrentHashMap<>( 256 ); + private final Map> results = new ConcurrentHashMap<>(256); - ParallelDescriptorResolver( int threads ) - { - this.executorService = ExecutorUtils.threadPool( threads, getClass().getSimpleName() + "-" ); + ParallelDescriptorResolver(int threads) { + this.executorService = ExecutorUtils.threadPool(threads, getClass().getSimpleName() + "-"); } - void resolveDescriptors( Artifact artifact, Callable callable ) - { - results.computeIfAbsent( ArtifactIdUtils.toId( artifact ), - key -> this.executorService.submit( callable ) ); + void resolveDescriptors(Artifact artifact, Callable callable) { + results.computeIfAbsent(ArtifactIdUtils.toId(artifact), key -> this.executorService.submit(callable)); } - void cacheVersionRangeDescriptor( Artifact artifact, DescriptorResolutionResult resolutionResult ) - { - results.computeIfAbsent( ArtifactIdUtils.toId( artifact ), - key -> ConcurrentUtils.constantFuture( resolutionResult ) ); + void cacheVersionRangeDescriptor(Artifact artifact, DescriptorResolutionResult resolutionResult) { + results.computeIfAbsent( + ArtifactIdUtils.toId(artifact), key -> ConcurrentUtils.constantFuture(resolutionResult)); } - Future find( Artifact artifact ) - { - return results.get( ArtifactIdUtils.toId( artifact ) ); + Future find(Artifact artifact) { + return results.get(ArtifactIdUtils.toId(artifact)); } @Override - public void close() - { + public void close() { executorService.shutdown(); } } - static class DescriptorResolutionResult - { + static class DescriptorResolutionResult { Artifact artifact; VersionRangeResult rangeResult; Map descriptors; - DescriptorResolutionResult( Artifact artifact, VersionRangeResult rangeResult ) - { + DescriptorResolutionResult(Artifact artifact, VersionRangeResult rangeResult) { this.artifact = artifact; this.rangeResult = rangeResult; - this.descriptors = new LinkedHashMap<>( rangeResult.getVersions().size() ); + this.descriptors = new LinkedHashMap<>(rangeResult.getVersions().size()); } - DescriptorResolutionResult( VersionRangeResult rangeResult, - Version version, ArtifactDescriptorResult descriptor ) - { - this( descriptor.getArtifact(), rangeResult ); - this.descriptors.put( version, descriptor ); + DescriptorResolutionResult( + VersionRangeResult rangeResult, Version version, ArtifactDescriptorResult descriptor) { + this(descriptor.getArtifact(), rangeResult); + this.descriptors.put(version, descriptor); } - List flatten() - { - if ( descriptors.size() > 1 ) - { + List flatten() { + if (descriptors.size() > 1) { return descriptors.entrySet().stream() - .map( e -> new DescriptorResolutionResult( rangeResult, e.getKey(), e.getValue() ) ) - .collect( Collectors.toList() ); - } - else - { + .map(e -> new DescriptorResolutionResult(rangeResult, e.getKey(), e.getValue())) + .collect(Collectors.toList()); + } else { return Collections.emptyList(); } } } - static class Args - { + static class Args { final RepositorySystemSession session; @@ -558,7 +545,7 @@ static class Args final DataPool pool; - final Queue dependencyProcessingQueue = new ArrayDeque<>( 128 ); + final Queue dependencyProcessingQueue = new ArrayDeque<>(128); final DefaultDependencyCollectionContext collectionContext; @@ -570,22 +557,23 @@ static class Args final ParallelDescriptorResolver resolver; - Args( RepositorySystemSession session, DataPool pool, - DefaultDependencyCollectionContext collectionContext, DefaultVersionFilterContext versionContext, - CollectRequest request, DependencyResolutionSkipper skipper, - ParallelDescriptorResolver resolver ) - { + Args( + RepositorySystemSession session, + DataPool pool, + DefaultDependencyCollectionContext collectionContext, + DefaultVersionFilterContext versionContext, + CollectRequest request, + DependencyResolutionSkipper skipper, + ParallelDescriptorResolver resolver) { this.session = session; this.request = request; this.ignoreRepos = session.isIgnoreArtifactDescriptorRepositories(); - this.premanagedState = ConfigUtils.getBoolean( session, false, DependencyManagerUtils.CONFIG_PROP_VERBOSE ); + this.premanagedState = ConfigUtils.getBoolean(session, false, DependencyManagerUtils.CONFIG_PROP_VERBOSE); this.pool = pool; this.collectionContext = collectionContext; this.versionContext = versionContext; this.skipper = skipper; this.resolver = resolver; } - } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/DependencyProcessingContext.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/DependencyProcessingContext.java index 508d2d04d..ef9d2be11 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/DependencyProcessingContext.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/DependencyProcessingContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect.bf; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect.bf; import java.util.List; @@ -36,8 +35,7 @@ * * @since 1.8.0 */ -final class DependencyProcessingContext -{ +final class DependencyProcessingContext { final DependencySelector depSelector; final DependencyManager depManager; final DependencyTraverser depTraverser; @@ -49,22 +47,23 @@ final class DependencyProcessingContext * All parents of the dependency in the top > down order. */ final List parents; + final PremanagedDependency premanagedDependency; final RequestTrace trace; Dependency dependency; - @SuppressWarnings( "checkstyle:parameternumber" ) - DependencyProcessingContext( DependencySelector depSelector, - DependencyManager depManager, - DependencyTraverser depTraverser, - VersionFilter verFilter, - RequestTrace trace, - List repositories, - List managedDependencies, - List parents, - Dependency dependency, - PremanagedDependency premanagedDependency ) - { + @SuppressWarnings("checkstyle:parameternumber") + DependencyProcessingContext( + DependencySelector depSelector, + DependencyManager depManager, + DependencyTraverser depTraverser, + VersionFilter verFilter, + RequestTrace trace, + List repositories, + List managedDependencies, + List parents, + Dependency dependency, + PremanagedDependency premanagedDependency) { this.depSelector = depSelector; this.depManager = depManager; this.depTraverser = depTraverser; @@ -77,21 +76,26 @@ final class DependencyProcessingContext this.parents = parents; } - DependencyProcessingContext withDependency( Dependency dependency ) - { + DependencyProcessingContext withDependency(Dependency dependency) { this.dependency = dependency; return this; } - DependencyProcessingContext copy() - { - return new DependencyProcessingContext( depSelector, depManager, depTraverser, - verFilter, trace, repositories, managedDependencies, parents, dependency, - premanagedDependency ); + DependencyProcessingContext copy() { + return new DependencyProcessingContext( + depSelector, + depManager, + depTraverser, + verFilter, + trace, + repositories, + managedDependencies, + parents, + dependency, + premanagedDependency); } - DependencyNode getParent() - { - return parents.get( parents.size() - 1 ); + DependencyNode getParent() { + return parents.get(parents.size() - 1); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/DependencyResolutionSkipper.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/DependencyResolutionSkipper.java index 34107046e..d010695fd 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/DependencyResolutionSkipper.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/bf/DependencyResolutionSkipper.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect.bf; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.eclipse.aether.artifact.Artifact; -import org.eclipse.aether.graph.DependencyNode; -import org.eclipse.aether.util.artifact.ArtifactIdUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +package org.eclipse.aether.internal.impl.collect.bf; import java.io.Closeable; import java.util.HashMap; @@ -32,14 +25,19 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; +import org.eclipse.aether.artifact.Artifact; +import org.eclipse.aether.graph.DependencyNode; +import org.eclipse.aether.util.artifact.ArtifactIdUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * A skipper that determines whether to skip resolving given node during the dependency collection. * Internal helper for {@link BfDependencyCollector}. * * @since 1.8.0 */ -abstract class DependencyResolutionSkipper implements Closeable -{ +abstract class DependencyResolutionSkipper implements Closeable { /** * Check whether the resolution of current node can be skipped before resolving. * @@ -48,7 +46,7 @@ abstract class DependencyResolutionSkipper implements Closeable * * @return {@code true} if the node can be skipped for resolution, {@code false} if resolution required. */ - abstract boolean skipResolution( DependencyNode node, List parents ); + abstract boolean skipResolution(DependencyNode node, List parents); /** * Cache the resolution result when a node is resolved by {@link BfDependencyCollector) after resolution. @@ -56,7 +54,7 @@ abstract class DependencyResolutionSkipper implements Closeable * @param node Current node * @param parents All parent nodes of current node */ - abstract void cache( DependencyNode node, List parents ); + abstract void cache(DependencyNode node, List parents); /** * Close: Print the skip/resolve status report for all nodes. @@ -69,118 +67,95 @@ abstract class DependencyResolutionSkipper implements Closeable * * Note: type is specialized for testing purposes. */ - public static DefaultDependencyResolutionSkipper defaultSkipper() - { + public static DefaultDependencyResolutionSkipper defaultSkipper() { return new DefaultDependencyResolutionSkipper(); } /** * Returns instance of "never" skipper. */ - public static DependencyResolutionSkipper neverSkipper() - { + public static DependencyResolutionSkipper neverSkipper() { return NeverDependencyResolutionSkipper.INSTANCE; } /** * NEVER implementation. */ - private static final class NeverDependencyResolutionSkipper extends DependencyResolutionSkipper - { + private static final class NeverDependencyResolutionSkipper extends DependencyResolutionSkipper { private static final DependencyResolutionSkipper INSTANCE = new NeverDependencyResolutionSkipper(); @Override - public boolean skipResolution( DependencyNode node, List parents ) - { + public boolean skipResolution(DependencyNode node, List parents) { return false; } @Override - public void cache( DependencyNode node, List parents ) - { - } + public void cache(DependencyNode node, List parents) {} @Override - public void close() - { - } + public void close() {} } /** * Visible for testing. */ - static final class DefaultDependencyResolutionSkipper extends DependencyResolutionSkipper - { - private static final Logger LOGGER = LoggerFactory.getLogger( DependencyResolutionSkipper.class ); + static final class DefaultDependencyResolutionSkipper extends DependencyResolutionSkipper { + private static final Logger LOGGER = LoggerFactory.getLogger(DependencyResolutionSkipper.class); - private final Map results = new LinkedHashMap<>( 256 ); + private final Map results = new LinkedHashMap<>(256); private final CacheManager cacheManager = new CacheManager(); private final CoordinateManager coordinateManager = new CoordinateManager(); @Override - public boolean skipResolution( DependencyNode node, List parents ) - { - DependencyResolutionResult result = new DependencyResolutionResult( node ); - results.put( node, result ); + public boolean skipResolution(DependencyNode node, List parents) { + DependencyResolutionResult result = new DependencyResolutionResult(node); + results.put(node, result); int depth = parents.size() + 1; - coordinateManager.createCoordinate( node, depth ); + coordinateManager.createCoordinate(node, depth); - if ( cacheManager.isVersionConflict( node ) ) - { + if (cacheManager.isVersionConflict(node)) { /* * Skip resolving version conflict losers (omitted for conflict) */ result.skippedAsVersionConflict = true; - if ( LOGGER.isTraceEnabled() ) - { - LOGGER.trace( "Skipped resolving node: {} as version conflict", - ArtifactIdUtils.toId( node.getArtifact() ) ); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace( + "Skipped resolving node: {} as version conflict", ArtifactIdUtils.toId(node.getArtifact())); } - } - else if ( cacheManager.isDuplicate( node ) ) - { - if ( coordinateManager.isLeftmost( node, parents ) ) - { + } else if (cacheManager.isDuplicate(node)) { + if (coordinateManager.isLeftmost(node, parents)) { /* * Force resolving the node to retain conflict paths when its coordinate is * more left than last resolved * This is because Maven picks the widest scope present among conflicting dependencies */ result.forceResolution = true; - if ( LOGGER.isTraceEnabled() ) - { - LOGGER.trace( "Force resolving node: {} for scope selection", - ArtifactIdUtils.toId( node.getArtifact() ) ); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace( + "Force resolving node: {} for scope selection", + ArtifactIdUtils.toId(node.getArtifact())); } - } - else - { + } else { /* * Skip resolving as duplicate (depth deeper, omitted for duplicate) * No need to compare depth as the depth of winner for given artifact is always shallower */ result.skippedAsDuplicate = true; - if ( LOGGER.isTraceEnabled() ) - { - LOGGER.trace( "Skipped resolving node: {} as duplicate", - ArtifactIdUtils.toId( node.getArtifact() ) ); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace( + "Skipped resolving node: {} as duplicate", ArtifactIdUtils.toId(node.getArtifact())); } } - } - else - { + } else { result.resolve = true; - if ( LOGGER.isTraceEnabled() ) - { - LOGGER.trace( "Resolving node: {}", - ArtifactIdUtils.toId( node.getArtifact() ) ); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Resolving node: {}", ArtifactIdUtils.toId(node.getArtifact())); } } - if ( result.toResolve() ) - { - coordinateManager.updateLeftmost( node ); + if (result.toResolve()) { + coordinateManager.updateLeftmost(node); return false; } @@ -188,151 +163,136 @@ else if ( cacheManager.isDuplicate( node ) ) } @Override - public void cache( DependencyNode node, List parents ) - { - boolean parentForceResolution = parents.stream() - .anyMatch( n -> results.containsKey( n ) && results.get( n ).forceResolution ); - if ( parentForceResolution ) - { - if ( LOGGER.isTraceEnabled() ) - { - LOGGER.trace( "Won't cache as node: {} inherits from a force-resolved node " - + "and will be omitted for duplicate", ArtifactIdUtils.toId( node.getArtifact() ) ); + public void cache(DependencyNode node, List parents) { + boolean parentForceResolution = + parents.stream().anyMatch(n -> results.containsKey(n) && results.get(n).forceResolution); + if (parentForceResolution) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace( + "Won't cache as node: {} inherits from a force-resolved node " + + "and will be omitted for duplicate", + ArtifactIdUtils.toId(node.getArtifact())); } - } - else - { - cacheManager.cacheWinner( node ); + } else { + cacheManager.cacheWinner(node); } } @Override - public void close() - { - if ( LOGGER.isTraceEnabled() ) - { - LOGGER.trace( "Skipped {} nodes as duplicate", - results.entrySet().stream().filter( n -> n.getValue().skippedAsDuplicate ).count() ); - LOGGER.trace( "Skipped {} nodes as having version conflict", - results.entrySet().stream().filter( n -> n.getValue().skippedAsVersionConflict ).count() ); - LOGGER.trace( "Resolved {} nodes", - results.entrySet().stream().filter( n -> n.getValue().resolve ).count() ); - LOGGER.trace( "Forced resolving {} nodes for scope selection", - results.entrySet().stream().filter( n -> n.getValue().forceResolution ).count() ); + public void close() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace( + "Skipped {} nodes as duplicate", + results.entrySet().stream() + .filter(n -> n.getValue().skippedAsDuplicate) + .count()); + LOGGER.trace( + "Skipped {} nodes as having version conflict", + results.entrySet().stream() + .filter(n -> n.getValue().skippedAsVersionConflict) + .count()); + LOGGER.trace( + "Resolved {} nodes", + results.entrySet().stream() + .filter(n -> n.getValue().resolve) + .count()); + LOGGER.trace( + "Forced resolving {} nodes for scope selection", + results.entrySet().stream() + .filter(n -> n.getValue().forceResolution) + .count()); } } - public Map getResults() - { + public Map getResults() { return results; } - private static final class CacheManager - { + private static final class CacheManager { /** * artifact -> node */ - private final Map winners = new HashMap<>( 256 ); - + private final Map winners = new HashMap<>(256); /** * versionLessId -> Artifact, only cache winners */ - private final Map winnerGAs = new HashMap<>( 256 ); - - boolean isVersionConflict( DependencyNode node ) - { - String ga = ArtifactIdUtils.toVersionlessId( node.getArtifact() ); - if ( winnerGAs.containsKey( ga ) ) - { - Artifact result = winnerGAs.get( ga ); - return !node.getArtifact().getVersion().equals( result.getVersion() ); + private final Map winnerGAs = new HashMap<>(256); + + boolean isVersionConflict(DependencyNode node) { + String ga = ArtifactIdUtils.toVersionlessId(node.getArtifact()); + if (winnerGAs.containsKey(ga)) { + Artifact result = winnerGAs.get(ga); + return !node.getArtifact().getVersion().equals(result.getVersion()); } return false; } - void cacheWinner( DependencyNode node ) - { - winners.put( node.getArtifact(), node ); - winnerGAs.put( ArtifactIdUtils.toVersionlessId( node.getArtifact() ), node.getArtifact() ); + void cacheWinner(DependencyNode node) { + winners.put(node.getArtifact(), node); + winnerGAs.put(ArtifactIdUtils.toVersionlessId(node.getArtifact()), node.getArtifact()); } - boolean isDuplicate( DependencyNode node ) - { - return winners.containsKey( node.getArtifact() ); + boolean isDuplicate(DependencyNode node) { + return winners.containsKey(node.getArtifact()); } - } - - private static final class CoordinateManager - { - private final Map sequenceGen = new HashMap<>( 256 ); + private static final class CoordinateManager { + private final Map sequenceGen = new HashMap<>(256); /** * Dependency node -> Coordinate */ - private final Map coordinateMap = new HashMap<>( 256 ); + private final Map coordinateMap = new HashMap<>(256); /** * Leftmost coordinate of given artifact */ - private final Map leftmostCoordinates = new HashMap<>( 256 ); - + private final Map leftmostCoordinates = new HashMap<>(256); - Coordinate getCoordinate( DependencyNode node ) - { - return coordinateMap.get( node ); + Coordinate getCoordinate(DependencyNode node) { + return coordinateMap.get(node); } - Coordinate createCoordinate( DependencyNode node, int depth ) - { - int seq = sequenceGen.computeIfAbsent( depth, k -> new AtomicInteger() ).incrementAndGet(); - Coordinate coordinate = new Coordinate( depth, seq ); - coordinateMap.put( node, coordinate ); + Coordinate createCoordinate(DependencyNode node, int depth) { + int seq = sequenceGen + .computeIfAbsent(depth, k -> new AtomicInteger()) + .incrementAndGet(); + Coordinate coordinate = new Coordinate(depth, seq); + coordinateMap.put(node, coordinate); return coordinate; } - void updateLeftmost( DependencyNode current ) - { - leftmostCoordinates.put( current.getArtifact(), getCoordinate( current ) ); + void updateLeftmost(DependencyNode current) { + leftmostCoordinates.put(current.getArtifact(), getCoordinate(current)); } - boolean isLeftmost( DependencyNode node, List parents ) - { - Coordinate leftmost = leftmostCoordinates.get( node.getArtifact() ); - if ( leftmost != null && leftmost.depth <= parents.size() ) - { - DependencyNode sameLevelNode = parents.get( leftmost.depth - 1 ); - return getCoordinate( sameLevelNode ).sequence < leftmost.sequence; + boolean isLeftmost(DependencyNode node, List parents) { + Coordinate leftmost = leftmostCoordinates.get(node.getArtifact()); + if (leftmost != null && leftmost.depth <= parents.size()) { + DependencyNode sameLevelNode = parents.get(leftmost.depth - 1); + return getCoordinate(sameLevelNode).sequence < leftmost.sequence; } return false; } } - private static final class Coordinate - { + private static final class Coordinate { int depth; int sequence; - Coordinate( int depth, int sequence ) - { + Coordinate(int depth, int sequence) { this.depth = depth; this.sequence = sequence; } @Override - public String toString() - { - return "{" - + "depth=" - + depth - + ", sequence=" - + sequence - + '}'; + public String toString() { + return "{" + "depth=" + depth + ", sequence=" + sequence + '}'; } } } @@ -340,21 +300,18 @@ public String toString() /** * Visible for testing. */ - static final class DependencyResolutionResult - { + static final class DependencyResolutionResult { DependencyNode current; - boolean skippedAsVersionConflict; //omitted for conflict - boolean skippedAsDuplicate; //omitted for duplicate, depth is deeper - boolean resolve; //node to resolve (winner node) - boolean forceResolution; //force resolving (duplicate node) for scope selection + boolean skippedAsVersionConflict; // omitted for conflict + boolean skippedAsDuplicate; // omitted for duplicate, depth is deeper + boolean resolve; // node to resolve (winner node) + boolean forceResolution; // force resolving (duplicate node) for scope selection - DependencyResolutionResult( DependencyNode current ) - { + DependencyResolutionResult(DependencyNode current) { this.current = current; } - boolean toResolve() - { + boolean toResolve() { return resolve || forceResolution; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/df/DfDependencyCollector.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/df/DfDependencyCollector.java index 268100f0e..f6d9900f4 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/df/DfDependencyCollector.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/df/DfDependencyCollector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect.df; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,14 +16,15 @@ * specific language governing permissions and limitations * under the License. */ - -import java.util.Collections; -import java.util.List; +package org.eclipse.aether.internal.impl.collect.df; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; +import java.util.Collections; +import java.util.List; + import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.RequestTrace; import org.eclipse.aether.artifact.Artifact; @@ -65,10 +64,8 @@ * @since 1.8.0 */ @Singleton -@Named( DfDependencyCollector.NAME ) -public class DfDependencyCollector - extends DependencyCollectorDelegate implements Service -{ +@Named(DfDependencyCollector.NAME) +public class DfDependencyCollector extends DependencyCollectorDelegate implements Service { public static final String NAME = "df"; /** @@ -77,263 +74,327 @@ public class DfDependencyCollector * @deprecated Will be dropped once SL gone. */ @Deprecated - public DfDependencyCollector() - { + public DfDependencyCollector() { // enables default constructor } @Inject - DfDependencyCollector( RemoteRepositoryManager remoteRepositoryManager, - ArtifactDescriptorReader artifactDescriptorReader, - VersionRangeResolver versionRangeResolver ) - { - super( remoteRepositoryManager, artifactDescriptorReader, versionRangeResolver ); + DfDependencyCollector( + RemoteRepositoryManager remoteRepositoryManager, + ArtifactDescriptorReader artifactDescriptorReader, + VersionRangeResolver versionRangeResolver) { + super(remoteRepositoryManager, artifactDescriptorReader, versionRangeResolver); } - @SuppressWarnings( "checkstyle:parameternumber" ) + @SuppressWarnings("checkstyle:parameternumber") @Override - protected void doCollectDependencies( RepositorySystemSession session, RequestTrace trace, DataPool pool, - DefaultDependencyCollectionContext context, - DefaultVersionFilterContext versionContext, - CollectRequest request, DependencyNode node, - List repositories, List dependencies, - List managedDependencies, Results results ) - { + protected void doCollectDependencies( + RepositorySystemSession session, + RequestTrace trace, + DataPool pool, + DefaultDependencyCollectionContext context, + DefaultVersionFilterContext versionContext, + CollectRequest request, + DependencyNode node, + List repositories, + List dependencies, + List managedDependencies, + Results results) { NodeStack nodes = new NodeStack(); - nodes.push( node ); + nodes.push(node); - Args args = new Args( session, pool, nodes, context, versionContext, request ); + Args args = new Args(session, pool, nodes, context, versionContext, request); - process( args, trace, results, dependencies, repositories, + process( + args, + trace, + results, + dependencies, + repositories, session.getDependencySelector() != null - ? session.getDependencySelector().deriveChildSelector( context ) : null, + ? session.getDependencySelector().deriveChildSelector(context) + : null, session.getDependencyManager() != null - ? session.getDependencyManager().deriveChildManager( context ) : null, + ? session.getDependencyManager().deriveChildManager(context) + : null, session.getDependencyTraverser() != null - ? session.getDependencyTraverser().deriveChildTraverser( context ) : null, - session.getVersionFilter() != null - ? session.getVersionFilter().deriveChildFilter( context ) : null ); + ? session.getDependencyTraverser().deriveChildTraverser(context) + : null, + session.getVersionFilter() != null ? session.getVersionFilter().deriveChildFilter(context) : null); } - @SuppressWarnings( "checkstyle:parameternumber" ) - private void process( final Args args, RequestTrace trace, Results results, List dependencies, - List repositories, DependencySelector depSelector, - DependencyManager depManager, DependencyTraverser depTraverser, VersionFilter verFilter ) - { - for ( Dependency dependency : dependencies ) - { - processDependency( args, trace, results, repositories, depSelector, depManager, depTraverser, verFilter, - dependency ); + @SuppressWarnings("checkstyle:parameternumber") + private void process( + final Args args, + RequestTrace trace, + Results results, + List dependencies, + List repositories, + DependencySelector depSelector, + DependencyManager depManager, + DependencyTraverser depTraverser, + VersionFilter verFilter) { + for (Dependency dependency : dependencies) { + processDependency( + args, trace, results, repositories, depSelector, depManager, depTraverser, verFilter, dependency); } } - @SuppressWarnings( "checkstyle:parameternumber" ) - private void processDependency( Args args, RequestTrace trace, Results results, List repositories, - DependencySelector depSelector, DependencyManager depManager, - DependencyTraverser depTraverser, VersionFilter verFilter, Dependency dependency ) - { + @SuppressWarnings("checkstyle:parameternumber") + private void processDependency( + Args args, + RequestTrace trace, + Results results, + List repositories, + DependencySelector depSelector, + DependencyManager depManager, + DependencyTraverser depTraverser, + VersionFilter verFilter, + Dependency dependency) { List relocations = Collections.emptyList(); - processDependency( args, trace, results, repositories, depSelector, depManager, depTraverser, verFilter, - dependency, relocations, false ); + processDependency( + args, + trace, + results, + repositories, + depSelector, + depManager, + depTraverser, + verFilter, + dependency, + relocations, + false); } - @SuppressWarnings( "checkstyle:parameternumber" ) - private void processDependency( Args args, RequestTrace parent, Results results, - List repositories, DependencySelector depSelector, - DependencyManager depManager, DependencyTraverser depTraverser, - VersionFilter verFilter, Dependency dependency, List relocations, - boolean disableVersionManagement ) - { - if ( depSelector != null && !depSelector.selectDependency( dependency ) ) - { + @SuppressWarnings("checkstyle:parameternumber") + private void processDependency( + Args args, + RequestTrace parent, + Results results, + List repositories, + DependencySelector depSelector, + DependencyManager depManager, + DependencyTraverser depTraverser, + VersionFilter verFilter, + Dependency dependency, + List relocations, + boolean disableVersionManagement) { + if (depSelector != null && !depSelector.selectDependency(dependency)) { return; } - RequestTrace trace = collectStepTrace( parent, args.request.getRequestContext(), args.nodes.nodes, dependency ); + RequestTrace trace = collectStepTrace(parent, args.request.getRequestContext(), args.nodes.nodes, dependency); PremanagedDependency preManaged = - PremanagedDependency.create( depManager, dependency, disableVersionManagement, args.premanagedState ); + PremanagedDependency.create(depManager, dependency, disableVersionManagement, args.premanagedState); dependency = preManaged.getManagedDependency(); - boolean noDescriptor = isLackingDescriptor( dependency.getArtifact() ); + boolean noDescriptor = isLackingDescriptor(dependency.getArtifact()); - boolean traverse = !noDescriptor && ( depTraverser == null || depTraverser.traverseDependency( dependency ) ); + boolean traverse = !noDescriptor && (depTraverser == null || depTraverser.traverseDependency(dependency)); List versions; VersionRangeResult rangeResult; - try - { - VersionRangeRequest rangeRequest = createVersionRangeRequest( args.request.getRequestContext(), trace, - repositories, dependency ); + try { + VersionRangeRequest rangeRequest = + createVersionRangeRequest(args.request.getRequestContext(), trace, repositories, dependency); - rangeResult = cachedResolveRangeResult( rangeRequest, args.pool, args.session ); + rangeResult = cachedResolveRangeResult(rangeRequest, args.pool, args.session); - versions = filterVersions( dependency, rangeResult, verFilter, args.versionContext ); - } - catch ( VersionRangeResolutionException e ) - { - results.addException( dependency, e, args.nodes.nodes ); + versions = filterVersions(dependency, rangeResult, verFilter, args.versionContext); + } catch (VersionRangeResolutionException e) { + results.addException(dependency, e, args.nodes.nodes); return; } - for ( Version version : versions ) - { - Artifact originalArtifact = dependency.getArtifact().setVersion( version.toString() ); - Dependency d = dependency.setArtifact( originalArtifact ); + for (Version version : versions) { + Artifact originalArtifact = dependency.getArtifact().setVersion(version.toString()); + Dependency d = dependency.setArtifact(originalArtifact); - ArtifactDescriptorRequest descriptorRequest = createArtifactDescriptorRequest( - args.request.getRequestContext(), trace, repositories, d ); + ArtifactDescriptorRequest descriptorRequest = + createArtifactDescriptorRequest(args.request.getRequestContext(), trace, repositories, d); final ArtifactDescriptorResult descriptorResult = - getArtifactDescriptorResult( args, results, noDescriptor, d, descriptorRequest ); - if ( descriptorResult != null ) - { - d = d.setArtifact( descriptorResult.getArtifact() ); + getArtifactDescriptorResult(args, results, noDescriptor, d, descriptorRequest); + if (descriptorResult != null) { + d = d.setArtifact(descriptorResult.getArtifact()); DependencyNode node = args.nodes.top(); - int cycleEntry = DefaultDependencyCycle.find( args.nodes.nodes, d.getArtifact() ); - if ( cycleEntry >= 0 ) - { - results.addCycle( args.nodes.nodes, cycleEntry, d ); - DependencyNode cycleNode = args.nodes.get( cycleEntry ); - if ( cycleNode.getDependency() != null ) - { - DefaultDependencyNode child = - createDependencyNode( relocations, preManaged, rangeResult, version, d, descriptorResult, - cycleNode ); - node.getChildren().add( child ); + int cycleEntry = DefaultDependencyCycle.find(args.nodes.nodes, d.getArtifact()); + if (cycleEntry >= 0) { + results.addCycle(args.nodes.nodes, cycleEntry, d); + DependencyNode cycleNode = args.nodes.get(cycleEntry); + if (cycleNode.getDependency() != null) { + DefaultDependencyNode child = createDependencyNode( + relocations, preManaged, rangeResult, version, d, descriptorResult, cycleNode); + node.getChildren().add(child); continue; } } - if ( !descriptorResult.getRelocations().isEmpty() ) - { + if (!descriptorResult.getRelocations().isEmpty()) { boolean disableVersionManagementSubsequently = - originalArtifact.getGroupId().equals( d.getArtifact().getGroupId() ) - && originalArtifact.getArtifactId().equals( d.getArtifact().getArtifactId() ); - - processDependency( args, parent, results, repositories, depSelector, depManager, depTraverser, - verFilter, d, descriptorResult.getRelocations(), disableVersionManagementSubsequently ); + originalArtifact.getGroupId().equals(d.getArtifact().getGroupId()) + && originalArtifact + .getArtifactId() + .equals(d.getArtifact().getArtifactId()); + + processDependency( + args, + parent, + results, + repositories, + depSelector, + depManager, + depTraverser, + verFilter, + d, + descriptorResult.getRelocations(), + disableVersionManagementSubsequently); return; - } - else - { - d = args.pool.intern( d.setArtifact( args.pool.intern( d.getArtifact() ) ) ); + } else { + d = args.pool.intern(d.setArtifact(args.pool.intern(d.getArtifact()))); List repos = - getRemoteRepositories( rangeResult.getRepository( version ), repositories ); - - DefaultDependencyNode child = - createDependencyNode( relocations, preManaged, rangeResult, version, d, - descriptorResult.getAliases(), repos, args.request.getRequestContext() ); - - node.getChildren().add( child ); - - boolean recurse = traverse && !descriptorResult.getDependencies().isEmpty(); - if ( recurse ) - { - doRecurse( args, parent, results, repositories, depSelector, depManager, depTraverser, - verFilter, d, descriptorResult, child ); + getRemoteRepositories(rangeResult.getRepository(version), repositories); + + DefaultDependencyNode child = createDependencyNode( + relocations, + preManaged, + rangeResult, + version, + d, + descriptorResult.getAliases(), + repos, + args.request.getRequestContext()); + + node.getChildren().add(child); + + boolean recurse = + traverse && !descriptorResult.getDependencies().isEmpty(); + if (recurse) { + doRecurse( + args, + parent, + results, + repositories, + depSelector, + depManager, + depTraverser, + verFilter, + d, + descriptorResult, + child); } } - } - else - { + } else { DependencyNode node = args.nodes.top(); - List repos = - getRemoteRepositories( rangeResult.getRepository( version ), repositories ); - DefaultDependencyNode child = - createDependencyNode( relocations, preManaged, rangeResult, version, d, null, repos, - args.request.getRequestContext() ); - node.getChildren().add( child ); + List repos = getRemoteRepositories(rangeResult.getRepository(version), repositories); + DefaultDependencyNode child = createDependencyNode( + relocations, + preManaged, + rangeResult, + version, + d, + null, + repos, + args.request.getRequestContext()); + node.getChildren().add(child); } } } - @SuppressWarnings( "checkstyle:parameternumber" ) - private void doRecurse( Args args, RequestTrace trace, Results results, List repositories, - DependencySelector depSelector, DependencyManager depManager, - DependencyTraverser depTraverser, VersionFilter verFilter, Dependency d, - ArtifactDescriptorResult descriptorResult, DefaultDependencyNode child ) - { + @SuppressWarnings("checkstyle:parameternumber") + private void doRecurse( + Args args, + RequestTrace trace, + Results results, + List repositories, + DependencySelector depSelector, + DependencyManager depManager, + DependencyTraverser depTraverser, + VersionFilter verFilter, + Dependency d, + ArtifactDescriptorResult descriptorResult, + DefaultDependencyNode child) { DefaultDependencyCollectionContext context = args.collectionContext; - context.set( d, descriptorResult.getManagedDependencies() ); + context.set(d, descriptorResult.getManagedDependencies()); - DependencySelector childSelector = depSelector != null ? depSelector.deriveChildSelector( context ) : null; - DependencyManager childManager = depManager != null ? depManager.deriveChildManager( context ) : null; - DependencyTraverser childTraverser = depTraverser != null ? depTraverser.deriveChildTraverser( context ) : null; - VersionFilter childFilter = verFilter != null ? verFilter.deriveChildFilter( context ) : null; + DependencySelector childSelector = depSelector != null ? depSelector.deriveChildSelector(context) : null; + DependencyManager childManager = depManager != null ? depManager.deriveChildManager(context) : null; + DependencyTraverser childTraverser = depTraverser != null ? depTraverser.deriveChildTraverser(context) : null; + VersionFilter childFilter = verFilter != null ? verFilter.deriveChildFilter(context) : null; - final List childRepos = - args.ignoreRepos + final List childRepos = args.ignoreRepos ? repositories - : remoteRepositoryManager.aggregateRepositories( args.session, repositories, - descriptorResult.getRepositories(), true ); + : remoteRepositoryManager.aggregateRepositories( + args.session, repositories, descriptorResult.getRepositories(), true); Object key = - args.pool.toKey( d.getArtifact(), childRepos, childSelector, childManager, childTraverser, childFilter ); + args.pool.toKey(d.getArtifact(), childRepos, childSelector, childManager, childTraverser, childFilter); - List children = args.pool.getChildren( key ); - if ( children == null ) - { - args.pool.putChildren( key, child.getChildren() ); + List children = args.pool.getChildren(key); + if (children == null) { + args.pool.putChildren(key, child.getChildren()); - args.nodes.push( child ); + args.nodes.push(child); - process( args, trace, results, descriptorResult.getDependencies(), childRepos, childSelector, childManager, - childTraverser, childFilter ); + process( + args, + trace, + results, + descriptorResult.getDependencies(), + childRepos, + childSelector, + childManager, + childTraverser, + childFilter); args.nodes.pop(); - } - else - { - child.setChildren( children ); + } else { + child.setChildren(children); } } - private ArtifactDescriptorResult getArtifactDescriptorResult( Args args, Results results, boolean noDescriptor, - Dependency d, - ArtifactDescriptorRequest descriptorRequest ) - { + private ArtifactDescriptorResult getArtifactDescriptorResult( + Args args, + Results results, + boolean noDescriptor, + Dependency d, + ArtifactDescriptorRequest descriptorRequest) { return noDescriptor - ? new ArtifactDescriptorResult( descriptorRequest ) - : resolveCachedArtifactDescriptor( args.pool, descriptorRequest, args.session, d, results, args ); - + ? new ArtifactDescriptorResult(descriptorRequest) + : resolveCachedArtifactDescriptor(args.pool, descriptorRequest, args.session, d, results, args); } - private ArtifactDescriptorResult resolveCachedArtifactDescriptor( DataPool pool, - ArtifactDescriptorRequest descriptorRequest, - RepositorySystemSession session, Dependency d, - Results results, Args args ) - { - Object key = pool.toKey( descriptorRequest ); - ArtifactDescriptorResult descriptorResult = pool.getDescriptor( key, descriptorRequest ); - if ( descriptorResult == null ) - { - try - { - descriptorResult = descriptorReader.readArtifactDescriptor( session, descriptorRequest ); - pool.putDescriptor( key, descriptorResult ); - } - catch ( ArtifactDescriptorException e ) - { - results.addException( d, e, args.nodes.nodes ); - pool.putDescriptor( key, e ); + private ArtifactDescriptorResult resolveCachedArtifactDescriptor( + DataPool pool, + ArtifactDescriptorRequest descriptorRequest, + RepositorySystemSession session, + Dependency d, + Results results, + Args args) { + Object key = pool.toKey(descriptorRequest); + ArtifactDescriptorResult descriptorResult = pool.getDescriptor(key, descriptorRequest); + if (descriptorResult == null) { + try { + descriptorResult = descriptorReader.readArtifactDescriptor(session, descriptorRequest); + pool.putDescriptor(key, descriptorResult); + } catch (ArtifactDescriptorException e) { + results.addException(d, e, args.nodes.nodes); + pool.putDescriptor(key, e); return null; } - } - else if ( descriptorResult == DataPool.NO_DESCRIPTOR ) - { + } else if (descriptorResult == DataPool.NO_DESCRIPTOR) { return null; } return descriptorResult; } - static class Args - { + static class Args { final RepositorySystemSession session; @@ -351,19 +412,21 @@ static class Args final CollectRequest request; - Args( RepositorySystemSession session, DataPool pool, NodeStack nodes, - DefaultDependencyCollectionContext collectionContext, DefaultVersionFilterContext versionContext, - CollectRequest request ) - { + Args( + RepositorySystemSession session, + DataPool pool, + NodeStack nodes, + DefaultDependencyCollectionContext collectionContext, + DefaultVersionFilterContext versionContext, + CollectRequest request) { this.session = session; this.request = request; this.ignoreRepos = session.isIgnoreArtifactDescriptorRepositories(); - this.premanagedState = ConfigUtils.getBoolean( session, false, DependencyManagerUtils.CONFIG_PROP_VERBOSE ); + this.premanagedState = ConfigUtils.getBoolean(session, false, DependencyManagerUtils.CONFIG_PROP_VERBOSE); this.pool = pool; this.nodes = nodes; this.collectionContext = collectionContext; this.versionContext = versionContext; } - } -} \ No newline at end of file +} diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/df/NodeStack.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/df/NodeStack.java index dafe7a2fe..18e1a01c7 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/df/NodeStack.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/df/NodeStack.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect.df; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect.df; import java.util.ArrayList; @@ -29,51 +28,41 @@ * * @since 1.8.0 */ -final class NodeStack -{ +final class NodeStack { - @SuppressWarnings( {"checkstyle:magicnumber" } ) + @SuppressWarnings({"checkstyle:magicnumber"}) // CHECKSTYLE_OFF: MagicNumber - ArrayList nodes = new ArrayList<>( 96 ); + ArrayList nodes = new ArrayList<>(96); // CHECKSTYLE_ON: MagicNumber - public DependencyNode top() - { - if ( nodes.isEmpty() ) - { - throw new IllegalStateException( "stack empty" ); + public DependencyNode top() { + if (nodes.isEmpty()) { + throw new IllegalStateException("stack empty"); } - return nodes.get( nodes.size() - 1 ); + return nodes.get(nodes.size() - 1); } - public void push( DependencyNode node ) - { - nodes.add( node ); + public void push(DependencyNode node) { + nodes.add(node); } - public void pop() - { - if ( nodes.isEmpty() ) - { - throw new IllegalStateException( "stack empty" ); + public void pop() { + if (nodes.isEmpty()) { + throw new IllegalStateException("stack empty"); } - nodes.remove( nodes.size() - 1 ); + nodes.remove(nodes.size() - 1); } - public int size() - { + public int size() { return nodes.size(); } - public DependencyNode get( int index ) - { - return nodes.get( index ); + public DependencyNode get(int index) { + return nodes.get(index); } @Override - public String toString() - { + public String toString() { return nodes.toString(); } - -} \ No newline at end of file +} diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/package-info.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/package-info.java index 85baeedcb..2c84a68aa 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/package-info.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/collect/package-info.java @@ -20,4 +20,4 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - */ \ No newline at end of file + */ diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/DefaultRemoteRepositoryFilterManager.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/DefaultRemoteRepositoryFilterManager.java index fcfed9d6d..f6070e91b 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/DefaultRemoteRepositoryFilterManager.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/DefaultRemoteRepositoryFilterManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.filter; import javax.inject.Inject; import javax.inject.Named; @@ -48,9 +47,7 @@ */ @Singleton @Named -public final class DefaultRemoteRepositoryFilterManager - implements RemoteRepositoryFilterManager -{ +public final class DefaultRemoteRepositoryFilterManager implements RemoteRepositoryFilterManager { private static final String INSTANCE_KEY = DefaultRemoteRepositoryFilterManager.class.getName() + ".instance"; private final Map sources; @@ -61,72 +58,56 @@ public final class DefaultRemoteRepositoryFilterManager * @deprecated for SL and testing purposes only. */ @Deprecated - public DefaultRemoteRepositoryFilterManager() - { + public DefaultRemoteRepositoryFilterManager() { this.sources = new HashMap<>(); } @Inject - public DefaultRemoteRepositoryFilterManager( Map sources ) - { - this.sources = requireNonNull( sources ); + public DefaultRemoteRepositoryFilterManager(Map sources) { + this.sources = requireNonNull(sources); } @Override - public RemoteRepositoryFilter getRemoteRepositoryFilter( RepositorySystemSession session ) - { - return (RemoteRepositoryFilter) session.getData().computeIfAbsent( INSTANCE_KEY, () -> - { - HashMap filters = new HashMap<>(); - for ( Map.Entry entry : sources.entrySet() ) - { - RemoteRepositoryFilter filter = entry.getValue().getRemoteRepositoryFilter( session ); - if ( filter != null ) - { - filters.put( entry.getKey(), filter ); - } - } - if ( !filters.isEmpty() ) - { - return new Participants( filters ); - } - else - { - return null; - } + public RemoteRepositoryFilter getRemoteRepositoryFilter(RepositorySystemSession session) { + return (RemoteRepositoryFilter) session.getData().computeIfAbsent(INSTANCE_KEY, () -> { + HashMap filters = new HashMap<>(); + for (Map.Entry entry : sources.entrySet()) { + RemoteRepositoryFilter filter = entry.getValue().getRemoteRepositoryFilter(session); + if (filter != null) { + filters.put(entry.getKey(), filter); } - ); + } + if (!filters.isEmpty()) { + return new Participants(filters); + } else { + return null; + } + }); } /** * {@link RemoteRepositoryFilter} instance when there are participant filters present. It evaluates into result * using {@link Consensus}. */ - private static class Participants implements RemoteRepositoryFilter - { + private static class Participants implements RemoteRepositoryFilter { private final Map participants; - private Participants( Map participants ) - { - this.participants = Collections.unmodifiableMap( participants ); + private Participants(Map participants) { + this.participants = Collections.unmodifiableMap(participants); } @Override - public RemoteRepositoryFilter.Result acceptArtifact( RemoteRepository remoteRepository, Artifact artifact ) - { - return new Consensus( participants.entrySet().stream() - .collect( Collectors.toMap( - Map.Entry::getKey, - e -> e.getValue().acceptArtifact( remoteRepository, artifact ) ) ) ); + public RemoteRepositoryFilter.Result acceptArtifact(RemoteRepository remoteRepository, Artifact artifact) { + return new Consensus( + participants.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue() + .acceptArtifact(remoteRepository, artifact)))); } @Override - public RemoteRepositoryFilter.Result acceptMetadata( RemoteRepository remoteRepository, Metadata metadata ) - { - return new Consensus( participants.entrySet().stream() - .collect( Collectors.toMap( - Map.Entry::getKey, - e -> e.getValue().acceptMetadata( remoteRepository, metadata ) ) ) ); + public RemoteRepositoryFilter.Result acceptMetadata(RemoteRepository remoteRepository, Metadata metadata) { + return new Consensus( + participants.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue() + .acceptMetadata(remoteRepository, metadata)))); } } @@ -134,29 +115,26 @@ public RemoteRepositoryFilter.Result acceptMetadata( RemoteRepository remoteRepo * {@link RemoteRepositoryFilter.Result} based on "consensus". All participant have to "accept" to make this * instance "accept". */ - private static class Consensus implements RemoteRepositoryFilter.Result - { + private static class Consensus implements RemoteRepositoryFilter.Result { private final boolean accepted; private final String reasoning; - Consensus( Map results ) - { - this.accepted = results.values().stream().allMatch( RemoteRepositoryFilter.Result::isAccepted ); - this.reasoning = results.values().stream().filter( r -> !r.isAccepted() ).map( - RemoteRepositoryFilter.Result::reasoning ).collect( - Collectors.joining( "; " ) ); + Consensus(Map results) { + this.accepted = results.values().stream().allMatch(RemoteRepositoryFilter.Result::isAccepted); + this.reasoning = results.values().stream() + .filter(r -> !r.isAccepted()) + .map(RemoteRepositoryFilter.Result::reasoning) + .collect(Collectors.joining("; ")); } @Override - public boolean isAccepted() - { + public boolean isAccepted() { return accepted; } @Override - public String reasoning() - { + public String reasoning() { return reasoning; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/FilteringRepositoryConnector.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/FilteringRepositoryConnector.java index 497293186..0ffe4ce94 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/FilteringRepositoryConnector.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/FilteringRepositoryConnector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.filter; import java.util.ArrayList; import java.util.Collection; @@ -40,85 +39,71 @@ * * @since 1.9.0 */ -public final class FilteringRepositoryConnector - implements RepositoryConnector -{ +public final class FilteringRepositoryConnector implements RepositoryConnector { private final RemoteRepository remoteRepository; private final RepositoryConnector delegate; private final RemoteRepositoryFilter remoteRepositoryFilter; - public FilteringRepositoryConnector( RemoteRepository remoteRepository, - RepositoryConnector delegate, - RemoteRepositoryFilter remoteRepositoryFilter ) - { - this.remoteRepository = requireNonNull( remoteRepository ); - this.delegate = requireNonNull( delegate ); - this.remoteRepositoryFilter = requireNonNull( remoteRepositoryFilter ); + public FilteringRepositoryConnector( + RemoteRepository remoteRepository, + RepositoryConnector delegate, + RemoteRepositoryFilter remoteRepositoryFilter) { + this.remoteRepository = requireNonNull(remoteRepository); + this.delegate = requireNonNull(delegate); + this.remoteRepositoryFilter = requireNonNull(remoteRepositoryFilter); } @Override - public void close() - { + public void close() { delegate.close(); } @Override - public void get( Collection artifactDownloads, - Collection metadataDownloads ) - { + public void get( + Collection artifactDownloads, + Collection metadataDownloads) { List filteredArtifactDownloads = null; - if ( artifactDownloads != null && !artifactDownloads.isEmpty() ) - { - filteredArtifactDownloads = new ArrayList<>( artifactDownloads.size() ); - for ( ArtifactDownload artifactDownload : artifactDownloads ) - { - RemoteRepositoryFilter.Result result = remoteRepositoryFilter.acceptArtifact( - remoteRepository, artifactDownload.getArtifact() ); - if ( result.isAccepted() ) - { - filteredArtifactDownloads.add( artifactDownload ); - } - else - { - artifactDownload.setException( new ArtifactNotFoundException( artifactDownload.getArtifact(), - remoteRepository, result.reasoning() ) ); + if (artifactDownloads != null && !artifactDownloads.isEmpty()) { + filteredArtifactDownloads = new ArrayList<>(artifactDownloads.size()); + for (ArtifactDownload artifactDownload : artifactDownloads) { + RemoteRepositoryFilter.Result result = + remoteRepositoryFilter.acceptArtifact(remoteRepository, artifactDownload.getArtifact()); + if (result.isAccepted()) { + filteredArtifactDownloads.add(artifactDownload); + } else { + artifactDownload.setException(new ArtifactNotFoundException( + artifactDownload.getArtifact(), remoteRepository, result.reasoning())); } } } List filteredMetadataDownloads = null; - if ( metadataDownloads != null && !metadataDownloads.isEmpty() ) - { - filteredMetadataDownloads = new ArrayList<>( metadataDownloads.size() ); - for ( MetadataDownload metadataDownload : metadataDownloads ) - { - RemoteRepositoryFilter.Result result = remoteRepositoryFilter.acceptMetadata( - remoteRepository, metadataDownload.getMetadata() ); - if ( result.isAccepted() ) - { - filteredMetadataDownloads.add( metadataDownload ); - } - else - { - metadataDownload.setException( new MetadataNotFoundException( metadataDownload.getMetadata(), - remoteRepository, result.reasoning() ) ); + if (metadataDownloads != null && !metadataDownloads.isEmpty()) { + filteredMetadataDownloads = new ArrayList<>(metadataDownloads.size()); + for (MetadataDownload metadataDownload : metadataDownloads) { + RemoteRepositoryFilter.Result result = + remoteRepositoryFilter.acceptMetadata(remoteRepository, metadataDownload.getMetadata()); + if (result.isAccepted()) { + filteredMetadataDownloads.add(metadataDownload); + } else { + metadataDownload.setException(new MetadataNotFoundException( + metadataDownload.getMetadata(), remoteRepository, result.reasoning())); } } } - delegate.get( filteredArtifactDownloads, filteredMetadataDownloads ); + delegate.get(filteredArtifactDownloads, filteredMetadataDownloads); } @Override - public void put( Collection artifactUploads, - Collection metadataUploads ) - { - delegate.put( artifactUploads, metadataUploads ); + public void put( + Collection artifactUploads, + Collection metadataUploads) { + delegate.put(artifactUploads, metadataUploads); } @Override - public String toString() - { + public String toString() { return "filtered(" + delegate.toString() + ")"; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/GroupIdRemoteRepositoryFilterSource.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/GroupIdRemoteRepositoryFilterSource.java index 28df92342..993f1fdbc 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/GroupIdRemoteRepositoryFilterSource.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/GroupIdRemoteRepositoryFilterSource.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.filter; import javax.inject.Inject; import javax.inject.Named; @@ -71,11 +70,9 @@ * @since 1.9.0 */ @Singleton -@Named( GroupIdRemoteRepositoryFilterSource.NAME ) -public final class GroupIdRemoteRepositoryFilterSource - extends RemoteRepositoryFilterSourceSupport - implements ArtifactResolverPostProcessor -{ +@Named(GroupIdRemoteRepositoryFilterSource.NAME) +public final class GroupIdRemoteRepositoryFilterSource extends RemoteRepositoryFilterSourceSupport + implements ArtifactResolverPostProcessor { public static final String NAME = "groupId"; private static final String CONF_NAME_RECORD = "record"; @@ -84,7 +81,7 @@ public final class GroupIdRemoteRepositoryFilterSource static final String GROUP_ID_FILE_SUFFIX = ".txt"; - private static final Logger LOGGER = LoggerFactory.getLogger( GroupIdRemoteRepositoryFilterSource.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(GroupIdRemoteRepositoryFilterSource.class); private final RepositorySystemLifecycle repositorySystemLifecycle; @@ -95,46 +92,38 @@ public final class GroupIdRemoteRepositoryFilterSource private final AtomicBoolean onShutdownHandlerRegistered; @Inject - public GroupIdRemoteRepositoryFilterSource( RepositorySystemLifecycle repositorySystemLifecycle ) - { - super( NAME ); - this.repositorySystemLifecycle = requireNonNull( repositorySystemLifecycle ); + public GroupIdRemoteRepositoryFilterSource(RepositorySystemLifecycle repositorySystemLifecycle) { + super(NAME); + this.repositorySystemLifecycle = requireNonNull(repositorySystemLifecycle); this.rules = new ConcurrentHashMap<>(); this.changedRules = new ConcurrentHashMap<>(); - this.onShutdownHandlerRegistered = new AtomicBoolean( false ); + this.onShutdownHandlerRegistered = new AtomicBoolean(false); } @Override - public RemoteRepositoryFilter getRemoteRepositoryFilter( RepositorySystemSession session ) - { - if ( isEnabled( session ) && !isRecord( session ) ) - { - return new GroupIdFilter( session ); + public RemoteRepositoryFilter getRemoteRepositoryFilter(RepositorySystemSession session) { + if (isEnabled(session) && !isRecord(session)) { + return new GroupIdFilter(session); } return null; } @Override - public void postProcess( RepositorySystemSession session, List artifactResults ) - { - if ( isEnabled( session ) && isRecord( session ) ) - { - if ( onShutdownHandlerRegistered.compareAndSet( false, true ) ) - { - repositorySystemLifecycle.addOnSystemEndedHandler( this::saveRecordedLines ); + public void postProcess(RepositorySystemSession session, List artifactResults) { + if (isEnabled(session) && isRecord(session)) { + if (onShutdownHandlerRegistered.compareAndSet(false, true)) { + repositorySystemLifecycle.addOnSystemEndedHandler(this::saveRecordedLines); } - for ( ArtifactResult artifactResult : artifactResults ) - { - if ( artifactResult.isResolved() && artifactResult.getRepository() instanceof RemoteRepository ) - { - Path filePath = filePath( getBasedir( session, false ), - artifactResult.getRepository().getId() ); - boolean newGroupId = - rules.computeIfAbsent( filePath, f -> Collections.synchronizedSet( new TreeSet<>() ) ) - .add( artifactResult.getArtifact().getGroupId() ); - if ( newGroupId ) - { - changedRules.put( filePath, Boolean.TRUE ); + for (ArtifactResult artifactResult : artifactResults) { + if (artifactResult.isResolved() && artifactResult.getRepository() instanceof RemoteRepository) { + Path filePath = filePath( + getBasedir(session, false), + artifactResult.getRepository().getId()); + boolean newGroupId = rules.computeIfAbsent( + filePath, f -> Collections.synchronizedSet(new TreeSet<>())) + .add(artifactResult.getArtifact().getGroupId()); + if (newGroupId) { + changedRules.put(filePath, Boolean.TRUE); } } } @@ -144,49 +133,34 @@ public void postProcess( RepositorySystemSession session, List a /** * Returns the groupId path. The file and parents may not exist, this method merely calculate the path. */ - private Path filePath( Path basedir, String remoteRepositoryId ) - { - return basedir.resolve( - GROUP_ID_FILE_PREFIX + remoteRepositoryId + GROUP_ID_FILE_SUFFIX ); + private Path filePath(Path basedir, String remoteRepositoryId) { + return basedir.resolve(GROUP_ID_FILE_PREFIX + remoteRepositoryId + GROUP_ID_FILE_SUFFIX); } - private Set cacheRules( RepositorySystemSession session, - RemoteRepository remoteRepository ) - { - Path filePath = filePath( getBasedir( session, false ), remoteRepository.getId() ); - return rules.computeIfAbsent( filePath, r -> - { - Set rules = loadRepositoryRules( filePath ); - if ( rules != NOT_PRESENT ) - { - LOGGER.info( "Loaded {} groupId for remote repository {}", rules.size(), - remoteRepository.getId() ); - } - return rules; - } - ); + private Set cacheRules(RepositorySystemSession session, RemoteRepository remoteRepository) { + Path filePath = filePath(getBasedir(session, false), remoteRepository.getId()); + return rules.computeIfAbsent(filePath, r -> { + Set rules = loadRepositoryRules(filePath); + if (rules != NOT_PRESENT) { + LOGGER.info("Loaded {} groupId for remote repository {}", rules.size(), remoteRepository.getId()); + } + return rules; + }); } - private Set loadRepositoryRules( Path filePath ) - { - if ( Files.isReadable( filePath ) ) - { - try ( BufferedReader reader = Files.newBufferedReader( filePath, StandardCharsets.UTF_8 ) ) - { + private Set loadRepositoryRules(Path filePath) { + if (Files.isReadable(filePath)) { + try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) { TreeSet result = new TreeSet<>(); String groupId; - while ( ( groupId = reader.readLine() ) != null ) - { - if ( !groupId.startsWith( "#" ) && !groupId.trim().isEmpty() ) - { - result.add( groupId ); + while ((groupId = reader.readLine()) != null) { + if (!groupId.startsWith("#") && !groupId.trim().isEmpty()) { + result.add(groupId); } } - return Collections.unmodifiableSet( result ); - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + return Collections.unmodifiableSet(result); + } catch (IOException e) { + throw new UncheckedIOException(e); } } return NOT_PRESENT; @@ -194,95 +168,75 @@ private Set loadRepositoryRules( Path filePath ) private static final TreeSet NOT_PRESENT = new TreeSet<>(); - private class GroupIdFilter implements RemoteRepositoryFilter - { + private class GroupIdFilter implements RemoteRepositoryFilter { private final RepositorySystemSession session; - private GroupIdFilter( RepositorySystemSession session ) - { + private GroupIdFilter(RepositorySystemSession session) { this.session = session; } @Override - public Result acceptArtifact( RemoteRepository remoteRepository, Artifact artifact ) - { - return acceptGroupId( remoteRepository, artifact.getGroupId() ); + public Result acceptArtifact(RemoteRepository remoteRepository, Artifact artifact) { + return acceptGroupId(remoteRepository, artifact.getGroupId()); } @Override - public Result acceptMetadata( RemoteRepository remoteRepository, Metadata metadata ) - { - return acceptGroupId( remoteRepository, metadata.getGroupId() ); + public Result acceptMetadata(RemoteRepository remoteRepository, Metadata metadata) { + return acceptGroupId(remoteRepository, metadata.getGroupId()); } - private Result acceptGroupId( RemoteRepository remoteRepository, String groupId ) - { - Set groupIds = cacheRules( session, remoteRepository ); - if ( NOT_PRESENT == groupIds ) - { + private Result acceptGroupId(RemoteRepository remoteRepository, String groupId) { + Set groupIds = cacheRules(session, remoteRepository); + if (NOT_PRESENT == groupIds) { return NOT_PRESENT_RESULT; } - if ( groupIds.contains( groupId ) ) - { - return new SimpleResult( true, - "G:" + groupId + " allowed from " + remoteRepository ); - } - else - { - return new SimpleResult( false, - "G:" + groupId + " NOT allowed from " + remoteRepository ); + if (groupIds.contains(groupId)) { + return new SimpleResult(true, "G:" + groupId + " allowed from " + remoteRepository); + } else { + return new SimpleResult(false, "G:" + groupId + " NOT allowed from " + remoteRepository); } } } - private static final RemoteRepositoryFilter.Result NOT_PRESENT_RESULT = new SimpleResult( - true, "GroupId file not present" ); + private static final RemoteRepositoryFilter.Result NOT_PRESENT_RESULT = + new SimpleResult(true, "GroupId file not present"); /** * Returns {@code true} if given session is recording. */ - private boolean isRecord( RepositorySystemSession session ) - { - return ConfigUtils.getBoolean( session, false, configPropKey( CONF_NAME_RECORD ) ); + private boolean isRecord(RepositorySystemSession session) { + return ConfigUtils.getBoolean(session, false, configPropKey(CONF_NAME_RECORD)); } /** * On-close handler that saves recorded rules, if any. */ - private void saveRecordedLines() - { - if ( changedRules.isEmpty() ) - { + private void saveRecordedLines() { + if (changedRules.isEmpty()) { return; } ArrayList exceptions = new ArrayList<>(); - for ( Map.Entry> entry : rules.entrySet() ) - { + for (Map.Entry> entry : rules.entrySet()) { Path filePath = entry.getKey(); - if ( changedRules.get( filePath ) != Boolean.TRUE ) - { + if (changedRules.get(filePath) != Boolean.TRUE) { continue; } Set recordedLines = entry.getValue(); - if ( !recordedLines.isEmpty() ) - { - try - { + if (!recordedLines.isEmpty()) { + try { TreeSet result = new TreeSet<>(); - result.addAll( loadRepositoryRules( filePath ) ); - result.addAll( recordedLines ); + result.addAll(loadRepositoryRules(filePath)); + result.addAll(recordedLines); - LOGGER.info( "Saving {} groupIds to '{}'", result.size(), filePath ); - FileUtils.writeFileWithBackup( filePath, p -> Files.write( p, result ) ); - } - catch ( IOException e ) - { - exceptions.add( e ); + LOGGER.info("Saving {} groupIds to '{}'", result.size(), filePath); + FileUtils.writeFileWithBackup(filePath, p -> Files.write(p, result)); + } catch (IOException e) { + exceptions.add(e); } } } - MultiRuntimeException.mayThrow( "session save groupIds failure", exceptions ); + MultiRuntimeException.mayThrow("session save groupIds failure", exceptions); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/PrefixesRemoteRepositoryFilterSource.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/PrefixesRemoteRepositoryFilterSource.java index 65ab38425..7fa18e968 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/PrefixesRemoteRepositoryFilterSource.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/PrefixesRemoteRepositoryFilterSource.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.filter; import javax.inject.Inject; import javax.inject.Named; @@ -74,17 +73,15 @@ * @since 1.9.0 */ @Singleton -@Named( PrefixesRemoteRepositoryFilterSource.NAME ) -public final class PrefixesRemoteRepositoryFilterSource - extends RemoteRepositoryFilterSourceSupport -{ +@Named(PrefixesRemoteRepositoryFilterSource.NAME) +public final class PrefixesRemoteRepositoryFilterSource extends RemoteRepositoryFilterSourceSupport { public static final String NAME = "prefixes"; static final String PREFIXES_FILE_PREFIX = "prefixes-"; static final String PREFIXES_FILE_SUFFIX = ".txt"; - private static final Logger LOGGER = LoggerFactory.getLogger( PrefixesRemoteRepositoryFilterSource.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(PrefixesRemoteRepositoryFilterSource.class); private final RepositoryLayoutProvider repositoryLayoutProvider; @@ -93,20 +90,17 @@ public final class PrefixesRemoteRepositoryFilterSource private final ConcurrentHashMap layouts; @Inject - public PrefixesRemoteRepositoryFilterSource( RepositoryLayoutProvider repositoryLayoutProvider ) - { - super( NAME ); - this.repositoryLayoutProvider = requireNonNull( repositoryLayoutProvider ); + public PrefixesRemoteRepositoryFilterSource(RepositoryLayoutProvider repositoryLayoutProvider) { + super(NAME); + this.repositoryLayoutProvider = requireNonNull(repositoryLayoutProvider); this.prefixes = new ConcurrentHashMap<>(); this.layouts = new ConcurrentHashMap<>(); } @Override - public RemoteRepositoryFilter getRemoteRepositoryFilter( RepositorySystemSession session ) - { - if ( isEnabled( session ) ) - { - return new PrefixesFilter( session, getBasedir( session, false ) ); + public RemoteRepositoryFilter getRemoteRepositoryFilter(RepositorySystemSession session) { + if (isEnabled(session)) { + return new PrefixesFilter(session, getBasedir(session, false)); } return null; } @@ -116,188 +110,153 @@ public RemoteRepositoryFilter getRemoteRepositoryFilter( RepositorySystemSession * * @return the layout instance of {@code null} if layout not supported. */ - private RepositoryLayout cacheLayout( RepositorySystemSession session, RemoteRepository remoteRepository ) - { - return layouts.computeIfAbsent( remoteRepository, r -> - { - try - { - return repositoryLayoutProvider.newRepositoryLayout( session, remoteRepository ); - } - catch ( NoRepositoryLayoutException e ) - { + private RepositoryLayout cacheLayout(RepositorySystemSession session, RemoteRepository remoteRepository) { + return layouts.computeIfAbsent(remoteRepository, r -> { + try { + return repositoryLayoutProvider.newRepositoryLayout(session, remoteRepository); + } catch (NoRepositoryLayoutException e) { return null; } - } ); + }); } /** * Caches prefixes instances for remote repository. */ - private Node cacheNode( Path basedir, - RemoteRepository remoteRepository ) - { - return prefixes.computeIfAbsent( remoteRepository, r -> loadRepositoryPrefixes( basedir, remoteRepository ) ); + private Node cacheNode(Path basedir, RemoteRepository remoteRepository) { + return prefixes.computeIfAbsent(remoteRepository, r -> loadRepositoryPrefixes(basedir, remoteRepository)); } /** * Loads prefixes file and preprocesses it into {@link Node} instance. */ - private Node loadRepositoryPrefixes( Path baseDir, RemoteRepository remoteRepository ) - { - Path filePath = baseDir.resolve( PREFIXES_FILE_PREFIX + remoteRepository.getId() + PREFIXES_FILE_SUFFIX ); - if ( Files.isReadable( filePath ) ) - { - try ( BufferedReader reader = Files.newBufferedReader( filePath, StandardCharsets.UTF_8 ) ) - { - LOGGER.debug( "Loading prefixes for remote repository {} from file '{}'", remoteRepository.getId(), - filePath ); - Node root = new Node( "" ); + private Node loadRepositoryPrefixes(Path baseDir, RemoteRepository remoteRepository) { + Path filePath = baseDir.resolve(PREFIXES_FILE_PREFIX + remoteRepository.getId() + PREFIXES_FILE_SUFFIX); + if (Files.isReadable(filePath)) { + try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) { + LOGGER.debug( + "Loading prefixes for remote repository {} from file '{}'", remoteRepository.getId(), filePath); + Node root = new Node(""); String prefix; int lines = 0; - while ( ( prefix = reader.readLine() ) != null ) - { - if ( !prefix.startsWith( "#" ) && !prefix.trim().isEmpty() ) - { + while ((prefix = reader.readLine()) != null) { + if (!prefix.startsWith("#") && !prefix.trim().isEmpty()) { lines++; Node currentNode = root; - for ( String element : elementsOf( prefix ) ) - { - currentNode = currentNode.addSibling( element ); + for (String element : elementsOf(prefix)) { + currentNode = currentNode.addSibling(element); } } } - LOGGER.info( "Loaded {} prefixes for remote repository {}", lines, remoteRepository.getId() ); + LOGGER.info("Loaded {} prefixes for remote repository {}", lines, remoteRepository.getId()); return root; - } - catch ( FileNotFoundException e ) - { + } catch (FileNotFoundException e) { // strange: we tested for it above, still, we should not fail - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + } catch (IOException e) { + throw new UncheckedIOException(e); } } - LOGGER.debug( "Prefix file for remote repository {} not found at '{}'", remoteRepository, filePath ); + LOGGER.debug("Prefix file for remote repository {} not found at '{}'", remoteRepository, filePath); return NOT_PRESENT_NODE; } - private class PrefixesFilter implements RemoteRepositoryFilter - { + private class PrefixesFilter implements RemoteRepositoryFilter { private final RepositorySystemSession session; private final Path basedir; - private PrefixesFilter( RepositorySystemSession session, Path basedir ) - { + private PrefixesFilter(RepositorySystemSession session, Path basedir) { this.session = session; this.basedir = basedir; } @Override - public Result acceptArtifact( RemoteRepository remoteRepository, Artifact artifact ) - { - RepositoryLayout repositoryLayout = cacheLayout( session, remoteRepository ); - if ( repositoryLayout == null ) - { - return new SimpleResult( true, "Unsupported layout: " + remoteRepository ); + public Result acceptArtifact(RemoteRepository remoteRepository, Artifact artifact) { + RepositoryLayout repositoryLayout = cacheLayout(session, remoteRepository); + if (repositoryLayout == null) { + return new SimpleResult(true, "Unsupported layout: " + remoteRepository); } - return acceptPrefix( remoteRepository, - repositoryLayout.getLocation( artifact, false ).getPath() ); + return acceptPrefix( + remoteRepository, + repositoryLayout.getLocation(artifact, false).getPath()); } @Override - public Result acceptMetadata( RemoteRepository remoteRepository, Metadata metadata ) - { - RepositoryLayout repositoryLayout = cacheLayout( session, remoteRepository ); - if ( repositoryLayout == null ) - { - return new SimpleResult( true, "Unsupported layout: " + remoteRepository ); + public Result acceptMetadata(RemoteRepository remoteRepository, Metadata metadata) { + RepositoryLayout repositoryLayout = cacheLayout(session, remoteRepository); + if (repositoryLayout == null) { + return new SimpleResult(true, "Unsupported layout: " + remoteRepository); } - return acceptPrefix( remoteRepository, - repositoryLayout.getLocation( metadata, false ).getPath() ); + return acceptPrefix( + remoteRepository, + repositoryLayout.getLocation(metadata, false).getPath()); } - private Result acceptPrefix( RemoteRepository remoteRepository, String path ) - { - Node root = cacheNode( basedir, remoteRepository ); - if ( NOT_PRESENT_NODE == root ) - { + private Result acceptPrefix(RemoteRepository remoteRepository, String path) { + Node root = cacheNode(basedir, remoteRepository); + if (NOT_PRESENT_NODE == root) { return NOT_PRESENT_RESULT; } List prefix = new ArrayList<>(); - final List pathElements = elementsOf( path ); + final List pathElements = elementsOf(path); Node currentNode = root; - for ( String pathElement : pathElements ) - { - prefix.add( pathElement ); - currentNode = currentNode.getSibling( pathElement ); - if ( currentNode == null || currentNode.isLeaf() ) - { + for (String pathElement : pathElements) { + prefix.add(pathElement); + currentNode = currentNode.getSibling(pathElement); + if (currentNode == null || currentNode.isLeaf()) { break; } } - if ( currentNode != null && currentNode.isLeaf() ) - { - return new SimpleResult( true, "Prefix " - + String.join( "/", prefix ) + " allowed from " + remoteRepository ); - } - else - { - return new SimpleResult( false, "Prefix " - + String.join( "/", prefix ) + " NOT allowed from " + remoteRepository ); + if (currentNode != null && currentNode.isLeaf()) { + return new SimpleResult( + true, "Prefix " + String.join("/", prefix) + " allowed from " + remoteRepository); + } else { + return new SimpleResult( + false, "Prefix " + String.join("/", prefix) + " NOT allowed from " + remoteRepository); } } } - private static final Node NOT_PRESENT_NODE = new Node( - "not-present-node" ); + private static final Node NOT_PRESENT_NODE = new Node("not-present-node"); - private static final RemoteRepositoryFilter.Result NOT_PRESENT_RESULT = new SimpleResult( - true, "Prefix file not present" ); + private static final RemoteRepositoryFilter.Result NOT_PRESENT_RESULT = + new SimpleResult(true, "Prefix file not present"); - private static class Node - { + private static class Node { private final String name; private final HashMap siblings; - private Node( String name ) - { + private Node(String name) { this.name = name; this.siblings = new HashMap<>(); } - public String getName() - { + public String getName() { return name; } - public boolean isLeaf() - { + public boolean isLeaf() { return siblings.isEmpty(); } - public Node addSibling( String name ) - { - Node sibling = siblings.get( name ); - if ( sibling == null ) - { - sibling = new Node( name ); - siblings.put( name, sibling ); + public Node addSibling(String name) { + Node sibling = siblings.get(name); + if (sibling == null) { + sibling = new Node(name); + siblings.put(name, sibling); } return sibling; } - public Node getSibling( String name ) - { - return siblings.get( name ); + public Node getSibling(String name) { + return siblings.get(name); } } - private static List elementsOf( final String path ) - { - return Arrays.stream( path.split( "/" ) ).filter( e -> e != null && !e.isEmpty() ).collect( toList() ); + private static List elementsOf(final String path) { + return Arrays.stream(path.split("/")) + .filter(e -> e != null && !e.isEmpty()) + .collect(toList()); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/RemoteRepositoryFilterSourceSupport.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/RemoteRepositoryFilterSourceSupport.java index 828bb0051..42003ddf8 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/RemoteRepositoryFilterSourceSupport.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/filter/RemoteRepositoryFilterSourceSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.filter; import java.io.IOException; import java.io.UncheckedIOException; @@ -48,9 +47,7 @@ * * @since 1.9.0 */ -public abstract class RemoteRepositoryFilterSourceSupport - implements RemoteRepositoryFilterSource -{ +public abstract class RemoteRepositoryFilterSourceSupport implements RemoteRepositoryFilterSource { private static final String CONFIG_PROP_PREFIX = "aether.remoteRepositoryFilter."; private static final String CONF_NAME_BASEDIR = "basedir"; @@ -59,16 +56,14 @@ public abstract class RemoteRepositoryFilterSourceSupport private final String name; - protected RemoteRepositoryFilterSourceSupport( String name ) - { - this.name = requireNonNull( name ); + protected RemoteRepositoryFilterSourceSupport(String name) { + this.name = requireNonNull(name); } /** * Utility method to create scoped configuration property key of given name. */ - protected String configPropKey( String name ) - { + protected String configPropKey(String name) { return CONFIG_PROP_PREFIX + this.name + "." + name; } @@ -77,9 +72,8 @@ protected String configPropKey( String name ) *

    * Default is {@code false}. */ - protected boolean isEnabled( RepositorySystemSession session ) - { - return ConfigUtils.getBoolean( session, false, CONFIG_PROP_PREFIX + this.name ); + protected boolean isEnabled(RepositorySystemSession session) { + return ConfigUtils.getBoolean(session, false, CONFIG_PROP_PREFIX + this.name); } /** @@ -91,43 +85,35 @@ protected boolean isEnabled( RepositorySystemSession session ) * * @return The {@link Path} of basedir, never {@code null}. */ - protected Path getBasedir( RepositorySystemSession session, boolean mayCreate ) - { - try - { + protected Path getBasedir(RepositorySystemSession session, boolean mayCreate) { + try { return DirectoryUtils.resolveDirectory( - session, LOCAL_REPO_PREFIX_DIR, configPropKey( CONF_NAME_BASEDIR ), mayCreate ); - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + session, LOCAL_REPO_PREFIX_DIR, configPropKey(CONF_NAME_BASEDIR), mayCreate); + } catch (IOException e) { + throw new UncheckedIOException(e); } } /** * Simple {@link RemoteRepositoryFilter.Result} immutable implementation. */ - protected static class SimpleResult implements RemoteRepositoryFilter.Result - { + protected static class SimpleResult implements RemoteRepositoryFilter.Result { private final boolean accepted; private final String reasoning; - public SimpleResult( boolean accepted, String reasoning ) - { + public SimpleResult(boolean accepted, String reasoning) { this.accepted = accepted; - this.reasoning = requireNonNull( reasoning ); + this.reasoning = requireNonNull(reasoning); } @Override - public boolean isAccepted() - { + public boolean isAccepted() { return accepted; } @Override - public String reasoning() - { + public String reasoning() { return reasoning; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/package-info.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/package-info.java index 813b21df3..e466ea909 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/package-info.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -18,7 +18,6 @@ * under the License. */ /** - * The various sub components that collectively implement the repository system. + * The various sub components that collectively implement the repository system. */ package org.eclipse.aether.internal.impl; - diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/resolution/ArtifactResolverPostProcessorSupport.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/resolution/ArtifactResolverPostProcessorSupport.java index 59f6b429b..2622a80a1 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/resolution/ArtifactResolverPostProcessorSupport.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/resolution/ArtifactResolverPostProcessorSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.resolution; import java.util.List; @@ -33,38 +32,32 @@ * * @since 1.9.0 */ -public abstract class ArtifactResolverPostProcessorSupport - implements ArtifactResolverPostProcessor -{ +public abstract class ArtifactResolverPostProcessorSupport implements ArtifactResolverPostProcessor { private static final String CONFIG_PROP_PREFIX = "aether.artifactResolver.postProcessor."; private final String name; - protected ArtifactResolverPostProcessorSupport( String name ) - { - this.name = requireNonNull( name ); + protected ArtifactResolverPostProcessorSupport(String name) { + this.name = requireNonNull(name); } /** * This implementation will call into underlying code only if enabled. */ @Override - public void postProcess( RepositorySystemSession session, List artifactResults ) - { - if ( isEnabled( session ) ) - { - doPostProcess( session, artifactResults ); + public void postProcess(RepositorySystemSession session, List artifactResults) { + if (isEnabled(session)) { + doPostProcess(session, artifactResults); } } - protected abstract void doPostProcess( RepositorySystemSession session, List artifactResults ); + protected abstract void doPostProcess(RepositorySystemSession session, List artifactResults); /** * To be used by underlying implementations to form configuration property keys properly scoped. */ - protected String configPropKey( String name ) - { - requireNonNull( name ); + protected String configPropKey(String name) { + requireNonNull(name); return CONFIG_PROP_PREFIX + this.name + "." + name; } @@ -73,8 +66,7 @@ protected String configPropKey( String name ) *

    * Default value is {@code false}. */ - protected boolean isEnabled( RepositorySystemSession session ) - { - return ConfigUtils.getBoolean( session, false, CONFIG_PROP_PREFIX + this.name ); + protected boolean isEnabled(RepositorySystemSession session) { + return ConfigUtils.getBoolean(session, false, CONFIG_PROP_PREFIX + this.name); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/resolution/TrustedChecksumsArtifactResolverPostProcessor.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/resolution/TrustedChecksumsArtifactResolverPostProcessor.java index c6ccc985c..dd2283d48 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/resolution/TrustedChecksumsArtifactResolverPostProcessor.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/resolution/TrustedChecksumsArtifactResolverPostProcessor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.resolution; import javax.inject.Inject; import javax.inject.Named; @@ -76,10 +75,8 @@ * @since 1.9.0 */ @Singleton -@Named( TrustedChecksumsArtifactResolverPostProcessor.NAME ) -public final class TrustedChecksumsArtifactResolverPostProcessor - extends ArtifactResolverPostProcessorSupport -{ +@Named(TrustedChecksumsArtifactResolverPostProcessor.NAME) +public final class TrustedChecksumsArtifactResolverPostProcessor extends ArtifactResolverPostProcessorSupport { public static final String NAME = "trustedChecksums"; private static final String CONF_NAME_CHECKSUM_ALGORITHMS = "checksumAlgorithms"; @@ -95,7 +92,7 @@ public final class TrustedChecksumsArtifactResolverPostProcessor private static final String CHECKSUM_ALGORITHMS_CACHE_KEY = TrustedChecksumsArtifactResolverPostProcessor.class.getName() + ".checksumAlgorithms"; - private static final Logger LOGGER = LoggerFactory.getLogger( TrustedChecksumsArtifactResolverPostProcessor.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(TrustedChecksumsArtifactResolverPostProcessor.class); private final ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector; @@ -104,46 +101,35 @@ public final class TrustedChecksumsArtifactResolverPostProcessor @Inject public TrustedChecksumsArtifactResolverPostProcessor( ChecksumAlgorithmFactorySelector checksumAlgorithmFactorySelector, - Map trustedChecksumsSources ) - { - super( NAME ); - this.checksumAlgorithmFactorySelector = requireNonNull( checksumAlgorithmFactorySelector ); - this.trustedChecksumsSources = requireNonNull( trustedChecksumsSources ); + Map trustedChecksumsSources) { + super(NAME); + this.checksumAlgorithmFactorySelector = requireNonNull(checksumAlgorithmFactorySelector); + this.trustedChecksumsSources = requireNonNull(trustedChecksumsSources); } - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") @Override - protected void doPostProcess( RepositorySystemSession session, List artifactResults ) - { + protected void doPostProcess(RepositorySystemSession session, List artifactResults) { final List checksumAlgorithms = (List) session.getData() - .computeIfAbsent( CHECKSUM_ALGORITHMS_CACHE_KEY, () -> - checksumAlgorithmFactorySelector.selectList( - ConfigUtils.parseCommaSeparatedUniqueNames( ConfigUtils.getString( - session, DEFAULT_CHECKSUM_ALGORITHMS, CONF_NAME_CHECKSUM_ALGORITHMS ) ) - ) ); - - final boolean failIfMissing = ConfigUtils.getBoolean( - session, false, configPropKey( CONF_NAME_FAIL_IF_MISSING ) ); - final boolean record = ConfigUtils.getBoolean( - session, false, configPropKey( CONF_NAME_RECORD ) ); - final boolean snapshots = ConfigUtils.getBoolean( - session, false, configPropKey( CONF_NAME_SNAPSHOTS ) ); - - for ( ArtifactResult artifactResult : artifactResults ) - { - if ( artifactResult.getArtifact().isSnapshot() && !snapshots ) - { + .computeIfAbsent( + CHECKSUM_ALGORITHMS_CACHE_KEY, + () -> checksumAlgorithmFactorySelector.selectList( + ConfigUtils.parseCommaSeparatedUniqueNames(ConfigUtils.getString( + session, DEFAULT_CHECKSUM_ALGORITHMS, CONF_NAME_CHECKSUM_ALGORITHMS)))); + + final boolean failIfMissing = ConfigUtils.getBoolean(session, false, configPropKey(CONF_NAME_FAIL_IF_MISSING)); + final boolean record = ConfigUtils.getBoolean(session, false, configPropKey(CONF_NAME_RECORD)); + final boolean snapshots = ConfigUtils.getBoolean(session, false, configPropKey(CONF_NAME_SNAPSHOTS)); + + for (ArtifactResult artifactResult : artifactResults) { + if (artifactResult.getArtifact().isSnapshot() && !snapshots) { continue; } - if ( artifactResult.isResolved() ) - { - if ( record ) - { - recordArtifactChecksums( session, artifactResult, checksumAlgorithms ); - } - else if ( !validateArtifactChecksums( session, artifactResult, checksumAlgorithms, failIfMissing ) ) - { - artifactResult.setArtifact( artifactResult.getArtifact().setFile( null ) ); // make it unresolved + if (artifactResult.isResolved()) { + if (record) { + recordArtifactChecksums(session, artifactResult, checksumAlgorithms); + } else if (!validateArtifactChecksums(session, artifactResult, checksumAlgorithms, failIfMissing)) { + artifactResult.setArtifact(artifactResult.getArtifact().setFile(null)); // make it unresolved } } } @@ -152,40 +138,31 @@ else if ( !validateArtifactChecksums( session, artifactResult, checksumAlgorithm /** * Calculates and records checksums into trusted sources that support writing. */ - private void recordArtifactChecksums( RepositorySystemSession session, - ArtifactResult artifactResult, - List checksumAlgorithmFactories ) - { + private void recordArtifactChecksums( + RepositorySystemSession session, + ArtifactResult artifactResult, + List checksumAlgorithmFactories) { Artifact artifact = artifactResult.getArtifact(); ArtifactRepository artifactRepository = artifactResult.getRepository(); - try - { - final Map calculatedChecksums = ChecksumAlgorithmHelper.calculate( - artifact.getFile(), checksumAlgorithmFactories ); - - for ( TrustedChecksumsSource trustedChecksumsSource : trustedChecksumsSources.values() ) - { - TrustedChecksumsSource.Writer writer = trustedChecksumsSource - .getTrustedArtifactChecksumsWriter( session ); - if ( writer != null ) - { - try - { - writer.addTrustedArtifactChecksums( artifact, artifactRepository, checksumAlgorithmFactories, - calculatedChecksums ); - } - catch ( IOException e ) - { - throw new UncheckedIOException( "Could not write required checksums for " - + artifact.getFile(), e ); + try { + final Map calculatedChecksums = + ChecksumAlgorithmHelper.calculate(artifact.getFile(), checksumAlgorithmFactories); + + for (TrustedChecksumsSource trustedChecksumsSource : trustedChecksumsSources.values()) { + TrustedChecksumsSource.Writer writer = + trustedChecksumsSource.getTrustedArtifactChecksumsWriter(session); + if (writer != null) { + try { + writer.addTrustedArtifactChecksums( + artifact, artifactRepository, checksumAlgorithmFactories, calculatedChecksums); + } catch (IOException e) { + throw new UncheckedIOException( + "Could not write required checksums for " + artifact.getFile(), e); } } } - } - catch ( IOException e ) - { - throw new UncheckedIOException( "Could not calculate required checksums for " - + artifact.getFile(), e ); + } catch (IOException e) { + throw new UncheckedIOException("Could not calculate required checksums for " + artifact.getFile(), e); } } @@ -193,77 +170,67 @@ private void recordArtifactChecksums( RepositorySystemSession session, * Validates trusted checksums against {@link ArtifactResult}, returns {@code true} denoting "valid" checksums or * {@code false} denoting "invalid" checksums. */ - private boolean validateArtifactChecksums( RepositorySystemSession session, - ArtifactResult artifactResult, - List checksumAlgorithmFactories, - boolean failIfMissing ) - { + private boolean validateArtifactChecksums( + RepositorySystemSession session, + ArtifactResult artifactResult, + List checksumAlgorithmFactories, + boolean failIfMissing) { Artifact artifact = artifactResult.getArtifact(); ArtifactRepository artifactRepository = artifactResult.getRepository(); boolean valid = true; boolean validated = false; - try - { + try { // full set: calculate all algorithms we were asked for - final Map calculatedChecksums = ChecksumAlgorithmHelper.calculate( - artifact.getFile(), checksumAlgorithmFactories ); + final Map calculatedChecksums = + ChecksumAlgorithmHelper.calculate(artifact.getFile(), checksumAlgorithmFactories); - for ( Map.Entry entry : trustedChecksumsSources.entrySet() ) - { + for (Map.Entry entry : trustedChecksumsSources.entrySet()) { final String trustedSourceName = entry.getKey(); final TrustedChecksumsSource trustedChecksumsSource = entry.getValue(); // upper bound set: ask source for checksums, ideally same as calculatedChecksums but may be less Map trustedChecksums = trustedChecksumsSource.getTrustedArtifactChecksums( - session, artifact, artifactRepository, checksumAlgorithmFactories ); + session, artifact, artifactRepository, checksumAlgorithmFactories); - if ( trustedChecksums == null ) - { + if (trustedChecksums == null) { continue; // not enabled } validated = true; - if ( !calculatedChecksums.equals( trustedChecksums ) ) - { - Set missingTrustedAlg = new HashSet<>( calculatedChecksums.keySet() ); - missingTrustedAlg.removeAll( trustedChecksums.keySet() ); + if (!calculatedChecksums.equals(trustedChecksums)) { + Set missingTrustedAlg = new HashSet<>(calculatedChecksums.keySet()); + missingTrustedAlg.removeAll(trustedChecksums.keySet()); - if ( !missingTrustedAlg.isEmpty() && failIfMissing ) - { - artifactResult.addException( new ChecksumFailureException( "Missing from " + trustedSourceName + if (!missingTrustedAlg.isEmpty() && failIfMissing) { + artifactResult.addException(new ChecksumFailureException("Missing from " + trustedSourceName + " trusted checksum(s) " + missingTrustedAlg + " for artifact " - + ArtifactIdUtils.toId( artifact ) ) ); + + ArtifactIdUtils.toId(artifact))); valid = false; } // compare values but only present ones, failIfMissing handled above // we still want to report all: algX - missing, algY - mismatch, etc - for ( ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories ) - { - String calculatedChecksum = calculatedChecksums.get( checksumAlgorithmFactory.getName() ); - String trustedChecksum = trustedChecksums.get( checksumAlgorithmFactory.getName() ); - if ( trustedChecksum != null && !Objects.equals( calculatedChecksum, trustedChecksum ) ) - { - artifactResult.addException( new ChecksumFailureException( "Artifact " - + ArtifactIdUtils.toId( artifact ) + " trusted checksum mismatch: " + for (ChecksumAlgorithmFactory checksumAlgorithmFactory : checksumAlgorithmFactories) { + String calculatedChecksum = calculatedChecksums.get(checksumAlgorithmFactory.getName()); + String trustedChecksum = trustedChecksums.get(checksumAlgorithmFactory.getName()); + if (trustedChecksum != null && !Objects.equals(calculatedChecksum, trustedChecksum)) { + artifactResult.addException(new ChecksumFailureException("Artifact " + + ArtifactIdUtils.toId(artifact) + " trusted checksum mismatch: " + trustedSourceName + "=" + trustedChecksum + "; calculated=" - + calculatedChecksum ) ); + + calculatedChecksum)); valid = false; } } } } - if ( !validated && failIfMissing ) - { - artifactResult.addException( new ChecksumFailureException( "There are no enabled trusted checksums" - + " source(s) to validate against." ) ); + if (!validated && failIfMissing) { + artifactResult.addException(new ChecksumFailureException( + "There are no enabled trusted checksums" + " source(s) to validate against.")); valid = false; } - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + } catch (IOException e) { + throw new UncheckedIOException(e); } return valid; } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/slf4j/Slf4jLoggerFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/slf4j/Slf4jLoggerFactory.java index d9a634649..fa148fd7b 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/slf4j/Slf4jLoggerFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/slf4j/Slf4jLoggerFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.slf4j; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.slf4j; import javax.inject.Inject; import javax.inject.Named; @@ -37,31 +36,24 @@ * @deprecated Use SLF4J instead */ @Singleton -@Named( "slf4j" ) +@Named("slf4j") @Deprecated -public class Slf4jLoggerFactory - implements LoggerFactory, Service -{ +public class Slf4jLoggerFactory implements LoggerFactory, Service { private static final boolean AVAILABLE; - static - { + static { boolean available; - try - { - Slf4jLoggerFactory.class.getClassLoader().loadClass( "org.slf4j.ILoggerFactory" ); + try { + Slf4jLoggerFactory.class.getClassLoader().loadClass("org.slf4j.ILoggerFactory"); available = true; - } - catch ( Exception | LinkageError e ) - { + } catch (Exception | LinkageError e) { available = false; } AVAILABLE = available; } - public static boolean isSlf4jAvailable() - { + public static boolean isSlf4jAvailable() { return AVAILABLE; } @@ -70,133 +62,104 @@ public static boolean isSlf4jAvailable() /** * Creates an instance of this logger factory. */ - public Slf4jLoggerFactory() - { + public Slf4jLoggerFactory() { // enables no-arg constructor } @Inject - Slf4jLoggerFactory( @Nullable ILoggerFactory factory ) - { - setLoggerFactory( factory ); + Slf4jLoggerFactory(@Nullable ILoggerFactory factory) { + setLoggerFactory(factory); } - public void initService( ServiceLocator locator ) - { - setLoggerFactory( locator.getService( ILoggerFactory.class ) ); + public void initService(ServiceLocator locator) { + setLoggerFactory(locator.getService(ILoggerFactory.class)); } - public Slf4jLoggerFactory setLoggerFactory( ILoggerFactory factory ) - { + public Slf4jLoggerFactory setLoggerFactory(ILoggerFactory factory) { this.factory = factory; return this; } - public Logger getLogger( String name ) - { - org.slf4j.Logger logger = getFactory().getLogger( name ); - if ( logger instanceof LocationAwareLogger ) - { - return new Slf4jLoggerEx( (LocationAwareLogger) logger ); + public Logger getLogger(String name) { + org.slf4j.Logger logger = getFactory().getLogger(name); + if (logger instanceof LocationAwareLogger) { + return new Slf4jLoggerEx((LocationAwareLogger) logger); } - return new Slf4jLogger( logger ); + return new Slf4jLogger(logger); } - private ILoggerFactory getFactory() - { - if ( factory == null ) - { + private ILoggerFactory getFactory() { + if (factory == null) { factory = org.slf4j.LoggerFactory.getILoggerFactory(); } return factory; } - private static final class Slf4jLogger - implements Logger - { + private static final class Slf4jLogger implements Logger { private final org.slf4j.Logger logger; - Slf4jLogger( org.slf4j.Logger logger ) - { + Slf4jLogger(org.slf4j.Logger logger) { this.logger = logger; } - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return logger.isDebugEnabled(); } - public void debug( String msg ) - { - logger.debug( msg ); + public void debug(String msg) { + logger.debug(msg); } - public void debug( String msg, Throwable error ) - { - logger.debug( msg, error ); + public void debug(String msg, Throwable error) { + logger.debug(msg, error); } - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return logger.isWarnEnabled(); } - public void warn( String msg ) - { - logger.warn( msg ); + public void warn(String msg) { + logger.warn(msg); } - public void warn( String msg, Throwable error ) - { - logger.warn( msg, error ); + public void warn(String msg, Throwable error) { + logger.warn(msg, error); } - } - private static final class Slf4jLoggerEx - implements Logger - { + private static final class Slf4jLoggerEx implements Logger { private static final String FQCN = Slf4jLoggerEx.class.getName(); private final LocationAwareLogger logger; - Slf4jLoggerEx( LocationAwareLogger logger ) - { + Slf4jLoggerEx(LocationAwareLogger logger) { this.logger = logger; } - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return logger.isDebugEnabled(); } - public void debug( String msg ) - { - logger.log( null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, null ); + public void debug(String msg) { + logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, null); } - public void debug( String msg, Throwable error ) - { - logger.log( null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, error ); + public void debug(String msg, Throwable error) { + logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, error); } - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return logger.isWarnEnabled(); } - public void warn( String msg ) - { - logger.log( null, FQCN, LocationAwareLogger.WARN_INT, msg, null, null ); + public void warn(String msg) { + logger.log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, null); } - public void warn( String msg, Throwable error ) - { - logger.log( null, FQCN, LocationAwareLogger.WARN_INT, msg, null, error ); + public void warn(String msg, Throwable error) { + logger.log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, error); } - } - } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/DefaultSyncContextFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/DefaultSyncContextFactory.java index 646e49687..1af9d52ab 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/DefaultSyncContextFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/DefaultSyncContextFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext; import javax.inject.Inject; import javax.inject.Named; @@ -41,9 +40,7 @@ */ @Singleton @Named -public final class DefaultSyncContextFactory - implements SyncContextFactory, Service -{ +public final class DefaultSyncContextFactory implements SyncContextFactory, Service { private static final String ADAPTER_KEY = DefaultSyncContextFactory.class.getName() + ".adapter"; private NamedLockFactoryAdapterFactory namedLockFactoryAdapterFactory; @@ -52,9 +49,8 @@ public final class DefaultSyncContextFactory * Constructor used with DI, where factories are injected and selected based on key. */ @Inject - public DefaultSyncContextFactory( final NamedLockFactoryAdapterFactory namedLockFactoryAdapterFactory ) - { - this.namedLockFactoryAdapterFactory = requireNonNull( namedLockFactoryAdapterFactory ); + public DefaultSyncContextFactory(final NamedLockFactoryAdapterFactory namedLockFactoryAdapterFactory) { + this.namedLockFactoryAdapterFactory = requireNonNull(namedLockFactoryAdapterFactory); } /** @@ -63,24 +59,20 @@ public DefaultSyncContextFactory( final NamedLockFactoryAdapterFactory namedLock * @deprecated Will be removed once ServiceLocator removed. */ @Deprecated - public DefaultSyncContextFactory() - { + public DefaultSyncContextFactory() { // ctor for ServiceLoader } @Override - public void initService( final ServiceLocator locator ) - { - this.namedLockFactoryAdapterFactory = requireNonNull( - locator.getService( NamedLockFactoryAdapterFactory.class ) ); + public void initService(final ServiceLocator locator) { + this.namedLockFactoryAdapterFactory = requireNonNull(locator.getService(NamedLockFactoryAdapterFactory.class)); } @Override - public SyncContext newInstance( final RepositorySystemSession session, final boolean shared ) - { - requireNonNull( session, "session cannot be null" ); - NamedLockFactoryAdapter adapter = (NamedLockFactoryAdapter) session.getData().computeIfAbsent( - ADAPTER_KEY, () -> namedLockFactoryAdapterFactory.getAdapter( session ) ); - return adapter.newInstance( session, shared ); + public SyncContext newInstance(final RepositorySystemSession session, final boolean shared) { + requireNonNull(session, "session cannot be null"); + NamedLockFactoryAdapter adapter = (NamedLockFactoryAdapter) session.getData() + .computeIfAbsent(ADAPTER_KEY, () -> namedLockFactoryAdapterFactory.getAdapter(session)); + return adapter.newInstance(session, shared); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/legacy/DefaultSyncContextFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/legacy/DefaultSyncContextFactory.java index 669f5587a..59afbce05 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/legacy/DefaultSyncContextFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/legacy/DefaultSyncContextFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.legacy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import java.util.Objects; +package org.eclipse.aether.internal.impl.synccontext.legacy; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; +import java.util.Objects; + import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.SyncContext; import org.eclipse.aether.spi.locator.Service; @@ -43,32 +42,26 @@ @Singleton @Named @Deprecated -public final class DefaultSyncContextFactory - implements org.eclipse.aether.impl.SyncContextFactory, Service -{ +public final class DefaultSyncContextFactory implements org.eclipse.aether.impl.SyncContextFactory, Service { private SyncContextFactory delegate; - public DefaultSyncContextFactory() - { + public DefaultSyncContextFactory() { // default ctor for ServiceLocator } @Inject - public DefaultSyncContextFactory( final SyncContextFactory delegate ) - { - this.delegate = Objects.requireNonNull( delegate ); + public DefaultSyncContextFactory(final SyncContextFactory delegate) { + this.delegate = Objects.requireNonNull(delegate); } @Override - public void initService( final ServiceLocator locator ) - { - this.delegate = Objects.requireNonNull( locator.getService( SyncContextFactory.class ) ); + public void initService(final ServiceLocator locator) { + this.delegate = Objects.requireNonNull(locator.getService(SyncContextFactory.class)); } @Override - public SyncContext newInstance( final RepositorySystemSession session, final boolean shared ) - { - requireNonNull( session, "session cannot be null" ); - return delegate.newInstance( session, shared ); + public SyncContext newInstance(final RepositorySystemSession session, final boolean shared) { + requireNonNull(session, "session cannot be null"); + return delegate.newInstance(session, shared); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/BasedirNameMapper.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/BasedirNameMapper.java index bfd311f22..3ce330aa6 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/BasedirNameMapper.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/BasedirNameMapper.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; import java.io.IOException; import java.io.UncheckedIOException; @@ -39,40 +38,33 @@ * * @since 1.9.0 */ -public class BasedirNameMapper implements NameMapper -{ +public class BasedirNameMapper implements NameMapper { private static final String CONFIG_PROP_LOCKS_DIR = "aether.syncContext.named.basedir.locksDir"; private final NameMapper delegate; - public BasedirNameMapper( final NameMapper delegate ) - { - this.delegate = requireNonNull( delegate ); + public BasedirNameMapper(final NameMapper delegate) { + this.delegate = requireNonNull(delegate); } @Override - public boolean isFileSystemFriendly() - { + public boolean isFileSystemFriendly() { return delegate.isFileSystemFriendly(); } @Override - public Collection nameLocks( final RepositorySystemSession session, - final Collection artifacts, - final Collection metadatas ) - { - try - { - final Path basedir = DirectoryUtils.resolveDirectory( - session, ".locks", CONFIG_PROP_LOCKS_DIR, false ); + public Collection nameLocks( + final RepositorySystemSession session, + final Collection artifacts, + final Collection metadatas) { + try { + final Path basedir = DirectoryUtils.resolveDirectory(session, ".locks", CONFIG_PROP_LOCKS_DIR, false); - return delegate.nameLocks( session, artifacts, metadatas ).stream() - .map( name -> basedir.resolve( name ).toAbsolutePath().toString() ) - .collect( Collectors.toList() ); - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + return delegate.nameLocks(session, artifacts, metadatas).stream() + .map(name -> basedir.resolve(name).toAbsolutePath().toString()) + .collect(Collectors.toList()); + } catch (IOException e) { + throw new UncheckedIOException(e); } } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/DiscriminatingNameMapper.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/DiscriminatingNameMapper.java index 0aa74aee0..ddfed7e6d 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/DiscriminatingNameMapper.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/DiscriminatingNameMapper.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; + +import java.io.File; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Collection; +import java.util.Objects; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -27,12 +32,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Collection; -import java.util.Objects; - import static java.util.stream.Collectors.toList; /** @@ -44,8 +43,7 @@ *

    * The default setup wraps {@link GAVNameMapper}, but manually may be created any instance needed. */ -public class DiscriminatingNameMapper implements NameMapper -{ +public class DiscriminatingNameMapper implements NameMapper { /** * Configuration property to pass in discriminator */ @@ -60,64 +58,53 @@ public class DiscriminatingNameMapper implements NameMapper private static final String DEFAULT_HOSTNAME = "localhost"; - private static final Logger LOGGER = LoggerFactory.getLogger( DiscriminatingNameMapper.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(DiscriminatingNameMapper.class); private final NameMapper delegate; private final String hostname; - public DiscriminatingNameMapper( final NameMapper delegate ) - { - this.delegate = Objects.requireNonNull( delegate ); + public DiscriminatingNameMapper(final NameMapper delegate) { + this.delegate = Objects.requireNonNull(delegate); this.hostname = getHostname(); } @Override - public boolean isFileSystemFriendly() - { + public boolean isFileSystemFriendly() { return false; // uses ":" in produced lock names } @Override - public Collection nameLocks( final RepositorySystemSession session, - final Collection artifacts, - final Collection metadatas ) - { - String discriminator = createDiscriminator( session ); - return delegate.nameLocks( session, artifacts, metadatas ).stream() - .map( s -> discriminator + ":" + s ) - .collect( toList() ); + public Collection nameLocks( + final RepositorySystemSession session, + final Collection artifacts, + final Collection metadatas) { + String discriminator = createDiscriminator(session); + return delegate.nameLocks(session, artifacts, metadatas).stream() + .map(s -> discriminator + ":" + s) + .collect(toList()); } - private String getHostname() - { - try - { + private String getHostname() { + try { return InetAddress.getLocalHost().getHostName(); - } - catch ( UnknownHostException e ) - { - LOGGER.warn( "Failed to get hostname, using '{}'", DEFAULT_HOSTNAME, e ); + } catch (UnknownHostException e) { + LOGGER.warn("Failed to get hostname, using '{}'", DEFAULT_HOSTNAME, e); return DEFAULT_HOSTNAME; } } - private String createDiscriminator( final RepositorySystemSession session ) - { - String discriminator = ConfigUtils.getString( session, null, CONFIG_PROP_DISCRIMINATOR ); + private String createDiscriminator(final RepositorySystemSession session) { + String discriminator = ConfigUtils.getString(session, null, CONFIG_PROP_DISCRIMINATOR); - if ( discriminator == null || discriminator.isEmpty() ) - { - String hostname = ConfigUtils.getString( session, this.hostname, CONFIG_PROP_HOSTNAME ); + if (discriminator == null || discriminator.isEmpty()) { + String hostname = ConfigUtils.getString(session, this.hostname, CONFIG_PROP_HOSTNAME); File basedir = session.getLocalRepository().getBasedir(); discriminator = hostname + ":" + basedir; - try - { - return StringDigestUtil.sha1( discriminator ); - } - catch ( Exception e ) - { - LOGGER.warn( "Failed to calculate discriminator digest, using '{}'", DEFAULT_DISCRIMINATOR_DIGEST, e ); + try { + return StringDigestUtil.sha1(discriminator); + } catch (Exception e) { + LOGGER.warn("Failed to calculate discriminator digest, using '{}'", DEFAULT_DISCRIMINATOR_DIGEST, e); return DEFAULT_DISCRIMINATOR_DIGEST; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/GAVNameMapper.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/GAVNameMapper.java index 1492aa3d4..8c47aea7b 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/GAVNameMapper.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/GAVNameMapper.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; import java.util.Collection; import java.util.TreeSet; @@ -33,8 +32,7 @@ * considering local repository, only the artifact coordinates. May use custom prefixes and sufixes and separators, * hence this instance may or may not be filesystem friendly (depends on strings used). */ -public class GAVNameMapper implements NameMapper -{ +public class GAVNameMapper implements NameMapper { private final boolean fileSystemFriendly; private final String artifactPrefix; @@ -47,70 +45,65 @@ public class GAVNameMapper implements NameMapper private final String fieldSeparator; - public GAVNameMapper( boolean fileSystemFriendly, - String artifactPrefix, String artifactSuffix, - String metadataPrefix, String metadataSuffix, - String fieldSeparator ) - { + public GAVNameMapper( + boolean fileSystemFriendly, + String artifactPrefix, + String artifactSuffix, + String metadataPrefix, + String metadataSuffix, + String fieldSeparator) { this.fileSystemFriendly = fileSystemFriendly; - this.artifactPrefix = requireNonNull( artifactPrefix ); - this.artifactSuffix = requireNonNull( artifactSuffix ); - this.metadataPrefix = requireNonNull( metadataPrefix ); - this.metadataSuffix = requireNonNull( metadataSuffix ); - this.fieldSeparator = requireNonNull( fieldSeparator ); + this.artifactPrefix = requireNonNull(artifactPrefix); + this.artifactSuffix = requireNonNull(artifactSuffix); + this.metadataPrefix = requireNonNull(metadataPrefix); + this.metadataSuffix = requireNonNull(metadataSuffix); + this.fieldSeparator = requireNonNull(fieldSeparator); } @Override - public boolean isFileSystemFriendly() - { + public boolean isFileSystemFriendly() { return fileSystemFriendly; } @Override - public Collection nameLocks( final RepositorySystemSession session, - final Collection artifacts, - final Collection metadatas ) - { + public Collection nameLocks( + final RepositorySystemSession session, + final Collection artifacts, + final Collection metadatas) { // Deadlock prevention: https://stackoverflow.com/a/16780988/696632 // We must acquire multiple locks always in the same order! TreeSet keys = new TreeSet<>(); - if ( artifacts != null ) - { - for ( Artifact artifact : artifacts ) - { - keys.add( getArtifactName( artifact ) ); + if (artifacts != null) { + for (Artifact artifact : artifacts) { + keys.add(getArtifactName(artifact)); } } - if ( metadatas != null ) - { - for ( Metadata metadata : metadatas ) - { - keys.add( getMetadataName( metadata ) ); + if (metadatas != null) { + for (Metadata metadata : metadatas) { + keys.add(getMetadataName(metadata)); } } return keys; } - private String getArtifactName( Artifact artifact ) - { - return artifactPrefix + artifact.getGroupId() - + fieldSeparator + artifact.getArtifactId() - + fieldSeparator + artifact.getBaseVersion() + private String getArtifactName(Artifact artifact) { + return artifactPrefix + + artifact.getGroupId() + + fieldSeparator + + artifact.getArtifactId() + + fieldSeparator + + artifact.getBaseVersion() + artifactSuffix; } - private String getMetadataName( Metadata metadata ) - { + private String getMetadataName(Metadata metadata) { String name = metadataPrefix; - if ( !metadata.getGroupId().isEmpty() ) - { + if (!metadata.getGroupId().isEmpty()) { name += metadata.getGroupId(); - if ( !metadata.getArtifactId().isEmpty() ) - { + if (!metadata.getArtifactId().isEmpty()) { name += fieldSeparator + metadata.getArtifactId(); - if ( !metadata.getVersion().isEmpty() ) - { + if (!metadata.getVersion().isEmpty()) { name += fieldSeparator + metadata.getVersion(); } } @@ -118,13 +111,11 @@ private String getMetadataName( Metadata metadata ) return name + metadataSuffix; } - public static NameMapper gav() - { - return new GAVNameMapper( false, "artifact:", "", "metadata:", "", ":" ); + public static NameMapper gav() { + return new GAVNameMapper(false, "artifact:", "", "metadata:", "", ":"); } - public static NameMapper fileGav() - { - return new GAVNameMapper( true, "", ".lock", "", ".lock", "~" ); + public static NameMapper fileGav() { + return new GAVNameMapper(true, "", ".lock", "", ".lock", "~"); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/HashingNameMapper.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/HashingNameMapper.java index 51b641a1b..e9529ff2a 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/HashingNameMapper.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/HashingNameMapper.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; import java.util.Collection; import java.util.stream.Collectors; @@ -40,52 +39,45 @@ * * @since 1.9.0 */ -public class HashingNameMapper implements NameMapper -{ +public class HashingNameMapper implements NameMapper { private static final String CONFIG_PROP_DEPTH = "aether.syncContext.named.hashing.depth"; private final NameMapper delegate; - public HashingNameMapper( final NameMapper delegate ) - { - this.delegate = requireNonNull( delegate ); + public HashingNameMapper(final NameMapper delegate) { + this.delegate = requireNonNull(delegate); } @Override - public boolean isFileSystemFriendly() - { + public boolean isFileSystemFriendly() { return true; // hashes delegated strings, so whatever it wrapped, it does not come through } @Override - public Collection nameLocks( RepositorySystemSession session, - Collection artifacts, - Collection metadatas ) - { - final int depth = ConfigUtils.getInteger( session, 2, CONFIG_PROP_DEPTH ); - if ( depth < 0 || depth > 4 ) - { - throw new IllegalArgumentException( "allowed depth value is between 0 and 4 (inclusive)" ); + public Collection nameLocks( + RepositorySystemSession session, + Collection artifacts, + Collection metadatas) { + final int depth = ConfigUtils.getInteger(session, 2, CONFIG_PROP_DEPTH); + if (depth < 0 || depth > 4) { + throw new IllegalArgumentException("allowed depth value is between 0 and 4 (inclusive)"); } - return delegate.nameLocks( session, artifacts, metadatas ).stream() - .map( n -> hashName( n, depth ) ) - .collect( Collectors.toList() ); + return delegate.nameLocks(session, artifacts, metadatas).stream() + .map(n -> hashName(n, depth)) + .collect(Collectors.toList()); } - private String hashName( final String name, final int depth ) - { - String hashedName = StringDigestUtil.sha1( name ); - if ( depth == 0 ) - { + private String hashName(final String name, final int depth) { + String hashedName = StringDigestUtil.sha1(name); + if (depth == 0) { return hashedName; } - StringBuilder prefix = new StringBuilder( "" ); + StringBuilder prefix = new StringBuilder(""); int i = 0; - while ( i < hashedName.length() && i / 2 < depth ) - { - prefix.append( hashedName, i, i + 2 ).append( "/" ); + while (i < hashedName.length() && i / 2 < depth) { + prefix.append(hashedName, i, i + 2).append("/"); i += 2; } - return prefix.append( hashedName ).toString(); + return prefix.append(hashedName).toString(); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NameMapper.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NameMapper.java index 11eaaceb5..761e832ec 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NameMapper.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NameMapper.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; import java.util.Collection; @@ -28,8 +27,7 @@ /** * Component mapping lock names to passed in artifacts and metadata as required. */ -public interface NameMapper -{ +public interface NameMapper { /** * Returns {@code true} if lock names returned by this lock name mapper are file system friendly, can be used * as file names and paths. @@ -50,7 +48,8 @@ public interface NameMapper * size). If returned collection is empty, no locking will happen, if single element, one lock will be used, if two * then two named locks will be used etc. */ - Collection nameLocks( RepositorySystemSession session, - Collection artifacts, - Collection metadatas ); + Collection nameLocks( + RepositorySystemSession session, + Collection artifacts, + Collection metadatas); } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NameMappers.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NameMappers.java index 0a5303e75..156b21054 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NameMappers.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NameMappers.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; /** * As end-user "mappers" are actually configurations/compositions and are constructed from several NameMapper @@ -26,8 +25,7 @@ * * @since 1.9.4 */ -public final class NameMappers -{ +public final class NameMappers { public static final String STATIC_NAME = "static"; public static final String GAV_NAME = "gav"; @@ -38,28 +36,23 @@ public final class NameMappers public static final String DISCRIMINATING_NAME = "discriminating"; - public static NameMapper staticNameMapper() - { + public static NameMapper staticNameMapper() { return new StaticNameMapper(); } - public static NameMapper gavNameMapper() - { + public static NameMapper gavNameMapper() { return GAVNameMapper.gav(); } - public static NameMapper fileGavNameMapper() - { - return new BasedirNameMapper( GAVNameMapper.fileGav() ); + public static NameMapper fileGavNameMapper() { + return new BasedirNameMapper(GAVNameMapper.fileGav()); } - public static NameMapper fileHashingGavNameMapper() - { - return new BasedirNameMapper( new HashingNameMapper( GAVNameMapper.gav() ) ); + public static NameMapper fileHashingGavNameMapper() { + return new BasedirNameMapper(new HashingNameMapper(GAVNameMapper.gav())); } - public static NameMapper discriminatingNameMapper() - { - return new DiscriminatingNameMapper( GAVNameMapper.gav() ); + public static NameMapper discriminatingNameMapper() { + return new DiscriminatingNameMapper(GAVNameMapper.gav()); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapter.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapter.java index 29f992bfc..3b254c738 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapter.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; + +import java.util.ArrayDeque; +import java.util.Collection; +import java.util.Deque; +import java.util.Objects; +import java.util.concurrent.TimeUnit; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.SyncContext; @@ -27,21 +32,13 @@ import org.eclipse.aether.named.NamedLockFactory; import org.eclipse.aether.named.providers.FileLockNamedLockFactory; import org.eclipse.aether.util.ConfigUtils; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayDeque; -import java.util.Collection; -import java.util.Deque; -import java.util.Objects; -import java.util.concurrent.TimeUnit; - /** * Adapter to adapt {@link NamedLockFactory} and {@link NamedLock} to {@link SyncContext}. */ -public final class NamedLockFactoryAdapter -{ +public final class NamedLockFactoryAdapter { public static final String TIME_KEY = "aether.syncContext.named.time"; public static final long DEFAULT_TIME = 30L; @@ -54,52 +51,43 @@ public final class NamedLockFactoryAdapter private final NamedLockFactory namedLockFactory; - public NamedLockFactoryAdapter( final NameMapper nameMapper, final NamedLockFactory namedLockFactory ) - { - this.nameMapper = Objects.requireNonNull( nameMapper ); - this.namedLockFactory = Objects.requireNonNull( namedLockFactory ); + public NamedLockFactoryAdapter(final NameMapper nameMapper, final NamedLockFactory namedLockFactory) { + this.nameMapper = Objects.requireNonNull(nameMapper); + this.namedLockFactory = Objects.requireNonNull(namedLockFactory); // TODO: this is ad-hoc "validation", experimental and likely to change - if ( this.namedLockFactory instanceof FileLockNamedLockFactory - && !this.nameMapper.isFileSystemFriendly() ) - { + if (this.namedLockFactory instanceof FileLockNamedLockFactory && !this.nameMapper.isFileSystemFriendly()) { throw new IllegalArgumentException( - "Misconfiguration: FileLockNamedLockFactory lock factory requires FS friendly NameMapper" - ); + "Misconfiguration: FileLockNamedLockFactory lock factory requires FS friendly NameMapper"); } } - public SyncContext newInstance( final RepositorySystemSession session, final boolean shared ) - { - return new AdaptedLockSyncContext( session, shared, nameMapper, namedLockFactory ); + public SyncContext newInstance(final RepositorySystemSession session, final boolean shared) { + return new AdaptedLockSyncContext(session, shared, nameMapper, namedLockFactory); } /** * @since 1.9.1 */ - public NameMapper getNameMapper() - { + public NameMapper getNameMapper() { return nameMapper; } /** * @since 1.9.1 */ - public NamedLockFactory getNamedLockFactory() - { + public NamedLockFactory getNamedLockFactory() { return namedLockFactory; } - public String toString() - { + public String toString() { return getClass().getSimpleName() + "(nameMapper=" + nameMapper + ", namedLockFactory=" + namedLockFactory + ")"; } - private static class AdaptedLockSyncContext implements SyncContext - { - private static final Logger LOGGER = LoggerFactory.getLogger( AdaptedLockSyncContext.class ); + private static class AdaptedLockSyncContext implements SyncContext { + private static final Logger LOGGER = LoggerFactory.getLogger(AdaptedLockSyncContext.class); private final RepositorySystemSession session; @@ -115,108 +103,87 @@ private static class AdaptedLockSyncContext implements SyncContext private final Deque locks; - private AdaptedLockSyncContext( final RepositorySystemSession session, final boolean shared, - final NameMapper lockNaming, final NamedLockFactory namedLockFactory ) - { + private AdaptedLockSyncContext( + final RepositorySystemSession session, + final boolean shared, + final NameMapper lockNaming, + final NamedLockFactory namedLockFactory) { this.session = session; this.shared = shared; this.lockNaming = lockNaming; this.namedLockFactory = namedLockFactory; - this.time = getTime( session ); - this.timeUnit = getTimeUnit( session ); + this.time = getTime(session); + this.timeUnit = getTimeUnit(session); this.locks = new ArrayDeque<>(); - if ( time < 0L ) - { - throw new IllegalArgumentException( "time cannot be negative" ); + if (time < 0L) { + throw new IllegalArgumentException("time cannot be negative"); } } - private long getTime( final RepositorySystemSession session ) - { - return ConfigUtils.getLong( session, DEFAULT_TIME, TIME_KEY ); + private long getTime(final RepositorySystemSession session) { + return ConfigUtils.getLong(session, DEFAULT_TIME, TIME_KEY); } - private TimeUnit getTimeUnit( final RepositorySystemSession session ) - { - return TimeUnit.valueOf( ConfigUtils.getString( - session, DEFAULT_TIME_UNIT.name(), TIME_UNIT_KEY - ) ); + private TimeUnit getTimeUnit(final RepositorySystemSession session) { + return TimeUnit.valueOf(ConfigUtils.getString(session, DEFAULT_TIME_UNIT.name(), TIME_UNIT_KEY)); } @Override - public void acquire( Collection artifacts, Collection metadatas ) - { - Collection keys = lockNaming.nameLocks( session, artifacts, metadatas ); - if ( keys.isEmpty() ) - { + public void acquire(Collection artifacts, Collection metadatas) { + Collection keys = lockNaming.nameLocks(session, artifacts, metadatas); + if (keys.isEmpty()) { return; } - LOGGER.trace( "Need {} {} lock(s) for {}", keys.size(), shared ? "read" : "write", keys ); + LOGGER.trace("Need {} {} lock(s) for {}", keys.size(), shared ? "read" : "write", keys); int acquiredLockCount = 0; - for ( String key : keys ) - { - NamedLock namedLock = namedLockFactory.getLock( key ); - try - { - LOGGER.trace( "Acquiring {} lock for '{}'", - shared ? "read" : "write", key ); + for (String key : keys) { + NamedLock namedLock = namedLockFactory.getLock(key); + try { + LOGGER.trace("Acquiring {} lock for '{}'", shared ? "read" : "write", key); boolean locked; - if ( shared ) - { - locked = namedLock.lockShared( time, timeUnit ); - } - else - { - locked = namedLock.lockExclusively( time, timeUnit ); + if (shared) { + locked = namedLock.lockShared(time, timeUnit); + } else { + locked = namedLock.lockExclusively(time, timeUnit); } - if ( !locked ) - { - LOGGER.trace( "Failed to acquire {} lock for '{}'", - shared ? "read" : "write", key ); + if (!locked) { + LOGGER.trace("Failed to acquire {} lock for '{}'", shared ? "read" : "write", key); namedLock.close(); - throw new IllegalStateException( - "Could not acquire " + ( shared ? "read" : "write" ) - + " lock for '" + namedLock.name() + "'" ); + throw new IllegalStateException("Could not acquire " + (shared ? "read" : "write") + + " lock for '" + namedLock.name() + "'"); } - locks.push( namedLock ); + locks.push(namedLock); acquiredLockCount++; - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); - throw new RuntimeException( e ); + throw new RuntimeException(e); } } - LOGGER.trace( "Total locks acquired: {}", acquiredLockCount ); + LOGGER.trace("Total locks acquired: {}", acquiredLockCount); } @Override - public void close() - { - if ( locks.isEmpty() ) - { + public void close() { + if (locks.isEmpty()) { return; } // Release locks in reverse insertion order int released = 0; - while ( !locks.isEmpty() ) - { - try ( NamedLock namedLock = locks.pop() ) - { - LOGGER.trace( "Releasing {} lock for '{}'", - shared ? "read" : "write", namedLock.name() ); + while (!locks.isEmpty()) { + try (NamedLock namedLock = locks.pop()) { + LOGGER.trace("Releasing {} lock for '{}'", shared ? "read" : "write", namedLock.name()); namedLock.unlock(); released++; } } - LOGGER.trace( "Total locks released: {}", released ); + LOGGER.trace("Total locks released: {}", released); } } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactory.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactory.java index 195bb9cb0..93b803f15 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactory.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; import org.eclipse.aether.RepositorySystemSession; @@ -26,8 +25,7 @@ * * @since 1.9.1 */ -public interface NamedLockFactoryAdapterFactory -{ +public interface NamedLockFactoryAdapterFactory { /** * Creates or returns pre-created {@link NamedLockFactoryAdapter}, never {@code null}. *

    @@ -35,5 +33,5 @@ public interface NamedLockFactoryAdapterFactory * instances, or return the same instance. One thing is required for the implementation: to shut down any name * lock factory it used during any invocation of this method. */ - NamedLockFactoryAdapter getAdapter( RepositorySystemSession session ); -} \ No newline at end of file + NamedLockFactoryAdapter getAdapter(RepositorySystemSession session); +} diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactoryImpl.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactoryImpl.java index 0890c1b9a..132c47260 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactoryImpl.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/NamedLockFactoryAdapterFactoryImpl.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; import javax.inject.Inject; import javax.inject.Named; @@ -58,38 +57,35 @@ */ @Singleton @Named -public class NamedLockFactoryAdapterFactoryImpl implements NamedLockFactoryAdapterFactory, Service -{ +public class NamedLockFactoryAdapterFactoryImpl implements NamedLockFactoryAdapterFactory, Service { private static final String DEFAULT_FACTORY_NAME = LocalReadWriteLockNamedLockFactory.NAME; private static final String DEFAULT_NAME_MAPPER_NAME = NameMappers.GAV_NAME; - private static Map getManuallyCreatedFactories() - { + private static Map getManuallyCreatedFactories() { HashMap factories = new HashMap<>(); - factories.put( NoopNamedLockFactory.NAME, new NoopNamedLockFactory() ); - factories.put( LocalReadWriteLockNamedLockFactory.NAME, new LocalReadWriteLockNamedLockFactory() ); - factories.put( LocalSemaphoreNamedLockFactory.NAME, new LocalSemaphoreNamedLockFactory() ); - factories.put( FileLockNamedLockFactory.NAME, new FileLockNamedLockFactory() ); - return Collections.unmodifiableMap( factories ); + factories.put(NoopNamedLockFactory.NAME, new NoopNamedLockFactory()); + factories.put(LocalReadWriteLockNamedLockFactory.NAME, new LocalReadWriteLockNamedLockFactory()); + factories.put(LocalSemaphoreNamedLockFactory.NAME, new LocalSemaphoreNamedLockFactory()); + factories.put(FileLockNamedLockFactory.NAME, new FileLockNamedLockFactory()); + return Collections.unmodifiableMap(factories); } - private static Map getManuallyCreatedNameMappers() - { + private static Map getManuallyCreatedNameMappers() { HashMap mappers = new HashMap<>(); - mappers.put( NameMappers.STATIC_NAME, NameMappers.staticNameMapper() ); - mappers.put( NameMappers.GAV_NAME, NameMappers.gavNameMapper() ); - mappers.put( NameMappers.DISCRIMINATING_NAME, NameMappers.discriminatingNameMapper() ); - mappers.put( NameMappers.FILE_GAV_NAME, NameMappers.fileGavNameMapper() ); - mappers.put( NameMappers.FILE_HGAV_NAME, NameMappers.fileHashingGavNameMapper() ); - return Collections.unmodifiableMap( mappers ); + mappers.put(NameMappers.STATIC_NAME, NameMappers.staticNameMapper()); + mappers.put(NameMappers.GAV_NAME, NameMappers.gavNameMapper()); + mappers.put(NameMappers.DISCRIMINATING_NAME, NameMappers.discriminatingNameMapper()); + mappers.put(NameMappers.FILE_GAV_NAME, NameMappers.fileGavNameMapper()); + mappers.put(NameMappers.FILE_HGAV_NAME, NameMappers.fileHashingGavNameMapper()); + return Collections.unmodifiableMap(mappers); } protected static final String FACTORY_KEY = "aether.syncContext.named.factory"; protected static final String NAME_MAPPER_KEY = "aether.syncContext.named.nameMapper"; - protected final Logger logger = LoggerFactory.getLogger( getClass() ); + protected final Logger logger = LoggerFactory.getLogger(getClass()); protected final Map factories; @@ -105,8 +101,7 @@ private static Map getManuallyCreatedNameMappers() * @deprecated for use in SL only. */ @Deprecated - public NamedLockFactoryAdapterFactoryImpl() - { + public NamedLockFactoryAdapterFactoryImpl() { this.factories = getManuallyCreatedFactories(); this.defaultFactoryName = DEFAULT_FACTORY_NAME; this.nameMappers = getManuallyCreatedNameMappers(); @@ -114,100 +109,92 @@ public NamedLockFactoryAdapterFactoryImpl() } @Override - public void initService( ServiceLocator locator ) - { - locator.getService( RepositorySystemLifecycle.class ).addOnSystemEndedHandler( this::shutdown ); + public void initService(ServiceLocator locator) { + locator.getService(RepositorySystemLifecycle.class).addOnSystemEndedHandler(this::shutdown); } @Inject - public NamedLockFactoryAdapterFactoryImpl( final Map factories, - final Map nameMappers, - final RepositorySystemLifecycle lifecycle ) - { - this( factories, DEFAULT_FACTORY_NAME, nameMappers, DEFAULT_NAME_MAPPER_NAME, lifecycle ); + public NamedLockFactoryAdapterFactoryImpl( + final Map factories, + final Map nameMappers, + final RepositorySystemLifecycle lifecycle) { + this(factories, DEFAULT_FACTORY_NAME, nameMappers, DEFAULT_NAME_MAPPER_NAME, lifecycle); } - public NamedLockFactoryAdapterFactoryImpl( final Map factories, - final String defaultFactoryName, - final Map nameMappers, - final String defaultNameMapperName, - final RepositorySystemLifecycle lifecycle ) - { - this.factories = requireNonNull( factories ); - this.defaultFactoryName = requireNonNull( defaultFactoryName ); - this.nameMappers = requireNonNull( nameMappers ); - this.defaultNameMapperName = requireNonNull( defaultNameMapperName ); - lifecycle.addOnSystemEndedHandler( this::shutdown ); - - logger.debug( "Created adapter factory; available factories {}; available name mappers {}", - factories.keySet(), nameMappers.keySet() ); + public NamedLockFactoryAdapterFactoryImpl( + final Map factories, + final String defaultFactoryName, + final Map nameMappers, + final String defaultNameMapperName, + final RepositorySystemLifecycle lifecycle) { + this.factories = requireNonNull(factories); + this.defaultFactoryName = requireNonNull(defaultFactoryName); + this.nameMappers = requireNonNull(nameMappers); + this.defaultNameMapperName = requireNonNull(defaultNameMapperName); + lifecycle.addOnSystemEndedHandler(this::shutdown); + + logger.debug( + "Created adapter factory; available factories {}; available name mappers {}", + factories.keySet(), + nameMappers.keySet()); } /** * Current implementation simply delegates to {@link #createAdapter(RepositorySystemSession)}. */ @Override - public NamedLockFactoryAdapter getAdapter( RepositorySystemSession session ) - { - return createAdapter( session ); + public NamedLockFactoryAdapter getAdapter(RepositorySystemSession session) { + return createAdapter(session); } /** * Creates a new adapter instance, never returns {@code null}. */ - protected NamedLockFactoryAdapter createAdapter( RepositorySystemSession session ) - { - final String nameMapperName = requireNonNull( getNameMapperName( session ) ); - final String factoryName = requireNonNull( getFactoryName( session ) ); - final NameMapper nameMapper = selectNameMapper( nameMapperName ); - final NamedLockFactory factory = selectFactory( factoryName ); - logger.debug( "Creating adapter using nameMapper '{}' and factory '{}'", - nameMapperName, factoryName ); - return new NamedLockFactoryAdapter( nameMapper, factory ); + protected NamedLockFactoryAdapter createAdapter(RepositorySystemSession session) { + final String nameMapperName = requireNonNull(getNameMapperName(session)); + final String factoryName = requireNonNull(getFactoryName(session)); + final NameMapper nameMapper = selectNameMapper(nameMapperName); + final NamedLockFactory factory = selectFactory(factoryName); + logger.debug("Creating adapter using nameMapper '{}' and factory '{}'", nameMapperName, factoryName); + return new NamedLockFactoryAdapter(nameMapper, factory); } /** * Returns the selected (user configured or default) named lock factory name, never {@code null}. */ - protected String getFactoryName( RepositorySystemSession session ) - { - return ConfigUtils.getString( session, getDefaultFactoryName(), FACTORY_KEY ); + protected String getFactoryName(RepositorySystemSession session) { + return ConfigUtils.getString(session, getDefaultFactoryName(), FACTORY_KEY); } /** * Returns the default named lock factory name, never {@code null}. */ - protected String getDefaultFactoryName() - { + protected String getDefaultFactoryName() { return defaultFactoryName; } /** * Returns the selected (user configured or default) name mapper name, never {@code null}. */ - protected String getNameMapperName( RepositorySystemSession session ) - { - return ConfigUtils.getString( session, getDefaultNameMapperName(), NAME_MAPPER_KEY ); + protected String getNameMapperName(RepositorySystemSession session) { + return ConfigUtils.getString(session, getDefaultNameMapperName(), NAME_MAPPER_KEY); } /** * Returns the default name mapper name, never {@code null}. */ - protected String getDefaultNameMapperName() - { + protected String getDefaultNameMapperName() { return defaultNameMapperName; } /** * Selects a named lock factory, never returns {@code null}. */ - protected NamedLockFactory selectFactory( final String factoryName ) - { - NamedLockFactory factory = factories.get( factoryName ); - if ( factory == null ) - { + protected NamedLockFactory selectFactory(final String factoryName) { + NamedLockFactory factory = factories.get(factoryName); + if (factory == null) { throw new IllegalArgumentException( - "Unknown NamedLockFactory name: '" + factoryName + "', known ones: " + factories.keySet() ); + "Unknown NamedLockFactory name: '" + factoryName + "', known ones: " + factories.keySet()); } return factory; } @@ -215,13 +202,11 @@ protected NamedLockFactory selectFactory( final String factoryName ) /** * Selects a name mapper, never returns {@code null}. */ - protected NameMapper selectNameMapper( final String nameMapperName ) - { - NameMapper nameMapper = nameMappers.get( nameMapperName ); - if ( nameMapper == null ) - { + protected NameMapper selectNameMapper(final String nameMapperName) { + NameMapper nameMapper = nameMappers.get(nameMapperName); + if (nameMapper == null) { throw new IllegalArgumentException( - "Unknown NameMapper name: '" + nameMapperName + "', known ones: " + nameMappers.keySet() ); + "Unknown NameMapper name: '" + nameMapperName + "', known ones: " + nameMappers.keySet()); } return nameMapper; } @@ -229,23 +214,20 @@ protected NameMapper selectNameMapper( final String nameMapperName ) /** * To be invoked on repository system shut down. This method will shut down each {@link NamedLockFactory}. */ - protected void shutdown() - { - logger.debug( "Shutting down adapter factory; available factories {}; available name mappers {}", - factories.keySet(), nameMappers.keySet() ); + protected void shutdown() { + logger.debug( + "Shutting down adapter factory; available factories {}; available name mappers {}", + factories.keySet(), + nameMappers.keySet()); ArrayList exceptions = new ArrayList<>(); - for ( Map.Entry entry : factories.entrySet() ) - { - try - { - logger.debug( "Shutting down '{}' factory", entry.getKey() ); + for (Map.Entry entry : factories.entrySet()) { + try { + logger.debug("Shutting down '{}' factory", entry.getKey()); entry.getValue().shutdown(); - } - catch ( Exception e ) - { - exceptions.add( e ); + } catch (Exception e) { + exceptions.add(e); } } - MultiRuntimeException.mayThrow( "Problem shutting down factories", exceptions ); + MultiRuntimeException.mayThrow("Problem shutting down factories", exceptions); } -} \ No newline at end of file +} diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/StaticNameMapper.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/StaticNameMapper.java index 4dcfaac4b..ab3427005 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/StaticNameMapper.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/StaticNameMapper.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; import java.util.Collection; import java.util.Collections; @@ -30,25 +29,20 @@ * Static {@link NameMapper}, always assigns one same name, effectively becoming equivalent to "static" sync context: * always maps ANY input to same name. */ -public class StaticNameMapper implements NameMapper -{ +public class StaticNameMapper implements NameMapper { @Override - public boolean isFileSystemFriendly() - { + public boolean isFileSystemFriendly() { return true; } @Override - public Collection nameLocks( final RepositorySystemSession session, - final Collection artifacts, - final Collection metadatas ) - { - if ( ( artifacts != null && !artifacts.isEmpty() ) || ( metadatas != null && !metadatas.isEmpty() ) ) - { - return Collections.singletonList( "static" ); - } - else - { + public Collection nameLocks( + final RepositorySystemSession session, + final Collection artifacts, + final Collection metadatas) { + if ((artifacts != null && !artifacts.isEmpty()) || (metadatas != null && !metadatas.isEmpty())) { + return Collections.singletonList("static"); + } else { return Collections.emptyList(); } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/DiscriminatingNameMapperProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/DiscriminatingNameMapperProvider.java index 0107f18a4..9bf2d57cc 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/DiscriminatingNameMapperProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/DiscriminatingNameMapperProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named.providers; import javax.inject.Named; import javax.inject.Provider; @@ -32,19 +31,16 @@ * @since 1.9.0 */ @Singleton -@Named( NameMappers.DISCRIMINATING_NAME ) -public class DiscriminatingNameMapperProvider implements Provider -{ +@Named(NameMappers.DISCRIMINATING_NAME) +public class DiscriminatingNameMapperProvider implements Provider { private final NameMapper mapper; - public DiscriminatingNameMapperProvider() - { + public DiscriminatingNameMapperProvider() { this.mapper = NameMappers.discriminatingNameMapper(); } @Override - public NameMapper get() - { + public NameMapper get() { return mapper; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/FileGAVNameMapperProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/FileGAVNameMapperProvider.java index 65c870181..f0b24d283 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/FileGAVNameMapperProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/FileGAVNameMapperProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named.providers; import javax.inject.Named; import javax.inject.Provider; @@ -32,19 +31,16 @@ * @since 1.9.0 */ @Singleton -@Named( NameMappers.FILE_GAV_NAME ) -public class FileGAVNameMapperProvider implements Provider -{ +@Named(NameMappers.FILE_GAV_NAME) +public class FileGAVNameMapperProvider implements Provider { private final NameMapper mapper; - public FileGAVNameMapperProvider() - { + public FileGAVNameMapperProvider() { this.mapper = NameMappers.fileGavNameMapper(); } @Override - public NameMapper get() - { + public NameMapper get() { return mapper; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/FileHashingGAVNameMapperProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/FileHashingGAVNameMapperProvider.java index 80463a3ee..a308fe4fd 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/FileHashingGAVNameMapperProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/FileHashingGAVNameMapperProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named.providers; import javax.inject.Named; import javax.inject.Provider; @@ -32,19 +31,16 @@ * @since 1.9.0 */ @Singleton -@Named( NameMappers.FILE_HGAV_NAME ) -public class FileHashingGAVNameMapperProvider implements Provider -{ +@Named(NameMappers.FILE_HGAV_NAME) +public class FileHashingGAVNameMapperProvider implements Provider { private final NameMapper mapper; - public FileHashingGAVNameMapperProvider() - { + public FileHashingGAVNameMapperProvider() { this.mapper = NameMappers.fileHashingGavNameMapper(); } @Override - public NameMapper get() - { + public NameMapper get() { return mapper; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/GAVNameMapperProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/GAVNameMapperProvider.java index a84f3b8fa..e39a7809a 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/GAVNameMapperProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/GAVNameMapperProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named.providers; import javax.inject.Named; import javax.inject.Provider; @@ -32,19 +31,16 @@ * @since 1.9.0 */ @Singleton -@Named( NameMappers.GAV_NAME ) -public class GAVNameMapperProvider implements Provider -{ +@Named(NameMappers.GAV_NAME) +public class GAVNameMapperProvider implements Provider { private final NameMapper mapper; - public GAVNameMapperProvider() - { + public GAVNameMapperProvider() { this.mapper = NameMappers.gavNameMapper(); } @Override - public NameMapper get() - { + public NameMapper get() { return mapper; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/StaticNameMapperProvider.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/StaticNameMapperProvider.java index e9348c4ef..fcef6ed22 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/StaticNameMapperProvider.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/StaticNameMapperProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named.providers; import javax.inject.Named; import javax.inject.Provider; @@ -32,19 +31,16 @@ * @since 1.9.0 */ @Singleton -@Named( NameMappers.STATIC_NAME ) -public class StaticNameMapperProvider implements Provider -{ +@Named(NameMappers.STATIC_NAME) +public class StaticNameMapperProvider implements Provider { private final NameMapper mapper; - public StaticNameMapperProvider() - { + public StaticNameMapperProvider() { this.mapper = NameMappers.staticNameMapper(); } @Override - public NameMapper get() - { + public NameMapper get() { return mapper; } } diff --git a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/package-info.java b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/package-info.java index a7b6dab5c..9000a50ef 100644 --- a/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/package-info.java +++ b/maven-resolver-impl/src/main/java/org/eclipse/aether/internal/impl/synccontext/named/providers/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -24,4 +24,3 @@ * when Guice/Sisu is used, as they assume {@link javax.inject.Provider} class to be present. */ package org.eclipse.aether.internal.impl.synccontext.named.providers; - diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/DefaultServiceLocatorTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/DefaultServiceLocatorTest.java index 72317d798..1d339649b 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/DefaultServiceLocatorTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/DefaultServiceLocatorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.impl; import java.util.Arrays; import java.util.List; @@ -29,71 +26,60 @@ import org.eclipse.aether.spi.locator.ServiceLocator; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DefaultServiceLocatorTest -{ +public class DefaultServiceLocatorTest { @Test - public void testGetRepositorySystem() - { + public void testGetRepositorySystem() { DefaultServiceLocator locator = new DefaultServiceLocator(); - locator.addService( ArtifactDescriptorReader.class, StubArtifactDescriptorReader.class ); - locator.addService( VersionResolver.class, StubVersionResolver.class ); - locator.addService( VersionRangeResolver.class, StubVersionRangeResolver.class ); + locator.addService(ArtifactDescriptorReader.class, StubArtifactDescriptorReader.class); + locator.addService(VersionResolver.class, StubVersionResolver.class); + locator.addService(VersionRangeResolver.class, StubVersionRangeResolver.class); - RepositorySystem repoSys = locator.getService( RepositorySystem.class ); - assertNotNull( repoSys ); + RepositorySystem repoSys = locator.getService(RepositorySystem.class); + assertNotNull(repoSys); } @Test - public void testGetServicesUnmodifiable() - { + public void testGetServicesUnmodifiable() { DefaultServiceLocator locator = new DefaultServiceLocator(); - locator.setServices( String.class, "one", "two" ); - List services = locator.getServices( String.class ); - assertNotNull( services ); - try - { - services.set( 0, "fail" ); - fail( "service list is modifable" ); - } - catch ( UnsupportedOperationException e ) - { + locator.setServices(String.class, "one", "two"); + List services = locator.getServices(String.class); + assertNotNull(services); + try { + services.set(0, "fail"); + fail("service list is modifable"); + } catch (UnsupportedOperationException e) { // expected } } @Test - public void testSetInstancesAddClass() - { + public void testSetInstancesAddClass() { DefaultServiceLocator locator = new DefaultServiceLocator(); - locator.setServices( String.class, "one", "two" ); - locator.addService( String.class, String.class ); - assertEquals( Arrays.asList( "one", "two", "" ), locator.getServices( String.class ) ); + locator.setServices(String.class, "one", "two"); + locator.addService(String.class, String.class); + assertEquals(Arrays.asList("one", "two", ""), locator.getServices(String.class)); } @Test - public void testInitService() - { + public void testInitService() { DefaultServiceLocator locator = new DefaultServiceLocator(); - locator.setService( DummyService.class, DummyService.class ); - DummyService service = locator.getService( DummyService.class ); - assertNotNull( service ); - assertNotNull( service.locator ); + locator.setService(DummyService.class, DummyService.class); + DummyService service = locator.getService(DummyService.class); + assertNotNull(service); + assertNotNull(service.locator); } - private static class DummyService - implements Service - { + private static class DummyService implements Service { public ServiceLocator locator; - public void initService( ServiceLocator locator ) - { + public void initService(ServiceLocator locator) { this.locator = locator; } - } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubArtifactDescriptorReader.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubArtifactDescriptorReader.java index 2882dc2c1..339d41481 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubArtifactDescriptorReader.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubArtifactDescriptorReader.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,21 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.resolution.ArtifactDescriptorException; import org.eclipse.aether.resolution.ArtifactDescriptorRequest; import org.eclipse.aether.resolution.ArtifactDescriptorResult; -public class StubArtifactDescriptorReader - implements ArtifactDescriptorReader -{ +public class StubArtifactDescriptorReader implements ArtifactDescriptorReader { - public ArtifactDescriptorResult readArtifactDescriptor( RepositorySystemSession session, - ArtifactDescriptorRequest request ) - throws ArtifactDescriptorException - { - return new ArtifactDescriptorResult( request ); + public ArtifactDescriptorResult readArtifactDescriptor( + RepositorySystemSession session, ArtifactDescriptorRequest request) throws ArtifactDescriptorException { + return new ArtifactDescriptorResult(request); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubVersionRangeResolver.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubVersionRangeResolver.java index d3ba16440..61eba4de5 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubVersionRangeResolver.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubVersionRangeResolver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.resolution.VersionRangeRequest; @@ -25,15 +24,11 @@ import static java.util.Objects.requireNonNull; -public class StubVersionRangeResolver - implements VersionRangeResolver -{ +public class StubVersionRangeResolver implements VersionRangeResolver { - public VersionRangeResult resolveVersionRange( RepositorySystemSession session, VersionRangeRequest request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); - return new VersionRangeResult( request ); + public VersionRangeResult resolveVersionRange(RepositorySystemSession session, VersionRangeRequest request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); + return new VersionRangeResult(request); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubVersionResolver.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubVersionResolver.java index f760f4c72..63329d51f 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubVersionResolver.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/StubVersionResolver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.resolution.VersionRequest; @@ -26,16 +25,12 @@ import static java.util.Objects.requireNonNull; -public class StubVersionResolver - implements VersionResolver -{ +public class StubVersionResolver implements VersionResolver { - public VersionResult resolveVersion( RepositorySystemSession session, VersionRequest request ) - throws VersionResolutionException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); - return new VersionResult( request ); + public VersionResult resolveVersion(RepositorySystemSession session, VersionRequest request) + throws VersionResolutionException { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); + return new VersionResult(request); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/guice/AetherModuleTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/guice/AetherModuleTest.java index efcda199f..74649dc13 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/guice/AetherModuleTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/impl/guice/AetherModuleTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.impl.guice; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,12 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.impl.guice; import java.util.Collections; import java.util.Set; +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Provides; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.impl.ArtifactDescriptorReader; import org.eclipse.aether.impl.MetadataGeneratorFactory; @@ -36,50 +36,38 @@ import org.eclipse.aether.spi.connector.transport.TransporterFactory; import org.junit.Test; -import com.google.inject.AbstractModule; -import com.google.inject.Guice; -import com.google.inject.Provides; +import static org.junit.Assert.*; -public class AetherModuleTest -{ +public class AetherModuleTest { @Test - public void testModuleCompleteness() - { - assertNotNull( Guice.createInjector( new SystemModule() ).getInstance( RepositorySystem.class ) ); + public void testModuleCompleteness() { + assertNotNull(Guice.createInjector(new SystemModule()).getInstance(RepositorySystem.class)); } - static class SystemModule - extends AbstractModule - { + static class SystemModule extends AbstractModule { @Override - protected void configure() - { - install( new AetherModule() ); - bind( ArtifactDescriptorReader.class ).to( StubArtifactDescriptorReader.class ); - bind( VersionRangeResolver.class ).to( StubVersionRangeResolver.class ); - bind( VersionResolver.class ).to( StubVersionResolver.class ); + protected void configure() { + install(new AetherModule()); + bind(ArtifactDescriptorReader.class).to(StubArtifactDescriptorReader.class); + bind(VersionRangeResolver.class).to(StubVersionRangeResolver.class); + bind(VersionResolver.class).to(StubVersionResolver.class); } @Provides - public Set metadataGeneratorFactories() - { + public Set metadataGeneratorFactories() { return Collections.emptySet(); } @Provides - public Set repositoryConnectorFactories() - { + public Set repositoryConnectorFactories() { return Collections.emptySet(); } @Provides - public Set transporterFactories() - { + public Set transporterFactories() { return Collections.emptySet(); } - } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultArtifactResolverTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultArtifactResolverTest.java index e6665a654..f286f13ad 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultArtifactResolverTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultArtifactResolverTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.io.File; import java.io.IOException; @@ -32,8 +29,8 @@ import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositoryEvent; -import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.RepositoryEvent.EventType; +import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.ArtifactProperties; import org.eclipse.aether.artifact.DefaultArtifact; @@ -74,10 +71,11 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DefaultArtifactResolverTest -{ +public class DefaultArtifactResolverTest { private DefaultArtifactResolver resolver; private DefaultRepositorySystemSession session; @@ -95,936 +93,791 @@ public class DefaultArtifactResolverTest private DefaultRemoteRepositoryFilterManager remoteRepositoryFilterManager; @Before - public void setup() - { + public void setup() { remoteRepositoryFilterSources = new HashMap<>(); - remoteRepositoryFilterManager = new DefaultRemoteRepositoryFilterManager( remoteRepositoryFilterSources ); + remoteRepositoryFilterManager = new DefaultRemoteRepositoryFilterManager(remoteRepositoryFilterSources); - UpdateCheckManager updateCheckManager = new StaticUpdateCheckManager( true ); + UpdateCheckManager updateCheckManager = new StaticUpdateCheckManager(true); repositoryConnectorProvider = new StubRepositoryConnectorProvider(); VersionResolver versionResolver = new StubVersionResolver(); session = TestUtils.newSession(); lrm = (TestLocalRepositoryManager) session.getLocalRepositoryManager(); resolver = new DefaultArtifactResolver(); - resolver.setFileProcessor( new TestFileProcessor() ); - resolver.setRepositoryEventDispatcher( new StubRepositoryEventDispatcher() ); - resolver.setVersionResolver( versionResolver ); - resolver.setUpdateCheckManager( updateCheckManager ); - resolver.setRepositoryConnectorProvider( repositoryConnectorProvider ); - resolver.setRemoteRepositoryManager( new StubRemoteRepositoryManager() ); - resolver.setSyncContextFactory( new StubSyncContextFactory() ); - resolver.setOfflineController( new DefaultOfflineController() ); - resolver.setArtifactResolverPostProcessors( Collections.emptyMap() ); - resolver.setRemoteRepositoryFilterManager( remoteRepositoryFilterManager ); - - artifact = new DefaultArtifact( "gid", "aid", "", "ext", "ver" ); + resolver.setFileProcessor(new TestFileProcessor()); + resolver.setRepositoryEventDispatcher(new StubRepositoryEventDispatcher()); + resolver.setVersionResolver(versionResolver); + resolver.setUpdateCheckManager(updateCheckManager); + resolver.setRepositoryConnectorProvider(repositoryConnectorProvider); + resolver.setRemoteRepositoryManager(new StubRemoteRepositoryManager()); + resolver.setSyncContextFactory(new StubSyncContextFactory()); + resolver.setOfflineController(new DefaultOfflineController()); + resolver.setArtifactResolverPostProcessors(Collections.emptyMap()); + resolver.setRemoteRepositoryFilterManager(remoteRepositoryFilterManager); + + artifact = new DefaultArtifact("gid", "aid", "", "ext", "ver"); connector = new RecordingRepositoryConnector(); - repositoryConnectorProvider.setConnector( connector ); + repositoryConnectorProvider.setConnector(connector); } @After - public void teardown() - throws Exception - { - if ( session.getLocalRepository() != null ) - { - TestFileUtils.deleteFile( session.getLocalRepository().getBasedir() ); + public void teardown() throws Exception { + if (session.getLocalRepository() != null) { + TestFileUtils.deleteFile(session.getLocalRepository().getBasedir()); } } @Test - public void testResolveLocalArtifactSuccessful() - throws IOException, ArtifactResolutionException - { - File tmpFile = TestFileUtils.createTempFile( "tmp" ); + public void testResolveLocalArtifactSuccessful() throws IOException, ArtifactResolutionException { + File tmpFile = TestFileUtils.createTempFile("tmp"); Map properties = new HashMap<>(); - properties.put( ArtifactProperties.LOCAL_PATH, tmpFile.getAbsolutePath() ); - artifact = artifact.setProperties( properties ); + properties.put(ArtifactProperties.LOCAL_PATH, tmpFile.getAbsolutePath()); + artifact = artifact.setProperties(properties); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - ArtifactResult result = resolver.resolveArtifact( session, request ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + ArtifactResult result = resolver.resolveArtifact(session, request); - assertTrue( result.getExceptions().isEmpty() ); + assertTrue(result.getExceptions().isEmpty()); Artifact resolved = result.getArtifact(); - assertNotNull( resolved.getFile() ); - resolved = resolved.setFile( null ); + assertNotNull(resolved.getFile()); + resolved = resolved.setFile(null); - assertEquals( artifact, resolved ); + assertEquals(artifact, resolved); } @Test - public void testResolveLocalArtifactUnsuccessful() - throws IOException - { - File tmpFile = TestFileUtils.createTempFile( "tmp" ); + public void testResolveLocalArtifactUnsuccessful() throws IOException { + File tmpFile = TestFileUtils.createTempFile("tmp"); Map properties = new HashMap<>(); - properties.put( ArtifactProperties.LOCAL_PATH, tmpFile.getAbsolutePath() ); - artifact = artifact.setProperties( properties ); + properties.put(ArtifactProperties.LOCAL_PATH, tmpFile.getAbsolutePath()); + artifact = artifact.setProperties(properties); tmpFile.delete(); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); - try - { - resolver.resolveArtifact( session, request ); - fail( "expected exception" ); - } - catch ( ArtifactResolutionException e ) - { - assertNotNull( e.getResults() ); - assertEquals( 1, e.getResults().size() ); + try { + resolver.resolveArtifact(session, request); + fail("expected exception"); + } catch (ArtifactResolutionException e) { + assertNotNull(e.getResults()); + assertEquals(1, e.getResults().size()); - ArtifactResult result = e.getResults().get( 0 ); + ArtifactResult result = e.getResults().get(0); - assertSame( request, result.getRequest() ); + assertSame(request, result.getRequest()); - assertFalse( result.getExceptions().isEmpty() ); - assertTrue( result.getExceptions().get( 0 ) instanceof ArtifactNotFoundException ); + assertFalse(result.getExceptions().isEmpty()); + assertTrue(result.getExceptions().get(0) instanceof ArtifactNotFoundException); Artifact resolved = result.getArtifact(); - assertNull( resolved ); + assertNull(resolved); } - } @Test - public void testResolveRemoteArtifact() - throws ArtifactResolutionException - { - connector.setExpectGet( artifact ); + public void testResolveRemoteArtifact() throws ArtifactResolutionException { + connector.setExpectGet(artifact); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); - ArtifactResult result = resolver.resolveArtifact( session, request ); + ArtifactResult result = resolver.resolveArtifact(session, request); - assertTrue( result.getExceptions().isEmpty() ); + assertTrue(result.getExceptions().isEmpty()); Artifact resolved = result.getArtifact(); - assertNotNull( resolved.getFile() ); + assertNotNull(resolved.getFile()); - resolved = resolved.setFile( null ); - assertEquals( artifact, resolved ); + resolved = resolved.setFile(null); + assertEquals(artifact, resolved); connector.assertSeenExpected(); } @Test - public void testResolveRemoteArtifactUnsuccessful() - { - RecordingRepositoryConnector connector = new RecordingRepositoryConnector() - { + public void testResolveRemoteArtifactUnsuccessful() { + RecordingRepositoryConnector connector = new RecordingRepositoryConnector() { @Override - public void get( Collection artifactDownloads, - Collection metadataDownloads ) - { - super.get( artifactDownloads, metadataDownloads ); + public void get( + Collection artifactDownloads, + Collection metadataDownloads) { + super.get(artifactDownloads, metadataDownloads); ArtifactDownload download = artifactDownloads.iterator().next(); ArtifactTransferException exception = - new ArtifactNotFoundException( download.getArtifact(), null, "not found" ); - download.setException( exception ); + new ArtifactNotFoundException(download.getArtifact(), null, "not found"); + download.setException(exception); } - }; - connector.setExpectGet( artifact ); - repositoryConnectorProvider.setConnector( connector ); + connector.setExpectGet(artifact); + repositoryConnectorProvider.setConnector(connector); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); - try - { - resolver.resolveArtifact( session, request ); - fail( "expected exception" ); - } - catch ( ArtifactResolutionException e ) - { + try { + resolver.resolveArtifact(session, request); + fail("expected exception"); + } catch (ArtifactResolutionException e) { connector.assertSeenExpected(); - assertNotNull( e.getResults() ); - assertEquals( 1, e.getResults().size() ); + assertNotNull(e.getResults()); + assertEquals(1, e.getResults().size()); - ArtifactResult result = e.getResults().get( 0 ); + ArtifactResult result = e.getResults().get(0); - assertSame( request, result.getRequest() ); + assertSame(request, result.getRequest()); - assertFalse( result.getExceptions().isEmpty() ); - assertTrue( result.getExceptions().get( 0 ) instanceof ArtifactNotFoundException ); + assertFalse(result.getExceptions().isEmpty()); + assertTrue(result.getExceptions().get(0) instanceof ArtifactNotFoundException); Artifact resolved = result.getArtifact(); - assertNull( resolved ); + assertNull(resolved); } - } @Test - public void testResolveRemoteArtifactAlwaysAcceptFilter() - throws ArtifactResolutionException - { - remoteRepositoryFilterSources.put( "filter1", Filters.neverAcceptFrom("invalid repo id") ); - remoteRepositoryFilterSources.put( "filter2", Filters.alwaysAccept() ); - connector.setExpectGet( artifact ); + public void testResolveRemoteArtifactAlwaysAcceptFilter() throws ArtifactResolutionException { + remoteRepositoryFilterSources.put("filter1", Filters.neverAcceptFrom("invalid repo id")); + remoteRepositoryFilterSources.put("filter2", Filters.alwaysAccept()); + connector.setExpectGet(artifact); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); - ArtifactResult result = resolver.resolveArtifact( session, request ); + ArtifactResult result = resolver.resolveArtifact(session, request); - assertTrue( result.getExceptions().isEmpty() ); + assertTrue(result.getExceptions().isEmpty()); Artifact resolved = result.getArtifact(); - assertNotNull( resolved.getFile() ); + assertNotNull(resolved.getFile()); - resolved = resolved.setFile( null ); - assertEquals( artifact, resolved ); + resolved = resolved.setFile(null); + assertEquals(artifact, resolved); connector.assertSeenExpected(); } @Test - public void testResolveRemoteArtifactNeverAcceptFilter() - { - remoteRepositoryFilterSources.put( "filter1", Filters.neverAcceptFrom("invalid repo id") ); - remoteRepositoryFilterSources.put( "filter2", Filters.neverAccept() ); - //connector.setExpectGet( artifact ); // should not see it - - ArtifactRequest request = new ArtifactRequest( artifact, null, "project" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); - - try - { - resolver.resolveArtifact( session, request ); - fail( "expected exception" ); - } - catch ( ArtifactResolutionException e ) - { + public void testResolveRemoteArtifactNeverAcceptFilter() { + remoteRepositoryFilterSources.put("filter1", Filters.neverAcceptFrom("invalid repo id")); + remoteRepositoryFilterSources.put("filter2", Filters.neverAccept()); + // connector.setExpectGet( artifact ); // should not see it + + ArtifactRequest request = new ArtifactRequest(artifact, null, "project"); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); + + try { + resolver.resolveArtifact(session, request); + fail("expected exception"); + } catch (ArtifactResolutionException e) { connector.assertSeenExpected(); - assertNotNull( e.getResults() ); - assertEquals( 1, e.getResults().size() ); + assertNotNull(e.getResults()); + assertEquals(1, e.getResults().size()); - ArtifactResult result = e.getResults().get( 0 ); + ArtifactResult result = e.getResults().get(0); - assertSame( request, result.getRequest() ); + assertSame(request, result.getRequest()); - assertFalse( result.getExceptions().isEmpty() ); - assertTrue( result.getExceptions().get( 0 ) instanceof ArtifactNotFoundException ); - assertEquals( "never-accept", result.getExceptions().get( 0 ).getMessage() ); + assertFalse(result.getExceptions().isEmpty()); + assertTrue(result.getExceptions().get(0) instanceof ArtifactNotFoundException); + assertEquals("never-accept", result.getExceptions().get(0).getMessage()); Artifact resolved = result.getArtifact(); - assertNull( resolved ); + assertNull(resolved); } } - @Test - public void testResolveRemoteArtifactAlwaysAcceptFromRepoFilter() - throws ArtifactResolutionException - { - remoteRepositoryFilterSources.put( "filter1", Filters.alwaysAcceptFrom( "id" ) ); - connector.setExpectGet( artifact ); + public void testResolveRemoteArtifactAlwaysAcceptFromRepoFilter() throws ArtifactResolutionException { + remoteRepositoryFilterSources.put("filter1", Filters.alwaysAcceptFrom("id")); + connector.setExpectGet(artifact); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); - ArtifactResult result = resolver.resolveArtifact( session, request ); + ArtifactResult result = resolver.resolveArtifact(session, request); - assertTrue( result.getExceptions().isEmpty() ); + assertTrue(result.getExceptions().isEmpty()); Artifact resolved = result.getArtifact(); - assertNotNull( resolved.getFile() ); + assertNotNull(resolved.getFile()); - resolved = resolved.setFile( null ); - assertEquals( artifact, resolved ); + resolved = resolved.setFile(null); + assertEquals(artifact, resolved); connector.assertSeenExpected(); } @Test - public void testResolveRemoteArtifactNeverAcceptFilterFromRepo() - { - remoteRepositoryFilterSources.put( "filter1", Filters.neverAcceptFrom( "id" ) ); - //connector.setExpectGet( artifact ); // should not see it - - ArtifactRequest request = new ArtifactRequest( artifact, null, "project" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); - - try - { - resolver.resolveArtifact( session, request ); - fail( "expected exception" ); - } - catch ( ArtifactResolutionException e ) - { + public void testResolveRemoteArtifactNeverAcceptFilterFromRepo() { + remoteRepositoryFilterSources.put("filter1", Filters.neverAcceptFrom("id")); + // connector.setExpectGet( artifact ); // should not see it + + ArtifactRequest request = new ArtifactRequest(artifact, null, "project"); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); + + try { + resolver.resolveArtifact(session, request); + fail("expected exception"); + } catch (ArtifactResolutionException e) { connector.assertSeenExpected(); - assertNotNull( e.getResults() ); - assertEquals( 1, e.getResults().size() ); + assertNotNull(e.getResults()); + assertEquals(1, e.getResults().size()); - ArtifactResult result = e.getResults().get( 0 ); + ArtifactResult result = e.getResults().get(0); - assertSame( request, result.getRequest() ); + assertSame(request, result.getRequest()); - assertFalse( result.getExceptions().isEmpty() ); - assertTrue( result.getExceptions().get( 0 ) instanceof ArtifactNotFoundException ); - assertEquals( "never-accept-id", result.getExceptions().get( 0 ).getMessage() ); + assertFalse(result.getExceptions().isEmpty()); + assertTrue(result.getExceptions().get(0) instanceof ArtifactNotFoundException); + assertEquals("never-accept-id", result.getExceptions().get(0).getMessage()); Artifact resolved = result.getArtifact(); - assertNull( resolved ); + assertNull(resolved); } } @Test - public void testArtifactNotFoundCache() - throws Exception - { - RecordingRepositoryConnector connector = new RecordingRepositoryConnector() - { + public void testArtifactNotFoundCache() throws Exception { + RecordingRepositoryConnector connector = new RecordingRepositoryConnector() { @Override - public void get( Collection artifactDownloads, - Collection metadataDownloads ) - { - super.get( artifactDownloads, metadataDownloads ); - for ( ArtifactDownload download : artifactDownloads ) - { + public void get( + Collection artifactDownloads, + Collection metadataDownloads) { + super.get(artifactDownloads, metadataDownloads); + for (ArtifactDownload download : artifactDownloads) { download.getFile().delete(); ArtifactTransferException exception = - new ArtifactNotFoundException( download.getArtifact(), null, "not found" ); - download.setException( exception ); + new ArtifactNotFoundException(download.getArtifact(), null, "not found"); + download.setException(exception); } } }; - repositoryConnectorProvider.setConnector( connector ); - resolver.setUpdateCheckManager( new DefaultUpdateCheckManager() - .setUpdatePolicyAnalyzer( new DefaultUpdatePolicyAnalyzer() ) - .setTrackingFileManager( new DefaultTrackingFileManager() ) - ); + repositoryConnectorProvider.setConnector(connector); + resolver.setUpdateCheckManager(new DefaultUpdateCheckManager() + .setUpdatePolicyAnalyzer(new DefaultUpdatePolicyAnalyzer()) + .setTrackingFileManager(new DefaultTrackingFileManager())); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( true, false ) ); - session.setUpdatePolicy( RepositoryPolicy.UPDATE_POLICY_NEVER ); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(true, false)); + session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_NEVER); - RemoteRepository remoteRepo = new RemoteRepository.Builder( "id", "default", "file:///" ).build(); + RemoteRepository remoteRepo = new RemoteRepository.Builder("id", "default", "file:///").build(); Artifact artifact1 = artifact; - Artifact artifact2 = artifact.setVersion( "ver2" ); + Artifact artifact2 = artifact.setVersion("ver2"); - ArtifactRequest request1 = new ArtifactRequest( artifact1, Arrays.asList( remoteRepo ), "" ); - ArtifactRequest request2 = new ArtifactRequest( artifact2, Arrays.asList( remoteRepo ), "" ); + ArtifactRequest request1 = new ArtifactRequest(artifact1, Arrays.asList(remoteRepo), ""); + ArtifactRequest request2 = new ArtifactRequest(artifact2, Arrays.asList(remoteRepo), ""); - connector.setExpectGet( artifact1, artifact2 ); - try - { - resolver.resolveArtifacts( session, Arrays.asList( request1, request2 ) ); - fail( "expected exception" ); - } - catch ( ArtifactResolutionException e ) - { + connector.setExpectGet(artifact1, artifact2); + try { + resolver.resolveArtifacts(session, Arrays.asList(request1, request2)); + fail("expected exception"); + } catch (ArtifactResolutionException e) { connector.assertSeenExpected(); } - TestFileUtils.writeString( new File( lrm.getRepository().getBasedir(), lrm.getPathForLocalArtifact( artifact2 ) ), - "artifact" ); - lrm.setArtifactAvailability( artifact2, false ); + TestFileUtils.writeString( + new File(lrm.getRepository().getBasedir(), lrm.getPathForLocalArtifact(artifact2)), "artifact"); + lrm.setArtifactAvailability(artifact2, false); - DefaultUpdateCheckManagerTest.resetSessionData( session ); + DefaultUpdateCheckManagerTest.resetSessionData(session); connector.resetActual(); - connector.setExpectGet( new Artifact[0] ); - try - { - resolver.resolveArtifacts( session, Arrays.asList( request1, request2 ) ); - fail( "expected exception" ); - } - catch ( ArtifactResolutionException e ) - { + connector.setExpectGet(new Artifact[0]); + try { + resolver.resolveArtifacts(session, Arrays.asList(request1, request2)); + fail("expected exception"); + } catch (ArtifactResolutionException e) { connector.assertSeenExpected(); - for ( ArtifactResult result : e.getResults() ) - { - Throwable t = result.getExceptions().get( 0 ); - assertTrue( t.toString(), t instanceof ArtifactNotFoundException ); - assertTrue( t.toString(), t.getMessage().contains( "cached" ) ); + for (ArtifactResult result : e.getResults()) { + Throwable t = result.getExceptions().get(0); + assertTrue(t.toString(), t instanceof ArtifactNotFoundException); + assertTrue(t.toString(), t.getMessage().contains("cached")); } } } @Test - public void testResolveFromWorkspace() - throws IOException, ArtifactResolutionException - { - WorkspaceReader workspace = new WorkspaceReader() - { - - public WorkspaceRepository getRepository() - { - return new WorkspaceRepository( "default" ); + public void testResolveFromWorkspace() throws IOException, ArtifactResolutionException { + WorkspaceReader workspace = new WorkspaceReader() { + + public WorkspaceRepository getRepository() { + return new WorkspaceRepository("default"); } - public List findVersions( Artifact artifact ) - { - return Arrays.asList( artifact.getVersion() ); + public List findVersions(Artifact artifact) { + return Arrays.asList(artifact.getVersion()); } - public File findArtifact( Artifact artifact ) - { - try - { - return TestFileUtils.createTempFile( artifact.toString() ); - } - catch ( IOException e ) - { - throw new RuntimeException( e.getMessage(), e ); + public File findArtifact(Artifact artifact) { + try { + return TestFileUtils.createTempFile(artifact.toString()); + } catch (IOException e) { + throw new RuntimeException(e.getMessage(), e); } } }; - session.setWorkspaceReader( workspace ); + session.setWorkspaceReader(workspace); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); - ArtifactResult result = resolver.resolveArtifact( session, request ); + ArtifactResult result = resolver.resolveArtifact(session, request); - assertTrue( result.getExceptions().isEmpty() ); + assertTrue(result.getExceptions().isEmpty()); Artifact resolved = result.getArtifact(); - assertNotNull( resolved.getFile() ); + assertNotNull(resolved.getFile()); - assertEquals( resolved.toString(), TestFileUtils.readString( resolved.getFile() ) ); + assertEquals(resolved.toString(), TestFileUtils.readString(resolved.getFile())); - resolved = resolved.setFile( null ); - assertEquals( artifact, resolved ); + resolved = resolved.setFile(null); + assertEquals(artifact, resolved); connector.assertSeenExpected(); } @Test - public void testResolveFromWorkspaceFallbackToRepository() - throws ArtifactResolutionException - { - WorkspaceReader workspace = new WorkspaceReader() - { - - public WorkspaceRepository getRepository() - { - return new WorkspaceRepository( "default" ); + public void testResolveFromWorkspaceFallbackToRepository() throws ArtifactResolutionException { + WorkspaceReader workspace = new WorkspaceReader() { + + public WorkspaceRepository getRepository() { + return new WorkspaceRepository("default"); } - public List findVersions( Artifact artifact ) - { - return Arrays.asList( artifact.getVersion() ); + public List findVersions(Artifact artifact) { + return Arrays.asList(artifact.getVersion()); } - public File findArtifact( Artifact artifact ) - { + public File findArtifact(Artifact artifact) { return null; } }; - session.setWorkspaceReader( workspace ); + session.setWorkspaceReader(workspace); - connector.setExpectGet( artifact ); - repositoryConnectorProvider.setConnector( connector ); + connector.setExpectGet(artifact); + repositoryConnectorProvider.setConnector(connector); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); - ArtifactResult result = resolver.resolveArtifact( session, request ); + ArtifactResult result = resolver.resolveArtifact(session, request); - assertTrue( "exception on resolveArtifact", result.getExceptions().isEmpty() ); + assertTrue("exception on resolveArtifact", result.getExceptions().isEmpty()); Artifact resolved = result.getArtifact(); - assertNotNull( resolved.getFile() ); + assertNotNull(resolved.getFile()); - resolved = resolved.setFile( null ); - assertEquals( artifact, resolved ); + resolved = resolved.setFile(null); + assertEquals(artifact, resolved); connector.assertSeenExpected(); } @Test - public void testRepositoryEventsSuccessfulLocal() - throws ArtifactResolutionException, IOException - { + public void testRepositoryEventsSuccessfulLocal() throws ArtifactResolutionException, IOException { RecordingRepositoryListener listener = new RecordingRepositoryListener(); - session.setRepositoryListener( listener ); + session.setRepositoryListener(listener); - File tmpFile = TestFileUtils.createTempFile( "tmp" ); + File tmpFile = TestFileUtils.createTempFile("tmp"); Map properties = new HashMap<>(); - properties.put( ArtifactProperties.LOCAL_PATH, tmpFile.getAbsolutePath() ); - artifact = artifact.setProperties( properties ); + properties.put(ArtifactProperties.LOCAL_PATH, tmpFile.getAbsolutePath()); + artifact = artifact.setProperties(properties); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - resolver.resolveArtifact( session, request ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + resolver.resolveArtifact(session, request); List events = listener.getEvents(); - assertEquals( 2, events.size() ); - RepositoryEvent event = events.get( 0 ); - assertEquals( EventType.ARTIFACT_RESOLVING, event.getType() ); - assertNull( event.getException() ); - assertEquals( artifact, event.getArtifact() ); - - event = events.get( 1 ); - assertEquals( EventType.ARTIFACT_RESOLVED, event.getType() ); - assertNull( event.getException() ); - assertEquals( artifact, event.getArtifact().setFile( null ) ); + assertEquals(2, events.size()); + RepositoryEvent event = events.get(0); + assertEquals(EventType.ARTIFACT_RESOLVING, event.getType()); + assertNull(event.getException()); + assertEquals(artifact, event.getArtifact()); + + event = events.get(1); + assertEquals(EventType.ARTIFACT_RESOLVED, event.getType()); + assertNull(event.getException()); + assertEquals(artifact, event.getArtifact().setFile(null)); } @Test - public void testRepositoryEventsUnsuccessfulLocal() - { + public void testRepositoryEventsUnsuccessfulLocal() { RecordingRepositoryListener listener = new RecordingRepositoryListener(); - session.setRepositoryListener( listener ); + session.setRepositoryListener(listener); Map properties = new HashMap<>(); - properties.put( ArtifactProperties.LOCAL_PATH, "doesnotexist" ); - artifact = artifact.setProperties( properties ); - - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - try - { - resolver.resolveArtifact( session, request ); - fail( "expected exception" ); - } - catch ( ArtifactResolutionException ignored ) - { + properties.put(ArtifactProperties.LOCAL_PATH, "doesnotexist"); + artifact = artifact.setProperties(properties); + + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + try { + resolver.resolveArtifact(session, request); + fail("expected exception"); + } catch (ArtifactResolutionException ignored) { } List events = listener.getEvents(); - assertEquals( 2, events.size() ); - - RepositoryEvent event = events.get( 0 ); - assertEquals( artifact, event.getArtifact() ); - assertEquals( EventType.ARTIFACT_RESOLVING, event.getType() ); + assertEquals(2, events.size()); - event = events.get( 1 ); - assertEquals( artifact, event.getArtifact() ); - assertEquals( EventType.ARTIFACT_RESOLVED, event.getType() ); - assertNotNull( event.getException() ); - assertEquals( 1, event.getExceptions().size() ); + RepositoryEvent event = events.get(0); + assertEquals(artifact, event.getArtifact()); + assertEquals(EventType.ARTIFACT_RESOLVING, event.getType()); + event = events.get(1); + assertEquals(artifact, event.getArtifact()); + assertEquals(EventType.ARTIFACT_RESOLVED, event.getType()); + assertNotNull(event.getException()); + assertEquals(1, event.getExceptions().size()); } @Test - public void testRepositoryEventsSuccessfulRemote() - throws ArtifactResolutionException - { + public void testRepositoryEventsSuccessfulRemote() throws ArtifactResolutionException { RecordingRepositoryListener listener = new RecordingRepositoryListener(); - session.setRepositoryListener( listener ); + session.setRepositoryListener(listener); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); - resolver.resolveArtifact( session, request ); + resolver.resolveArtifact(session, request); List events = listener.getEvents(); - assertEquals( events.toString(), 4, events.size() ); - RepositoryEvent event = events.get( 0 ); - assertEquals( EventType.ARTIFACT_RESOLVING, event.getType() ); - assertNull( event.getException() ); - assertEquals( artifact, event.getArtifact() ); - - event = events.get( 1 ); - assertEquals( EventType.ARTIFACT_DOWNLOADING, event.getType() ); - assertNull( event.getException() ); - assertEquals( artifact, event.getArtifact().setFile( null ) ); - - event = events.get( 2 ); - assertEquals( EventType.ARTIFACT_DOWNLOADED, event.getType() ); - assertNull( event.getException() ); - assertEquals( artifact, event.getArtifact().setFile( null ) ); - - event = events.get( 3 ); - assertEquals( EventType.ARTIFACT_RESOLVED, event.getType() ); - assertNull( event.getException() ); - assertEquals( artifact, event.getArtifact().setFile( null ) ); + assertEquals(events.toString(), 4, events.size()); + RepositoryEvent event = events.get(0); + assertEquals(EventType.ARTIFACT_RESOLVING, event.getType()); + assertNull(event.getException()); + assertEquals(artifact, event.getArtifact()); + + event = events.get(1); + assertEquals(EventType.ARTIFACT_DOWNLOADING, event.getType()); + assertNull(event.getException()); + assertEquals(artifact, event.getArtifact().setFile(null)); + + event = events.get(2); + assertEquals(EventType.ARTIFACT_DOWNLOADED, event.getType()); + assertNull(event.getException()); + assertEquals(artifact, event.getArtifact().setFile(null)); + + event = events.get(3); + assertEquals(EventType.ARTIFACT_RESOLVED, event.getType()); + assertNull(event.getException()); + assertEquals(artifact, event.getArtifact().setFile(null)); } @Test - public void testRepositoryEventsUnsuccessfulRemote() - { - RecordingRepositoryConnector connector = new RecordingRepositoryConnector() - { + public void testRepositoryEventsUnsuccessfulRemote() { + RecordingRepositoryConnector connector = new RecordingRepositoryConnector() { @Override - public void get( Collection artifactDownloads, - Collection metadataDownloads ) - { - super.get( artifactDownloads, metadataDownloads ); + public void get( + Collection artifactDownloads, + Collection metadataDownloads) { + super.get(artifactDownloads, metadataDownloads); ArtifactDownload download = artifactDownloads.iterator().next(); ArtifactTransferException exception = - new ArtifactNotFoundException( download.getArtifact(), null, "not found" ); - download.setException( exception ); + new ArtifactNotFoundException(download.getArtifact(), null, "not found"); + download.setException(exception); } - }; - repositoryConnectorProvider.setConnector( connector ); + repositoryConnectorProvider.setConnector(connector); RecordingRepositoryListener listener = new RecordingRepositoryListener(); - session.setRepositoryListener( listener ); + session.setRepositoryListener(listener); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); - try - { - resolver.resolveArtifact( session, request ); - fail( "expected exception" ); - } - catch ( ArtifactResolutionException ignored ) - { + try { + resolver.resolveArtifact(session, request); + fail("expected exception"); + } catch (ArtifactResolutionException ignored) { } List events = listener.getEvents(); - assertEquals( events.toString(), 4, events.size() ); - - RepositoryEvent event = events.get( 0 ); - assertEquals( artifact, event.getArtifact() ); - assertEquals( EventType.ARTIFACT_RESOLVING, event.getType() ); - - event = events.get( 1 ); - assertEquals( artifact, event.getArtifact() ); - assertEquals( EventType.ARTIFACT_DOWNLOADING, event.getType() ); - - event = events.get( 2 ); - assertEquals( artifact, event.getArtifact() ); - assertEquals( EventType.ARTIFACT_DOWNLOADED, event.getType() ); - assertNotNull( event.getException() ); - assertEquals( 1, event.getExceptions().size() ); - - event = events.get( 3 ); - assertEquals( artifact, event.getArtifact() ); - assertEquals( EventType.ARTIFACT_RESOLVED, event.getType() ); - assertNotNull( event.getException() ); - assertEquals( 1, event.getExceptions().size() ); + assertEquals(events.toString(), 4, events.size()); + + RepositoryEvent event = events.get(0); + assertEquals(artifact, event.getArtifact()); + assertEquals(EventType.ARTIFACT_RESOLVING, event.getType()); + + event = events.get(1); + assertEquals(artifact, event.getArtifact()); + assertEquals(EventType.ARTIFACT_DOWNLOADING, event.getType()); + + event = events.get(2); + assertEquals(artifact, event.getArtifact()); + assertEquals(EventType.ARTIFACT_DOWNLOADED, event.getType()); + assertNotNull(event.getException()); + assertEquals(1, event.getExceptions().size()); + + event = events.get(3); + assertEquals(artifact, event.getArtifact()); + assertEquals(EventType.ARTIFACT_RESOLVED, event.getType()); + assertNotNull(event.getException()); + assertEquals(1, event.getExceptions().size()); } @Test - public void testVersionResolverFails() - { - resolver.setVersionResolver( new VersionResolver() - { - - public VersionResult resolveVersion( RepositorySystemSession session, VersionRequest request ) - throws VersionResolutionException - { - throw new VersionResolutionException( new VersionResult( request ) ); + public void testVersionResolverFails() { + resolver.setVersionResolver(new VersionResolver() { + + public VersionResult resolveVersion(RepositorySystemSession session, VersionRequest request) + throws VersionResolutionException { + throw new VersionResolutionException(new VersionResult(request)); } - } ); + }); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - try - { - resolver.resolveArtifact( session, request ); - fail( "expected exception" ); - } - catch ( ArtifactResolutionException e ) - { + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + try { + resolver.resolveArtifact(session, request); + fail("expected exception"); + } catch (ArtifactResolutionException e) { connector.assertSeenExpected(); - assertNotNull( e.getResults() ); - assertEquals( 1, e.getResults().size() ); + assertNotNull(e.getResults()); + assertEquals(1, e.getResults().size()); - ArtifactResult result = e.getResults().get( 0 ); + ArtifactResult result = e.getResults().get(0); - assertSame( request, result.getRequest() ); + assertSame(request, result.getRequest()); - assertFalse( result.getExceptions().isEmpty() ); - assertTrue( result.getExceptions().get( 0 ) instanceof VersionResolutionException ); + assertFalse(result.getExceptions().isEmpty()); + assertTrue(result.getExceptions().get(0) instanceof VersionResolutionException); Artifact resolved = result.getArtifact(); - assertNull( resolved ); + assertNull(resolved); } } @Test - public void testRepositoryEventsOnVersionResolverFail() - { - resolver.setVersionResolver( new VersionResolver() - { - - public VersionResult resolveVersion( RepositorySystemSession session, VersionRequest request ) - throws VersionResolutionException - { - throw new VersionResolutionException( new VersionResult( request ) ); + public void testRepositoryEventsOnVersionResolverFail() { + resolver.setVersionResolver(new VersionResolver() { + + public VersionResult resolveVersion(RepositorySystemSession session, VersionRequest request) + throws VersionResolutionException { + throw new VersionResolutionException(new VersionResult(request)); } - } ); + }); RecordingRepositoryListener listener = new RecordingRepositoryListener(); - session.setRepositoryListener( listener ); + session.setRepositoryListener(listener); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - try - { - resolver.resolveArtifact( session, request ); - fail( "expected exception" ); - } - catch ( ArtifactResolutionException ignored ) - { + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + try { + resolver.resolveArtifact(session, request); + fail("expected exception"); + } catch (ArtifactResolutionException ignored) { } List events = listener.getEvents(); - assertEquals( 2, events.size() ); + assertEquals(2, events.size()); - RepositoryEvent event = events.get( 0 ); - assertEquals( artifact, event.getArtifact() ); - assertEquals( EventType.ARTIFACT_RESOLVING, event.getType() ); + RepositoryEvent event = events.get(0); + assertEquals(artifact, event.getArtifact()); + assertEquals(EventType.ARTIFACT_RESOLVING, event.getType()); - event = events.get( 1 ); - assertEquals( artifact, event.getArtifact() ); - assertEquals( EventType.ARTIFACT_RESOLVED, event.getType() ); - assertNotNull( event.getException() ); - assertEquals( 1, event.getExceptions().size() ); + event = events.get(1); + assertEquals(artifact, event.getArtifact()); + assertEquals(EventType.ARTIFACT_RESOLVED, event.getType()); + assertNotNull(event.getException()); + assertEquals(1, event.getExceptions().size()); } @Test - public void testLocalArtifactAvailable() - throws ArtifactResolutionException - { - session.setLocalRepositoryManager( new LocalRepositoryManager() - { - - public LocalRepository getRepository() - { + public void testLocalArtifactAvailable() throws ArtifactResolutionException { + session.setLocalRepositoryManager(new LocalRepositoryManager() { + + public LocalRepository getRepository() { return null; } - public String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repository, String context ) - { + public String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context) { return null; } - public String getPathForRemoteArtifact( Artifact artifact, RemoteRepository repository, String context ) - { + public String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context) { return null; } - public String getPathForLocalMetadata( Metadata metadata ) - { + public String getPathForLocalMetadata(Metadata metadata) { return null; } - public String getPathForLocalArtifact( Artifact artifact ) - { + public String getPathForLocalArtifact(Artifact artifact) { return null; } - public LocalArtifactResult find( RepositorySystemSession session, LocalArtifactRequest request ) - { + public LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request) { - LocalArtifactResult result = new LocalArtifactResult( request ); - result.setAvailable( true ); - try - { - result.setFile( TestFileUtils.createTempFile( "" ) ); - } - catch ( IOException e ) - { + LocalArtifactResult result = new LocalArtifactResult(request); + result.setAvailable(true); + try { + result.setFile(TestFileUtils.createTempFile("")); + } catch (IOException e) { e.printStackTrace(); } return result; } - public void add( RepositorySystemSession session, LocalArtifactRegistration request ) - { - } + public void add(RepositorySystemSession session, LocalArtifactRegistration request) {} - public LocalMetadataResult find( RepositorySystemSession session, LocalMetadataRequest request ) - { - LocalMetadataResult result = new LocalMetadataResult( request ); - try - { - result.setFile( TestFileUtils.createTempFile( "" ) ); - } - catch ( IOException e ) - { + public LocalMetadataResult find(RepositorySystemSession session, LocalMetadataRequest request) { + LocalMetadataResult result = new LocalMetadataResult(request); + try { + result.setFile(TestFileUtils.createTempFile("")); + } catch (IOException e) { e.printStackTrace(); } return result; } - public void add( RepositorySystemSession session, LocalMetadataRegistration request ) - { - } - } ); + public void add(RepositorySystemSession session, LocalMetadataRegistration request) {} + }); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); - ArtifactResult result = resolver.resolveArtifact( session, request ); + ArtifactResult result = resolver.resolveArtifact(session, request); - assertTrue( result.getExceptions().isEmpty() ); + assertTrue(result.getExceptions().isEmpty()); Artifact resolved = result.getArtifact(); - assertNotNull( resolved.getFile() ); - - resolved = resolved.setFile( null ); - assertEquals( artifact, resolved ); + assertNotNull(resolved.getFile()); + resolved = resolved.setFile(null); + assertEquals(artifact, resolved); } @Test - public void testFindInLocalRepositoryWhenVersionWasFoundInLocalRepository() - throws ArtifactResolutionException - { - session.setLocalRepositoryManager( new LocalRepositoryManager() - { - - public LocalRepository getRepository() - { - return new LocalRepository( new File("") ); + public void testFindInLocalRepositoryWhenVersionWasFoundInLocalRepository() throws ArtifactResolutionException { + session.setLocalRepositoryManager(new LocalRepositoryManager() { + + public LocalRepository getRepository() { + return new LocalRepository(new File("")); } - public String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repository, String context ) - { + public String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context) { return null; } - public String getPathForRemoteArtifact( Artifact artifact, RemoteRepository repository, String context ) - { + public String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context) { return null; } - public String getPathForLocalMetadata( Metadata metadata ) - { + public String getPathForLocalMetadata(Metadata metadata) { return null; } - public String getPathForLocalArtifact( Artifact artifact ) - { + public String getPathForLocalArtifact(Artifact artifact) { return null; } - public LocalArtifactResult find( RepositorySystemSession session, LocalArtifactRequest request ) - { + public LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request) { - LocalArtifactResult result = new LocalArtifactResult( request ); - result.setAvailable( false ); - try - { - result.setFile( TestFileUtils.createTempFile( "" ) ); - } - catch ( IOException e ) - { + LocalArtifactResult result = new LocalArtifactResult(request); + result.setAvailable(false); + try { + result.setFile(TestFileUtils.createTempFile("")); + } catch (IOException e) { e.printStackTrace(); } return result; } - public void add( RepositorySystemSession session, LocalArtifactRegistration request ) - { - } + public void add(RepositorySystemSession session, LocalArtifactRegistration request) {} - public LocalMetadataResult find( RepositorySystemSession session, LocalMetadataRequest request ) - { - return new LocalMetadataResult( request ); + public LocalMetadataResult find(RepositorySystemSession session, LocalMetadataRequest request) { + return new LocalMetadataResult(request); } - public void add( RepositorySystemSession session, LocalMetadataRegistration request ) - { - } - } ); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); - request.addRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); + public void add(RepositorySystemSession session, LocalMetadataRegistration request) {} + }); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); + request.addRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); - resolver.setVersionResolver( new VersionResolver() - { + resolver.setVersionResolver(new VersionResolver() { - public VersionResult resolveVersion( RepositorySystemSession session, VersionRequest request ) - { - return new VersionResult( request ).setRepository( new LocalRepository( "id" ) ).setVersion( request.getArtifact().getVersion() ); + public VersionResult resolveVersion(RepositorySystemSession session, VersionRequest request) { + return new VersionResult(request) + .setRepository(new LocalRepository("id")) + .setVersion(request.getArtifact().getVersion()); } - } ); - ArtifactResult result = resolver.resolveArtifact( session, request ); + }); + ArtifactResult result = resolver.resolveArtifact(session, request); - assertTrue( result.getExceptions().isEmpty() ); + assertTrue(result.getExceptions().isEmpty()); Artifact resolved = result.getArtifact(); - assertNotNull( resolved.getFile() ); + assertNotNull(resolved.getFile()); - resolved = resolved.setFile( null ); - assertEquals( artifact, resolved ); + resolved = resolved.setFile(null); + assertEquals(artifact, resolved); } @Test public void testFindInLocalRepositoryWhenVersionRangeWasResolvedFromLocalRepository() - throws ArtifactResolutionException - { - session.setLocalRepositoryManager( new LocalRepositoryManager() - { - - public LocalRepository getRepository() - { - return new LocalRepository( new File( "" ) ); + throws ArtifactResolutionException { + session.setLocalRepositoryManager(new LocalRepositoryManager() { + + public LocalRepository getRepository() { + return new LocalRepository(new File("")); } - public String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repository, String context ) - { + public String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context) { return null; } - public String getPathForRemoteArtifact( Artifact artifact, RemoteRepository repository, String context ) - { + public String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context) { return null; } - public String getPathForLocalMetadata( Metadata metadata ) - { + public String getPathForLocalMetadata(Metadata metadata) { return null; } - public String getPathForLocalArtifact( Artifact artifact ) - { + public String getPathForLocalArtifact(Artifact artifact) { return null; } - public LocalArtifactResult find( RepositorySystemSession session, LocalArtifactRequest request ) - { + public LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request) { - LocalArtifactResult result = new LocalArtifactResult( request ); - result.setAvailable( false ); - try - { - result.setFile( TestFileUtils.createTempFile( "" ) ); - } - catch ( IOException e ) - { + LocalArtifactResult result = new LocalArtifactResult(request); + result.setAvailable(false); + try { + result.setFile(TestFileUtils.createTempFile("")); + } catch (IOException e) { e.printStackTrace(); } return result; } - public void add( RepositorySystemSession session, LocalArtifactRegistration request ) - { - } - - public LocalMetadataResult find( RepositorySystemSession session, LocalMetadataRequest request ) - { - return new LocalMetadataResult( request ); - } + public void add(RepositorySystemSession session, LocalArtifactRegistration request) {} - public void add( RepositorySystemSession session, LocalMetadataRegistration request ) - { + public LocalMetadataResult find(RepositorySystemSession session, LocalMetadataRequest request) { + return new LocalMetadataResult(request); } - } ); - ArtifactRequest request = new ArtifactRequest( artifact, null, "" ); + public void add(RepositorySystemSession session, LocalMetadataRegistration request) {} + }); + ArtifactRequest request = new ArtifactRequest(artifact, null, ""); - resolver.setVersionResolver( new VersionResolver() - { + resolver.setVersionResolver(new VersionResolver() { - public VersionResult resolveVersion( RepositorySystemSession session, VersionRequest request ) - { - return new VersionResult( request ).setVersion( request.getArtifact().getVersion() ); + public VersionResult resolveVersion(RepositorySystemSession session, VersionRequest request) { + return new VersionResult(request) + .setVersion(request.getArtifact().getVersion()); } - } ); - ArtifactResult result = resolver.resolveArtifact( session, request ); + }); + ArtifactResult result = resolver.resolveArtifact(session, request); - assertTrue( result.getExceptions().isEmpty() ); + assertTrue(result.getExceptions().isEmpty()); Artifact resolved = result.getArtifact(); - assertNotNull( resolved.getFile() ); + assertNotNull(resolved.getFile()); - resolved = resolved.setFile( null ); - assertEquals( artifact, resolved ); + resolved = resolved.setFile(null); + assertEquals(artifact, resolved); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultChecksumPolicyProviderTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultChecksumPolicyProviderTest.java index 7025771c0..169738b6f 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultChecksumPolicyProviderTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultChecksumPolicyProviderTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; +package org.eclipse.aether.internal.impl; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.internal.test.util.TestUtils; @@ -30,14 +24,18 @@ import org.eclipse.aether.repository.RepositoryPolicy; import org.eclipse.aether.spi.connector.checksum.ChecksumPolicy; import org.eclipse.aether.transfer.TransferResource; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; import org.junit.After; import org.junit.Before; import org.junit.Test; -public class DefaultChecksumPolicyProviderTest -{ +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; + +public class DefaultChecksumPolicyProviderTest { private static final String CHECKSUM_POLICY_UNKNOWN = "unknown"; @@ -50,17 +48,15 @@ public class DefaultChecksumPolicyProviderTest private TransferResource resource; @Before - public void setup() - { + public void setup() { session = TestUtils.newSession(); provider = new DefaultChecksumPolicyProvider(); - repository = new RemoteRepository.Builder( "test", "default", "file:/void" ).build(); - resource = new TransferResource( repository.getId(), repository.getUrl(), "file.txt", null, null ); + repository = new RemoteRepository.Builder("test", "default", "file:/void").build(); + resource = new TransferResource(repository.getId(), repository.getUrl(), "file.txt", null, null); } @After - public void teardown() - { + public void teardown() { provider = null; session = null; repository = null; @@ -68,83 +64,82 @@ public void teardown() } @Test - public void testNewChecksumPolicy_Fail() - { + public void testNewChecksumPolicy_Fail() { ChecksumPolicy policy = - provider.newChecksumPolicy( session, repository, resource, RepositoryPolicy.CHECKSUM_POLICY_FAIL ); - assertNotNull( policy ); - assertEquals( FailChecksumPolicy.class, policy.getClass() ); + provider.newChecksumPolicy(session, repository, resource, RepositoryPolicy.CHECKSUM_POLICY_FAIL); + assertNotNull(policy); + assertEquals(FailChecksumPolicy.class, policy.getClass()); } @Test - public void testNewChecksumPolicy_Warn() - { + public void testNewChecksumPolicy_Warn() { ChecksumPolicy policy = - provider.newChecksumPolicy( session, repository, resource, RepositoryPolicy.CHECKSUM_POLICY_WARN ); - assertNotNull( policy ); - assertEquals( WarnChecksumPolicy.class, policy.getClass() ); + provider.newChecksumPolicy(session, repository, resource, RepositoryPolicy.CHECKSUM_POLICY_WARN); + assertNotNull(policy); + assertEquals(WarnChecksumPolicy.class, policy.getClass()); } @Test - public void testNewChecksumPolicy_Ignore() - { + public void testNewChecksumPolicy_Ignore() { ChecksumPolicy policy = - provider.newChecksumPolicy( session, repository, resource, RepositoryPolicy.CHECKSUM_POLICY_IGNORE ); - assertNull( policy ); + provider.newChecksumPolicy(session, repository, resource, RepositoryPolicy.CHECKSUM_POLICY_IGNORE); + assertNull(policy); } - @Test( expected = IllegalArgumentException.class ) - public void testNewChecksumPolicy_Unknown() - { - ChecksumPolicy policy = provider.newChecksumPolicy( session, repository, resource, CHECKSUM_POLICY_UNKNOWN ); - assertNotNull( policy ); - assertEquals( WarnChecksumPolicy.class, policy.getClass() ); + @Test(expected = IllegalArgumentException.class) + public void testNewChecksumPolicy_Unknown() { + ChecksumPolicy policy = provider.newChecksumPolicy(session, repository, resource, CHECKSUM_POLICY_UNKNOWN); + assertNotNull(policy); + assertEquals(WarnChecksumPolicy.class, policy.getClass()); } @Test - public void testGetEffectiveChecksumPolicy_EqualPolicies() - { - String[] policies = - { RepositoryPolicy.CHECKSUM_POLICY_FAIL, RepositoryPolicy.CHECKSUM_POLICY_WARN, - RepositoryPolicy.CHECKSUM_POLICY_IGNORE }; - for ( String policy : policies ) - { - assertEquals( policy, policy, provider.getEffectiveChecksumPolicy( session, policy, policy ) ); + public void testGetEffectiveChecksumPolicy_EqualPolicies() { + String[] policies = { + RepositoryPolicy.CHECKSUM_POLICY_FAIL, + RepositoryPolicy.CHECKSUM_POLICY_WARN, + RepositoryPolicy.CHECKSUM_POLICY_IGNORE + }; + for (String policy : policies) { + assertEquals(policy, policy, provider.getEffectiveChecksumPolicy(session, policy, policy)); } } @Test - public void testGetEffectiveChecksumPolicy_DifferentPolicies() - { - String[][] testCases = - { { RepositoryPolicy.CHECKSUM_POLICY_WARN, RepositoryPolicy.CHECKSUM_POLICY_FAIL }, - { RepositoryPolicy.CHECKSUM_POLICY_IGNORE, RepositoryPolicy.CHECKSUM_POLICY_FAIL }, - { RepositoryPolicy.CHECKSUM_POLICY_IGNORE, RepositoryPolicy.CHECKSUM_POLICY_WARN } }; - for ( String[] testCase : testCases ) - { - assertEquals( testCase[0] + " vs " + testCase[1], testCase[0], - provider.getEffectiveChecksumPolicy( session, testCase[0], testCase[1] ) ); - assertEquals( testCase[0] + " vs " + testCase[1], testCase[0], - provider.getEffectiveChecksumPolicy( session, testCase[1], testCase[0] ) ); + public void testGetEffectiveChecksumPolicy_DifferentPolicies() { + String[][] testCases = { + {RepositoryPolicy.CHECKSUM_POLICY_WARN, RepositoryPolicy.CHECKSUM_POLICY_FAIL}, + {RepositoryPolicy.CHECKSUM_POLICY_IGNORE, RepositoryPolicy.CHECKSUM_POLICY_FAIL}, + {RepositoryPolicy.CHECKSUM_POLICY_IGNORE, RepositoryPolicy.CHECKSUM_POLICY_WARN} + }; + for (String[] testCase : testCases) { + assertEquals( + testCase[0] + " vs " + testCase[1], + testCase[0], + provider.getEffectiveChecksumPolicy(session, testCase[0], testCase[1])); + assertEquals( + testCase[0] + " vs " + testCase[1], + testCase[0], + provider.getEffectiveChecksumPolicy(session, testCase[1], testCase[0])); } } @Test - public void testGetEffectiveChecksumPolicy_UnknownPolicies() - { - String[][] testCases = - { { RepositoryPolicy.CHECKSUM_POLICY_WARN, RepositoryPolicy.CHECKSUM_POLICY_FAIL }, - { RepositoryPolicy.CHECKSUM_POLICY_WARN, RepositoryPolicy.CHECKSUM_POLICY_WARN }, - { RepositoryPolicy.CHECKSUM_POLICY_IGNORE, RepositoryPolicy.CHECKSUM_POLICY_IGNORE } }; - for ( String[] testCase : testCases ) - { - IllegalArgumentException e = assertThrows( IllegalArgumentException.class, - () -> provider.getEffectiveChecksumPolicy( session, CHECKSUM_POLICY_UNKNOWN, testCase[1] ) ); - assertThat( e.getMessage(), is("Unsupported policy: unknown") ); - e = assertThrows( IllegalArgumentException.class, - () -> provider.getEffectiveChecksumPolicy( session, testCase[1], CHECKSUM_POLICY_UNKNOWN ) ); - assertThat( e.getMessage(), is("Unsupported policy: unknown") ); + public void testGetEffectiveChecksumPolicy_UnknownPolicies() { + String[][] testCases = { + {RepositoryPolicy.CHECKSUM_POLICY_WARN, RepositoryPolicy.CHECKSUM_POLICY_FAIL}, + {RepositoryPolicy.CHECKSUM_POLICY_WARN, RepositoryPolicy.CHECKSUM_POLICY_WARN}, + {RepositoryPolicy.CHECKSUM_POLICY_IGNORE, RepositoryPolicy.CHECKSUM_POLICY_IGNORE} + }; + for (String[] testCase : testCases) { + IllegalArgumentException e = assertThrows( + IllegalArgumentException.class, + () -> provider.getEffectiveChecksumPolicy(session, CHECKSUM_POLICY_UNKNOWN, testCase[1])); + assertThat(e.getMessage(), is("Unsupported policy: unknown")); + e = assertThrows( + IllegalArgumentException.class, + () -> provider.getEffectiveChecksumPolicy(session, testCase[1], CHECKSUM_POLICY_UNKNOWN)); + assertThat(e.getMessage(), is("Unsupported policy: unknown")); } } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultDeployerTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultDeployerTest.java index 6664d28bb..499f3107b 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultDeployerTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultDeployerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,12 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Objects.requireNonNull; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +package org.eclipse.aether.internal.impl; import java.io.ByteArrayInputStream; import java.io.File; @@ -64,8 +57,13 @@ import org.junit.Before; import org.junit.Test; -public class DefaultDeployerTest -{ +import static java.util.Objects.requireNonNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +public class DefaultDeployerTest { private Artifact artifact; @@ -84,43 +82,37 @@ public class DefaultDeployerTest private RecordingRepositoryListener listener; @Before - public void setup() - throws IOException - { - artifact = new DefaultArtifact( "gid", "aid", "jar", "ver" ); - artifact = artifact.setFile( TestFileUtils.createTempFile( "artifact" ) ); - metadata = - new DefaultMetadata( "gid", "aid", "ver", "type", Nature.RELEASE_OR_SNAPSHOT, - TestFileUtils.createTempFile( "metadata" ) ); + public void setup() throws IOException { + artifact = new DefaultArtifact("gid", "aid", "jar", "ver"); + artifact = artifact.setFile(TestFileUtils.createTempFile("artifact")); + metadata = new DefaultMetadata( + "gid", "aid", "ver", "type", Nature.RELEASE_OR_SNAPSHOT, TestFileUtils.createTempFile("metadata")); session = TestUtils.newSession(); connectorProvider = new StubRepositoryConnectorProvider(); deployer = new DefaultDeployer(); - deployer.setRepositoryConnectorProvider( connectorProvider ); - deployer.setRemoteRepositoryManager( new StubRemoteRepositoryManager() ); - deployer.setRepositoryEventDispatcher( new StubRepositoryEventDispatcher() ); - deployer.setUpdateCheckManager( new StaticUpdateCheckManager( true ) ); - deployer.setFileProcessor( new TestFileProcessor() ); - deployer.setSyncContextFactory( new StubSyncContextFactory() ); - deployer.setOfflineController( new DefaultOfflineController() ); + deployer.setRepositoryConnectorProvider(connectorProvider); + deployer.setRemoteRepositoryManager(new StubRemoteRepositoryManager()); + deployer.setRepositoryEventDispatcher(new StubRepositoryEventDispatcher()); + deployer.setUpdateCheckManager(new StaticUpdateCheckManager(true)); + deployer.setFileProcessor(new TestFileProcessor()); + deployer.setSyncContextFactory(new StubSyncContextFactory()); + deployer.setOfflineController(new DefaultOfflineController()); request = new DeployRequest(); - request.setRepository( new RemoteRepository.Builder( "id", "default", "file:///" ).build() ); - connector = new RecordingRepositoryConnector( session ); - connectorProvider.setConnector( connector ); + request.setRepository(new RemoteRepository.Builder("id", "default", "file:///").build()); + connector = new RecordingRepositoryConnector(session); + connectorProvider.setConnector(connector); listener = new RecordingRepositoryListener(); - session.setRepositoryListener( listener ); + session.setRepositoryListener(listener); } @After - public void teardown() - throws Exception - { - if ( session.getLocalRepository() != null ) - { - TestFileUtils.deleteFile( session.getLocalRepository().getBasedir() ); + public void teardown() throws Exception { + if (session.getLocalRepository() != null) { + TestFileUtils.deleteFile(session.getLocalRepository().getBasedir()); } session = null; listener = null; @@ -130,297 +122,248 @@ public void teardown() } @Test - public void testSuccessfulDeploy() - throws DeploymentException - { + public void testSuccessfulDeploy() throws DeploymentException { - connector.setExpectPut( artifact ); - connector.setExpectPut( metadata ); + connector.setExpectPut(artifact); + connector.setExpectPut(metadata); - request.addArtifact( artifact ); - request.addMetadata( metadata ); + request.addArtifact(artifact); + request.addMetadata(metadata); - deployer.deploy( session, request ); + deployer.deploy(session, request); connector.assertSeenExpected(); } - @Test( expected = DeploymentException.class ) - public void testNullArtifactFile() - throws DeploymentException - { - request.addArtifact( artifact.setFile( null ) ); - deployer.deploy( session, request ); + @Test(expected = DeploymentException.class) + public void testNullArtifactFile() throws DeploymentException { + request.addArtifact(artifact.setFile(null)); + deployer.deploy(session, request); } - @Test( expected = DeploymentException.class ) - public void testNullMetadataFile() - throws DeploymentException - { - request.addArtifact( artifact.setFile( null ) ); - deployer.deploy( session, request ); + @Test(expected = DeploymentException.class) + public void testNullMetadataFile() throws DeploymentException { + request.addArtifact(artifact.setFile(null)); + deployer.deploy(session, request); } @Test - public void testSuccessfulArtifactEvents() - throws DeploymentException - { - request.addArtifact( artifact ); + public void testSuccessfulArtifactEvents() throws DeploymentException { + request.addArtifact(artifact); - deployer.deploy( session, request ); + deployer.deploy(session, request); List events = listener.getEvents(); - assertEquals( 2, events.size() ); + assertEquals(2, events.size()); - RepositoryEvent event = events.get( 0 ); - assertEquals( EventType.ARTIFACT_DEPLOYING, event.getType() ); - assertEquals( artifact, event.getArtifact() ); - assertNull( event.getException() ); + RepositoryEvent event = events.get(0); + assertEquals(EventType.ARTIFACT_DEPLOYING, event.getType()); + assertEquals(artifact, event.getArtifact()); + assertNull(event.getException()); - event = events.get( 1 ); - assertEquals( EventType.ARTIFACT_DEPLOYED, event.getType() ); - assertEquals( artifact, event.getArtifact() ); - assertNull( event.getException() ); + event = events.get(1); + assertEquals(EventType.ARTIFACT_DEPLOYED, event.getType()); + assertEquals(artifact, event.getArtifact()); + assertNull(event.getException()); } @Test - public void testFailingArtifactEvents() - { + public void testFailingArtifactEvents() { connector.fail = true; - request.addArtifact( artifact ); + request.addArtifact(artifact); - try - { - deployer.deploy( session, request ); - fail( "expected exception" ); - } - catch ( DeploymentException e ) - { + try { + deployer.deploy(session, request); + fail("expected exception"); + } catch (DeploymentException e) { List events = listener.getEvents(); - assertEquals( 2, events.size() ); + assertEquals(2, events.size()); - RepositoryEvent event = events.get( 0 ); - assertEquals( EventType.ARTIFACT_DEPLOYING, event.getType() ); - assertEquals( artifact, event.getArtifact() ); - assertNull( event.getException() ); + RepositoryEvent event = events.get(0); + assertEquals(EventType.ARTIFACT_DEPLOYING, event.getType()); + assertEquals(artifact, event.getArtifact()); + assertNull(event.getException()); - event = events.get( 1 ); - assertEquals( EventType.ARTIFACT_DEPLOYED, event.getType() ); - assertEquals( artifact, event.getArtifact() ); - assertNotNull( event.getException() ); + event = events.get(1); + assertEquals(EventType.ARTIFACT_DEPLOYED, event.getType()); + assertEquals(artifact, event.getArtifact()); + assertNotNull(event.getException()); } } @Test - public void testSuccessfulMetadataEvents() - throws DeploymentException - { - request.addMetadata( metadata ); + public void testSuccessfulMetadataEvents() throws DeploymentException { + request.addMetadata(metadata); - deployer.deploy( session, request ); + deployer.deploy(session, request); List events = listener.getEvents(); - assertEquals( 2, events.size() ); + assertEquals(2, events.size()); - RepositoryEvent event = events.get( 0 ); - assertEquals( EventType.METADATA_DEPLOYING, event.getType() ); - assertEquals( metadata, event.getMetadata() ); - assertNull( event.getException() ); + RepositoryEvent event = events.get(0); + assertEquals(EventType.METADATA_DEPLOYING, event.getType()); + assertEquals(metadata, event.getMetadata()); + assertNull(event.getException()); - event = events.get( 1 ); - assertEquals( EventType.METADATA_DEPLOYED, event.getType() ); - assertEquals( metadata, event.getMetadata() ); - assertNull( event.getException() ); + event = events.get(1); + assertEquals(EventType.METADATA_DEPLOYED, event.getType()); + assertEquals(metadata, event.getMetadata()); + assertNull(event.getException()); } @Test - public void testFailingMetdataEvents() - { + public void testFailingMetdataEvents() { connector.fail = true; - request.addMetadata( metadata ); + request.addMetadata(metadata); - try - { - deployer.deploy( session, request ); - fail( "expected exception" ); - } - catch ( DeploymentException e ) - { + try { + deployer.deploy(session, request); + fail("expected exception"); + } catch (DeploymentException e) { List events = listener.getEvents(); - assertEquals( 2, events.size() ); + assertEquals(2, events.size()); - RepositoryEvent event = events.get( 0 ); - assertEquals( EventType.METADATA_DEPLOYING, event.getType() ); - assertEquals( metadata, event.getMetadata() ); - assertNull( event.getException() ); + RepositoryEvent event = events.get(0); + assertEquals(EventType.METADATA_DEPLOYING, event.getType()); + assertEquals(metadata, event.getMetadata()); + assertNull(event.getException()); - event = events.get( 1 ); - assertEquals( EventType.METADATA_DEPLOYED, event.getType() ); - assertEquals( metadata, event.getMetadata() ); - assertNotNull( event.getException() ); + event = events.get(1); + assertEquals(EventType.METADATA_DEPLOYED, event.getType()); + assertEquals(metadata, event.getMetadata()); + assertNotNull(event.getException()); } } @Test public void testStaleLocalMetadataCopyGetsDeletedBeforeMergeWhenMetadataIsNotCurrentlyPresentInRemoteRepo() - throws Exception - { - MergeableMetadata metadata = new MergeableMetadata() - { + throws Exception { + MergeableMetadata metadata = new MergeableMetadata() { - public Metadata setFile( File file ) - { + public Metadata setFile(File file) { return this; } - public String getVersion() - { + public String getVersion() { return ""; } - public String getType() - { + public String getType() { return "test.properties"; } - public Nature getNature() - { + public Nature getNature() { return Nature.RELEASE; } - public String getGroupId() - { + public String getGroupId() { return "org"; } - public File getFile() - { + public File getFile() { return null; } - public String getArtifactId() - { + public String getArtifactId() { return "aether"; } - public Metadata setProperties( Map properties ) - { + public Metadata setProperties(Map properties) { return this; } - public Map getProperties() - { + public Map getProperties() { return Collections.emptyMap(); } - public String getProperty( String key, String defaultValue ) - { + public String getProperty(String key, String defaultValue) { return defaultValue; } - public void merge( File current, File result ) - throws RepositoryException - { - requireNonNull( current, "current cannot be null" ); - requireNonNull( result, "result cannot be null" ); + public void merge(File current, File result) throws RepositoryException { + requireNonNull(current, "current cannot be null"); + requireNonNull(result, "result cannot be null"); Properties props = new Properties(); - try - { - if ( current.isFile() ) - { - TestFileUtils.readProps( current, props ); + try { + if (current.isFile()) { + TestFileUtils.readProps(current, props); } - props.setProperty( "new", "value" ); + props.setProperty("new", "value"); - TestFileUtils.writeProps( result, props ); - } - catch ( IOException e ) - { - throw new RepositoryException( e.getMessage(), e ); + TestFileUtils.writeProps(result, props); + } catch (IOException e) { + throw new RepositoryException(e.getMessage(), e); } } - public boolean isMerged() - { + public boolean isMerged() { return false; } }; - connectorProvider.setConnector( new RepositoryConnector() - { + connectorProvider.setConnector(new RepositoryConnector() { - public void put( Collection artifactUploads, - Collection metadataUploads ) - { - } + public void put( + Collection artifactUploads, + Collection metadataUploads) {} - public void get( Collection artifactDownloads, - Collection metadataDownloads ) - { - if ( metadataDownloads != null ) - { - for ( MetadataDownload download : metadataDownloads ) - { - download.setException( new MetadataNotFoundException( download.getMetadata(), null, null ) ); + public void get( + Collection artifactDownloads, + Collection metadataDownloads) { + if (metadataDownloads != null) { + for (MetadataDownload download : metadataDownloads) { + download.setException(new MetadataNotFoundException(download.getMetadata(), null, null)); } } } - public void close() - { - } - } ); + public void close() {} + }); - request.addMetadata( metadata ); + request.addMetadata(metadata); - File metadataFile = - new File( session.getLocalRepository().getBasedir(), - session.getLocalRepositoryManager().getPathForRemoteMetadata( metadata, request.getRepository(), - "" ) ); + File metadataFile = new File( + session.getLocalRepository().getBasedir(), + session.getLocalRepositoryManager().getPathForRemoteMetadata(metadata, request.getRepository(), "")); Properties props = new Properties(); - props.setProperty( "old", "value" ); - TestFileUtils.writeProps( metadataFile, props ); + props.setProperty("old", "value"); + TestFileUtils.writeProps(metadataFile, props); - deployer.deploy( session, request ); + deployer.deploy(session, request); props = new Properties(); - TestFileUtils.readProps( metadataFile, props ); - assertNull( props.toString(), props.get( "old" ) ); + TestFileUtils.readProps(metadataFile, props); + assertNull(props.toString(), props.get("old")); } @Test - public void testFileTransformer() throws Exception - { - final Artifact transformedArtifact = new SubArtifact( artifact, null, "raj" ); - FileTransformer transformer = new FileTransformer() - { + public void testFileTransformer() throws Exception { + final Artifact transformedArtifact = new SubArtifact(artifact, null, "raj"); + FileTransformer transformer = new FileTransformer() { @Override - public InputStream transformData( File file ) - { - return new ByteArrayInputStream( "transformed data".getBytes( StandardCharsets.UTF_8 ) ); + public InputStream transformData(File file) { + return new ByteArrayInputStream("transformed data".getBytes(StandardCharsets.UTF_8)); } - + @Override - public Artifact transformArtifact( Artifact artifact ) - { + public Artifact transformArtifact(Artifact artifact) { return transformedArtifact; } }; - + StubFileTransformerManager fileTransformerManager = new StubFileTransformerManager(); - fileTransformerManager.addFileTransformer( "jar", transformer ); - session.setFileTransformerManager( fileTransformerManager ); - + fileTransformerManager.addFileTransformer("jar", transformer); + session.setFileTransformerManager(fileTransformerManager); + request = new DeployRequest(); - request.addArtifact( artifact ); - deployer.deploy( session, request ); - - Artifact putArtifact = connector.getActualArtifactPutRequests().get( 0 ); - assertEquals( transformedArtifact, putArtifact ); - } + request.addArtifact(artifact); + deployer.deploy(session, request); + Artifact putArtifact = connector.getActualArtifactPutRequests().get(0); + assertEquals(transformedArtifact, putArtifact); + } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultFileProcessorTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultFileProcessorTest.java index 4afa53420..81bc77a2b 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultFileProcessorTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultFileProcessorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.io.ByteArrayInputStream; import java.io.File; @@ -28,114 +25,97 @@ import java.nio.charset.StandardCharsets; import java.util.concurrent.atomic.AtomicInteger; -import org.eclipse.aether.internal.impl.DefaultFileProcessor; import org.eclipse.aether.internal.test.util.TestFileUtils; import org.eclipse.aether.spi.io.FileProcessor.ProgressListener; import org.junit.After; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DefaultFileProcessorTest -{ +public class DefaultFileProcessorTest { private File targetDir; private DefaultFileProcessor fileProcessor; @Before - public void setup() - throws IOException - { - targetDir = TestFileUtils.createTempDir( getClass().getSimpleName() ); + public void setup() throws IOException { + targetDir = TestFileUtils.createTempDir(getClass().getSimpleName()); fileProcessor = new DefaultFileProcessor(); } @After - public void teardown() - throws Exception - { - TestFileUtils.deleteFile( targetDir ); + public void teardown() throws Exception { + TestFileUtils.deleteFile(targetDir); fileProcessor = null; } @Test - public void testCopy() - throws IOException - { + public void testCopy() throws IOException { String data = "testCopy\nasdf"; - File file = TestFileUtils.createTempFile( data ); - File target = new File( targetDir, "testCopy.txt" ); + File file = TestFileUtils.createTempFile(data); + File target = new File(targetDir, "testCopy.txt"); - fileProcessor.copy( file, target ); + fileProcessor.copy(file, target); - assertEquals( data, TestFileUtils.readString( file ) ); + assertEquals(data, TestFileUtils.readString(file)); file.delete(); } @Test - public void testOverwrite() - throws IOException - { + public void testOverwrite() throws IOException { String data = "testCopy\nasdf"; - File file = TestFileUtils.createTempFile( data ); + File file = TestFileUtils.createTempFile(data); - for ( int i = 0; i < 5; i++ ) - { - File target = new File( targetDir, "testCopy.txt" ); - fileProcessor.copy( file, target ); - assertEquals( data, TestFileUtils.readString( file ) ); + for (int i = 0; i < 5; i++) { + File target = new File(targetDir, "testCopy.txt"); + fileProcessor.copy(file, target); + assertEquals(data, TestFileUtils.readString(file)); } file.delete(); } @Test - public void testCopyEmptyFile() - throws IOException - { - File file = TestFileUtils.createTempFile( "" ); - File target = new File( targetDir, "testCopyEmptyFile" ); + public void testCopyEmptyFile() throws IOException { + File file = TestFileUtils.createTempFile(""); + File target = new File(targetDir, "testCopyEmptyFile"); target.delete(); - fileProcessor.copy( file, target ); - assertTrue( "empty file was not copied", target.exists() && target.length() == 0L ); + fileProcessor.copy(file, target); + assertTrue("empty file was not copied", target.exists() && target.length() == 0L); target.delete(); } @Test - public void testProgressingChannel() - throws IOException - { - File file = TestFileUtils.createTempFile( "test" ); - File target = new File( targetDir, "testProgressingChannel" ); + public void testProgressingChannel() throws IOException { + File file = TestFileUtils.createTempFile("test"); + File target = new File(targetDir, "testProgressingChannel"); target.delete(); final AtomicInteger progressed = new AtomicInteger(); - ProgressListener listener = new ProgressListener() - { - public void progressed( ByteBuffer buffer ) - { - progressed.addAndGet( buffer.remaining() ); + ProgressListener listener = new ProgressListener() { + public void progressed(ByteBuffer buffer) { + progressed.addAndGet(buffer.remaining()); } }; - fileProcessor.copy( file, target, listener ); - assertTrue( "file was not created", target.isFile() ); - assertEquals( "file was not fully copied", 4L, target.length() ); - assertEquals( "listener not called", 4, progressed.intValue() ); + fileProcessor.copy(file, target, listener); + assertTrue("file was not created", target.isFile()); + assertEquals("file was not fully copied", 4L, target.length()); + assertEquals("listener not called", 4, progressed.intValue()); target.delete(); } @Test - public void testWrite() - throws IOException - { + public void testWrite() throws IOException { String data = "testCopy\nasdf"; - File target = new File( targetDir, "testWrite.txt" ); + File target = new File(targetDir, "testWrite.txt"); - fileProcessor.write( target, data ); + fileProcessor.write(target, data); - assertEquals( data, TestFileUtils.readString( target ) ); + assertEquals(data, TestFileUtils.readString(target)); target.delete(); } @@ -144,17 +124,14 @@ public void testWrite() * Used ONLY when FileProcessor present, never otherwise. */ @Test - public void testWriteStream() - throws IOException - { + public void testWriteStream() throws IOException { String data = "testCopy\nasdf"; - File target = new File( targetDir, "testWriteStream.txt" ); + File target = new File(targetDir, "testWriteStream.txt"); - fileProcessor.write( target, new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) ); + fileProcessor.write(target, new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8))); - assertEquals( data, TestFileUtils.readString( target ) ); + assertEquals(data, TestFileUtils.readString(target)); target.delete(); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultInstallerTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultInstallerTest.java index 0fb0e567d..9313c6925 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultInstallerTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultInstallerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,13 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +package org.eclipse.aether.internal.impl; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -56,8 +48,14 @@ import org.junit.Before; import org.junit.Test; -public class DefaultInstallerTest -{ +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class DefaultInstallerTest { private Artifact artifact; @@ -80,383 +78,337 @@ public class DefaultInstallerTest private TestLocalRepositoryManager lrm; @Before - public void setup() - throws IOException - { - artifact = new DefaultArtifact( "gid", "aid", "jar", "ver" ); - artifact = artifact.setFile( TestFileUtils.createTempFile( "artifact".getBytes(), 1 ) ); - metadata = - new DefaultMetadata( "gid", "aid", "ver", "type", Nature.RELEASE_OR_SNAPSHOT, - TestFileUtils.createTempFile( "metadata".getBytes(), 1 ) ); + public void setup() throws IOException { + artifact = new DefaultArtifact("gid", "aid", "jar", "ver"); + artifact = artifact.setFile(TestFileUtils.createTempFile("artifact".getBytes(), 1)); + metadata = new DefaultMetadata( + "gid", + "aid", + "ver", + "type", + Nature.RELEASE_OR_SNAPSHOT, + TestFileUtils.createTempFile("metadata".getBytes(), 1)); session = TestUtils.newSession(); - localArtifactPath = session.getLocalRepositoryManager().getPathForLocalArtifact( artifact ); - localMetadataPath = session.getLocalRepositoryManager().getPathForLocalMetadata( metadata ); + localArtifactPath = session.getLocalRepositoryManager().getPathForLocalArtifact(artifact); + localMetadataPath = session.getLocalRepositoryManager().getPathForLocalMetadata(metadata); - localArtifactFile = new File( session.getLocalRepository().getBasedir(), localArtifactPath ); + localArtifactFile = new File(session.getLocalRepository().getBasedir(), localArtifactPath); installer = new DefaultInstaller(); - installer.setFileProcessor( new TestFileProcessor() ); - installer.setRepositoryEventDispatcher( new StubRepositoryEventDispatcher() ); - installer.setSyncContextFactory( new StubSyncContextFactory() ); + installer.setFileProcessor(new TestFileProcessor()); + installer.setRepositoryEventDispatcher(new StubRepositoryEventDispatcher()); + installer.setSyncContextFactory(new StubSyncContextFactory()); request = new InstallRequest(); listener = new RecordingRepositoryListener(); - session.setRepositoryListener( listener ); + session.setRepositoryListener(listener); lrm = (TestLocalRepositoryManager) session.getLocalRepositoryManager(); - TestFileUtils.deleteFile( session.getLocalRepository().getBasedir() ); + TestFileUtils.deleteFile(session.getLocalRepository().getBasedir()); } @After - public void teardown() - throws Exception - { - TestFileUtils.deleteFile( session.getLocalRepository().getBasedir() ); + public void teardown() throws Exception { + TestFileUtils.deleteFile(session.getLocalRepository().getBasedir()); } @Test - public void testSuccessfulInstall() - throws InstallationException, IOException - { + public void testSuccessfulInstall() throws InstallationException, IOException { File artifactFile = - new File( session.getLocalRepositoryManager().getRepository().getBasedir(), localArtifactPath ); + new File(session.getLocalRepositoryManager().getRepository().getBasedir(), localArtifactPath); File metadataFile = - new File( session.getLocalRepositoryManager().getRepository().getBasedir(), localMetadataPath ); + new File(session.getLocalRepositoryManager().getRepository().getBasedir(), localMetadataPath); artifactFile.delete(); metadataFile.delete(); - request.addArtifact( artifact ); - request.addMetadata( metadata ); + request.addArtifact(artifact); + request.addMetadata(metadata); - InstallResult result = installer.install( session, request ); + InstallResult result = installer.install(session, request); - assertTrue( artifactFile.exists() ); - assertEquals( "artifact", TestFileUtils.readString( artifactFile ) ); + assertTrue(artifactFile.exists()); + assertEquals("artifact", TestFileUtils.readString(artifactFile)); - assertTrue( metadataFile.exists() ); - assertEquals( "metadata", TestFileUtils.readString( metadataFile ) ); + assertTrue(metadataFile.exists()); + assertEquals("metadata", TestFileUtils.readString(metadataFile)); - assertEquals( result.getRequest(), request ); + assertEquals(result.getRequest(), request); - assertEquals( result.getArtifacts().size(), 1 ); - assertTrue( result.getArtifacts().contains( artifact ) ); + assertEquals(result.getArtifacts().size(), 1); + assertTrue(result.getArtifacts().contains(artifact)); - assertEquals( result.getMetadata().size(), 1 ); - assertTrue( result.getMetadata().contains( metadata ) ); + assertEquals(result.getMetadata().size(), 1); + assertTrue(result.getMetadata().contains(metadata)); - assertEquals( 1, lrm.getMetadataRegistration().size() ); - assertTrue( lrm.getMetadataRegistration().contains( metadata ) ); - assertEquals( 1, lrm.getArtifactRegistration().size() ); - assertTrue( lrm.getArtifactRegistration().contains( artifact ) ); + assertEquals(1, lrm.getMetadataRegistration().size()); + assertTrue(lrm.getMetadataRegistration().contains(metadata)); + assertEquals(1, lrm.getArtifactRegistration().size()); + assertTrue(lrm.getArtifactRegistration().contains(artifact)); } - @Test( expected = InstallationException.class ) - public void testNullArtifactFile() - throws InstallationException - { + @Test(expected = InstallationException.class) + public void testNullArtifactFile() throws InstallationException { InstallRequest request = new InstallRequest(); - request.addArtifact( artifact.setFile( null ) ); + request.addArtifact(artifact.setFile(null)); - installer.install( session, request ); + installer.install(session, request); } - @Test( expected = InstallationException.class ) - public void testNullMetadataFile() - throws InstallationException - { + @Test(expected = InstallationException.class) + public void testNullMetadataFile() throws InstallationException { InstallRequest request = new InstallRequest(); - request.addMetadata( metadata.setFile( null ) ); + request.addMetadata(metadata.setFile(null)); - installer.install( session, request ); + installer.install(session, request); } - @Test( expected = InstallationException.class ) - public void testNonExistentArtifactFile() - throws InstallationException - { + @Test(expected = InstallationException.class) + public void testNonExistentArtifactFile() throws InstallationException { InstallRequest request = new InstallRequest(); - request.addArtifact( artifact.setFile( new File( "missing.txt" ) ) ); + request.addArtifact(artifact.setFile(new File("missing.txt"))); - installer.install( session, request ); + installer.install(session, request); } - @Test( expected = InstallationException.class ) - public void testNonExistentMetadataFile() - throws InstallationException - { + @Test(expected = InstallationException.class) + public void testNonExistentMetadataFile() throws InstallationException { InstallRequest request = new InstallRequest(); - request.addMetadata( metadata.setFile( new File( "missing.xml" ) ) ); + request.addMetadata(metadata.setFile(new File("missing.xml"))); - installer.install( session, request ); + installer.install(session, request); } - @Test( expected = InstallationException.class ) - public void testArtifactExistsAsDir() - throws InstallationException - { - String path = session.getLocalRepositoryManager().getPathForLocalArtifact( artifact ); - File file = new File( session.getLocalRepository().getBasedir(), path ); - assertFalse( file.getAbsolutePath() + " is a file, not directory", file.isFile() ); - assertFalse( file.getAbsolutePath() + " already exists", file.exists() ); - assertTrue( "failed to setup test: could not create " + file.getAbsolutePath(), - file.mkdirs() || file.isDirectory() ); - - request.addArtifact( artifact ); - installer.install( session, request ); + @Test(expected = InstallationException.class) + public void testArtifactExistsAsDir() throws InstallationException { + String path = session.getLocalRepositoryManager().getPathForLocalArtifact(artifact); + File file = new File(session.getLocalRepository().getBasedir(), path); + assertFalse(file.getAbsolutePath() + " is a file, not directory", file.isFile()); + assertFalse(file.getAbsolutePath() + " already exists", file.exists()); + assertTrue( + "failed to setup test: could not create " + file.getAbsolutePath(), + file.mkdirs() || file.isDirectory()); + + request.addArtifact(artifact); + installer.install(session, request); } - @Test( expected = InstallationException.class ) - public void testMetadataExistsAsDir() - throws InstallationException - { - String path = session.getLocalRepositoryManager().getPathForLocalMetadata( metadata ); - assertTrue( "failed to setup test: could not create " + path, - new File( session.getLocalRepository().getBasedir(), path ).mkdirs() ); + @Test(expected = InstallationException.class) + public void testMetadataExistsAsDir() throws InstallationException { + String path = session.getLocalRepositoryManager().getPathForLocalMetadata(metadata); + assertTrue( + "failed to setup test: could not create " + path, + new File(session.getLocalRepository().getBasedir(), path).mkdirs()); - request.addMetadata( metadata ); - installer.install( session, request ); + request.addMetadata(metadata); + installer.install(session, request); } - @Test( expected = InstallationException.class ) - public void testArtifactDestinationEqualsSource() - throws Exception - { - String path = session.getLocalRepositoryManager().getPathForLocalArtifact( artifact ); - File file = new File( session.getLocalRepository().getBasedir(), path ); - artifact = artifact.setFile( file ); - TestFileUtils.writeString( file, "test" ); - - request.addArtifact( artifact ); - installer.install( session, request ); + @Test(expected = InstallationException.class) + public void testArtifactDestinationEqualsSource() throws Exception { + String path = session.getLocalRepositoryManager().getPathForLocalArtifact(artifact); + File file = new File(session.getLocalRepository().getBasedir(), path); + artifact = artifact.setFile(file); + TestFileUtils.writeString(file, "test"); + + request.addArtifact(artifact); + installer.install(session, request); } - @Test( expected = InstallationException.class ) - public void testMetadataDestinationEqualsSource() - throws Exception - { - String path = session.getLocalRepositoryManager().getPathForLocalMetadata( metadata ); - File file = new File( session.getLocalRepository().getBasedir(), path ); - metadata = metadata.setFile( file ); - TestFileUtils.writeString( file, "test" ); - - request.addMetadata( metadata ); - installer.install( session, request ); + @Test(expected = InstallationException.class) + public void testMetadataDestinationEqualsSource() throws Exception { + String path = session.getLocalRepositoryManager().getPathForLocalMetadata(metadata); + File file = new File(session.getLocalRepository().getBasedir(), path); + metadata = metadata.setFile(file); + TestFileUtils.writeString(file, "test"); + + request.addMetadata(metadata); + installer.install(session, request); } @Test - public void testSuccessfulArtifactEvents() - throws InstallationException - { + public void testSuccessfulArtifactEvents() throws InstallationException { InstallRequest request = new InstallRequest(); - request.addArtifact( artifact ); + request.addArtifact(artifact); - installer.install( session, request ); - checkEvents( "Repository Event problem", artifact, false ); + installer.install(session, request); + checkEvents("Repository Event problem", artifact, false); } @Test - public void testSuccessfulMetadataEvents() - throws InstallationException - { + public void testSuccessfulMetadataEvents() throws InstallationException { InstallRequest request = new InstallRequest(); - request.addMetadata( metadata ); + request.addMetadata(metadata); - installer.install( session, request ); - checkEvents( "Repository Event problem", metadata, false ); + installer.install(session, request); + checkEvents("Repository Event problem", metadata, false); } @Test - public void testFailingEventsNullArtifactFile() - { - checkFailedEvents( "null artifact file", this.artifact.setFile( null ) ); + public void testFailingEventsNullArtifactFile() { + checkFailedEvents("null artifact file", this.artifact.setFile(null)); } @Test - public void testFailingEventsNullMetadataFile() - { - checkFailedEvents( "null metadata file", this.metadata.setFile( null ) ); + public void testFailingEventsNullMetadataFile() { + checkFailedEvents("null metadata file", this.metadata.setFile(null)); } @Test - public void testFailingEventsArtifactExistsAsDir() - { - String path = session.getLocalRepositoryManager().getPathForLocalArtifact( artifact ); - assertTrue( "failed to setup test: could not create " + path, - new File( session.getLocalRepository().getBasedir(), path ).mkdirs() ); - checkFailedEvents( "target exists as dir", artifact ); + public void testFailingEventsArtifactExistsAsDir() { + String path = session.getLocalRepositoryManager().getPathForLocalArtifact(artifact); + assertTrue( + "failed to setup test: could not create " + path, + new File(session.getLocalRepository().getBasedir(), path).mkdirs()); + checkFailedEvents("target exists as dir", artifact); } @Test - public void testFailingEventsMetadataExistsAsDir() - { - String path = session.getLocalRepositoryManager().getPathForLocalMetadata( metadata ); - assertTrue( "failed to setup test: could not create " + path, - new File( session.getLocalRepository().getBasedir(), path ).mkdirs() ); - checkFailedEvents( "target exists as dir", metadata ); + public void testFailingEventsMetadataExistsAsDir() { + String path = session.getLocalRepositoryManager().getPathForLocalMetadata(metadata); + assertTrue( + "failed to setup test: could not create " + path, + new File(session.getLocalRepository().getBasedir(), path).mkdirs()); + checkFailedEvents("target exists as dir", metadata); } - private void checkFailedEvents( String msg, Metadata metadata ) - { - InstallRequest request = new InstallRequest().addMetadata( metadata ); + private void checkFailedEvents(String msg, Metadata metadata) { + InstallRequest request = new InstallRequest().addMetadata(metadata); msg = "Repository events problem (case: " + msg + ")"; - try - { - installer.install( session, request ); - fail( "expected exception" ); - } - catch ( InstallationException e ) - { - checkEvents( msg, metadata, true ); + try { + installer.install(session, request); + fail("expected exception"); + } catch (InstallationException e) { + checkEvents(msg, metadata, true); } - } - private void checkEvents( String msg, Metadata metadata, boolean failed ) - { + private void checkEvents(String msg, Metadata metadata, boolean failed) { List events = listener.getEvents(); - assertEquals( msg, 2, events.size() ); - RepositoryEvent event = events.get( 0 ); - assertEquals( msg, EventType.METADATA_INSTALLING, event.getType() ); - assertEquals( msg, metadata, event.getMetadata() ); - assertNull( msg, event.getException() ); - - event = events.get( 1 ); - assertEquals( msg, EventType.METADATA_INSTALLED, event.getType() ); - assertEquals( msg, metadata, event.getMetadata() ); - if ( failed ) - { - assertNotNull( msg, event.getException() ); - } - else - { - assertNull( msg, event.getException() ); + assertEquals(msg, 2, events.size()); + RepositoryEvent event = events.get(0); + assertEquals(msg, EventType.METADATA_INSTALLING, event.getType()); + assertEquals(msg, metadata, event.getMetadata()); + assertNull(msg, event.getException()); + + event = events.get(1); + assertEquals(msg, EventType.METADATA_INSTALLED, event.getType()); + assertEquals(msg, metadata, event.getMetadata()); + if (failed) { + assertNotNull(msg, event.getException()); + } else { + assertNull(msg, event.getException()); } } - private void checkFailedEvents( String msg, Artifact artifact ) - { - InstallRequest request = new InstallRequest().addArtifact( artifact ); + private void checkFailedEvents(String msg, Artifact artifact) { + InstallRequest request = new InstallRequest().addArtifact(artifact); msg = "Repository events problem (case: " + msg + ")"; - try - { - installer.install( session, request ); - fail( "expected exception" ); - } - catch ( InstallationException e ) - { - checkEvents( msg, artifact, true ); + try { + installer.install(session, request); + fail("expected exception"); + } catch (InstallationException e) { + checkEvents(msg, artifact, true); } } - private void checkEvents( String msg, Artifact artifact, boolean failed ) - { + private void checkEvents(String msg, Artifact artifact, boolean failed) { List events = listener.getEvents(); - assertEquals( msg, 2, events.size() ); - RepositoryEvent event = events.get( 0 ); - assertEquals( msg, EventType.ARTIFACT_INSTALLING, event.getType() ); - assertEquals( msg, artifact, event.getArtifact() ); - assertNull( msg, event.getException() ); - - event = events.get( 1 ); - assertEquals( msg, EventType.ARTIFACT_INSTALLED, event.getType() ); - assertEquals( msg, artifact, event.getArtifact() ); - if ( failed ) - { - assertNotNull( msg + " > expected exception", event.getException() ); - } - else - { - assertNull( msg + " > " + event.getException(), event.getException() ); + assertEquals(msg, 2, events.size()); + RepositoryEvent event = events.get(0); + assertEquals(msg, EventType.ARTIFACT_INSTALLING, event.getType()); + assertEquals(msg, artifact, event.getArtifact()); + assertNull(msg, event.getException()); + + event = events.get(1); + assertEquals(msg, EventType.ARTIFACT_INSTALLED, event.getType()); + assertEquals(msg, artifact, event.getArtifact()); + if (failed) { + assertNotNull(msg + " > expected exception", event.getException()); + } else { + assertNull(msg + " > " + event.getException(), event.getException()); } } @Test - public void testDoNotUpdateUnchangedArtifact() - throws InstallationException - { - request.addArtifact( artifact ); - installer.install( session, request ); - - installer.setFileProcessor( new DefaultFileProcessor() - { + public void testDoNotUpdateUnchangedArtifact() throws InstallationException { + request.addArtifact(artifact); + installer.install(session, request); + + installer.setFileProcessor(new DefaultFileProcessor() { @Override - public long copy( File src, File target, ProgressListener listener ) - throws IOException - { - throw new IOException( "copy called" ); + public long copy(File src, File target, ProgressListener listener) throws IOException { + throw new IOException("copy called"); } - } ); + }); request = new InstallRequest(); - request.addArtifact( artifact ); - installer.install( session, request ); + request.addArtifact(artifact); + installer.install(session, request); } @Test - public void testSetArtifactTimestamps() - throws InstallationException - { - artifact.getFile().setLastModified( artifact.getFile().lastModified() - 60000 ); + public void testSetArtifactTimestamps() throws InstallationException { + artifact.getFile().setLastModified(artifact.getFile().lastModified() - 60000); - request.addArtifact( artifact ); + request.addArtifact(artifact); - installer.install( session, request ); + installer.install(session, request); - assertEquals( "artifact timestamp was not set to src file", artifact.getFile().lastModified(), - localArtifactFile.lastModified() ); + assertEquals( + "artifact timestamp was not set to src file", + artifact.getFile().lastModified(), + localArtifactFile.lastModified()); request = new InstallRequest(); - request.addArtifact( artifact ); + request.addArtifact(artifact); - artifact.getFile().setLastModified( artifact.getFile().lastModified() - 60000 ); + artifact.getFile().setLastModified(artifact.getFile().lastModified() - 60000); - installer.install( session, request ); + installer.install(session, request); - assertEquals( "artifact timestamp was not set to src file", artifact.getFile().lastModified(), - localArtifactFile.lastModified() ); + assertEquals( + "artifact timestamp was not set to src file", + artifact.getFile().lastModified(), + localArtifactFile.lastModified()); } - + @Test - public void testFileTransformer() throws Exception - { - final Artifact transformedArtifact = new SubArtifact( artifact, null, "raj" ); - FileTransformer transformer = new FileTransformer() - { + public void testFileTransformer() throws Exception { + final Artifact transformedArtifact = new SubArtifact(artifact, null, "raj"); + FileTransformer transformer = new FileTransformer() { @Override - public InputStream transformData( File file ) - { - return new ByteArrayInputStream( "transformed data".getBytes( StandardCharsets.UTF_8 ) ); + public InputStream transformData(File file) { + return new ByteArrayInputStream("transformed data".getBytes(StandardCharsets.UTF_8)); } - + @Override - public Artifact transformArtifact( Artifact artifact ) - { + public Artifact transformArtifact(Artifact artifact) { return transformedArtifact; } }; - + StubFileTransformerManager fileTransformerManager = new StubFileTransformerManager(); - fileTransformerManager.addFileTransformer( "jar", transformer ); - session.setFileTransformerManager( fileTransformerManager ); - + fileTransformerManager.addFileTransformer("jar", transformer); + session.setFileTransformerManager(fileTransformerManager); + request = new InstallRequest(); - request.addArtifact( artifact ); - installer.install( session, request ); - - assertFalse( localArtifactFile.exists() ); - - String transformedArtifactPath = session.getLocalRepositoryManager().getPathForLocalArtifact( transformedArtifact ); - File transformedArtifactFile = new File( session.getLocalRepository().getBasedir(), transformedArtifactPath ); - assertTrue( transformedArtifactFile.exists() ); - - try ( BufferedReader r = new BufferedReader( new FileReader( transformedArtifactFile ) ) ) - { - assertEquals( "transformed data", r.readLine() ); + request.addArtifact(artifact); + installer.install(session, request); + + assertFalse(localArtifactFile.exists()); + + String transformedArtifactPath = + session.getLocalRepositoryManager().getPathForLocalArtifact(transformedArtifact); + File transformedArtifactFile = new File(session.getLocalRepository().getBasedir(), transformedArtifactPath); + assertTrue(transformedArtifactFile.exists()); + + try (BufferedReader r = new BufferedReader(new FileReader(transformedArtifactFile))) { + assertEquals("transformed data", r.readLine()); } } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultLocalPathPrefixComposerFactoryTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultLocalPathPrefixComposerFactoryTest.java index 2728c5bbb..cee4892bc 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultLocalPathPrefixComposerFactoryTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultLocalPathPrefixComposerFactoryTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -35,195 +34,195 @@ /** * UT for {@link DefaultLocalPathPrefixComposerFactory}. */ -public class DefaultLocalPathPrefixComposerFactoryTest -{ +public class DefaultLocalPathPrefixComposerFactoryTest { private final Artifact releaseArtifact = new DefaultArtifact("org.group:artifact:1.0"); private final Artifact snapshotArtifact = new DefaultArtifact("org.group:artifact:1.0-20220228.180000-1"); - private final Metadata releaseMetadata = new DefaultMetadata( "org.group", "artifact", "1.0", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); + private final Metadata releaseMetadata = new DefaultMetadata( + "org.group", "artifact", "1.0", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); - private final Metadata snapshotMetadata = new DefaultMetadata( "org.group", "artifact", "1.0-SNAPSHOT", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); + private final Metadata snapshotMetadata = new DefaultMetadata( + "org.group", "artifact", "1.0-SNAPSHOT", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); - private final Metadata gaMetadata = new DefaultMetadata( "org.group", "artifact", null, "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); + private final Metadata gaMetadata = new DefaultMetadata( + "org.group", "artifact", null, "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); - private final Metadata gMetadata = new DefaultMetadata( "org.group", null, null, "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); + private final Metadata gMetadata = + new DefaultMetadata("org.group", null, null, "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); - private final RemoteRepository repository = new RemoteRepository.Builder( "my-repo", "default", "https://repo.maven.apache.org/maven2/" ).build(); + private final RemoteRepository repository = + new RemoteRepository.Builder("my-repo", "default", "https://repo.maven.apache.org/maven2/").build(); @Test - public void defaultConfigNoSplitAllNulls() - { + public void defaultConfigNoSplitAllNulls() { DefaultRepositorySystemSession session = TestUtils.newSession(); LocalPathPrefixComposerFactory factory = new DefaultLocalPathPrefixComposerFactory(); - LocalPathPrefixComposer composer = factory.createComposer( session ); - assertNotNull( composer ); + LocalPathPrefixComposer composer = factory.createComposer(session); + assertNotNull(composer); String prefix; - prefix = composer.getPathPrefixForLocalArtifact( releaseArtifact ); - assertNull( prefix ); + prefix = composer.getPathPrefixForLocalArtifact(releaseArtifact); + assertNull(prefix); - prefix = composer.getPathPrefixForLocalMetadata( releaseMetadata ); - assertNull( prefix ); + prefix = composer.getPathPrefixForLocalMetadata(releaseMetadata); + assertNull(prefix); - prefix = composer.getPathPrefixForRemoteArtifact( releaseArtifact, repository ); - assertNull( prefix ); + prefix = composer.getPathPrefixForRemoteArtifact(releaseArtifact, repository); + assertNull(prefix); - prefix = composer.getPathPrefixForRemoteMetadata( releaseMetadata, repository ); - assertNull( prefix ); + prefix = composer.getPathPrefixForRemoteMetadata(releaseMetadata, repository); + assertNull(prefix); } @Test - public void splitEnabled() - { + public void splitEnabled() { DefaultRepositorySystemSession session = TestUtils.newSession(); - session.setConfigProperty( "aether.enhancedLocalRepository.split", Boolean.TRUE.toString() ); + session.setConfigProperty("aether.enhancedLocalRepository.split", Boolean.TRUE.toString()); LocalPathPrefixComposerFactory factory = new DefaultLocalPathPrefixComposerFactory(); - LocalPathPrefixComposer composer = factory.createComposer( session ); - assertNotNull( composer ); + LocalPathPrefixComposer composer = factory.createComposer(session); + assertNotNull(composer); String prefix; - prefix = composer.getPathPrefixForLocalArtifact( releaseArtifact ); - assertNotNull( prefix ); - assertEquals( "installed", prefix ); + prefix = composer.getPathPrefixForLocalArtifact(releaseArtifact); + assertNotNull(prefix); + assertEquals("installed", prefix); - prefix = composer.getPathPrefixForLocalMetadata( releaseMetadata ); - assertNotNull( prefix ); - assertEquals( "installed", prefix ); + prefix = composer.getPathPrefixForLocalMetadata(releaseMetadata); + assertNotNull(prefix); + assertEquals("installed", prefix); - prefix = composer.getPathPrefixForRemoteArtifact( releaseArtifact, repository ); - assertNotNull( prefix ); - assertEquals( "cached", prefix ); + prefix = composer.getPathPrefixForRemoteArtifact(releaseArtifact, repository); + assertNotNull(prefix); + assertEquals("cached", prefix); - prefix = composer.getPathPrefixForRemoteMetadata( releaseMetadata, repository ); - assertNotNull( prefix ); - assertEquals( "cached", prefix ); + prefix = composer.getPathPrefixForRemoteMetadata(releaseMetadata, repository); + assertNotNull(prefix); + assertEquals("cached", prefix); } @Test - public void saneConfig() - { + public void saneConfig() { DefaultRepositorySystemSession session = TestUtils.newSession(); - session.setConfigProperty( "aether.enhancedLocalRepository.split", Boolean.TRUE.toString() ); - session.setConfigProperty( "aether.enhancedLocalRepository.splitLocal", Boolean.TRUE.toString() ); - session.setConfigProperty( "aether.enhancedLocalRepository.splitRemoteRepository", Boolean.TRUE.toString() ); + session.setConfigProperty("aether.enhancedLocalRepository.split", Boolean.TRUE.toString()); + session.setConfigProperty("aether.enhancedLocalRepository.splitLocal", Boolean.TRUE.toString()); + session.setConfigProperty("aether.enhancedLocalRepository.splitRemoteRepository", Boolean.TRUE.toString()); LocalPathPrefixComposerFactory factory = new DefaultLocalPathPrefixComposerFactory(); - LocalPathPrefixComposer composer = factory.createComposer( session ); - assertNotNull( composer ); + LocalPathPrefixComposer composer = factory.createComposer(session); + assertNotNull(composer); String prefix; - prefix = composer.getPathPrefixForLocalArtifact( releaseArtifact ); - assertNotNull( prefix ); - assertEquals( "installed/releases", prefix ); + prefix = composer.getPathPrefixForLocalArtifact(releaseArtifact); + assertNotNull(prefix); + assertEquals("installed/releases", prefix); - prefix = composer.getPathPrefixForLocalArtifact( snapshotArtifact ); - assertNotNull( prefix ); - assertEquals( "installed/snapshots", prefix ); + prefix = composer.getPathPrefixForLocalArtifact(snapshotArtifact); + assertNotNull(prefix); + assertEquals("installed/snapshots", prefix); - prefix = composer.getPathPrefixForLocalMetadata( releaseMetadata ); - assertNotNull( prefix ); - assertEquals( "installed/releases", prefix ); + prefix = composer.getPathPrefixForLocalMetadata(releaseMetadata); + assertNotNull(prefix); + assertEquals("installed/releases", prefix); - prefix = composer.getPathPrefixForLocalMetadata( snapshotMetadata ); - assertNotNull( prefix ); - assertEquals( "installed/snapshots", prefix ); + prefix = composer.getPathPrefixForLocalMetadata(snapshotMetadata); + assertNotNull(prefix); + assertEquals("installed/snapshots", prefix); - prefix = composer.getPathPrefixForLocalMetadata( gaMetadata ); - assertNotNull( prefix ); - assertEquals( "installed/releases", prefix ); + prefix = composer.getPathPrefixForLocalMetadata(gaMetadata); + assertNotNull(prefix); + assertEquals("installed/releases", prefix); - prefix = composer.getPathPrefixForLocalMetadata( gMetadata ); - assertNotNull( prefix ); - assertEquals( "installed/releases", prefix ); + prefix = composer.getPathPrefixForLocalMetadata(gMetadata); + assertNotNull(prefix); + assertEquals("installed/releases", prefix); - prefix = composer.getPathPrefixForRemoteArtifact( releaseArtifact, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo", prefix ); + prefix = composer.getPathPrefixForRemoteArtifact(releaseArtifact, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo", prefix); - prefix = composer.getPathPrefixForRemoteArtifact( snapshotArtifact, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo", prefix ); + prefix = composer.getPathPrefixForRemoteArtifact(snapshotArtifact, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo", prefix); - prefix = composer.getPathPrefixForRemoteMetadata( releaseMetadata, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo", prefix ); + prefix = composer.getPathPrefixForRemoteMetadata(releaseMetadata, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo", prefix); - prefix = composer.getPathPrefixForRemoteMetadata( snapshotMetadata, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo", prefix ); + prefix = composer.getPathPrefixForRemoteMetadata(snapshotMetadata, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo", prefix); - prefix = composer.getPathPrefixForRemoteMetadata( gaMetadata, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo", prefix ); + prefix = composer.getPathPrefixForRemoteMetadata(gaMetadata, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo", prefix); - prefix = composer.getPathPrefixForRemoteMetadata( gMetadata, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo", prefix ); + prefix = composer.getPathPrefixForRemoteMetadata(gMetadata, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo", prefix); } @Test - public void fullConfig() - { + public void fullConfig() { DefaultRepositorySystemSession session = TestUtils.newSession(); - session.setConfigProperty( "aether.enhancedLocalRepository.split", Boolean.TRUE.toString() ); - session.setConfigProperty( "aether.enhancedLocalRepository.splitLocal", Boolean.TRUE.toString() ); - session.setConfigProperty( "aether.enhancedLocalRepository.splitRemote", Boolean.TRUE.toString() ); - session.setConfigProperty( "aether.enhancedLocalRepository.splitRemoteRepository", Boolean.TRUE.toString() ); + session.setConfigProperty("aether.enhancedLocalRepository.split", Boolean.TRUE.toString()); + session.setConfigProperty("aether.enhancedLocalRepository.splitLocal", Boolean.TRUE.toString()); + session.setConfigProperty("aether.enhancedLocalRepository.splitRemote", Boolean.TRUE.toString()); + session.setConfigProperty("aether.enhancedLocalRepository.splitRemoteRepository", Boolean.TRUE.toString()); LocalPathPrefixComposerFactory factory = new DefaultLocalPathPrefixComposerFactory(); - LocalPathPrefixComposer composer = factory.createComposer( session ); - assertNotNull( composer ); + LocalPathPrefixComposer composer = factory.createComposer(session); + assertNotNull(composer); String prefix; - prefix = composer.getPathPrefixForLocalArtifact( releaseArtifact ); - assertNotNull( prefix ); - assertEquals( "installed/releases", prefix ); + prefix = composer.getPathPrefixForLocalArtifact(releaseArtifact); + assertNotNull(prefix); + assertEquals("installed/releases", prefix); - prefix = composer.getPathPrefixForLocalArtifact( snapshotArtifact ); - assertNotNull( prefix ); - assertEquals( "installed/snapshots", prefix ); + prefix = composer.getPathPrefixForLocalArtifact(snapshotArtifact); + assertNotNull(prefix); + assertEquals("installed/snapshots", prefix); - prefix = composer.getPathPrefixForLocalMetadata( releaseMetadata ); - assertNotNull( prefix ); - assertEquals( "installed/releases", prefix ); + prefix = composer.getPathPrefixForLocalMetadata(releaseMetadata); + assertNotNull(prefix); + assertEquals("installed/releases", prefix); - prefix = composer.getPathPrefixForLocalMetadata( snapshotMetadata ); - assertNotNull( prefix ); - assertEquals( "installed/snapshots", prefix ); + prefix = composer.getPathPrefixForLocalMetadata(snapshotMetadata); + assertNotNull(prefix); + assertEquals("installed/snapshots", prefix); - prefix = composer.getPathPrefixForLocalMetadata( gaMetadata ); - assertNotNull( prefix ); - assertEquals( "installed/releases", prefix ); + prefix = composer.getPathPrefixForLocalMetadata(gaMetadata); + assertNotNull(prefix); + assertEquals("installed/releases", prefix); - prefix = composer.getPathPrefixForLocalMetadata( gMetadata ); - assertNotNull( prefix ); - assertEquals( "installed/releases", prefix ); + prefix = composer.getPathPrefixForLocalMetadata(gMetadata); + assertNotNull(prefix); + assertEquals("installed/releases", prefix); - prefix = composer.getPathPrefixForRemoteArtifact( releaseArtifact, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo/releases", prefix ); + prefix = composer.getPathPrefixForRemoteArtifact(releaseArtifact, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo/releases", prefix); - prefix = composer.getPathPrefixForRemoteArtifact( snapshotArtifact, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo/snapshots", prefix ); + prefix = composer.getPathPrefixForRemoteArtifact(snapshotArtifact, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo/snapshots", prefix); - prefix = composer.getPathPrefixForRemoteMetadata( releaseMetadata, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo/releases", prefix ); + prefix = composer.getPathPrefixForRemoteMetadata(releaseMetadata, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo/releases", prefix); - prefix = composer.getPathPrefixForRemoteMetadata( snapshotMetadata, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo/snapshots", prefix ); + prefix = composer.getPathPrefixForRemoteMetadata(snapshotMetadata, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo/snapshots", prefix); - prefix = composer.getPathPrefixForRemoteMetadata( gaMetadata, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo/releases", prefix ); + prefix = composer.getPathPrefixForRemoteMetadata(gaMetadata, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo/releases", prefix); - prefix = composer.getPathPrefixForRemoteMetadata( gMetadata, repository ); - assertNotNull( prefix ); - assertEquals( "cached/my-repo/releases", prefix ); + prefix = composer.getPathPrefixForRemoteMetadata(gMetadata, repository); + assertNotNull(prefix); + assertEquals("cached/my-repo/releases", prefix); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultMetadataResolverTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultMetadataResolverTest.java index bb5003300..48cabd732 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultMetadataResolverTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultMetadataResolverTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.io.File; import java.io.IOException; @@ -50,10 +47,11 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DefaultMetadataResolverTest -{ +public class DefaultMetadataResolverTest { private DefaultMetadataResolver resolver; @@ -74,323 +72,301 @@ public class DefaultMetadataResolverTest private DefaultRemoteRepositoryFilterManager remoteRepositoryFilterManager; @Before - public void setup() - throws Exception - { + public void setup() throws Exception { remoteRepositoryFilterSources = new HashMap<>(); - remoteRepositoryFilterManager = new DefaultRemoteRepositoryFilterManager( remoteRepositoryFilterSources ); + remoteRepositoryFilterManager = new DefaultRemoteRepositoryFilterManager(remoteRepositoryFilterSources); session = TestUtils.newSession(); lrm = (TestLocalRepositoryManager) session.getLocalRepositoryManager(); connectorProvider = new StubRepositoryConnectorProvider(); resolver = new DefaultMetadataResolver(); - resolver.setUpdateCheckManager( new StaticUpdateCheckManager( true ) ); - resolver.setRepositoryEventDispatcher( new StubRepositoryEventDispatcher() ); - resolver.setRepositoryConnectorProvider( connectorProvider ); - resolver.setRemoteRepositoryManager( new StubRemoteRepositoryManager() ); - resolver.setSyncContextFactory( new StubSyncContextFactory() ); - resolver.setOfflineController( new DefaultOfflineController() ); - resolver.setRemoteRepositoryFilterManager( remoteRepositoryFilterManager ); - repository = - new RemoteRepository.Builder( "test-DMRT", "default", - TestFileUtils.createTempDir().toURI().toURL().toString() ).build(); - metadata = new DefaultMetadata( "gid", "aid", "ver", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); + resolver.setUpdateCheckManager(new StaticUpdateCheckManager(true)); + resolver.setRepositoryEventDispatcher(new StubRepositoryEventDispatcher()); + resolver.setRepositoryConnectorProvider(connectorProvider); + resolver.setRemoteRepositoryManager(new StubRemoteRepositoryManager()); + resolver.setSyncContextFactory(new StubSyncContextFactory()); + resolver.setOfflineController(new DefaultOfflineController()); + resolver.setRemoteRepositoryFilterManager(remoteRepositoryFilterManager); + repository = new RemoteRepository.Builder( + "test-DMRT", + "default", + TestFileUtils.createTempDir().toURI().toURL().toString()) + .build(); + metadata = new DefaultMetadata("gid", "aid", "ver", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); connector = new RecordingRepositoryConnector(); - connectorProvider.setConnector( connector ); + connectorProvider.setConnector(connector); } @After - public void teardown() - throws Exception - { - TestFileUtils.deleteFile( new File( new URI( repository.getUrl() ) ) ); - TestFileUtils.deleteFile( session.getLocalRepository().getBasedir() ); + public void teardown() throws Exception { + TestFileUtils.deleteFile(new File(new URI(repository.getUrl()))); + TestFileUtils.deleteFile(session.getLocalRepository().getBasedir()); } @Test - public void testNoRepositoryFailing() - { - MetadataRequest request = new MetadataRequest( metadata, null, "" ); - List results = resolver.resolveMetadata( session, Arrays.asList( request ) ); + public void testNoRepositoryFailing() { + MetadataRequest request = new MetadataRequest(metadata, null, ""); + List results = resolver.resolveMetadata(session, Arrays.asList(request)); - assertEquals( 1, results.size() ); + assertEquals(1, results.size()); - MetadataResult result = results.get( 0 ); - assertSame( request, result.getRequest() ); - assertNotNull( "" + ( result.getMetadata() != null ? result.getMetadata().getFile() : result.getMetadata() ), - result.getException() ); - assertEquals( MetadataNotFoundException.class, result.getException().getClass() ); + MetadataResult result = results.get(0); + assertSame(request, result.getRequest()); + assertNotNull( + "" + (result.getMetadata() != null ? result.getMetadata().getFile() : result.getMetadata()), + result.getException()); + assertEquals(MetadataNotFoundException.class, result.getException().getClass()); - assertNull( result.getMetadata() ); + assertNull(result.getMetadata()); } @Test - public void testResolve() - throws IOException - { - connector.setExpectGet( metadata ); + public void testResolve() throws IOException { + connector.setExpectGet(metadata); // prepare "download" - File file = - new File( session.getLocalRepository().getBasedir(), - session.getLocalRepositoryManager().getPathForRemoteMetadata( metadata, repository, "" ) ); + File file = new File( + session.getLocalRepository().getBasedir(), + session.getLocalRepositoryManager().getPathForRemoteMetadata(metadata, repository, "")); - TestFileUtils.writeString( file, file.getAbsolutePath() ); + TestFileUtils.writeString(file, file.getAbsolutePath()); - MetadataRequest request = new MetadataRequest( metadata, repository, "" ); - List results = resolver.resolveMetadata( session, Arrays.asList( request ) ); + MetadataRequest request = new MetadataRequest(metadata, repository, ""); + List results = resolver.resolveMetadata(session, Arrays.asList(request)); - assertEquals( 1, results.size() ); + assertEquals(1, results.size()); - MetadataResult result = results.get( 0 ); - assertSame( request, result.getRequest() ); - assertNull( result.getException() ); - assertNotNull( result.getMetadata() ); - assertNotNull( result.getMetadata().getFile() ); + MetadataResult result = results.get(0); + assertSame(request, result.getRequest()); + assertNull(result.getException()); + assertNotNull(result.getMetadata()); + assertNotNull(result.getMetadata().getFile()); - assertEquals( file, result.getMetadata().getFile() ); - assertEquals( metadata, result.getMetadata().setFile( null ) ); + assertEquals(file, result.getMetadata().getFile()); + assertEquals(metadata, result.getMetadata().setFile(null)); connector.assertSeenExpected(); Set metadataRegistration = - ( (TestLocalRepositoryManager) session.getLocalRepositoryManager() ).getMetadataRegistration(); - assertTrue( metadataRegistration.contains( metadata ) ); - assertEquals( 1, metadataRegistration.size() ); + ((TestLocalRepositoryManager) session.getLocalRepositoryManager()).getMetadataRegistration(); + assertTrue(metadataRegistration.contains(metadata)); + assertEquals(1, metadataRegistration.size()); } @Test - public void testRemoveMetadataIfMissing() - throws IOException - { - connector = new RecordingRepositoryConnector() - { + public void testRemoveMetadataIfMissing() throws IOException { + connector = new RecordingRepositoryConnector() { @Override - public void get( Collection artifactDownloads, - Collection metadataDownloads ) - { - super.get( artifactDownloads, metadataDownloads ); - for ( MetadataDownload d : metadataDownloads ) - { - d.setException( new MetadataNotFoundException( metadata, repository ) ); + public void get( + Collection artifactDownloads, + Collection metadataDownloads) { + super.get(artifactDownloads, metadataDownloads); + for (MetadataDownload d : metadataDownloads) { + d.setException(new MetadataNotFoundException(metadata, repository)); } } - }; - connectorProvider.setConnector( connector ); + connectorProvider.setConnector(connector); - File file = - new File( session.getLocalRepository().getBasedir(), - session.getLocalRepositoryManager().getPathForRemoteMetadata( metadata, repository, "" ) ); - TestFileUtils.writeString( file, file.getAbsolutePath() ); - metadata.setFile( file ); + File file = new File( + session.getLocalRepository().getBasedir(), + session.getLocalRepositoryManager().getPathForRemoteMetadata(metadata, repository, "")); + TestFileUtils.writeString(file, file.getAbsolutePath()); + metadata.setFile(file); - MetadataRequest request = new MetadataRequest( metadata, repository, "" ); - request.setDeleteLocalCopyIfMissing( true ); + MetadataRequest request = new MetadataRequest(metadata, repository, ""); + request.setDeleteLocalCopyIfMissing(true); - List results = resolver.resolveMetadata( session, Arrays.asList( request ) ); - assertEquals( 1, results.size() ); - MetadataResult result = results.get( 0 ); + List results = resolver.resolveMetadata(session, Arrays.asList(request)); + assertEquals(1, results.size()); + MetadataResult result = results.get(0); - assertNotNull( result.getException() ); - assertFalse( file.exists() ); + assertNotNull(result.getException()); + assertFalse(file.exists()); } @Test - public void testOfflineSessionResolveMetadataMissing() - { - session.setOffline( true ); - MetadataRequest request = new MetadataRequest( metadata, repository, "" ); - List results = resolver.resolveMetadata( session, Arrays.asList( request ) ); + public void testOfflineSessionResolveMetadataMissing() { + session.setOffline(true); + MetadataRequest request = new MetadataRequest(metadata, repository, ""); + List results = resolver.resolveMetadata(session, Arrays.asList(request)); - assertEquals( 1, results.size() ); + assertEquals(1, results.size()); - MetadataResult result = results.get( 0 ); - assertSame( request, result.getRequest() ); - assertNotNull( result.getException() ); - assertNull( result.getMetadata() ); + MetadataResult result = results.get(0); + assertSame(request, result.getRequest()); + assertNotNull(result.getException()); + assertNull(result.getMetadata()); connector.assertSeenExpected(); } @Test - public void testOfflineSessionResolveMetadata() - throws IOException - { - session.setOffline( true ); + public void testOfflineSessionResolveMetadata() throws IOException { + session.setOffline(true); - String path = session.getLocalRepositoryManager().getPathForRemoteMetadata( metadata, repository, "" ); - File file = new File( session.getLocalRepository().getBasedir(), path ); - TestFileUtils.writeString( file, file.getAbsolutePath() ); + String path = session.getLocalRepositoryManager().getPathForRemoteMetadata(metadata, repository, ""); + File file = new File(session.getLocalRepository().getBasedir(), path); + TestFileUtils.writeString(file, file.getAbsolutePath()); // set file to use in TestLRM find() - metadata = metadata.setFile( file ); + metadata = metadata.setFile(file); - MetadataRequest request = new MetadataRequest( metadata, repository, "" ); - List results = resolver.resolveMetadata( session, Arrays.asList( request ) ); + MetadataRequest request = new MetadataRequest(metadata, repository, ""); + List results = resolver.resolveMetadata(session, Arrays.asList(request)); - assertEquals( 1, results.size() ); - MetadataResult result = results.get( 0 ); - assertSame( request, result.getRequest() ); - assertNull( String.valueOf( result.getException() ), result.getException() ); - assertNotNull( result.getMetadata() ); - assertNotNull( result.getMetadata().getFile() ); + assertEquals(1, results.size()); + MetadataResult result = results.get(0); + assertSame(request, result.getRequest()); + assertNull(String.valueOf(result.getException()), result.getException()); + assertNotNull(result.getMetadata()); + assertNotNull(result.getMetadata().getFile()); - assertEquals( file, result.getMetadata().getFile() ); - assertEquals( metadata.setFile( null ), result.getMetadata().setFile( null ) ); + assertEquals(file, result.getMetadata().getFile()); + assertEquals(metadata.setFile(null), result.getMetadata().setFile(null)); connector.assertSeenExpected(); } @Test - public void testFavorLocal() - throws IOException - { - lrm.add( session, new LocalMetadataRegistration( metadata ) ); - String path = session.getLocalRepositoryManager().getPathForLocalMetadata( metadata ); - File file = new File( session.getLocalRepository().getBasedir(), path ); - TestFileUtils.writeString( file, file.getAbsolutePath() ); + public void testFavorLocal() throws IOException { + lrm.add(session, new LocalMetadataRegistration(metadata)); + String path = session.getLocalRepositoryManager().getPathForLocalMetadata(metadata); + File file = new File(session.getLocalRepository().getBasedir(), path); + TestFileUtils.writeString(file, file.getAbsolutePath()); - MetadataRequest request = new MetadataRequest( metadata, repository, "" ); - request.setFavorLocalRepository( true ); - resolver.setUpdateCheckManager( new StaticUpdateCheckManager( true, true ) ); + MetadataRequest request = new MetadataRequest(metadata, repository, ""); + request.setFavorLocalRepository(true); + resolver.setUpdateCheckManager(new StaticUpdateCheckManager(true, true)); - List results = resolver.resolveMetadata( session, Arrays.asList( request ) ); + List results = resolver.resolveMetadata(session, Arrays.asList(request)); - assertEquals( 1, results.size() ); - MetadataResult result = results.get( 0 ); - assertSame( request, result.getRequest() ); - assertNull( String.valueOf( result.getException() ), result.getException() ); + assertEquals(1, results.size()); + MetadataResult result = results.get(0); + assertSame(request, result.getRequest()); + assertNull(String.valueOf(result.getException()), result.getException()); connector.assertSeenExpected(); } @Test - public void testResolveAlwaysAcceptFilter() - throws IOException - { - remoteRepositoryFilterSources.put( "filter1", Filters.neverAcceptFrom("invalid repo id") ); - remoteRepositoryFilterSources.put( "filter2", Filters.alwaysAccept() ); - connector.setExpectGet( metadata ); + public void testResolveAlwaysAcceptFilter() throws IOException { + remoteRepositoryFilterSources.put("filter1", Filters.neverAcceptFrom("invalid repo id")); + remoteRepositoryFilterSources.put("filter2", Filters.alwaysAccept()); + connector.setExpectGet(metadata); // prepare "download" - File file = - new File( session.getLocalRepository().getBasedir(), - session.getLocalRepositoryManager().getPathForRemoteMetadata( metadata, repository, "" ) ); + File file = new File( + session.getLocalRepository().getBasedir(), + session.getLocalRepositoryManager().getPathForRemoteMetadata(metadata, repository, "")); - TestFileUtils.writeString( file, file.getAbsolutePath() ); + TestFileUtils.writeString(file, file.getAbsolutePath()); - MetadataRequest request = new MetadataRequest( metadata, repository, "" ); - List results = resolver.resolveMetadata( session, Arrays.asList( request ) ); + MetadataRequest request = new MetadataRequest(metadata, repository, ""); + List results = resolver.resolveMetadata(session, Arrays.asList(request)); - assertEquals( 1, results.size() ); + assertEquals(1, results.size()); - MetadataResult result = results.get( 0 ); - assertSame( request, result.getRequest() ); - assertNull( result.getException() ); - assertNotNull( result.getMetadata() ); - assertNotNull( result.getMetadata().getFile() ); + MetadataResult result = results.get(0); + assertSame(request, result.getRequest()); + assertNull(result.getException()); + assertNotNull(result.getMetadata()); + assertNotNull(result.getMetadata().getFile()); - assertEquals( file, result.getMetadata().getFile() ); - assertEquals( metadata, result.getMetadata().setFile( null ) ); + assertEquals(file, result.getMetadata().getFile()); + assertEquals(metadata, result.getMetadata().setFile(null)); connector.assertSeenExpected(); Set metadataRegistration = - ( (TestLocalRepositoryManager) session.getLocalRepositoryManager() ).getMetadataRegistration(); - assertTrue( metadataRegistration.contains( metadata ) ); - assertEquals( 1, metadataRegistration.size() ); + ((TestLocalRepositoryManager) session.getLocalRepositoryManager()).getMetadataRegistration(); + assertTrue(metadataRegistration.contains(metadata)); + assertEquals(1, metadataRegistration.size()); } @Test - public void testResolveNeverAcceptFilter() - throws IOException - { - remoteRepositoryFilterSources.put( "filter1", Filters.neverAcceptFrom("invalid repo id") ); - remoteRepositoryFilterSources.put( "filter2", Filters.neverAccept() ); + public void testResolveNeverAcceptFilter() throws IOException { + remoteRepositoryFilterSources.put("filter1", Filters.neverAcceptFrom("invalid repo id")); + remoteRepositoryFilterSources.put("filter2", Filters.neverAccept()); // connector.setExpectGet( metadata ); // should not see it // prepare "download" - File file = - new File( session.getLocalRepository().getBasedir(), - session.getLocalRepositoryManager().getPathForRemoteMetadata( metadata, repository, "" ) ); + File file = new File( + session.getLocalRepository().getBasedir(), + session.getLocalRepositoryManager().getPathForRemoteMetadata(metadata, repository, "")); - TestFileUtils.writeString( file, file.getAbsolutePath() ); + TestFileUtils.writeString(file, file.getAbsolutePath()); - MetadataRequest request = new MetadataRequest( metadata, repository, "" ); - List results = resolver.resolveMetadata( session, Arrays.asList( request ) ); + MetadataRequest request = new MetadataRequest(metadata, repository, ""); + List results = resolver.resolveMetadata(session, Arrays.asList(request)); - assertEquals( 1, results.size() ); + assertEquals(1, results.size()); - MetadataResult result = results.get( 0 ); - assertSame( request, result.getRequest() ); - assertNotNull( result.getException() ); - assertTrue( result.getException() instanceof MetadataNotFoundException ); - assertEquals( "never-accept", result.getException().getMessage() ); - assertNull( result.getMetadata() ); + MetadataResult result = results.get(0); + assertSame(request, result.getRequest()); + assertNotNull(result.getException()); + assertTrue(result.getException() instanceof MetadataNotFoundException); + assertEquals("never-accept", result.getException().getMessage()); + assertNull(result.getMetadata()); connector.assertSeenExpected(); } @Test - public void testResolveAlwaysAcceptFromRepoFilter() - throws IOException - { - remoteRepositoryFilterSources.put( "filter1", Filters.alwaysAcceptFrom( repository.getId() ) ); - connector.setExpectGet( metadata ); + public void testResolveAlwaysAcceptFromRepoFilter() throws IOException { + remoteRepositoryFilterSources.put("filter1", Filters.alwaysAcceptFrom(repository.getId())); + connector.setExpectGet(metadata); // prepare "download" - File file = - new File( session.getLocalRepository().getBasedir(), - session.getLocalRepositoryManager().getPathForRemoteMetadata( metadata, repository, "" ) ); + File file = new File( + session.getLocalRepository().getBasedir(), + session.getLocalRepositoryManager().getPathForRemoteMetadata(metadata, repository, "")); - TestFileUtils.writeString( file, file.getAbsolutePath() ); + TestFileUtils.writeString(file, file.getAbsolutePath()); - MetadataRequest request = new MetadataRequest( metadata, repository, "" ); - List results = resolver.resolveMetadata( session, Arrays.asList( request ) ); + MetadataRequest request = new MetadataRequest(metadata, repository, ""); + List results = resolver.resolveMetadata(session, Arrays.asList(request)); - assertEquals( 1, results.size() ); + assertEquals(1, results.size()); - MetadataResult result = results.get( 0 ); - assertSame( request, result.getRequest() ); - assertNull( result.getException() ); - assertNotNull( result.getMetadata() ); - assertNotNull( result.getMetadata().getFile() ); + MetadataResult result = results.get(0); + assertSame(request, result.getRequest()); + assertNull(result.getException()); + assertNotNull(result.getMetadata()); + assertNotNull(result.getMetadata().getFile()); - assertEquals( file, result.getMetadata().getFile() ); - assertEquals( metadata, result.getMetadata().setFile( null ) ); + assertEquals(file, result.getMetadata().getFile()); + assertEquals(metadata, result.getMetadata().setFile(null)); connector.assertSeenExpected(); Set metadataRegistration = - ( (TestLocalRepositoryManager) session.getLocalRepositoryManager() ).getMetadataRegistration(); - assertTrue( metadataRegistration.contains( metadata ) ); - assertEquals( 1, metadataRegistration.size() ); + ((TestLocalRepositoryManager) session.getLocalRepositoryManager()).getMetadataRegistration(); + assertTrue(metadataRegistration.contains(metadata)); + assertEquals(1, metadataRegistration.size()); } @Test - public void testResolveNeverAcceptFromRepoFilter() - throws IOException - { - remoteRepositoryFilterSources.put( "filter1", Filters.neverAcceptFrom( repository.getId() ) ); + public void testResolveNeverAcceptFromRepoFilter() throws IOException { + remoteRepositoryFilterSources.put("filter1", Filters.neverAcceptFrom(repository.getId())); // connector.setExpectGet( metadata ); // should not see it // prepare "download" - File file = - new File( session.getLocalRepository().getBasedir(), - session.getLocalRepositoryManager().getPathForRemoteMetadata( metadata, repository, "" ) ); + File file = new File( + session.getLocalRepository().getBasedir(), + session.getLocalRepositoryManager().getPathForRemoteMetadata(metadata, repository, "")); - TestFileUtils.writeString( file, file.getAbsolutePath() ); + TestFileUtils.writeString(file, file.getAbsolutePath()); - MetadataRequest request = new MetadataRequest( metadata, repository, "" ); - List results = resolver.resolveMetadata( session, Arrays.asList( request ) ); + MetadataRequest request = new MetadataRequest(metadata, repository, ""); + List results = resolver.resolveMetadata(session, Arrays.asList(request)); - assertEquals( 1, results.size() ); + assertEquals(1, results.size()); - MetadataResult result = results.get( 0 ); - assertSame( request, result.getRequest() ); - assertNotNull( result.getException() ); - assertTrue( result.getException() instanceof MetadataNotFoundException ); - assertEquals( "never-accept-" + repository.getId(), result.getException().getMessage() ); - assertNull( result.getMetadata() ); + MetadataResult result = results.get(0); + assertSame(request, result.getRequest()); + assertNotNull(result.getException()); + assertTrue(result.getException() instanceof MetadataNotFoundException); + assertEquals("never-accept-" + repository.getId(), result.getException().getMessage()); + assertNull(result.getMetadata()); connector.assertSeenExpected(); } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultOfflineControllerTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultOfflineControllerTest.java index 7e427075c..9079f64f5 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultOfflineControllerTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultOfflineControllerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystemSession; @@ -26,77 +25,60 @@ import org.junit.Before; import org.junit.Test; -public class DefaultOfflineControllerTest -{ +public class DefaultOfflineControllerTest { private DefaultOfflineController controller; - private RepositorySystemSession newSession( boolean offline, String protocols, String hosts ) - { + private RepositorySystemSession newSession(boolean offline, String protocols, String hosts) { DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(); - session.setOffline( offline ); - session.setConfigProperty( DefaultOfflineController.CONFIG_PROP_OFFLINE_PROTOCOLS, protocols ); - session.setConfigProperty( DefaultOfflineController.CONFIG_PROP_OFFLINE_HOSTS, hosts ); + session.setOffline(offline); + session.setConfigProperty(DefaultOfflineController.CONFIG_PROP_OFFLINE_PROTOCOLS, protocols); + session.setConfigProperty(DefaultOfflineController.CONFIG_PROP_OFFLINE_HOSTS, hosts); return session; } - private RemoteRepository newRepo( String url ) - { - return new RemoteRepository.Builder( "central", "default", url ).build(); + private RemoteRepository newRepo(String url) { + return new RemoteRepository.Builder("central", "default", url).build(); } @Before - public void setup() - { + public void setup() { controller = new DefaultOfflineController(); } - @Test( expected = RepositoryOfflineException.class ) - public void testCheckOffline_Online() - throws Exception - { - controller.checkOffline( newSession( false, null, null ), newRepo( "http://eclipse.org" ) ); + @Test(expected = RepositoryOfflineException.class) + public void testCheckOffline_Online() throws Exception { + controller.checkOffline(newSession(false, null, null), newRepo("http://eclipse.org")); } - @Test( expected = RepositoryOfflineException.class ) - public void testCheckOffline_Offline() - throws Exception - { - controller.checkOffline( newSession( true, null, null ), newRepo( "http://eclipse.org" ) ); + @Test(expected = RepositoryOfflineException.class) + public void testCheckOffline_Offline() throws Exception { + controller.checkOffline(newSession(true, null, null), newRepo("http://eclipse.org")); } @Test - public void testCheckOffline_Offline_OfflineProtocol() - throws Exception - { - controller.checkOffline( newSession( true, "file", null ), newRepo( "file://repo" ) ); - controller.checkOffline( newSession( true, "file", null ), newRepo( "FILE://repo" ) ); - controller.checkOffline( newSession( true, " file , classpath ", null ), newRepo( "file://repo" ) ); - controller.checkOffline( newSession( true, " file , classpath ", null ), newRepo( "classpath://repo" ) ); + public void testCheckOffline_Offline_OfflineProtocol() throws Exception { + controller.checkOffline(newSession(true, "file", null), newRepo("file://repo")); + controller.checkOffline(newSession(true, "file", null), newRepo("FILE://repo")); + controller.checkOffline(newSession(true, " file , classpath ", null), newRepo("file://repo")); + controller.checkOffline(newSession(true, " file , classpath ", null), newRepo("classpath://repo")); } - @Test( expected = RepositoryOfflineException.class ) - public void testCheckOffline_Offline_OnlineProtocol() - throws Exception - { - controller.checkOffline( newSession( true, "file", null ), newRepo( "http://eclipse.org" ) ); + @Test(expected = RepositoryOfflineException.class) + public void testCheckOffline_Offline_OnlineProtocol() throws Exception { + controller.checkOffline(newSession(true, "file", null), newRepo("http://eclipse.org")); } @Test - public void testCheckOffline_Offline_OfflineHost() - throws Exception - { - controller.checkOffline( newSession( true, null, "localhost" ), newRepo( "http://localhost" ) ); - controller.checkOffline( newSession( true, null, "localhost" ), newRepo( "http://LOCALHOST" ) ); - controller.checkOffline( newSession( true, null, " localhost , 127.0.0.1 " ), newRepo( "http://localhost" ) ); - controller.checkOffline( newSession( true, null, " localhost , 127.0.0.1 " ), newRepo( "http://127.0.0.1" ) ); + public void testCheckOffline_Offline_OfflineHost() throws Exception { + controller.checkOffline(newSession(true, null, "localhost"), newRepo("http://localhost")); + controller.checkOffline(newSession(true, null, "localhost"), newRepo("http://LOCALHOST")); + controller.checkOffline(newSession(true, null, " localhost , 127.0.0.1 "), newRepo("http://localhost")); + controller.checkOffline(newSession(true, null, " localhost , 127.0.0.1 "), newRepo("http://127.0.0.1")); } - @Test( expected = RepositoryOfflineException.class ) - public void testCheckOffline_Offline_OnlineHost() - throws Exception - { - controller.checkOffline( newSession( true, null, "localhost" ), newRepo( "http://eclipse.org" ) ); + @Test(expected = RepositoryOfflineException.class) + public void testCheckOffline_Offline_OnlineHost() throws Exception { + controller.checkOffline(newSession(true, null, "localhost"), newRepo("http://eclipse.org")); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRemoteRepositoryManagerTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRemoteRepositoryManagerTest.java index 3700aa4b9..e788d5182 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRemoteRepositoryManagerTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRemoteRepositoryManagerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Objects.requireNonNull; -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.util.Arrays; import java.util.Collections; @@ -40,267 +36,238 @@ import org.junit.Before; import org.junit.Test; +import static java.util.Objects.requireNonNull; +import static org.junit.Assert.*; + /** - * + * */ -public class DefaultRemoteRepositoryManagerTest -{ +public class DefaultRemoteRepositoryManagerTest { private DefaultRepositorySystemSession session; private DefaultRemoteRepositoryManager manager; @Before - public void setup() - { + public void setup() { session = TestUtils.newSession(); - session.setChecksumPolicy( null ); - session.setUpdatePolicy( null ); + session.setChecksumPolicy(null); + session.setUpdatePolicy(null); manager = new DefaultRemoteRepositoryManager(); - manager.setUpdatePolicyAnalyzer( new StubUpdatePolicyAnalyzer() ); - manager.setChecksumPolicyProvider( new DefaultChecksumPolicyProvider() ); + manager.setUpdatePolicyAnalyzer(new StubUpdatePolicyAnalyzer()); + manager.setChecksumPolicyProvider(new DefaultChecksumPolicyProvider()); } @After - public void teardown() - { + public void teardown() { manager = null; session = null; } - private RemoteRepository.Builder newRepo( String id, String url, boolean enabled, String updates, String checksums ) - { - RepositoryPolicy policy = new RepositoryPolicy( enabled, updates, checksums ); - return new RemoteRepository.Builder( id, "test", url ).setPolicy( policy ); + private RemoteRepository.Builder newRepo(String id, String url, boolean enabled, String updates, String checksums) { + RepositoryPolicy policy = new RepositoryPolicy(enabled, updates, checksums); + return new RemoteRepository.Builder(id, "test", url).setPolicy(policy); } - private void assertEqual( RemoteRepository expected, RemoteRepository actual ) - { - assertEquals( "id", expected.getId(), actual.getId() ); - assertEquals( "url", expected.getUrl(), actual.getUrl() ); - assertEquals( "type", expected.getContentType(), actual.getContentType() ); - assertEqual( expected.getPolicy( false ), actual.getPolicy( false ) ); - assertEqual( expected.getPolicy( true ), actual.getPolicy( true ) ); + private void assertEqual(RemoteRepository expected, RemoteRepository actual) { + assertEquals("id", expected.getId(), actual.getId()); + assertEquals("url", expected.getUrl(), actual.getUrl()); + assertEquals("type", expected.getContentType(), actual.getContentType()); + assertEqual(expected.getPolicy(false), actual.getPolicy(false)); + assertEqual(expected.getPolicy(true), actual.getPolicy(true)); } - private void assertEqual( RepositoryPolicy expected, RepositoryPolicy actual ) - { - assertEquals( "enabled", expected.isEnabled(), actual.isEnabled() ); - assertEquals( "checksums", expected.getChecksumPolicy(), actual.getChecksumPolicy() ); - assertEquals( "updates", expected.getUpdatePolicy(), actual.getUpdatePolicy() ); + private void assertEqual(RepositoryPolicy expected, RepositoryPolicy actual) { + assertEquals("enabled", expected.isEnabled(), actual.isEnabled()); + assertEquals("checksums", expected.getChecksumPolicy(), actual.getChecksumPolicy()); + assertEquals("updates", expected.getUpdatePolicy(), actual.getUpdatePolicy()); } @Test - public void testGetPolicy() - { - RepositoryPolicy snapshotPolicy = - new RepositoryPolicy( true, RepositoryPolicy.UPDATE_POLICY_ALWAYS, RepositoryPolicy.CHECKSUM_POLICY_IGNORE ); + public void testGetPolicy() { + RepositoryPolicy snapshotPolicy = new RepositoryPolicy( + true, RepositoryPolicy.UPDATE_POLICY_ALWAYS, RepositoryPolicy.CHECKSUM_POLICY_IGNORE); RepositoryPolicy releasePolicy = - new RepositoryPolicy( true, RepositoryPolicy.UPDATE_POLICY_NEVER, RepositoryPolicy.CHECKSUM_POLICY_FAIL ); + new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_NEVER, RepositoryPolicy.CHECKSUM_POLICY_FAIL); - RemoteRepository repo = new RemoteRepository.Builder( "id", "type", "http://localhost" ) // - .setSnapshotPolicy( snapshotPolicy ).setReleasePolicy( releasePolicy ).build(); + RemoteRepository repo = new RemoteRepository.Builder("id", "type", "http://localhost") // + .setSnapshotPolicy(snapshotPolicy) + .setReleasePolicy(releasePolicy) + .build(); - RepositoryPolicy effectivePolicy = manager.getPolicy( session, repo, true, true ); - assertTrue( effectivePolicy.isEnabled() ); - assertEquals( RepositoryPolicy.CHECKSUM_POLICY_IGNORE, effectivePolicy.getChecksumPolicy() ); - assertEquals( RepositoryPolicy.UPDATE_POLICY_ALWAYS, effectivePolicy.getUpdatePolicy() ); + RepositoryPolicy effectivePolicy = manager.getPolicy(session, repo, true, true); + assertTrue(effectivePolicy.isEnabled()); + assertEquals(RepositoryPolicy.CHECKSUM_POLICY_IGNORE, effectivePolicy.getChecksumPolicy()); + assertEquals(RepositoryPolicy.UPDATE_POLICY_ALWAYS, effectivePolicy.getUpdatePolicy()); } @Test - public void testAggregateSimpleRepos() - { - RemoteRepository dominant1 = newRepo( "a", "file://", false, "", "" ).build(); + public void testAggregateSimpleRepos() { + RemoteRepository dominant1 = newRepo("a", "file://", false, "", "").build(); - RemoteRepository recessive1 = newRepo( "a", "http://", true, "", "" ).build(); - RemoteRepository recessive2 = newRepo( "b", "file://", true, "", "" ).build(); + RemoteRepository recessive1 = newRepo("a", "http://", true, "", "").build(); + RemoteRepository recessive2 = newRepo("b", "file://", true, "", "").build(); - List result = - manager.aggregateRepositories( session, Arrays.asList( dominant1 ), - Arrays.asList( recessive1, recessive2 ), false ); + List result = manager.aggregateRepositories( + session, Arrays.asList(dominant1), Arrays.asList(recessive1, recessive2), false); - assertEquals( 2, result.size() ); - assertEqual( dominant1, result.get( 0 ) ); - assertEqual( recessive2, result.get( 1 ) ); + assertEquals(2, result.size()); + assertEqual(dominant1, result.get(0)); + assertEqual(recessive2, result.get(1)); } @Test - public void testAggregateSimpleRepos_MustKeepDisabledRecessiveRepo() - { - RemoteRepository dominant = newRepo( "a", "file://", true, "", "" ).build(); + public void testAggregateSimpleRepos_MustKeepDisabledRecessiveRepo() { + RemoteRepository dominant = newRepo("a", "file://", true, "", "").build(); - RemoteRepository recessive1 = newRepo( "b", "http://", false, "", "" ).build(); + RemoteRepository recessive1 = newRepo("b", "http://", false, "", "").build(); List result = - manager.aggregateRepositories( session, Arrays.asList( dominant ), Arrays.asList( recessive1 ), false ); + manager.aggregateRepositories(session, Arrays.asList(dominant), Arrays.asList(recessive1), false); - RemoteRepository recessive2 = newRepo( recessive1.getId(), "http://", true, "", "" ).build(); + RemoteRepository recessive2 = + newRepo(recessive1.getId(), "http://", true, "", "").build(); - result = manager.aggregateRepositories( session, result, Arrays.asList( recessive2 ), false ); + result = manager.aggregateRepositories(session, result, Arrays.asList(recessive2), false); - assertEquals( 2, result.size() ); - assertEqual( dominant, result.get( 0 ) ); - assertEqual( recessive1, result.get( 1 ) ); + assertEquals(2, result.size()); + assertEqual(dominant, result.get(0)); + assertEqual(recessive1, result.get(1)); } @Test - public void testAggregateMirrorRepos_DominantMirrorComplete() - { - RemoteRepository dominant1 = newRepo( "a", "http://", false, "", "" ).build(); - RemoteRepository dominantMirror1 = - newRepo( "x", "file://", false, "", "" ).addMirroredRepository( dominant1 ).build(); - - RemoteRepository recessive1 = newRepo( "a", "https://", true, "", "" ).build(); - RemoteRepository recessiveMirror1 = - newRepo( "x", "http://", true, "", "" ).addMirroredRepository( recessive1 ).build(); - - List result = - manager.aggregateRepositories( session, Arrays.asList( dominantMirror1 ), - Arrays.asList( recessiveMirror1 ), false ); - - assertEquals( 1, result.size() ); - assertEqual( dominantMirror1, result.get( 0 ) ); - assertEquals( 1, result.get( 0 ).getMirroredRepositories().size() ); - assertEquals( dominant1, result.get( 0 ).getMirroredRepositories().get( 0 ) ); + public void testAggregateMirrorRepos_DominantMirrorComplete() { + RemoteRepository dominant1 = newRepo("a", "http://", false, "", "").build(); + RemoteRepository dominantMirror1 = newRepo("x", "file://", false, "", "") + .addMirroredRepository(dominant1) + .build(); + + RemoteRepository recessive1 = newRepo("a", "https://", true, "", "").build(); + RemoteRepository recessiveMirror1 = newRepo("x", "http://", true, "", "") + .addMirroredRepository(recessive1) + .build(); + + List result = manager.aggregateRepositories( + session, Arrays.asList(dominantMirror1), Arrays.asList(recessiveMirror1), false); + + assertEquals(1, result.size()); + assertEqual(dominantMirror1, result.get(0)); + assertEquals(1, result.get(0).getMirroredRepositories().size()); + assertEquals(dominant1, result.get(0).getMirroredRepositories().get(0)); } @Test - public void testAggregateMirrorRepos_DominantMirrorIncomplete() - { - RemoteRepository dominant1 = newRepo( "a", "http://", false, "", "" ).build(); - RemoteRepository dominantMirror1 = - newRepo( "x", "file://", false, "", "" ).addMirroredRepository( dominant1 ).build(); - - RemoteRepository recessive1 = newRepo( "a", "https://", true, "", "" ).build(); - RemoteRepository recessive2 = newRepo( "b", "https://", true, "", "" ).build(); - RemoteRepository recessiveMirror1 = - newRepo( "x", "http://", true, "", "" ).setMirroredRepositories( Arrays.asList( recessive1, recessive2 ) ).build(); - - List result = - manager.aggregateRepositories( session, Arrays.asList( dominantMirror1 ), - Arrays.asList( recessiveMirror1 ), false ); - - assertEquals( 1, result.size() ); - assertEqual( newRepo( "x", "file://", true, "", "" ).build(), result.get( 0 ) ); - assertEquals( 2, result.get( 0 ).getMirroredRepositories().size() ); - assertEquals( dominant1, result.get( 0 ).getMirroredRepositories().get( 0 ) ); - assertEquals( recessive2, result.get( 0 ).getMirroredRepositories().get( 1 ) ); + public void testAggregateMirrorRepos_DominantMirrorIncomplete() { + RemoteRepository dominant1 = newRepo("a", "http://", false, "", "").build(); + RemoteRepository dominantMirror1 = newRepo("x", "file://", false, "", "") + .addMirroredRepository(dominant1) + .build(); + + RemoteRepository recessive1 = newRepo("a", "https://", true, "", "").build(); + RemoteRepository recessive2 = newRepo("b", "https://", true, "", "").build(); + RemoteRepository recessiveMirror1 = newRepo("x", "http://", true, "", "") + .setMirroredRepositories(Arrays.asList(recessive1, recessive2)) + .build(); + + List result = manager.aggregateRepositories( + session, Arrays.asList(dominantMirror1), Arrays.asList(recessiveMirror1), false); + + assertEquals(1, result.size()); + assertEqual(newRepo("x", "file://", true, "", "").build(), result.get(0)); + assertEquals(2, result.get(0).getMirroredRepositories().size()); + assertEquals(dominant1, result.get(0).getMirroredRepositories().get(0)); + assertEquals(recessive2, result.get(0).getMirroredRepositories().get(1)); } @Test - public void testMirrorAuthentication() - { - final RemoteRepository repo = newRepo( "a", "http://", true, "", "" ).build(); - final RemoteRepository mirror = - newRepo( "a", "http://", true, "", "" ).setAuthentication( new AuthenticationBuilder().addUsername( "test" ).build() ).build(); - session.setMirrorSelector( new MirrorSelector() - { - public RemoteRepository getMirror( RemoteRepository repository ) - { + public void testMirrorAuthentication() { + final RemoteRepository repo = newRepo("a", "http://", true, "", "").build(); + final RemoteRepository mirror = newRepo("a", "http://", true, "", "") + .setAuthentication( + new AuthenticationBuilder().addUsername("test").build()) + .build(); + session.setMirrorSelector(new MirrorSelector() { + public RemoteRepository getMirror(RemoteRepository repository) { return mirror; } - } ); + }); - List result = - manager.aggregateRepositories( session, Collections. emptyList(), Arrays.asList( repo ), - true ); + List result = manager.aggregateRepositories( + session, Collections.emptyList(), Arrays.asList(repo), true); - assertEquals( 1, result.size() ); - assertSame( mirror.getAuthentication(), result.get( 0 ).getAuthentication() ); + assertEquals(1, result.size()); + assertSame(mirror.getAuthentication(), result.get(0).getAuthentication()); } @Test - public void testMirrorProxy() - { - final RemoteRepository repo = newRepo( "a", "http://", true, "", "" ).build(); - final RemoteRepository mirror = - newRepo( "a", "http://", true, "", "" ).setProxy( new Proxy( "http", "host", 2011, null ) ).build(); - session.setMirrorSelector( new MirrorSelector() - { - public RemoteRepository getMirror( RemoteRepository repository ) - { + public void testMirrorProxy() { + final RemoteRepository repo = newRepo("a", "http://", true, "", "").build(); + final RemoteRepository mirror = newRepo("a", "http://", true, "", "") + .setProxy(new Proxy("http", "host", 2011, null)) + .build(); + session.setMirrorSelector(new MirrorSelector() { + public RemoteRepository getMirror(RemoteRepository repository) { return mirror; } - } ); + }); - List result = - manager.aggregateRepositories( session, Collections. emptyList(), Arrays.asList( repo ), - true ); + List result = manager.aggregateRepositories( + session, Collections.emptyList(), Arrays.asList(repo), true); - assertEquals( 1, result.size() ); - assertEquals( "http", result.get( 0 ).getProxy().getType() ); - assertEquals( "host", result.get( 0 ).getProxy().getHost() ); - assertEquals( 2011, result.get( 0 ).getProxy().getPort() ); + assertEquals(1, result.size()); + assertEquals("http", result.get(0).getProxy().getType()); + assertEquals("host", result.get(0).getProxy().getHost()); + assertEquals(2011, result.get(0).getProxy().getPort()); } @Test - public void testProxySelector() - { - final RemoteRepository repo = newRepo( "a", "http://", true, "", "" ).build(); - final Proxy proxy = new Proxy( "http", "host", 2011, null ); - session.setProxySelector( new ProxySelector() - { - public Proxy getProxy( RemoteRepository repository ) - { + public void testProxySelector() { + final RemoteRepository repo = newRepo("a", "http://", true, "", "").build(); + final Proxy proxy = new Proxy("http", "host", 2011, null); + session.setProxySelector(new ProxySelector() { + public Proxy getProxy(RemoteRepository repository) { return proxy; } - } ); - session.setMirrorSelector( new MirrorSelector() - { - public RemoteRepository getMirror( RemoteRepository repository ) - { + }); + session.setMirrorSelector(new MirrorSelector() { + public RemoteRepository getMirror(RemoteRepository repository) { return null; } - } ); + }); - List result = - manager.aggregateRepositories( session, Collections. emptyList(), Arrays.asList( repo ), - true ); + List result = manager.aggregateRepositories( + session, Collections.emptyList(), Arrays.asList(repo), true); - assertEquals( 1, result.size() ); - assertEquals( "http", result.get( 0 ).getProxy().getType() ); - assertEquals( "host", result.get( 0 ).getProxy().getHost() ); - assertEquals( 2011, result.get( 0 ).getProxy().getPort() ); + assertEquals(1, result.size()); + assertEquals("http", result.get(0).getProxy().getType()); + assertEquals("host", result.get(0).getProxy().getHost()); + assertEquals(2011, result.get(0).getProxy().getPort()); } - private static class StubUpdatePolicyAnalyzer - implements UpdatePolicyAnalyzer - { + private static class StubUpdatePolicyAnalyzer implements UpdatePolicyAnalyzer { - public String getEffectiveUpdatePolicy( RepositorySystemSession session, String policy1, String policy2 ) - { - requireNonNull( session, "session cannot be null" ); - return ordinalOfUpdatePolicy( policy1 ) < ordinalOfUpdatePolicy( policy2 ) ? policy1 : policy2; + public String getEffectiveUpdatePolicy(RepositorySystemSession session, String policy1, String policy2) { + requireNonNull(session, "session cannot be null"); + return ordinalOfUpdatePolicy(policy1) < ordinalOfUpdatePolicy(policy2) ? policy1 : policy2; } - private int ordinalOfUpdatePolicy( String policy ) - { - if ( RepositoryPolicy.UPDATE_POLICY_DAILY.equals( policy ) ) - { + private int ordinalOfUpdatePolicy(String policy) { + if (RepositoryPolicy.UPDATE_POLICY_DAILY.equals(policy)) { return 1440; - } - else if ( RepositoryPolicy.UPDATE_POLICY_ALWAYS.equals( policy ) ) - { + } else if (RepositoryPolicy.UPDATE_POLICY_ALWAYS.equals(policy)) { return 0; - } - else if ( policy != null && policy.startsWith( RepositoryPolicy.UPDATE_POLICY_INTERVAL ) ) - { - String s = policy.substring( RepositoryPolicy.UPDATE_POLICY_INTERVAL.length() + 1 ); - return Integer.parseInt( s ); - } - else - { + } else if (policy != null && policy.startsWith(RepositoryPolicy.UPDATE_POLICY_INTERVAL)) { + String s = policy.substring(RepositoryPolicy.UPDATE_POLICY_INTERVAL.length() + 1); + return Integer.parseInt(s); + } else { // assume "never" return Integer.MAX_VALUE; } } - public boolean isUpdatedRequired( RepositorySystemSession session, long lastModified, String policy ) - { - requireNonNull( session, "session cannot be null" ); + public boolean isUpdatedRequired(RepositorySystemSession session, long lastModified, String policy) { + requireNonNull(session, "session cannot be null"); return false; } - } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRepositoryEventDispatcherTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRepositoryEventDispatcherTest.java index 14b165804..89bd757af 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRepositoryEventDispatcherTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRepositoryEventDispatcherTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -29,60 +26,53 @@ import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositoryEvent; import org.eclipse.aether.RepositoryListener; -import org.eclipse.aether.internal.impl.DefaultRepositoryEventDispatcher; import org.eclipse.aether.internal.test.util.TestUtils; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DefaultRepositoryEventDispatcherTest -{ +public class DefaultRepositoryEventDispatcherTest { @Test - public void testDispatchHandlesAllEventTypes() - { + public void testDispatchHandlesAllEventTypes() { DefaultRepositoryEventDispatcher dispatcher = new DefaultRepositoryEventDispatcher(); ListenerHandler handler = new ListenerHandler(); - RepositoryListener listener = - (RepositoryListener) Proxy.newProxyInstance( getClass().getClassLoader(), - new Class[] { RepositoryListener.class }, handler ); + RepositoryListener listener = (RepositoryListener) + Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] {RepositoryListener.class}, handler); DefaultRepositorySystemSession session = TestUtils.newSession(); - session.setRepositoryListener( listener ); + session.setRepositoryListener(listener); - for ( RepositoryEvent.EventType type : RepositoryEvent.EventType.values() ) - { - RepositoryEvent event = new RepositoryEvent.Builder( session, type ).build(); + for (RepositoryEvent.EventType type : RepositoryEvent.EventType.values()) { + RepositoryEvent event = new RepositoryEvent.Builder(session, type).build(); handler.methodName = null; - dispatcher.dispatch( event ); + dispatcher.dispatch(event); - assertNotNull( "not handled: " + type, handler.methodName ); + assertNotNull("not handled: " + type, handler.methodName); - assertEquals( "badly handled: " + type, type.name().replace( "_", "" ).toLowerCase( Locale.ENGLISH ), - handler.methodName.toLowerCase( Locale.ENGLISH ) ); + assertEquals( + "badly handled: " + type, + type.name().replace("_", "").toLowerCase(Locale.ENGLISH), + handler.methodName.toLowerCase(Locale.ENGLISH)); } } - static class ListenerHandler - implements InvocationHandler - { + static class ListenerHandler implements InvocationHandler { public String methodName; - public Object invoke( Object proxy, Method method, Object[] args ) - { - if ( args.length == 1 && args[0] instanceof RepositoryEvent ) - { + public Object invoke(Object proxy, Method method, Object[] args) { + if (args.length == 1 && args[0] instanceof RepositoryEvent) { methodName = method.getName(); } return null; } - } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRepositorySystemTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRepositorySystemTest.java index 65acfdb6f..0a6aacd95 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRepositorySystemTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultRepositorySystemTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.util.Arrays; import java.util.List; @@ -36,80 +33,77 @@ import org.junit.Before; import org.junit.Test; -public class DefaultRepositorySystemTest -{ +import static org.junit.Assert.*; + +public class DefaultRepositorySystemTest { private DefaultRepositorySystem system; private DefaultRepositorySystemSession session; @Before - public void init() - { + public void init() { DefaultRemoteRepositoryManager remoteRepoManager = new DefaultRemoteRepositoryManager(); system = new DefaultRepositorySystem(); - system.setRemoteRepositoryManager( remoteRepoManager ); + system.setRemoteRepositoryManager(remoteRepoManager); session = TestUtils.newSession(); } @Test - public void testNewResolutionRepositories() - { - Proxy proxy = new Proxy( "http", "localhost", 8080 ); + public void testNewResolutionRepositories() { + Proxy proxy = new Proxy("http", "localhost", 8080); DefaultProxySelector proxySelector = new DefaultProxySelector(); - proxySelector.add( proxy, null ); - session.setProxySelector( proxySelector ); + proxySelector.add(proxy, null); + session.setProxySelector(proxySelector); - Authentication auth = new AuthenticationBuilder().addUsername( "user" ).build(); + Authentication auth = new AuthenticationBuilder().addUsername("user").build(); DefaultAuthenticationSelector authSelector = new DefaultAuthenticationSelector(); - authSelector.add( "mirror", auth ); - authSelector.add( "test-2", auth ); - session.setAuthenticationSelector( authSelector ); + authSelector.add("mirror", auth); + authSelector.add("test-2", auth); + session.setAuthenticationSelector(authSelector); DefaultMirrorSelector mirrorSelector = new DefaultMirrorSelector(); - mirrorSelector.add( "mirror", "http:void", "default", false, "test-1", null ); - session.setMirrorSelector( mirrorSelector ); + mirrorSelector.add("mirror", "http:void", "default", false, "test-1", null); + session.setMirrorSelector(mirrorSelector); - RemoteRepository rawRepo1 = new RemoteRepository.Builder( "test-1", "default", "http://void" ).build(); - RemoteRepository rawRepo2 = new RemoteRepository.Builder( "test-2", "default", "http://null" ).build(); + RemoteRepository rawRepo1 = new RemoteRepository.Builder("test-1", "default", "http://void").build(); + RemoteRepository rawRepo2 = new RemoteRepository.Builder("test-2", "default", "http://null").build(); List resolveRepos = - system.newResolutionRepositories( session, Arrays.asList( rawRepo1, rawRepo2 ) ); - assertNotNull( resolveRepos ); - assertEquals( 2, resolveRepos.size() ); - RemoteRepository resolveRepo = resolveRepos.get( 0 ); - assertNotNull( resolveRepo ); - assertEquals( "mirror", resolveRepo.getId() ); - assertSame( proxy, resolveRepo.getProxy() ); - assertSame( auth, resolveRepo.getAuthentication() ); - resolveRepo = resolveRepos.get( 1 ); - assertNotNull( resolveRepo ); - assertEquals( "test-2", resolveRepo.getId() ); - assertSame( proxy, resolveRepo.getProxy() ); - assertSame( auth, resolveRepo.getAuthentication() ); + system.newResolutionRepositories(session, Arrays.asList(rawRepo1, rawRepo2)); + assertNotNull(resolveRepos); + assertEquals(2, resolveRepos.size()); + RemoteRepository resolveRepo = resolveRepos.get(0); + assertNotNull(resolveRepo); + assertEquals("mirror", resolveRepo.getId()); + assertSame(proxy, resolveRepo.getProxy()); + assertSame(auth, resolveRepo.getAuthentication()); + resolveRepo = resolveRepos.get(1); + assertNotNull(resolveRepo); + assertEquals("test-2", resolveRepo.getId()); + assertSame(proxy, resolveRepo.getProxy()); + assertSame(auth, resolveRepo.getAuthentication()); } @Test - public void testNewDeploymentRepository() - { - Proxy proxy = new Proxy( "http", "localhost", 8080 ); + public void testNewDeploymentRepository() { + Proxy proxy = new Proxy("http", "localhost", 8080); DefaultProxySelector proxySelector = new DefaultProxySelector(); - proxySelector.add( proxy, null ); - session.setProxySelector( proxySelector ); + proxySelector.add(proxy, null); + session.setProxySelector(proxySelector); - Authentication auth = new AuthenticationBuilder().addUsername( "user" ).build(); + Authentication auth = new AuthenticationBuilder().addUsername("user").build(); DefaultAuthenticationSelector authSelector = new DefaultAuthenticationSelector(); - authSelector.add( "test", auth ); - session.setAuthenticationSelector( authSelector ); + authSelector.add("test", auth); + session.setAuthenticationSelector(authSelector); DefaultMirrorSelector mirrorSelector = new DefaultMirrorSelector(); - mirrorSelector.add( "mirror", "file:void", "default", false, "*", null ); - session.setMirrorSelector( mirrorSelector ); - - RemoteRepository rawRepo = new RemoteRepository.Builder( "test", "default", "http://void" ).build(); - RemoteRepository deployRepo = system.newDeploymentRepository( session, rawRepo ); - assertNotNull( deployRepo ); - assertSame( proxy, deployRepo.getProxy() ); - assertSame( auth, deployRepo.getAuthentication() ); + mirrorSelector.add("mirror", "file:void", "default", false, "*", null); + session.setMirrorSelector(mirrorSelector); + + RemoteRepository rawRepo = new RemoteRepository.Builder("test", "default", "http://void").build(); + RemoteRepository deployRepo = system.newDeploymentRepository(session, rawRepo); + assertNotNull(deployRepo); + assertSame(proxy, deployRepo.getProxy()); + assertSame(auth, deployRepo.getAuthentication()); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultTrackingFileManagerTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultTrackingFileManagerTest.java index e6e29672e..22fbea792 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultTrackingFileManagerTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultTrackingFileManagerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.io.File; import java.nio.charset.StandardCharsets; @@ -27,87 +24,77 @@ import java.util.Map; import java.util.Properties; -import org.eclipse.aether.internal.impl.TrackingFileManager; import org.eclipse.aether.internal.test.util.TestFileUtils; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DefaultTrackingFileManagerTest -{ +public class DefaultTrackingFileManagerTest { @Test - public void testRead() - throws Exception - { + public void testRead() throws Exception { TrackingFileManager tfm = new DefaultTrackingFileManager(); - File propFile = TestFileUtils.createTempFile( "#COMMENT\nkey1=value1\nkey2 : value2" ); - Properties props = tfm.read( propFile ); + File propFile = TestFileUtils.createTempFile("#COMMENT\nkey1=value1\nkey2 : value2"); + Properties props = tfm.read(propFile); - assertNotNull( props ); - assertEquals( String.valueOf( props ), 2, props.size() ); - assertEquals( "value1", props.get( "key1" ) ); - assertEquals( "value2", props.get( "key2" ) ); + assertNotNull(props); + assertEquals(String.valueOf(props), 2, props.size()); + assertEquals("value1", props.get("key1")); + assertEquals("value2", props.get("key2")); - assertTrue( "Leaked file: " + propFile, propFile.delete() ); + assertTrue("Leaked file: " + propFile, propFile.delete()); - props = tfm.read( propFile ); - assertNull( String.valueOf( props ), props ); + props = tfm.read(propFile); + assertNull(String.valueOf(props), props); } @Test - public void testReadNoFileLeak() - throws Exception - { + public void testReadNoFileLeak() throws Exception { TrackingFileManager tfm = new DefaultTrackingFileManager(); - for ( int i = 0; i < 1000; i++ ) - { - File propFile = TestFileUtils.createTempFile( "#COMMENT\nkey1=value1\nkey2 : value2" ); - assertNotNull( tfm.read( propFile ) ); - assertTrue( "Leaked file: " + propFile, propFile.delete() ); + for (int i = 0; i < 1000; i++) { + File propFile = TestFileUtils.createTempFile("#COMMENT\nkey1=value1\nkey2 : value2"); + assertNotNull(tfm.read(propFile)); + assertTrue("Leaked file: " + propFile, propFile.delete()); } } @Test - public void testUpdate() - throws Exception - { + public void testUpdate() throws Exception { TrackingFileManager tfm = new DefaultTrackingFileManager(); // NOTE: The excessive repetitions are to check the update properly truncates the file - File propFile = TestFileUtils.createTempFile( "key1=value1\nkey2 : value2\n".getBytes( StandardCharsets.UTF_8 ), 1000 ); + File propFile = + TestFileUtils.createTempFile("key1=value1\nkey2 : value2\n".getBytes(StandardCharsets.UTF_8), 1000); Map updates = new HashMap<>(); - updates.put( "key1", "v" ); - updates.put( "key2", null ); + updates.put("key1", "v"); + updates.put("key2", null); - tfm.update( propFile, updates ); + tfm.update(propFile, updates); - Properties props = tfm.read( propFile ); + Properties props = tfm.read(propFile); - assertNotNull( props ); - assertEquals( String.valueOf( props ), 1, props.size() ); - assertEquals( "v", props.get( "key1" ) ); - assertNull( String.valueOf( props.get( "key2" ) ), props.get( "key2" ) ); + assertNotNull(props); + assertEquals(String.valueOf(props), 1, props.size()); + assertEquals("v", props.get("key1")); + assertNull(String.valueOf(props.get("key2")), props.get("key2")); } @Test - public void testUpdateNoFileLeak() - throws Exception - { + public void testUpdateNoFileLeak() throws Exception { TrackingFileManager tfm = new DefaultTrackingFileManager(); Map updates = new HashMap<>(); - updates.put( "k", "v" ); + updates.put("k", "v"); - for ( int i = 0; i < 1000; i++ ) - { - File propFile = TestFileUtils.createTempFile( "#COMMENT\nkey1=value1\nkey2 : value2" ); - assertNotNull( tfm.update( propFile, updates ) ); - assertTrue( "Leaked file: " + propFile, propFile.delete() ); + for (int i = 0; i < 1000; i++) { + File propFile = TestFileUtils.createTempFile("#COMMENT\nkey1=value1\nkey2 : value2"); + assertNotNull(tfm.update(propFile, updates)); + assertTrue("Leaked file: " + propFile, propFile.delete()); } } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultUpdateCheckManagerTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultUpdateCheckManagerTest.java index a85f5b039..ab61d5754 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultUpdateCheckManagerTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultUpdateCheckManagerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.io.File; import java.net.URI; @@ -32,8 +29,6 @@ import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.impl.UpdateCheck; -import org.eclipse.aether.impl.UpdateCheckManager; -import org.eclipse.aether.internal.impl.DefaultUpdateCheckManager; import org.eclipse.aether.internal.test.util.TestFileUtils; import org.eclipse.aether.internal.test.util.TestUtils; import org.eclipse.aether.metadata.DefaultMetadata; @@ -49,10 +44,11 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DefaultUpdateCheckManagerTest -{ +public class DefaultUpdateCheckManagerTest { private static final long HOUR = 60L * 60L * 1000L; @@ -67,721 +63,687 @@ public class DefaultUpdateCheckManagerTest private Artifact artifact; @Before - public void setup() - throws Exception - { - File dir = TestFileUtils.createTempFile( "" ); - TestFileUtils.deleteFile( dir ); + public void setup() throws Exception { + File dir = TestFileUtils.createTempFile(""); + TestFileUtils.deleteFile(dir); - File metadataFile = new File( dir, "metadata.txt" ); - TestFileUtils.writeString( metadataFile, "metadata" ); - File artifactFile = new File( dir, "artifact.txt" ); - TestFileUtils.writeString( artifactFile, "artifact" ); + File metadataFile = new File(dir, "metadata.txt"); + TestFileUtils.writeString(metadataFile, "metadata"); + File artifactFile = new File(dir, "artifact.txt"); + TestFileUtils.writeString(artifactFile, "artifact"); session = TestUtils.newSession(); - repository = - new RemoteRepository.Builder( "id", "default", TestFileUtils.createTempDir().toURI().toURL().toString() ).build(); + repository = new RemoteRepository.Builder( + "id", + "default", + TestFileUtils.createTempDir().toURI().toURL().toString()) + .build(); manager = new DefaultUpdateCheckManager() - .setUpdatePolicyAnalyzer( new DefaultUpdatePolicyAnalyzer() ) - .setTrackingFileManager( new DefaultTrackingFileManager() ); - metadata = - new DefaultMetadata( "gid", "aid", "ver", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT, - metadataFile ); - artifact = new DefaultArtifact( "gid", "aid", "", "ext", "ver" ).setFile( artifactFile ); + .setUpdatePolicyAnalyzer(new DefaultUpdatePolicyAnalyzer()) + .setTrackingFileManager(new DefaultTrackingFileManager()); + metadata = new DefaultMetadata( + "gid", "aid", "ver", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT, metadataFile); + artifact = new DefaultArtifact("gid", "aid", "", "ext", "ver").setFile(artifactFile); } @After - public void teardown() - throws Exception - { - new File( metadata.getFile().getParent(), "resolver-status.properties" ).delete(); - new File( artifact.getFile().getPath() + ".lastUpdated" ).delete(); + public void teardown() throws Exception { + new File(metadata.getFile().getParent(), "resolver-status.properties").delete(); + new File(artifact.getFile().getPath() + ".lastUpdated").delete(); metadata.getFile().delete(); artifact.getFile().delete(); - TestFileUtils.deleteFile( new File( new URI( repository.getUrl() ) ) ); + TestFileUtils.deleteFile(new File(new URI(repository.getUrl()))); } - static void resetSessionData( RepositorySystemSession session ) - { - session.getData().set( DefaultUpdateCheckManager.SESSION_CHECKS, null ); + static void resetSessionData(RepositorySystemSession session) { + session.getData().set(DefaultUpdateCheckManager.SESSION_CHECKS, null); } - private UpdateCheck newMetadataCheck() - { + private UpdateCheck newMetadataCheck() { UpdateCheck check = new UpdateCheck<>(); - check.setItem( metadata ); - check.setFile( metadata.getFile() ); - check.setRepository( repository ); - check.setAuthoritativeRepository( repository ); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":10" ); + check.setItem(metadata); + check.setFile(metadata.getFile()); + check.setRepository(repository); + check.setAuthoritativeRepository(repository); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":10"); return check; } - private UpdateCheck newArtifactCheck() - { + private UpdateCheck newArtifactCheck() { UpdateCheck check = new UpdateCheck<>(); - check.setItem( artifact ); - check.setFile( artifact.getFile() ); - check.setRepository( repository ); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":10" ); + check.setItem(artifact); + check.setFile(artifact.getFile()); + check.setRepository(repository); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":10"); return check; } - @Test( expected = Exception.class ) - public void testCheckMetadataFailOnNoFile() - { + @Test(expected = Exception.class) + public void testCheckMetadataFailOnNoFile() { UpdateCheck check = newMetadataCheck(); - check.setItem( metadata.setFile( null ) ); - check.setFile( null ); + check.setItem(metadata.setFile(null)); + check.setFile(null); - manager.checkMetadata( session, check ); + manager.checkMetadata(session, check); } @Test - public void testCheckMetadataUpdatePolicyRequired() - { + public void testCheckMetadataUpdatePolicyRequired() { UpdateCheck check = newMetadataCheck(); Calendar cal = Calendar.getInstance(); - cal.add( Calendar.DATE, -1 ); - check.setLocalLastUpdated( cal.getTimeInMillis() ); + cal.add(Calendar.DATE, -1); + check.setLocalLastUpdated(cal.getTimeInMillis()); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_ALWAYS ); - manager.checkMetadata( session, check ); - assertNull( check.getException() ); - assertTrue( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); + manager.checkMetadata(session, check); + assertNull(check.getException()); + assertTrue(check.isRequired()); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); - manager.checkMetadata( session, check ); - assertNull( check.getException() ); - assertTrue( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); + manager.checkMetadata(session, check); + assertNull(check.getException()); + assertTrue(check.isRequired()); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":60" ); - manager.checkMetadata( session, check ); - assertNull( check.getException() ); - assertTrue( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":60"); + manager.checkMetadata(session, check); + assertNull(check.getException()); + assertTrue(check.isRequired()); } @Test - public void testCheckMetadataUpdatePolicyNotRequired() - { + public void testCheckMetadataUpdatePolicyNotRequired() { UpdateCheck check = newMetadataCheck(); - check.setLocalLastUpdated( System.currentTimeMillis() ); + check.setLocalLastUpdated(System.currentTimeMillis()); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_NEVER ); - manager.checkMetadata( session, check ); - assertFalse( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_NEVER); + manager.checkMetadata(session, check); + assertFalse(check.isRequired()); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); - manager.checkMetadata( session, check ); - assertFalse( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); + manager.checkMetadata(session, check); + assertFalse(check.isRequired()); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":61" ); - manager.checkMetadata( session, check ); - assertFalse( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":61"); + manager.checkMetadata(session, check); + assertFalse(check.isRequired()); - check.setPolicy( "no particular policy" ); - manager.checkMetadata( session, check ); - assertFalse( check.isRequired() ); + check.setPolicy("no particular policy"); + manager.checkMetadata(session, check); + assertFalse(check.isRequired()); } @Test - public void testCheckMetadata() - { + public void testCheckMetadata() { UpdateCheck check = newMetadataCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); // existing file, never checked before - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); // just checked - manager.touchMetadata( session, check ); - resetSessionData( session ); + manager.touchMetadata(session, check); + resetSessionData(session); check = newMetadataCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":60" ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":60"); - manager.checkMetadata( session, check ); - assertFalse( check.isRequired() ); + manager.checkMetadata(session, check); + assertFalse(check.isRequired()); // no local file check.getFile().delete(); - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); // (! file.exists && ! repoKey) -> no timestamp } @Test - public void testCheckMetadataNoLocalFile() - { + public void testCheckMetadataNoLocalFile() { metadata.getFile().delete(); UpdateCheck check = newMetadataCheck(); long lastUpdate = new Date().getTime() - HOUR; - check.setLocalLastUpdated( lastUpdate ); + check.setLocalLastUpdated(lastUpdate); // ! file.exists && updateRequired -> check in remote repo - check.setLocalLastUpdated( lastUpdate ); - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + check.setLocalLastUpdated(lastUpdate); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckMetadataNotFoundInRepoCachingEnabled() - { + public void testCheckMetadataNotFoundInRepoCachingEnabled() { metadata.getFile().delete(); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( true, false ) ); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(true, false)); UpdateCheck check = newMetadataCheck(); - check.setException( new MetadataNotFoundException( metadata, repository, "" ) ); - manager.touchMetadata( session, check ); - resetSessionData( session ); + check.setException(new MetadataNotFoundException(metadata, repository, "")); + manager.touchMetadata(session, check); + resetSessionData(session); // ! file.exists && ! updateRequired -> artifact not found in remote repo - check = newMetadataCheck().setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); - manager.checkMetadata( session, check ); - assertFalse( check.isRequired() ); - assertTrue( check.getException() instanceof MetadataNotFoundException ); - assertTrue( check.getException().isFromCache() ); + check = newMetadataCheck().setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); + manager.checkMetadata(session, check); + assertFalse(check.isRequired()); + assertTrue(check.getException() instanceof MetadataNotFoundException); + assertTrue(check.getException().isFromCache()); } @Test - public void testCheckMetadataNotFoundInRepoCachingDisabled() - { + public void testCheckMetadataNotFoundInRepoCachingDisabled() { metadata.getFile().delete(); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( false, false ) ); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(false, false)); UpdateCheck check = newMetadataCheck(); - check.setException( new MetadataNotFoundException( metadata, repository, "" ) ); - manager.touchMetadata( session, check ); - resetSessionData( session ); + check.setException(new MetadataNotFoundException(metadata, repository, "")); + manager.touchMetadata(session, check); + resetSessionData(session); // ! file.exists && updateRequired -> check in remote repo - check = newMetadataCheck().setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); - assertNull( check.getException() ); + check = newMetadataCheck().setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); + assertNull(check.getException()); } @Test - public void testCheckMetadataErrorFromRepoCachingEnabled() - { + public void testCheckMetadataErrorFromRepoCachingEnabled() { metadata.getFile().delete(); UpdateCheck check = newMetadataCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); - check.setException( new MetadataTransferException( metadata, repository, "some error" ) ); - manager.touchMetadata( session, check ); - resetSessionData( session ); + check.setException(new MetadataTransferException(metadata, repository, "some error")); + manager.touchMetadata(session, check); + resetSessionData(session); // ! file.exists && ! updateRequired && previousError -> depends on transfer error caching check = newMetadataCheck(); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( false, true ) ); - manager.checkMetadata( session, check ); - assertFalse( check.isRequired() ); - assertTrue( check.getException() instanceof MetadataTransferException ); - assertTrue( String.valueOf( check.getException() ), check.getException().getMessage().contains( "some error" ) ); - assertTrue( check.getException().isFromCache() ); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(false, true)); + manager.checkMetadata(session, check); + assertFalse(check.isRequired()); + assertTrue(check.getException() instanceof MetadataTransferException); + assertTrue( + String.valueOf(check.getException()), + check.getException().getMessage().contains("some error")); + assertTrue(check.getException().isFromCache()); } @Test - public void testCheckMetadataErrorFromRepoCachingDisabled() - { + public void testCheckMetadataErrorFromRepoCachingDisabled() { metadata.getFile().delete(); UpdateCheck check = newMetadataCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); - check.setException( new MetadataTransferException( metadata, repository, "some error" ) ); - manager.touchMetadata( session, check ); - resetSessionData( session ); + check.setException(new MetadataTransferException(metadata, repository, "some error")); + manager.touchMetadata(session, check); + resetSessionData(session); // ! file.exists && ! updateRequired && previousError -> depends on transfer error caching check = newMetadataCheck(); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( false, false ) ); - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); - assertNull( check.getException() ); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(false, false)); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); + assertNull(check.getException()); } @Test - public void testCheckMetadataAtMostOnceDuringSessionEvenIfUpdatePolicyAlways() - { + public void testCheckMetadataAtMostOnceDuringSessionEvenIfUpdatePolicyAlways() { UpdateCheck check = newMetadataCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_ALWAYS ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); // first check - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); - manager.touchMetadata( session, check ); + manager.touchMetadata(session, check); // second check in same session - manager.checkMetadata( session, check ); - assertFalse( check.isRequired() ); + manager.checkMetadata(session, check); + assertFalse(check.isRequired()); } @Test - public void testCheckMetadataSessionStateModes() - { + public void testCheckMetadataSessionStateModes() { UpdateCheck check = newMetadataCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_ALWAYS ); - manager.touchMetadata( session, check ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); + manager.touchMetadata(session, check); - session.setConfigProperty( DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "bypass" ); - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + session.setConfigProperty(DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "bypass"); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); - resetSessionData( session ); - manager.touchMetadata( session, check ); + resetSessionData(session); + manager.touchMetadata(session, check); // TODO This will be changed to 'enabled' in a future version - session.setConfigProperty( DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "true" ); - manager.checkMetadata( session, check ); - assertFalse( check.isRequired() ); + session.setConfigProperty(DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "true"); + manager.checkMetadata(session, check); + assertFalse(check.isRequired()); // TODO This will be changed to 'disabled' in a future version - session.setConfigProperty( DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "false" ); - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + session.setConfigProperty(DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "false"); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckMetadataAtMostOnceDuringSessionEvenIfUpdatePolicyAlways_InvalidFile() - { + public void testCheckMetadataAtMostOnceDuringSessionEvenIfUpdatePolicyAlways_InvalidFile() { UpdateCheck check = newMetadataCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_ALWAYS ); - check.setFileValid( false ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); + check.setFileValid(false); // first check - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); // first touch, without exception - manager.touchMetadata( session, check ); + manager.touchMetadata(session, check); // another check in same session - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); // another touch, with exception - check.setException( new MetadataNotFoundException( check.getItem(), check.getRepository() ) ); - manager.touchMetadata( session, check ); + check.setException(new MetadataNotFoundException(check.getItem(), check.getRepository())); + manager.touchMetadata(session, check); // another check in same session - manager.checkMetadata( session, check ); - assertFalse( check.isRequired() ); + manager.checkMetadata(session, check); + assertFalse(check.isRequired()); } @Test - public void testCheckMetadataAtMostOnceDuringSessionEvenIfUpdatePolicyAlways_DifferentRepoIdSameUrl() - { + public void testCheckMetadataAtMostOnceDuringSessionEvenIfUpdatePolicyAlways_DifferentRepoIdSameUrl() { UpdateCheck check = newMetadataCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_ALWAYS ); - check.setFileValid( false ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); + check.setFileValid(false); // first check - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); - manager.touchMetadata( session, check ); + manager.touchMetadata(session, check); // second check in same session but for repo with different id - check.setRepository( new RemoteRepository.Builder( check.getRepository() ).setId( "check" ).build() ); - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + check.setRepository(new RemoteRepository.Builder(check.getRepository()) + .setId("check") + .build()); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckMetadataWhenLocallyMissingEvenIfUpdatePolicyIsNever() - { + public void testCheckMetadataWhenLocallyMissingEvenIfUpdatePolicyIsNever() { UpdateCheck check = newMetadataCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_NEVER ); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( true, false ) ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_NEVER); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(true, false)); check.getFile().delete(); - assertFalse( check.getFile().getAbsolutePath(), check.getFile().exists() ); + assertFalse(check.getFile().getAbsolutePath(), check.getFile().exists()); - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckMetadataWhenLocallyPresentButInvalidEvenIfUpdatePolicyIsNever() - { + public void testCheckMetadataWhenLocallyPresentButInvalidEvenIfUpdatePolicyIsNever() { UpdateCheck check = newMetadataCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_NEVER ); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( true, false ) ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_NEVER); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(true, false)); - manager.touchMetadata( session, check ); - resetSessionData( session ); + manager.touchMetadata(session, check); + resetSessionData(session); - check.setFileValid( false ); + check.setFileValid(false); - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckMetadataWhenLocallyDeletedEvenIfTimestampUpToDate() - { + public void testCheckMetadataWhenLocallyDeletedEvenIfTimestampUpToDate() { UpdateCheck check = newMetadataCheck(); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( true, false ) ); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(true, false)); - manager.touchMetadata( session, check ); - resetSessionData( session ); + manager.touchMetadata(session, check); + resetSessionData(session); check.getFile().delete(); - assertFalse( check.getFile().getAbsolutePath(), check.getFile().exists() ); + assertFalse(check.getFile().getAbsolutePath(), check.getFile().exists()); - manager.checkMetadata( session, check ); - assertTrue( check.isRequired() ); + manager.checkMetadata(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckMetadataNotWhenUpdatePolicyIsNeverAndTimestampIsUnavailable() - { + public void testCheckMetadataNotWhenUpdatePolicyIsNeverAndTimestampIsUnavailable() { UpdateCheck check = newMetadataCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_NEVER ); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( true, false ) ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_NEVER); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(true, false)); - manager.checkMetadata( session, check ); - assertFalse( check.isRequired() ); + manager.checkMetadata(session, check); + assertFalse(check.isRequired()); } - @Test( expected = NullPointerException.class ) - public void testCheckArtifactFailOnNoFile() - { + @Test(expected = NullPointerException.class) + public void testCheckArtifactFailOnNoFile() { UpdateCheck check = newArtifactCheck(); - check.setItem( artifact.setFile( null ) ); - check.setFile( null ); + check.setItem(artifact.setFile(null)); + check.setFile(null); - manager.checkArtifact( session, check ); - assertNotNull( check.getException() ); + manager.checkArtifact(session, check); + assertNotNull(check.getException()); } @Test - public void testCheckArtifactUpdatePolicyRequired() - { + public void testCheckArtifactUpdatePolicyRequired() { UpdateCheck check = newArtifactCheck(); - check.setItem( artifact ); - check.setFile( artifact.getFile() ); + check.setItem(artifact); + check.setFile(artifact.getFile()); - Calendar cal = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ); - cal.add( Calendar.DATE, -1 ); + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + cal.add(Calendar.DATE, -1); long lastUpdate = cal.getTimeInMillis(); - artifact.getFile().setLastModified( lastUpdate ); - check.setLocalLastUpdated( lastUpdate ); + artifact.getFile().setLastModified(lastUpdate); + check.setLocalLastUpdated(lastUpdate); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_ALWAYS ); - manager.checkArtifact( session, check ); - assertNull( check.getException() ); - assertTrue( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); + manager.checkArtifact(session, check); + assertNull(check.getException()); + assertTrue(check.isRequired()); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); - manager.checkArtifact( session, check ); - assertNull( check.getException() ); - assertTrue( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); + manager.checkArtifact(session, check); + assertNull(check.getException()); + assertTrue(check.isRequired()); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":60" ); - manager.checkArtifact( session, check ); - assertNull( check.getException() ); - assertTrue( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":60"); + manager.checkArtifact(session, check); + assertNull(check.getException()); + assertTrue(check.isRequired()); } @Test - public void testCheckArtifactUpdatePolicyNotRequired() - { + public void testCheckArtifactUpdatePolicyNotRequired() { UpdateCheck check = newArtifactCheck(); - check.setItem( artifact ); - check.setFile( artifact.getFile() ); + check.setItem(artifact); + check.setFile(artifact.getFile()); - Calendar cal = Calendar.getInstance( TimeZone.getTimeZone( "UTC" ) ); - cal.add( Calendar.HOUR_OF_DAY, -1 ); - check.setLocalLastUpdated( cal.getTimeInMillis() ); + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + cal.add(Calendar.HOUR_OF_DAY, -1); + check.setLocalLastUpdated(cal.getTimeInMillis()); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_NEVER ); - manager.checkArtifact( session, check ); - assertFalse( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_NEVER); + manager.checkArtifact(session, check); + assertFalse(check.isRequired()); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); - manager.checkArtifact( session, check ); - assertFalse( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); + manager.checkArtifact(session, check); + assertFalse(check.isRequired()); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":61" ); - manager.checkArtifact( session, check ); - assertFalse( check.isRequired() ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":61"); + manager.checkArtifact(session, check); + assertFalse(check.isRequired()); - check.setPolicy( "no particular policy" ); - manager.checkArtifact( session, check ); - assertFalse( check.isRequired() ); + check.setPolicy("no particular policy"); + manager.checkArtifact(session, check); + assertFalse(check.isRequired()); } @Test - public void testCheckArtifact() - { + public void testCheckArtifact() { UpdateCheck check = newArtifactCheck(); - long fifteenMinutes = new Date().getTime() - ( 15L * 60L * 1000L ); - check.getFile().setLastModified( fifteenMinutes ); + long fifteenMinutes = new Date().getTime() - (15L * 60L * 1000L); + check.getFile().setLastModified(fifteenMinutes); // time is truncated on setLastModfied fifteenMinutes = check.getFile().lastModified(); // never checked before - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); // just checked - check.setLocalLastUpdated( 0L ); + check.setLocalLastUpdated(0L); long lastUpdate = new Date().getTime(); - check.getFile().setLastModified( lastUpdate ); + check.getFile().setLastModified(lastUpdate); lastUpdate = check.getFile().lastModified(); - manager.checkArtifact( session, check ); - assertFalse( check.isRequired() ); + manager.checkArtifact(session, check); + assertFalse(check.isRequired()); // no local file, no repo timestamp - check.setLocalLastUpdated( 0L ); + check.setLocalLastUpdated(0L); check.getFile().delete(); - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckArtifactNoLocalFile() - { + public void testCheckArtifactNoLocalFile() { artifact.getFile().delete(); UpdateCheck check = newArtifactCheck(); long lastUpdate = new Date().getTime() - HOUR; // ! file.exists && updateRequired -> check in remote repo - check.setLocalLastUpdated( lastUpdate ); - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + check.setLocalLastUpdated(lastUpdate); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckArtifactNotFoundInRepoCachingEnabled() - { + public void testCheckArtifactNotFoundInRepoCachingEnabled() { artifact.getFile().delete(); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( true, false ) ); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(true, false)); UpdateCheck check = newArtifactCheck(); - check.setException( new ArtifactNotFoundException( artifact, repository ) ); - manager.touchArtifact( session, check ); - resetSessionData( session ); + check.setException(new ArtifactNotFoundException(artifact, repository)); + manager.touchArtifact(session, check); + resetSessionData(session); // ! file.exists && ! updateRequired -> artifact not found in remote repo - check = newArtifactCheck().setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); - manager.checkArtifact( session, check ); - assertFalse( check.isRequired() ); - assertTrue( check.getException() instanceof ArtifactNotFoundException ); - assertTrue( check.getException().isFromCache() ); + check = newArtifactCheck().setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); + manager.checkArtifact(session, check); + assertFalse(check.isRequired()); + assertTrue(check.getException() instanceof ArtifactNotFoundException); + assertTrue(check.getException().isFromCache()); } @Test - public void testCheckArtifactNotFoundInRepoCachingDisabled() - { + public void testCheckArtifactNotFoundInRepoCachingDisabled() { artifact.getFile().delete(); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( false, false ) ); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(false, false)); UpdateCheck check = newArtifactCheck(); - check.setException( new ArtifactNotFoundException( artifact, repository ) ); - manager.touchArtifact( session, check ); - resetSessionData( session ); + check.setException(new ArtifactNotFoundException(artifact, repository)); + manager.touchArtifact(session, check); + resetSessionData(session); // ! file.exists && updateRequired -> check in remote repo - check = newArtifactCheck().setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); - assertNull( check.getException() ); + check = newArtifactCheck().setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); + assertNull(check.getException()); } @Test - public void testCheckArtifactErrorFromRepoCachingEnabled() - { + public void testCheckArtifactErrorFromRepoCachingEnabled() { artifact.getFile().delete(); UpdateCheck check = newArtifactCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); - check.setException( new ArtifactTransferException( artifact, repository, "some error" ) ); - manager.touchArtifact( session, check ); - resetSessionData( session ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); + check.setException(new ArtifactTransferException(artifact, repository, "some error")); + manager.touchArtifact(session, check); + resetSessionData(session); // ! file.exists && ! updateRequired && previousError -> depends on transfer error caching check = newArtifactCheck(); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( false, true ) ); - manager.checkArtifact( session, check ); - assertFalse( check.isRequired() ); - assertTrue( check.getException() instanceof ArtifactTransferException ); - assertTrue( check.getException().isFromCache() ); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(false, true)); + manager.checkArtifact(session, check); + assertFalse(check.isRequired()); + assertTrue(check.getException() instanceof ArtifactTransferException); + assertTrue(check.getException().isFromCache()); } @Test - public void testCheckArtifactErrorFromRepoCachingDisabled() - { + public void testCheckArtifactErrorFromRepoCachingDisabled() { artifact.getFile().delete(); UpdateCheck check = newArtifactCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_DAILY ); - check.setException( new ArtifactTransferException( artifact, repository, "some error" ) ); - manager.touchArtifact( session, check ); - resetSessionData( session ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); + check.setException(new ArtifactTransferException(artifact, repository, "some error")); + manager.touchArtifact(session, check); + resetSessionData(session); // ! file.exists && ! updateRequired && previousError -> depends on transfer error caching check = newArtifactCheck(); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( false, false ) ); - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); - assertNull( check.getException() ); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(false, false)); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); + assertNull(check.getException()); } @Test - public void testCheckArtifactAtMostOnceDuringSessionEvenIfUpdatePolicyAlways() - { + public void testCheckArtifactAtMostOnceDuringSessionEvenIfUpdatePolicyAlways() { UpdateCheck check = newArtifactCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_ALWAYS ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); // first check - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); - manager.touchArtifact( session, check ); + manager.touchArtifact(session, check); // second check in same session - manager.checkArtifact( session, check ); - assertFalse( check.isRequired() ); + manager.checkArtifact(session, check); + assertFalse(check.isRequired()); } @Test - public void testCheckArtifactSessionStateModes() - { + public void testCheckArtifactSessionStateModes() { UpdateCheck check = newArtifactCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_ALWAYS ); - manager.touchArtifact( session, check ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); + manager.touchArtifact(session, check); - session.setConfigProperty( DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "bypass" ); - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + session.setConfigProperty(DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "bypass"); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); - resetSessionData( session ); - manager.touchArtifact( session, check ); + resetSessionData(session); + manager.touchArtifact(session, check); - session.setConfigProperty( DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "true" ); - manager.checkArtifact( session, check ); - assertFalse( check.isRequired() ); + session.setConfigProperty(DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "true"); + manager.checkArtifact(session, check); + assertFalse(check.isRequired()); - session.setConfigProperty( DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "false" ); - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + session.setConfigProperty(DefaultUpdateCheckManager.CONFIG_PROP_SESSION_STATE, "false"); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckArtifactAtMostOnceDuringSessionEvenIfUpdatePolicyAlways_InvalidFile() - { + public void testCheckArtifactAtMostOnceDuringSessionEvenIfUpdatePolicyAlways_InvalidFile() { UpdateCheck check = newArtifactCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_ALWAYS ); - check.setFileValid( false ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); + check.setFileValid(false); // first check - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); // first touch, without exception - manager.touchArtifact( session, check ); + manager.touchArtifact(session, check); // another check in same session - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); // another touch, with exception - check.setException( new ArtifactNotFoundException( check.getItem(), check.getRepository() ) ); - manager.touchArtifact( session, check ); + check.setException(new ArtifactNotFoundException(check.getItem(), check.getRepository())); + manager.touchArtifact(session, check); // another check in same session - manager.checkArtifact( session, check ); - assertFalse( check.isRequired() ); + manager.checkArtifact(session, check); + assertFalse(check.isRequired()); } @Test - public void testCheckArtifactAtMostOnceDuringSessionEvenIfUpdatePolicyAlways_DifferentRepoIdSameUrl() - { + public void testCheckArtifactAtMostOnceDuringSessionEvenIfUpdatePolicyAlways_DifferentRepoIdSameUrl() { UpdateCheck check = newArtifactCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_ALWAYS ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); // first check - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); - manager.touchArtifact( session, check ); + manager.touchArtifact(session, check); // second check in same session but for repo with different id - check.setRepository( new RemoteRepository.Builder( check.getRepository() ).setId( "check" ).build() ); - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + check.setRepository(new RemoteRepository.Builder(check.getRepository()) + .setId("check") + .build()); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckArtifactWhenLocallyMissingEvenIfUpdatePolicyIsNever() - { + public void testCheckArtifactWhenLocallyMissingEvenIfUpdatePolicyIsNever() { UpdateCheck check = newArtifactCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_NEVER ); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( true, false ) ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_NEVER); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(true, false)); check.getFile().delete(); - assertFalse( check.getFile().getAbsolutePath(), check.getFile().exists() ); + assertFalse(check.getFile().getAbsolutePath(), check.getFile().exists()); - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckArtifactWhenLocallyPresentButInvalidEvenIfUpdatePolicyIsNever() - { + public void testCheckArtifactWhenLocallyPresentButInvalidEvenIfUpdatePolicyIsNever() { UpdateCheck check = newArtifactCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_NEVER ); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( true, false ) ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_NEVER); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(true, false)); - manager.touchArtifact( session, check ); - resetSessionData( session ); + manager.touchArtifact(session, check); + resetSessionData(session); - check.setFileValid( false ); + check.setFileValid(false); - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckArtifactWhenLocallyDeletedEvenIfTimestampUpToDate() - { + public void testCheckArtifactWhenLocallyDeletedEvenIfTimestampUpToDate() { UpdateCheck check = newArtifactCheck(); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( true, false ) ); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(true, false)); - manager.touchArtifact( session, check ); - resetSessionData( session ); + manager.touchArtifact(session, check); + resetSessionData(session); check.getFile().delete(); - assertFalse( check.getFile().getAbsolutePath(), check.getFile().exists() ); + assertFalse(check.getFile().getAbsolutePath(), check.getFile().exists()); - manager.checkArtifact( session, check ); - assertTrue( check.isRequired() ); + manager.checkArtifact(session, check); + assertTrue(check.isRequired()); } @Test - public void testCheckArtifactNotWhenUpdatePolicyIsNeverAndTimestampIsUnavailable() - { + public void testCheckArtifactNotWhenUpdatePolicyIsNeverAndTimestampIsUnavailable() { UpdateCheck check = newArtifactCheck(); - check.setPolicy( RepositoryPolicy.UPDATE_POLICY_NEVER ); - session.setResolutionErrorPolicy( new SimpleResolutionErrorPolicy( true, false ) ); + check.setPolicy(RepositoryPolicy.UPDATE_POLICY_NEVER); + session.setResolutionErrorPolicy(new SimpleResolutionErrorPolicy(true, false)); - manager.checkArtifact( session, check ); - assertFalse( check.isRequired() ); + manager.checkArtifact(session, check); + assertFalse(check.isRequired()); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultUpdatePolicyAnalyzerTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultUpdatePolicyAnalyzerTest.java index 857d3cccb..762740827 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultUpdatePolicyAnalyzerTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DefaultUpdatePolicyAnalyzerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.eclipse.aether.repository.RepositoryPolicy.*; -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.util.Calendar; @@ -30,96 +26,95 @@ import org.junit.Before; import org.junit.Test; +import static org.eclipse.aether.repository.RepositoryPolicy.*; +import static org.junit.Assert.*; + /** */ -public class DefaultUpdatePolicyAnalyzerTest -{ +public class DefaultUpdatePolicyAnalyzerTest { private DefaultUpdatePolicyAnalyzer analyzer; private DefaultRepositorySystemSession session; @Before - public void setup() - { + public void setup() { analyzer = new DefaultUpdatePolicyAnalyzer(); session = TestUtils.newSession(); } - private long now() - { + private long now() { return System.currentTimeMillis(); } @Test - public void testIsUpdateRequired_PolicyNever() - { + public void testIsUpdateRequired_PolicyNever() { String policy = RepositoryPolicy.UPDATE_POLICY_NEVER; - assertFalse( analyzer.isUpdatedRequired( session, Long.MIN_VALUE, policy ) ); - assertFalse( analyzer.isUpdatedRequired( session, Long.MAX_VALUE, policy ) ); - assertFalse( analyzer.isUpdatedRequired( session, 0, policy ) ); - assertFalse( analyzer.isUpdatedRequired( session, 1, policy ) ); - assertFalse( analyzer.isUpdatedRequired( session, now() - 604800000, policy ) ); + assertFalse(analyzer.isUpdatedRequired(session, Long.MIN_VALUE, policy)); + assertFalse(analyzer.isUpdatedRequired(session, Long.MAX_VALUE, policy)); + assertFalse(analyzer.isUpdatedRequired(session, 0, policy)); + assertFalse(analyzer.isUpdatedRequired(session, 1, policy)); + assertFalse(analyzer.isUpdatedRequired(session, now() - 604800000, policy)); } @Test - public void testIsUpdateRequired_PolicyAlways() - { + public void testIsUpdateRequired_PolicyAlways() { String policy = RepositoryPolicy.UPDATE_POLICY_ALWAYS; - assertTrue( analyzer.isUpdatedRequired( session, Long.MIN_VALUE, policy ) ); - assertTrue( analyzer.isUpdatedRequired( session, Long.MAX_VALUE, policy ) ); - assertTrue( analyzer.isUpdatedRequired( session, 0, policy ) ); - assertTrue( analyzer.isUpdatedRequired( session, 1, policy ) ); - assertTrue( analyzer.isUpdatedRequired( session, now() - 1000, policy ) ); + assertTrue(analyzer.isUpdatedRequired(session, Long.MIN_VALUE, policy)); + assertTrue(analyzer.isUpdatedRequired(session, Long.MAX_VALUE, policy)); + assertTrue(analyzer.isUpdatedRequired(session, 0, policy)); + assertTrue(analyzer.isUpdatedRequired(session, 1, policy)); + assertTrue(analyzer.isUpdatedRequired(session, now() - 1000, policy)); } @Test - public void testIsUpdateRequired_PolicyDaily() - { + public void testIsUpdateRequired_PolicyDaily() { Calendar cal = Calendar.getInstance(); - cal.set( Calendar.HOUR_OF_DAY, 0 ); - cal.set( Calendar.MINUTE, 0 ); - cal.set( Calendar.SECOND, 0 ); - cal.set( Calendar.MILLISECOND, 0 ); + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); long localMidnight = cal.getTimeInMillis(); String policy = RepositoryPolicy.UPDATE_POLICY_DAILY; - assertTrue( analyzer.isUpdatedRequired( session, Long.MIN_VALUE, policy ) ); - assertFalse( analyzer.isUpdatedRequired( session, Long.MAX_VALUE, policy ) ); - assertFalse( analyzer.isUpdatedRequired( session, localMidnight, policy ) ); - assertFalse( analyzer.isUpdatedRequired( session, localMidnight + 1, policy ) ); - assertTrue( analyzer.isUpdatedRequired( session, localMidnight - 1, policy ) ); + assertTrue(analyzer.isUpdatedRequired(session, Long.MIN_VALUE, policy)); + assertFalse(analyzer.isUpdatedRequired(session, Long.MAX_VALUE, policy)); + assertFalse(analyzer.isUpdatedRequired(session, localMidnight, policy)); + assertFalse(analyzer.isUpdatedRequired(session, localMidnight + 1, policy)); + assertTrue(analyzer.isUpdatedRequired(session, localMidnight - 1, policy)); } @Test - public void testIsUpdateRequired_PolicyInterval() - { + public void testIsUpdateRequired_PolicyInterval() { String policy = RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":5"; - assertTrue( analyzer.isUpdatedRequired( session, Long.MIN_VALUE, policy ) ); - assertFalse( analyzer.isUpdatedRequired( session, Long.MAX_VALUE, policy ) ); - assertFalse( analyzer.isUpdatedRequired( session, now(), policy ) ); - assertFalse( analyzer.isUpdatedRequired( session, now() - 5 - 1, policy ) ); - assertFalse( analyzer.isUpdatedRequired( session, now() - 1000 * 5 - 1, policy ) ); - assertTrue( analyzer.isUpdatedRequired( session, now() - 1000 * 60 * 5 - 1, policy ) ); + assertTrue(analyzer.isUpdatedRequired(session, Long.MIN_VALUE, policy)); + assertFalse(analyzer.isUpdatedRequired(session, Long.MAX_VALUE, policy)); + assertFalse(analyzer.isUpdatedRequired(session, now(), policy)); + assertFalse(analyzer.isUpdatedRequired(session, now() - 5 - 1, policy)); + assertFalse(analyzer.isUpdatedRequired(session, now() - 1000 * 5 - 1, policy)); + assertTrue(analyzer.isUpdatedRequired(session, now() - 1000 * 60 * 5 - 1, policy)); policy = RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":invalid"; - assertFalse( analyzer.isUpdatedRequired( session, now(), policy ) ); + assertFalse(analyzer.isUpdatedRequired(session, now(), policy)); } @Test - public void testEffectivePolicy() - { - assertEquals( UPDATE_POLICY_ALWAYS, - analyzer.getEffectiveUpdatePolicy( session, UPDATE_POLICY_ALWAYS, UPDATE_POLICY_DAILY ) ); - assertEquals( UPDATE_POLICY_ALWAYS, - analyzer.getEffectiveUpdatePolicy( session, UPDATE_POLICY_ALWAYS, UPDATE_POLICY_NEVER ) ); - assertEquals( UPDATE_POLICY_DAILY, - analyzer.getEffectiveUpdatePolicy( session, UPDATE_POLICY_DAILY, UPDATE_POLICY_NEVER ) ); - assertEquals( UPDATE_POLICY_INTERVAL + ":60", - analyzer.getEffectiveUpdatePolicy( session, UPDATE_POLICY_DAILY, UPDATE_POLICY_INTERVAL + ":60" ) ); - assertEquals( UPDATE_POLICY_INTERVAL + ":60", - analyzer.getEffectiveUpdatePolicy( session, UPDATE_POLICY_INTERVAL + ":100", - UPDATE_POLICY_INTERVAL + ":60" ) ); + public void testEffectivePolicy() { + assertEquals( + UPDATE_POLICY_ALWAYS, + analyzer.getEffectiveUpdatePolicy(session, UPDATE_POLICY_ALWAYS, UPDATE_POLICY_DAILY)); + assertEquals( + UPDATE_POLICY_ALWAYS, + analyzer.getEffectiveUpdatePolicy(session, UPDATE_POLICY_ALWAYS, UPDATE_POLICY_NEVER)); + assertEquals( + UPDATE_POLICY_DAILY, + analyzer.getEffectiveUpdatePolicy(session, UPDATE_POLICY_DAILY, UPDATE_POLICY_NEVER)); + assertEquals( + UPDATE_POLICY_INTERVAL + ":60", + analyzer.getEffectiveUpdatePolicy(session, UPDATE_POLICY_DAILY, UPDATE_POLICY_INTERVAL + ":60")); + assertEquals( + UPDATE_POLICY_INTERVAL + ":60", + analyzer.getEffectiveUpdatePolicy( + session, UPDATE_POLICY_INTERVAL + ":100", UPDATE_POLICY_INTERVAL + ":60")); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DependencyGraphDumper.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DependencyGraphDumper.java index 8c8b1a6cb..0f62502c9 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DependencyGraphDumper.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/DependencyGraphDumper.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import java.io.PrintWriter; import java.util.ArrayList; @@ -33,124 +32,97 @@ /** * A helper to visualize dependency graphs. */ -public class DependencyGraphDumper -{ +public class DependencyGraphDumper { - public static void dump( PrintWriter writer, DependencyNode node ) - { + public static void dump(PrintWriter writer, DependencyNode node) { Context context = new Context(); - dump( context, node, 0, true ); + dump(context, node, 0, true); LinkedList indents = new LinkedList<>(); - for ( Line line : context.lines ) - { - if ( line.depth > indents.size() ) - { - if ( !indents.isEmpty() ) - { - if ( indents.getLast() == Indent.CHILD ) - { + for (Line line : context.lines) { + if (line.depth > indents.size()) { + if (!indents.isEmpty()) { + if (indents.getLast() == Indent.CHILD) { indents.removeLast(); - indents.addLast( Indent.CHILDREN ); - } - else if ( indents.getLast() == Indent.LAST_CHILD ) - { + indents.addLast(Indent.CHILDREN); + } else if (indents.getLast() == Indent.LAST_CHILD) { indents.removeLast(); - indents.addLast( Indent.NO_CHILDREN ); + indents.addLast(Indent.NO_CHILDREN); } } - indents.addLast( line.last ? Indent.LAST_CHILD : Indent.CHILD ); - } - else if ( line.depth < indents.size() ) - { - while ( line.depth <= indents.size() ) - { + indents.addLast(line.last ? Indent.LAST_CHILD : Indent.CHILD); + } else if (line.depth < indents.size()) { + while (line.depth <= indents.size()) { indents.removeLast(); } - indents.addLast( line.last ? Indent.LAST_CHILD : Indent.CHILD ); - } - else if ( line.last && !indents.isEmpty() ) - { + indents.addLast(line.last ? Indent.LAST_CHILD : Indent.CHILD); + } else if (line.last && !indents.isEmpty()) { indents.removeLast(); - indents.addLast( Indent.LAST_CHILD ); + indents.addLast(Indent.LAST_CHILD); } - for ( Indent indent : indents ) - { - writer.print( indent ); + for (Indent indent : indents) { + writer.print(indent); } - line.print( writer ); + line.print(writer); } writer.flush(); } - private static void dump( Context context, DependencyNode node, int depth, boolean last ) - { - Line line = context.nodes.get( node ); - if ( line != null ) - { - if ( line.id <= 0 ) - { + private static void dump(Context context, DependencyNode node, int depth, boolean last) { + Line line = context.nodes.get(node); + if (line != null) { + if (line.id <= 0) { line.id = ++context.ids; } - context.lines.add( new Line( null, line.id, depth, last ) ); + context.lines.add(new Line(null, line.id, depth, last)); return; } Dependency dependency = node.getDependency(); - if ( dependency == null ) - { - line = new Line( null, 0, depth, last ); - } - else - { - line = new Line( dependency, 0, depth, last ); + if (dependency == null) { + line = new Line(null, 0, depth, last); + } else { + line = new Line(dependency, 0, depth, last); } - context.lines.add( line ); + context.lines.add(line); - context.nodes.put( node, line ); + context.nodes.put(node, line); depth++; - for ( Iterator it = node.getChildren().iterator(); it.hasNext(); ) - { + for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { DependencyNode child = it.next(); - dump( context, child, depth, !it.hasNext() ); + dump(context, child, depth, !it.hasNext()); } } - enum Indent - { + enum Indent { + NO_CHILDREN(" "), - NO_CHILDREN( " " ), + CHILDREN("| "), - CHILDREN( "| " ), + CHILD("+- "), - CHILD( "+- " ), - - LAST_CHILD( "\\- " ); + LAST_CHILD("\\- "); private final String chars; - Indent( String chars ) - { + Indent(String chars) { this.chars = chars; } @Override - public String toString() - { + public String toString() { return chars; } - } - static class Context - { + static class Context { int ids; @@ -158,16 +130,13 @@ static class Context Map nodes; - Context() - { + Context() { this.lines = new ArrayList<>(); - this.nodes = new IdentityHashMap<>( 1024 ); + this.nodes = new IdentityHashMap<>(1024); } - } - static class Line - { + static class Line { Dependency dependency; @@ -177,46 +146,34 @@ static class Line boolean last; - Line( Dependency dependency, int id, int depth, boolean last ) - { + Line(Dependency dependency, int id, int depth, boolean last) { this.dependency = dependency; this.id = id; this.depth = depth; this.last = last; } - void print( PrintWriter writer ) - { - if ( dependency == null ) - { - if ( id > 0 ) - { - writer.print( "^" ); - writer.print( id ); + void print(PrintWriter writer) { + if (dependency == null) { + if (id > 0) { + writer.print("^"); + writer.print(id); + } else { + writer.print("(null)"); } - else - { - writer.print( "(null)" ); + } else { + if (id > 0) { + writer.print("("); + writer.print(id); + writer.print(")"); } - } - else - { - if ( id > 0 ) - { - writer.print( "(" ); - writer.print( id ); - writer.print( ")" ); - } - writer.print( dependency.getArtifact() ); - if ( dependency.getScope().length() > 0 ) - { - writer.print( ":" ); - writer.print( dependency.getScope() ); + writer.print(dependency.getArtifact()); + if (dependency.getScope().length() > 0) { + writer.print(":"); + writer.print(dependency.getScope()); } } writer.println(); } - } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManagerTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManagerTest.java index f69d8bd75..f5b204060 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManagerTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/EnhancedLocalRepositoryManagerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.io.File; import java.io.IOException; @@ -46,8 +43,9 @@ import org.junit.Before; import org.junit.Test; -public class EnhancedLocalRepositoryManagerTest -{ +import static org.junit.Assert.*; + +public class EnhancedLocalRepositoryManagerTest { private Artifact artifact; @@ -72,54 +70,60 @@ public class EnhancedLocalRepositoryManagerTest private Metadata noVerMetadata; @Before - public void setup() - throws Exception - { - String url = TestFileUtils.createTempDir( "enhanced-remote-repo" ).toURI().toURL().toString(); - repository = - new RemoteRepository.Builder( "enhanced-remote-repo", "default", url ).setRepositoryManager( true ).build(); - - artifact = - new DefaultArtifact( "gid", "aid", "", "jar", "1-test", Collections. emptyMap(), - TestFileUtils.createTempFile( "artifact" ) ); - - snapshot = - new DefaultArtifact( "gid", "aid", "", "jar", "1.0-20120710.231549-9", - Collections. emptyMap(), TestFileUtils.createTempFile( "artifact" ) ); - - metadata = - new DefaultMetadata( "gid", "aid", "1-test", "maven-metadata.xml", Nature.RELEASE, - TestFileUtils.createTempFile( "metadata" ) ); - - noVerMetadata = - new DefaultMetadata( "gid", "aid", null, "maven-metadata.xml", Nature.RELEASE, - TestFileUtils.createTempFile( "metadata" ) ); - - basedir = TestFileUtils.createTempDir( "enhanced-repo" ); + public void setup() throws Exception { + String url = TestFileUtils.createTempDir("enhanced-remote-repo") + .toURI() + .toURL() + .toString(); + repository = new RemoteRepository.Builder("enhanced-remote-repo", "default", url) + .setRepositoryManager(true) + .build(); + + artifact = new DefaultArtifact( + "gid", + "aid", + "", + "jar", + "1-test", + Collections.emptyMap(), + TestFileUtils.createTempFile("artifact")); + + snapshot = new DefaultArtifact( + "gid", + "aid", + "", + "jar", + "1.0-20120710.231549-9", + Collections.emptyMap(), + TestFileUtils.createTempFile("artifact")); + + metadata = new DefaultMetadata( + "gid", "aid", "1-test", "maven-metadata.xml", Nature.RELEASE, TestFileUtils.createTempFile("metadata")); + + noVerMetadata = new DefaultMetadata( + "gid", "aid", null, "maven-metadata.xml", Nature.RELEASE, TestFileUtils.createTempFile("metadata")); + + basedir = TestFileUtils.createTempDir("enhanced-repo"); session = TestUtils.newSession(); trackingFileManager = new DefaultTrackingFileManager(); manager = getManager(); - artifactFile = new File( basedir, manager.getPathForLocalArtifact( artifact ) ); + artifactFile = new File(basedir, manager.getPathForLocalArtifact(artifact)); } - protected EnhancedLocalRepositoryManager getManager() - { + protected EnhancedLocalRepositoryManager getManager() { return new EnhancedLocalRepositoryManager( basedir, new DefaultLocalPathComposer(), "_remote.repositories", trackingFileManager, - new DefaultLocalPathPrefixComposerFactory().createComposer( session ) - ); + new DefaultLocalPathPrefixComposerFactory().createComposer(session)); } @After - public void tearDown() - throws Exception - { - TestFileUtils.deleteFile( basedir ); - TestFileUtils.deleteFile( new File( new URI( repository.getUrl() ) ) ); + public void tearDown() throws Exception { + TestFileUtils.deleteFile(basedir); + TestFileUtils.deleteFile(new File(new URI(repository.getUrl()))); session = null; manager = null; @@ -127,230 +131,194 @@ public void tearDown() artifact = null; } - private long addLocalArtifact( Artifact artifact ) - throws IOException - { - manager.add( session, new LocalArtifactRegistration( artifact ) ); - String path = manager.getPathForLocalArtifact( artifact ); + private long addLocalArtifact(Artifact artifact) throws IOException { + manager.add(session, new LocalArtifactRegistration(artifact)); + String path = manager.getPathForLocalArtifact(artifact); - return copy( artifact, path ); + return copy(artifact, path); } - private long addRemoteArtifact( Artifact artifact ) - throws IOException - { - Collection contexts = Arrays.asList( testContext ); - manager.add( session, new LocalArtifactRegistration( artifact, repository, contexts ) ); - String path = manager.getPathForRemoteArtifact( artifact, repository, testContext ); - return copy( artifact, path ); + private long addRemoteArtifact(Artifact artifact) throws IOException { + Collection contexts = Arrays.asList(testContext); + manager.add(session, new LocalArtifactRegistration(artifact, repository, contexts)); + String path = manager.getPathForRemoteArtifact(artifact, repository, testContext); + return copy(artifact, path); } - private long copy( Metadata metadata, String path ) - throws IOException - { - if ( metadata.getFile() == null ) - { + private long copy(Metadata metadata, String path) throws IOException { + if (metadata.getFile() == null) { return -1L; } - return TestFileUtils.copyFile( metadata.getFile(), new File( basedir, path ) ); + return TestFileUtils.copyFile(metadata.getFile(), new File(basedir, path)); } - private long copy( Artifact artifact, String path ) - throws IOException - { - if ( artifact.getFile() == null ) - { + private long copy(Artifact artifact, String path) throws IOException { + if (artifact.getFile() == null) { return -1L; } - File artifactFile = new File( basedir, path ); - return TestFileUtils.copyFile( artifact.getFile(), artifactFile ); + File artifactFile = new File(basedir, path); + return TestFileUtils.copyFile(artifact.getFile(), artifactFile); } @Test - public void testGetPathForLocalArtifact() - { - Artifact artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-SNAPSHOT" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact( artifact ) ); - - artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-20110329.221805-4" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact( artifact ) ); + public void testGetPathForLocalArtifact() { + Artifact artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-SNAPSHOT"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals("g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact(artifact)); + + artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-20110329.221805-4"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals("g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact(artifact)); } @Test - public void testGetPathForRemoteArtifact() - { - RemoteRepository remoteRepo = new RemoteRepository.Builder( "repo", "default", "ram:/void" ).build(); - - Artifact artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-SNAPSHOT" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", - manager.getPathForRemoteArtifact( artifact, remoteRepo, "" ) ); - - artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-20110329.221805-4" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-20110329.221805-4.jar", - manager.getPathForRemoteArtifact( artifact, remoteRepo, "" ) ); + public void testGetPathForRemoteArtifact() { + RemoteRepository remoteRepo = new RemoteRepository.Builder("repo", "default", "ram:/void").build(); + + Artifact artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-SNAPSHOT"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals( + "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", + manager.getPathForRemoteArtifact(artifact, remoteRepo, "")); + + artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-20110329.221805-4"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals( + "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-20110329.221805-4.jar", + manager.getPathForRemoteArtifact(artifact, remoteRepo, "")); } @Test - public void testFindLocalArtifact() - throws Exception - { - addLocalArtifact( artifact ); - - LocalArtifactRequest request = new LocalArtifactRequest( artifact, null, null ); - LocalArtifactResult result = manager.find( session, request ); - assertTrue( result.isAvailable() ); - assertNull( result.getRepository() ); - - snapshot = snapshot.setVersion( snapshot.getBaseVersion() ); - addLocalArtifact( snapshot ); - - request = new LocalArtifactRequest( snapshot, null, null ); - result = manager.find( session, request ); - assertTrue( result.isAvailable() ); - assertNull( result.getRepository() ); + public void testFindLocalArtifact() throws Exception { + addLocalArtifact(artifact); + + LocalArtifactRequest request = new LocalArtifactRequest(artifact, null, null); + LocalArtifactResult result = manager.find(session, request); + assertTrue(result.isAvailable()); + assertNull(result.getRepository()); + + snapshot = snapshot.setVersion(snapshot.getBaseVersion()); + addLocalArtifact(snapshot); + + request = new LocalArtifactRequest(snapshot, null, null); + result = manager.find(session, request); + assertTrue(result.isAvailable()); + assertNull(result.getRepository()); } @Test - public void testFindRemoteArtifact() - throws Exception - { - addRemoteArtifact( artifact ); - - LocalArtifactRequest request = new LocalArtifactRequest( artifact, Arrays.asList( repository ), testContext ); - LocalArtifactResult result = manager.find( session, request ); - assertTrue( result.isAvailable() ); - assertEquals( repository, result.getRepository() ); - - addRemoteArtifact( snapshot ); - - request = new LocalArtifactRequest( snapshot, Arrays.asList( repository ), testContext ); - result = manager.find( session, request ); - assertTrue( result.isAvailable() ); - assertEquals( repository, result.getRepository() ); + public void testFindRemoteArtifact() throws Exception { + addRemoteArtifact(artifact); + + LocalArtifactRequest request = new LocalArtifactRequest(artifact, Arrays.asList(repository), testContext); + LocalArtifactResult result = manager.find(session, request); + assertTrue(result.isAvailable()); + assertEquals(repository, result.getRepository()); + + addRemoteArtifact(snapshot); + + request = new LocalArtifactRequest(snapshot, Arrays.asList(repository), testContext); + result = manager.find(session, request); + assertTrue(result.isAvailable()); + assertEquals(repository, result.getRepository()); } @Test - public void testDoNotFindDifferentContext() - throws Exception - { - addRemoteArtifact( artifact ); - - LocalArtifactRequest request = new LocalArtifactRequest( artifact, Arrays.asList( repository ), "different" ); - LocalArtifactResult result = manager.find( session, request ); - assertFalse( result.isAvailable() ); + public void testDoNotFindDifferentContext() throws Exception { + addRemoteArtifact(artifact); + + LocalArtifactRequest request = new LocalArtifactRequest(artifact, Arrays.asList(repository), "different"); + LocalArtifactResult result = manager.find(session, request); + assertFalse(result.isAvailable()); } @Test - public void testDoNotFindNullFile() - throws Exception - { - artifact = artifact.setFile( null ); - addLocalArtifact( artifact ); - - LocalArtifactRequest request = new LocalArtifactRequest( artifact, Arrays.asList( repository ), testContext ); - LocalArtifactResult result = manager.find( session, request ); - assertFalse( result.isAvailable() ); + public void testDoNotFindNullFile() throws Exception { + artifact = artifact.setFile(null); + addLocalArtifact(artifact); + + LocalArtifactRequest request = new LocalArtifactRequest(artifact, Arrays.asList(repository), testContext); + LocalArtifactResult result = manager.find(session, request); + assertFalse(result.isAvailable()); } @Test - public void testDoNotFindDeletedFile() - throws Exception - { - addLocalArtifact( artifact ); - assertTrue( "could not delete artifact file", artifactFile.delete() ); - - LocalArtifactRequest request = new LocalArtifactRequest( artifact, Arrays.asList( repository ), testContext ); - LocalArtifactResult result = manager.find( session, request ); - assertFalse( result.isAvailable() ); + public void testDoNotFindDeletedFile() throws Exception { + addLocalArtifact(artifact); + assertTrue("could not delete artifact file", artifactFile.delete()); + + LocalArtifactRequest request = new LocalArtifactRequest(artifact, Arrays.asList(repository), testContext); + LocalArtifactResult result = manager.find(session, request); + assertFalse(result.isAvailable()); } @Test - public void testFindUntrackedFile() - throws Exception - { - copy( artifact, manager.getPathForLocalArtifact( artifact ) ); - - LocalArtifactRequest request = new LocalArtifactRequest( artifact, Arrays.asList( repository ), testContext ); - LocalArtifactResult result = manager.find( session, request ); - assertTrue( result.isAvailable() ); + public void testFindUntrackedFile() throws Exception { + copy(artifact, manager.getPathForLocalArtifact(artifact)); + + LocalArtifactRequest request = new LocalArtifactRequest(artifact, Arrays.asList(repository), testContext); + LocalArtifactResult result = manager.find(session, request); + assertTrue(result.isAvailable()); } - private long addMetadata( Metadata metadata, RemoteRepository repo ) - throws IOException - { + private long addMetadata(Metadata metadata, RemoteRepository repo) throws IOException { String path; - if ( repo == null ) - { - path = manager.getPathForLocalMetadata( metadata ); + if (repo == null) { + path = manager.getPathForLocalMetadata(metadata); + } else { + path = manager.getPathForRemoteMetadata(metadata, repo, testContext); } - else - { - path = manager.getPathForRemoteMetadata( metadata, repo, testContext ); - } - System.err.println( path ); + System.err.println(path); - return copy( metadata, path ); + return copy(metadata, path); } @Test - public void testFindLocalMetadata() - throws Exception - { - addMetadata( metadata, null ); + public void testFindLocalMetadata() throws Exception { + addMetadata(metadata, null); - LocalMetadataRequest request = new LocalMetadataRequest( metadata, null, testContext ); - LocalMetadataResult result = manager.find( session, request ); + LocalMetadataRequest request = new LocalMetadataRequest(metadata, null, testContext); + LocalMetadataResult result = manager.find(session, request); - assertNotNull( result.getFile() ); + assertNotNull(result.getFile()); } @Test - public void testFindLocalMetadataNoVersion() - throws Exception - { - addMetadata( noVerMetadata, null ); + public void testFindLocalMetadataNoVersion() throws Exception { + addMetadata(noVerMetadata, null); - LocalMetadataRequest request = new LocalMetadataRequest( noVerMetadata, null, testContext ); - LocalMetadataResult result = manager.find( session, request ); + LocalMetadataRequest request = new LocalMetadataRequest(noVerMetadata, null, testContext); + LocalMetadataResult result = manager.find(session, request); - assertNotNull( result.getFile() ); + assertNotNull(result.getFile()); } @Test - public void testDoNotFindRemoteMetadataDifferentContext() - throws Exception - { - addMetadata( noVerMetadata, repository ); - addMetadata( metadata, repository ); - - LocalMetadataRequest request = new LocalMetadataRequest( noVerMetadata, repository, "different" ); - LocalMetadataResult result = manager.find( session, request ); - assertNull( result.getFile() ); - - request = new LocalMetadataRequest( metadata, repository, "different" ); - result = manager.find( session, request ); - assertNull( result.getFile() ); + public void testDoNotFindRemoteMetadataDifferentContext() throws Exception { + addMetadata(noVerMetadata, repository); + addMetadata(metadata, repository); + + LocalMetadataRequest request = new LocalMetadataRequest(noVerMetadata, repository, "different"); + LocalMetadataResult result = manager.find(session, request); + assertNull(result.getFile()); + + request = new LocalMetadataRequest(metadata, repository, "different"); + result = manager.find(session, request); + assertNull(result.getFile()); } @Test - public void testFindArtifactUsesTimestampedVersion() - throws Exception - { - Artifact artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-SNAPSHOT" ); - File file = new File( basedir, manager.getPathForLocalArtifact( artifact ) ); - TestFileUtils.writeString( file, "test" ); - addLocalArtifact( artifact ); - - artifact = artifact.setVersion( "1.0-20110329.221805-4" ); + public void testFindArtifactUsesTimestampedVersion() throws Exception { + Artifact artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-SNAPSHOT"); + File file = new File(basedir, manager.getPathForLocalArtifact(artifact)); + TestFileUtils.writeString(file, "test"); + addLocalArtifact(artifact); + + artifact = artifact.setVersion("1.0-20110329.221805-4"); LocalArtifactRequest request = new LocalArtifactRequest(); - request.setArtifact( artifact ); - LocalArtifactResult result = manager.find( session, request ); - assertNull( result.toString(), result.getFile() ); - assertFalse( result.toString(), result.isAvailable() ); + request.setArtifact(artifact); + LocalArtifactResult result = manager.find(session, request); + assertNull(result.toString(), result.getFile()); + assertFalse(result.toString(), result.isAvailable()); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/EnhancedSplitLocalRepositoryManagerTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/EnhancedSplitLocalRepositoryManagerTest.java index 540364604..81f40603a 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/EnhancedSplitLocalRepositoryManagerTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/EnhancedSplitLocalRepositoryManagerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; @@ -26,49 +25,48 @@ import static org.junit.Assert.assertEquals; -public class EnhancedSplitLocalRepositoryManagerTest extends EnhancedLocalRepositoryManagerTest -{ +public class EnhancedSplitLocalRepositoryManagerTest extends EnhancedLocalRepositoryManagerTest { @Override - protected EnhancedLocalRepositoryManager getManager() - { - session.setConfigProperty( "aether.enhancedLocalRepository.split", Boolean.TRUE.toString() ); + protected EnhancedLocalRepositoryManager getManager() { + session.setConfigProperty("aether.enhancedLocalRepository.split", Boolean.TRUE.toString()); return new EnhancedLocalRepositoryManager( basedir, new DefaultLocalPathComposer(), "_remote.repositories", trackingFileManager, - new DefaultLocalPathPrefixComposerFactory().createComposer( session ) - ); + new DefaultLocalPathPrefixComposerFactory().createComposer(session)); } @Test @Override - public void testGetPathForLocalArtifact() - { - Artifact artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-SNAPSHOT" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "installed/g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact( artifact ) ); + public void testGetPathForLocalArtifact() { + Artifact artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-SNAPSHOT"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals( + "installed/g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact(artifact)); - artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-20110329.221805-4" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "installed/g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact( artifact ) ); + artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-20110329.221805-4"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals( + "installed/g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact(artifact)); } @Test @Override - public void testGetPathForRemoteArtifact() - { - RemoteRepository remoteRepo = new RemoteRepository.Builder( "repo", "default", "ram:/void" ).build(); + public void testGetPathForRemoteArtifact() { + RemoteRepository remoteRepo = new RemoteRepository.Builder("repo", "default", "ram:/void").build(); - Artifact artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-SNAPSHOT" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "cached/g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", - manager.getPathForRemoteArtifact( artifact, remoteRepo, "" ) ); + Artifact artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-SNAPSHOT"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals( + "cached/g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", + manager.getPathForRemoteArtifact(artifact, remoteRepo, "")); - artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-20110329.221805-4" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "cached/g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-20110329.221805-4.jar", - manager.getPathForRemoteArtifact( artifact, remoteRepo, "" ) ); + artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-20110329.221805-4"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals( + "cached/g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-20110329.221805-4.jar", + manager.getPathForRemoteArtifact(artifact, remoteRepo, "")); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/FailChecksumPolicyTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/FailChecksumPolicyTest.java index 6ba71889c..a98702c3c 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/FailChecksumPolicyTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/FailChecksumPolicyTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import org.eclipse.aether.spi.connector.checksum.ChecksumPolicy.ChecksumKind; import org.eclipse.aether.transfer.ChecksumFailureException; @@ -27,86 +24,66 @@ import org.junit.Before; import org.junit.Test; -public class FailChecksumPolicyTest -{ +import static org.junit.Assert.*; + +public class FailChecksumPolicyTest { private FailChecksumPolicy policy; private ChecksumFailureException exception; @Before - public void setup() - { - policy = new FailChecksumPolicy( new TransferResource( "null", "file:/dev/null", "file.txt", null, null ) ); - exception = new ChecksumFailureException( "test" ); + public void setup() { + policy = new FailChecksumPolicy(new TransferResource("null", "file:/dev/null", "file.txt", null, null)); + exception = new ChecksumFailureException("test"); } @Test - public void testOnTransferChecksumFailure() - { - assertFalse( policy.onTransferChecksumFailure( exception ) ); + public void testOnTransferChecksumFailure() { + assertFalse(policy.onTransferChecksumFailure(exception)); } @Test - public void testOnChecksumMatch() - { - assertTrue( policy.onChecksumMatch( "SHA-1", ChecksumKind.REMOTE_EXTERNAL ) ); - assertTrue( policy.onChecksumMatch( "SHA-1", ChecksumKind.REMOTE_INCLUDED ) ); - assertTrue( policy.onChecksumMatch( "SHA-1", ChecksumKind.PROVIDED ) ); + public void testOnChecksumMatch() { + assertTrue(policy.onChecksumMatch("SHA-1", ChecksumKind.REMOTE_EXTERNAL)); + assertTrue(policy.onChecksumMatch("SHA-1", ChecksumKind.REMOTE_INCLUDED)); + assertTrue(policy.onChecksumMatch("SHA-1", ChecksumKind.PROVIDED)); } @Test - public void testOnChecksumMismatch() - throws Exception - { - try - { - policy.onChecksumMismatch( "SHA-1", ChecksumKind.REMOTE_EXTERNAL, exception ); - fail( "No exception" ); - } - catch ( ChecksumFailureException e ) - { - assertSame( exception, e ); - } - try - { - policy.onChecksumMismatch( "SHA-1", ChecksumKind.REMOTE_INCLUDED, exception ); - fail( "No exception" ); + public void testOnChecksumMismatch() throws Exception { + try { + policy.onChecksumMismatch("SHA-1", ChecksumKind.REMOTE_EXTERNAL, exception); + fail("No exception"); + } catch (ChecksumFailureException e) { + assertSame(exception, e); } - catch ( ChecksumFailureException e ) - { - assertSame( exception, e ); + try { + policy.onChecksumMismatch("SHA-1", ChecksumKind.REMOTE_INCLUDED, exception); + fail("No exception"); + } catch (ChecksumFailureException e) { + assertSame(exception, e); } - try - { + try { policy.onChecksumMismatch("SHA-1", ChecksumKind.PROVIDED, exception); - fail( "No exception" ); - } - catch ( ChecksumFailureException e) - { - assertSame( exception, e ); + fail("No exception"); + } catch (ChecksumFailureException e) { + assertSame(exception, e); } } @Test - public void testOnChecksumError() - throws Exception - { - policy.onChecksumError( "SHA-1", ChecksumKind.REMOTE_EXTERNAL, exception ); + public void testOnChecksumError() throws Exception { + policy.onChecksumError("SHA-1", ChecksumKind.REMOTE_EXTERNAL, exception); } @Test - public void testOnNoMoreChecksums() - { - try - { + public void testOnNoMoreChecksums() { + try { policy.onNoMoreChecksums(); - fail( "No exception" ); - } - catch ( ChecksumFailureException e ) - { - assertTrue( e.getMessage().contains( "no checksums available" ) ); + fail("No exception"); + } catch (ChecksumFailureException e) { + assertTrue(e.getMessage().contains("no checksums available")); } } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/IniArtifactDescriptorReader.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/IniArtifactDescriptorReader.java index 4ae2b9b9d..64e2e2007 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/IniArtifactDescriptorReader.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/IniArtifactDescriptorReader.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,22 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.impl.ArtifactDescriptorReader; /** */ -public class IniArtifactDescriptorReader - extends org.eclipse.aether.internal.test.util.IniArtifactDescriptorReader - implements ArtifactDescriptorReader -{ +public class IniArtifactDescriptorReader extends org.eclipse.aether.internal.test.util.IniArtifactDescriptorReader + implements ArtifactDescriptorReader { /** * Use the given prefix to load the artifact descriptions. */ - public IniArtifactDescriptorReader( String prefix ) - { - super( prefix ); + public IniArtifactDescriptorReader(String prefix) { + super(prefix); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/Maven2RepositoryLayoutFactoryTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/Maven2RepositoryLayoutFactoryTest.java index 7b7fecf09..5db78f196 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/Maven2RepositoryLayoutFactoryTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/Maven2RepositoryLayoutFactoryTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.net.URI; import java.util.Arrays; @@ -41,8 +38,9 @@ import org.junit.Before; import org.junit.Test; -public class Maven2RepositoryLayoutFactoryTest -{ +import static org.junit.Assert.*; + +public class Maven2RepositoryLayoutFactoryTest { private final ChecksumAlgorithmFactory SHA512 = new ChecksumAlgorithmFactorySupport("SHA-512", "sha512") { @Override public ChecksumAlgorithm getAlgorithm() { @@ -77,286 +75,256 @@ public ChecksumAlgorithm getAlgorithm() { private RepositoryLayout layout; - private RemoteRepository newRepo( String type ) - { - return new RemoteRepository.Builder( "test", type, "classpath:/nil" ).build(); + private RemoteRepository newRepo(String type) { + return new RemoteRepository.Builder("test", type, "classpath:/nil").build(); } - private void assertChecksum( ChecksumLocation actual, String expectedUri, String expectedAlgo ) - { - assertEquals( expectedUri, actual.getLocation().toString() ); - assertEquals( expectedAlgo, actual.getChecksumAlgorithmFactory().getName() ); + private void assertChecksum(ChecksumLocation actual, String expectedUri, String expectedAlgo) { + assertEquals(expectedUri, actual.getLocation().toString()); + assertEquals(expectedAlgo, actual.getChecksumAlgorithmFactory().getName()); } - private void assertChecksum( ChecksumLocation actual, String expectedUri, ChecksumAlgorithmFactory expectedAlgorithmFactory ) - { - assertChecksum( actual, expectedUri, expectedAlgorithmFactory.getName() ); + private void assertChecksum( + ChecksumLocation actual, String expectedUri, ChecksumAlgorithmFactory expectedAlgorithmFactory) { + assertChecksum(actual, expectedUri, expectedAlgorithmFactory.getName()); } - private void assertChecksums( List actual, String baseUri, ChecksumAlgorithmFactory... algos ) - { - assertEquals( algos.length, actual.size() ); - for ( int i = 0; i < algos.length; i++ ) - { + private void assertChecksums(List actual, String baseUri, ChecksumAlgorithmFactory... algos) { + assertEquals(algos.length, actual.size()); + for (int i = 0; i < algos.length; i++) { String uri = baseUri + '.' + algos[i].getFileExtension(); - assertChecksum( actual.get( i ), uri, algos[i] ); + assertChecksum(actual.get(i), uri, algos[i]); } } @Before - public void setUp() - throws Exception - { + public void setUp() throws Exception { session = TestUtils.newSession(); factory = new Maven2RepositoryLayoutFactory(); - layout = factory.newInstance( session, newRepo( "default" ) ); + layout = factory.newInstance(session, newRepo("default")); } - @Test( expected = NoRepositoryLayoutException.class ) - public void testBadLayout() - throws Exception - { - factory.newInstance( session, newRepo( "DEFAULT" ) ); + @Test(expected = NoRepositoryLayoutException.class) + public void testBadLayout() throws Exception { + factory.newInstance(session, newRepo("DEFAULT")); } @Test - public void testChecksumAlgorithmNames() - { - assertEquals( Arrays.asList( "SHA-1", "MD5" ), + public void testChecksumAlgorithmNames() { + assertEquals( + Arrays.asList("SHA-1", "MD5"), layout.getChecksumAlgorithmFactories().stream() - .map( ChecksumAlgorithmFactory::getName ) - .collect( Collectors.toList() ) - ); + .map(ChecksumAlgorithmFactory::getName) + .collect(Collectors.toList())); } @Test - public void testArtifactLocation_Release() - { - DefaultArtifact artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "ext", "1.0" ); - URI uri = layout.getLocation( artifact, false ); - assertEquals( "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext", uri.toString() ); - uri = layout.getLocation( artifact, true ); - assertEquals( "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext", uri.toString() ); + public void testArtifactLocation_Release() { + DefaultArtifact artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "ext", "1.0"); + URI uri = layout.getLocation(artifact, false); + assertEquals("g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext", uri.toString()); + uri = layout.getLocation(artifact, true); + assertEquals("g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext", uri.toString()); } @Test - public void testArtifactLocation_Snapshot() - { - DefaultArtifact artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "ext", "1.0-20110329.221805-4" ); - URI uri = layout.getLocation( artifact, false ); - assertEquals( "g/i/d/a-i.d/1.0-SNAPSHOT/a-i.d-1.0-20110329.221805-4-cls.ext", uri.toString() ); - uri = layout.getLocation( artifact, true ); - assertEquals( "g/i/d/a-i.d/1.0-SNAPSHOT/a-i.d-1.0-20110329.221805-4-cls.ext", uri.toString() ); + public void testArtifactLocation_Snapshot() { + DefaultArtifact artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "ext", "1.0-20110329.221805-4"); + URI uri = layout.getLocation(artifact, false); + assertEquals("g/i/d/a-i.d/1.0-SNAPSHOT/a-i.d-1.0-20110329.221805-4-cls.ext", uri.toString()); + uri = layout.getLocation(artifact, true); + assertEquals("g/i/d/a-i.d/1.0-SNAPSHOT/a-i.d-1.0-20110329.221805-4-cls.ext", uri.toString()); } @Test - public void testMetadataLocation_RootLevel() - { - DefaultMetadata metadata = new DefaultMetadata( "archetype-catalog.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); - URI uri = layout.getLocation( metadata, false ); - assertEquals( "archetype-catalog.xml", uri.toString() ); - uri = layout.getLocation( metadata, true ); - assertEquals( "archetype-catalog.xml", uri.toString() ); + public void testMetadataLocation_RootLevel() { + DefaultMetadata metadata = new DefaultMetadata("archetype-catalog.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); + URI uri = layout.getLocation(metadata, false); + assertEquals("archetype-catalog.xml", uri.toString()); + uri = layout.getLocation(metadata, true); + assertEquals("archetype-catalog.xml", uri.toString()); } @Test - public void testMetadataLocation_GroupLevel() - { - DefaultMetadata metadata = - new DefaultMetadata( "org.apache.maven.plugins", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); - URI uri = layout.getLocation( metadata, false ); - assertEquals( "org/apache/maven/plugins/maven-metadata.xml", uri.toString() ); - uri = layout.getLocation( metadata, true ); - assertEquals( "org/apache/maven/plugins/maven-metadata.xml", uri.toString() ); + public void testMetadataLocation_GroupLevel() { + DefaultMetadata metadata = new DefaultMetadata( + "org.apache.maven.plugins", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); + URI uri = layout.getLocation(metadata, false); + assertEquals("org/apache/maven/plugins/maven-metadata.xml", uri.toString()); + uri = layout.getLocation(metadata, true); + assertEquals("org/apache/maven/plugins/maven-metadata.xml", uri.toString()); } @Test - public void testMetadataLocation_ArtifactLevel() - { - DefaultMetadata metadata = - new DefaultMetadata( "org.apache.maven.plugins", "maven-jar-plugin", "maven-metadata.xml", - Metadata.Nature.RELEASE_OR_SNAPSHOT ); - URI uri = layout.getLocation( metadata, false ); - assertEquals( "org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml", uri.toString() ); - uri = layout.getLocation( metadata, true ); - assertEquals( "org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml", uri.toString() ); + public void testMetadataLocation_ArtifactLevel() { + DefaultMetadata metadata = new DefaultMetadata( + "org.apache.maven.plugins", + "maven-jar-plugin", + "maven-metadata.xml", + Metadata.Nature.RELEASE_OR_SNAPSHOT); + URI uri = layout.getLocation(metadata, false); + assertEquals("org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml", uri.toString()); + uri = layout.getLocation(metadata, true); + assertEquals("org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml", uri.toString()); } @Test - public void testMetadataLocation_VersionLevel() - { - DefaultMetadata metadata = - new DefaultMetadata( "org.apache.maven.plugins", "maven-jar-plugin", "1.0-SNAPSHOT", "maven-metadata.xml", - Metadata.Nature.RELEASE_OR_SNAPSHOT ); - URI uri = layout.getLocation( metadata, false ); - assertEquals( "org/apache/maven/plugins/maven-jar-plugin/1.0-SNAPSHOT/maven-metadata.xml", uri.toString() ); - uri = layout.getLocation( metadata, true ); - assertEquals( "org/apache/maven/plugins/maven-jar-plugin/1.0-SNAPSHOT/maven-metadata.xml", uri.toString() ); + public void testMetadataLocation_VersionLevel() { + DefaultMetadata metadata = new DefaultMetadata( + "org.apache.maven.plugins", + "maven-jar-plugin", + "1.0-SNAPSHOT", + "maven-metadata.xml", + Metadata.Nature.RELEASE_OR_SNAPSHOT); + URI uri = layout.getLocation(metadata, false); + assertEquals("org/apache/maven/plugins/maven-jar-plugin/1.0-SNAPSHOT/maven-metadata.xml", uri.toString()); + uri = layout.getLocation(metadata, true); + assertEquals("org/apache/maven/plugins/maven-jar-plugin/1.0-SNAPSHOT/maven-metadata.xml", uri.toString()); } @Test - public void testArtifactChecksums_Download() - { - DefaultArtifact artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "ext", "1.0" ); - URI uri = layout.getLocation( artifact, false ); - List checksums = layout.getChecksumLocations( artifact, false, uri ); - assertEquals( 2, checksums.size() ); - assertChecksum( checksums.get( 0 ), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.sha1", SHA1 ); - assertChecksum( checksums.get( 1 ), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.md5", MD5 ); + public void testArtifactChecksums_Download() { + DefaultArtifact artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "ext", "1.0"); + URI uri = layout.getLocation(artifact, false); + List checksums = layout.getChecksumLocations(artifact, false, uri); + assertEquals(2, checksums.size()); + assertChecksum(checksums.get(0), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.sha1", SHA1); + assertChecksum(checksums.get(1), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.md5", MD5); } @Test - public void testArtifactChecksums_DownloadWithCustomAlgorithms() throws NoRepositoryLayoutException - { - session.setConfigProperty( Maven2RepositoryLayoutFactory.CONFIG_PROP_CHECKSUMS_ALGORITHMS, "SHA-256,SHA-1"); - layout = factory.newInstance( session, newRepo( "default" ) ); - DefaultArtifact artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "ext", "1.0" ); - URI uri = layout.getLocation( artifact, false ); - List checksums = layout.getChecksumLocations( artifact, false, uri ); - assertEquals( 2, checksums.size() ); - assertChecksum( checksums.get( 0 ), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.sha256", SHA256 ); - assertChecksum( checksums.get( 1 ), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.sha1", SHA1 ); + public void testArtifactChecksums_DownloadWithCustomAlgorithms() throws NoRepositoryLayoutException { + session.setConfigProperty(Maven2RepositoryLayoutFactory.CONFIG_PROP_CHECKSUMS_ALGORITHMS, "SHA-256,SHA-1"); + layout = factory.newInstance(session, newRepo("default")); + DefaultArtifact artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "ext", "1.0"); + URI uri = layout.getLocation(artifact, false); + List checksums = layout.getChecksumLocations(artifact, false, uri); + assertEquals(2, checksums.size()); + assertChecksum(checksums.get(0), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.sha256", SHA256); + assertChecksum(checksums.get(1), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.sha1", SHA1); } - @Test( expected = IllegalArgumentException.class ) - public void testArtifactChecksums_DownloadWithUnsupportedAlgorithms() throws NoRepositoryLayoutException - { - session.setConfigProperty( Maven2RepositoryLayoutFactory.CONFIG_PROP_CHECKSUMS_ALGORITHMS, "FOO,SHA-1"); - layout = factory.newInstance( session, newRepo( "default" ) ); + @Test(expected = IllegalArgumentException.class) + public void testArtifactChecksums_DownloadWithUnsupportedAlgorithms() throws NoRepositoryLayoutException { + session.setConfigProperty(Maven2RepositoryLayoutFactory.CONFIG_PROP_CHECKSUMS_ALGORITHMS, "FOO,SHA-1"); + layout = factory.newInstance(session, newRepo("default")); } @Test - public void testArtifactChecksums_Upload() - { - DefaultArtifact artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "ext", "1.0" ); - URI uri = layout.getLocation( artifact, true ); - List checksums = layout.getChecksumLocations( artifact, true, uri ); - assertEquals( 2, checksums.size() ); - assertChecksum( checksums.get( 0 ), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.sha1", SHA1 ); - assertChecksum( checksums.get( 1 ), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.md5", MD5 ); + public void testArtifactChecksums_Upload() { + DefaultArtifact artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "ext", "1.0"); + URI uri = layout.getLocation(artifact, true); + List checksums = layout.getChecksumLocations(artifact, true, uri); + assertEquals(2, checksums.size()); + assertChecksum(checksums.get(0), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.sha1", SHA1); + assertChecksum(checksums.get(1), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.md5", MD5); } @Test - public void testArtifactChecksums_UploadWithCustomAlgorithms() throws NoRepositoryLayoutException - { - session.setConfigProperty( Maven2RepositoryLayoutFactory.CONFIG_PROP_CHECKSUMS_ALGORITHMS, "SHA-512,MD5" ); - layout = factory.newInstance( session, newRepo( "default" ) ); - DefaultArtifact artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "ext", "1.0" ); - URI uri = layout.getLocation( artifact, true ); - List checksums = layout.getChecksumLocations( artifact, true, uri ); - assertEquals( 2, checksums.size() ); - assertChecksum( checksums.get( 0 ), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.sha512", SHA512 ); - assertChecksum( checksums.get( 1 ), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.md5", MD5 ); + public void testArtifactChecksums_UploadWithCustomAlgorithms() throws NoRepositoryLayoutException { + session.setConfigProperty(Maven2RepositoryLayoutFactory.CONFIG_PROP_CHECKSUMS_ALGORITHMS, "SHA-512,MD5"); + layout = factory.newInstance(session, newRepo("default")); + DefaultArtifact artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "ext", "1.0"); + URI uri = layout.getLocation(artifact, true); + List checksums = layout.getChecksumLocations(artifact, true, uri); + assertEquals(2, checksums.size()); + assertChecksum(checksums.get(0), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.sha512", SHA512); + assertChecksum(checksums.get(1), "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.ext.md5", MD5); } @Test - public void testMetadataChecksums_Download() - { - DefaultMetadata metadata = - new DefaultMetadata( "org.apache.maven.plugins", "maven-jar-plugin", "maven-metadata.xml", - Metadata.Nature.RELEASE_OR_SNAPSHOT ); - URI uri = layout.getLocation( metadata, false ); - List checksums = layout.getChecksumLocations( metadata, false, uri ); - assertEquals( 2, checksums.size() ); - assertChecksum( checksums.get( 0 ), "org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml.sha1", - SHA1 ); - assertChecksum( checksums.get( 1 ), "org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml.md5", - MD5 ); + public void testMetadataChecksums_Download() { + DefaultMetadata metadata = new DefaultMetadata( + "org.apache.maven.plugins", + "maven-jar-plugin", + "maven-metadata.xml", + Metadata.Nature.RELEASE_OR_SNAPSHOT); + URI uri = layout.getLocation(metadata, false); + List checksums = layout.getChecksumLocations(metadata, false, uri); + assertEquals(2, checksums.size()); + assertChecksum(checksums.get(0), "org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml.sha1", SHA1); + assertChecksum(checksums.get(1), "org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml.md5", MD5); } @Test - public void testMetadataChecksums_Upload() - { - DefaultMetadata metadata = - new DefaultMetadata( "org.apache.maven.plugins", "maven-jar-plugin", "maven-metadata.xml", - Metadata.Nature.RELEASE_OR_SNAPSHOT ); - URI uri = layout.getLocation( metadata, true ); - List checksums = layout.getChecksumLocations( metadata, true, uri ); - assertEquals( 2, checksums.size() ); - assertChecksum( checksums.get( 0 ), "org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml.sha1", - SHA1 ); - assertChecksum( checksums.get( 1 ), "org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml.md5", - MD5 ); + public void testMetadataChecksums_Upload() { + DefaultMetadata metadata = new DefaultMetadata( + "org.apache.maven.plugins", + "maven-jar-plugin", + "maven-metadata.xml", + Metadata.Nature.RELEASE_OR_SNAPSHOT); + URI uri = layout.getLocation(metadata, true); + List checksums = layout.getChecksumLocations(metadata, true, uri); + assertEquals(2, checksums.size()); + assertChecksum(checksums.get(0), "org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml.sha1", SHA1); + assertChecksum(checksums.get(1), "org/apache/maven/plugins/maven-jar-plugin/maven-metadata.xml.md5", MD5); } @Test - public void testSignatureChecksums_Download() - { - DefaultArtifact artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "asc", "1.0" ); - URI uri = layout.getLocation( artifact, false ); - List checksums = layout.getChecksumLocations( artifact, false, uri ); - assertChecksums( checksums, "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.asc", SHA1, MD5 ); - - artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "jar.asc", "1.0" ); - uri = layout.getLocation( artifact, false ); - checksums = layout.getChecksumLocations( artifact, false, uri ); - assertEquals( 0, checksums.size() ); + public void testSignatureChecksums_Download() { + DefaultArtifact artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "asc", "1.0"); + URI uri = layout.getLocation(artifact, false); + List checksums = layout.getChecksumLocations(artifact, false, uri); + assertChecksums(checksums, "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.asc", SHA1, MD5); + + artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "jar.asc", "1.0"); + uri = layout.getLocation(artifact, false); + checksums = layout.getChecksumLocations(artifact, false, uri); + assertEquals(0, checksums.size()); } @Test - public void testSignatureChecksums_Upload() - { - DefaultArtifact artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "asc", "1.0" ); - URI uri = layout.getLocation( artifact, true ); - List checksums = layout.getChecksumLocations( artifact, true, uri ); - assertChecksums( checksums, "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.asc", SHA1, MD5 ); - - artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "jar.asc", "1.0" ); - uri = layout.getLocation( artifact, true ); - checksums = layout.getChecksumLocations( artifact, true, uri ); - assertEquals( 0, checksums.size() ); + public void testSignatureChecksums_Upload() { + DefaultArtifact artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "asc", "1.0"); + URI uri = layout.getLocation(artifact, true); + List checksums = layout.getChecksumLocations(artifact, true, uri); + assertChecksums(checksums, "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.asc", SHA1, MD5); + + artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "jar.asc", "1.0"); + uri = layout.getLocation(artifact, true); + checksums = layout.getChecksumLocations(artifact, true, uri); + assertEquals(0, checksums.size()); } @Test - public void testSignatureChecksums_Force() - throws Exception - { - session.setConfigProperty( Maven2RepositoryLayoutFactory.CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS, "" ); - layout = factory.newInstance( session, newRepo( "default" ) ); - DefaultArtifact artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "jar.asc", "1.0" ); - URI uri = layout.getLocation( artifact, true ); - List checksums = layout.getChecksumLocations( artifact, true, uri ); - assertChecksums( checksums, "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.jar.asc", SHA1, MD5 ); + public void testSignatureChecksums_Force() throws Exception { + session.setConfigProperty(Maven2RepositoryLayoutFactory.CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS, ""); + layout = factory.newInstance(session, newRepo("default")); + DefaultArtifact artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "jar.asc", "1.0"); + URI uri = layout.getLocation(artifact, true); + List checksums = layout.getChecksumLocations(artifact, true, uri); + assertChecksums(checksums, "g/i/d/a-i.d/1.0/a-i.d-1.0-cls.jar.asc", SHA1, MD5); } @Test - public void testCustomChecksumsIgnored() - throws Exception - { - session.setConfigProperty( Maven2RepositoryLayoutFactory.CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS, ".asc,.foo" ); - layout = factory.newInstance( session, newRepo( "default" ) ); - DefaultArtifact artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "jar.foo", "1.0" ); - URI uri = layout.getLocation( artifact, true ); - List checksums = layout.getChecksumLocations( artifact, true, uri ); - assertEquals( 0, checksums.size() ); + public void testCustomChecksumsIgnored() throws Exception { + session.setConfigProperty(Maven2RepositoryLayoutFactory.CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS, ".asc,.foo"); + layout = factory.newInstance(session, newRepo("default")); + DefaultArtifact artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "jar.foo", "1.0"); + URI uri = layout.getLocation(artifact, true); + List checksums = layout.getChecksumLocations(artifact, true, uri); + assertEquals(0, checksums.size()); } @Test - public void testNotConfiguredButSupportedChecksumsHandledAsChecksums() - throws Exception - { - layout = factory.newInstance( session, newRepo( "default" ) ); - DefaultArtifact artifact = new DefaultArtifact( "g.i.d", "a-i.d", "cls", "jar.sha512", "1.0" ); - URI uri = layout.getLocation( artifact, true ); - List checksums = layout.getChecksumLocations( artifact, true, uri ); - assertEquals( 0, checksums.size() ); + public void testNotConfiguredButSupportedChecksumsHandledAsChecksums() throws Exception { + layout = factory.newInstance(session, newRepo("default")); + DefaultArtifact artifact = new DefaultArtifact("g.i.d", "a-i.d", "cls", "jar.sha512", "1.0"); + URI uri = layout.getLocation(artifact, true); + List checksums = layout.getChecksumLocations(artifact, true, uri); + assertEquals(0, checksums.size()); } @Test - public void testCustomChecksumsIgnored_IllegalInout() - throws Exception - { - session.setConfigProperty( Maven2RepositoryLayoutFactory.CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS, ".asc,foo" ); - try - { - layout = factory.newInstance( session, newRepo( "default" ) ); - fail( "Should not get here" ); - } - catch ( IllegalArgumentException e ) - { + public void testCustomChecksumsIgnored_IllegalInout() throws Exception { + session.setConfigProperty(Maven2RepositoryLayoutFactory.CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS, ".asc,foo"); + try { + layout = factory.newInstance(session, newRepo("default")); + fail("Should not get here"); + } catch (IllegalArgumentException e) { String message = e.getMessage(); - assertTrue( message, message.contains( Maven2RepositoryLayoutFactory.CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS ) ); + assertTrue( + message, message.contains(Maven2RepositoryLayoutFactory.CONFIG_PROP_OMIT_CHECKSUMS_FOR_EXTENSIONS)); } } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/PrioritizedComponentTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/PrioritizedComponentTest.java index 1644f720d..7859a5c0e 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/PrioritizedComponentTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/PrioritizedComponentTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,56 +16,51 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import org.junit.Test; -public class PrioritizedComponentTest -{ +import static org.junit.Assert.*; + +public class PrioritizedComponentTest { @Test - public void testIsDisabled() - { - assertTrue(new PrioritizedComponent<>( "", String.class, Float.NaN, 0 ).isDisabled() ); - assertFalse(new PrioritizedComponent<>( "", String.class, 0, 0 ).isDisabled() ); - assertFalse(new PrioritizedComponent<>( "", String.class, 1, 0 ).isDisabled() ); - assertFalse(new PrioritizedComponent<>( "", String.class, -1, 0 ).isDisabled() ); + public void testIsDisabled() { + assertTrue(new PrioritizedComponent<>("", String.class, Float.NaN, 0).isDisabled()); + assertFalse(new PrioritizedComponent<>("", String.class, 0, 0).isDisabled()); + assertFalse(new PrioritizedComponent<>("", String.class, 1, 0).isDisabled()); + assertFalse(new PrioritizedComponent<>("", String.class, -1, 0).isDisabled()); } @Test - public void testCompareTo() - { - assertCompare( 0, Float.NaN, Float.NaN ); - assertCompare( 0, 0, 0 ); + public void testCompareTo() { + assertCompare(0, Float.NaN, Float.NaN); + assertCompare(0, 0, 0); - assertCompare( 1, 0, 1 ); - assertCompare( 1, 2, Float.POSITIVE_INFINITY ); - assertCompare( 1, Float.NEGATIVE_INFINITY, -3 ); + assertCompare(1, 0, 1); + assertCompare(1, 2, Float.POSITIVE_INFINITY); + assertCompare(1, Float.NEGATIVE_INFINITY, -3); - assertCompare( 1, Float.NaN, 0 ); - assertCompare( 1, Float.NaN, -1 ); - assertCompare( 1, Float.NaN, Float.NEGATIVE_INFINITY ); - assertCompare( 1, Float.NaN, Float.POSITIVE_INFINITY ); + assertCompare(1, Float.NaN, 0); + assertCompare(1, Float.NaN, -1); + assertCompare(1, Float.NaN, Float.NEGATIVE_INFINITY); + assertCompare(1, Float.NaN, Float.POSITIVE_INFINITY); - assertCompare( -1, Float.NaN, 0, 1 ); - assertCompare( -1, 10, 0, 1 ); + assertCompare(-1, Float.NaN, 0, 1); + assertCompare(-1, 10, 0, 1); } - private void assertCompare( int expected, float priority1, float priority2 ) - { - PrioritizedComponent one = new PrioritizedComponent<>( "", String.class, priority1, 0 ); - PrioritizedComponent two = new PrioritizedComponent<>( "", String.class, priority2, 0 ); - assertEquals( expected, one.compareTo( two ) ); - assertEquals( -expected, two.compareTo( one ) ); + private void assertCompare(int expected, float priority1, float priority2) { + PrioritizedComponent one = new PrioritizedComponent<>("", String.class, priority1, 0); + PrioritizedComponent two = new PrioritizedComponent<>("", String.class, priority2, 0); + assertEquals(expected, one.compareTo(two)); + assertEquals(-expected, two.compareTo(one)); } - private void assertCompare( int expected, float priority, int index1, int index2 ) - { - PrioritizedComponent one = new PrioritizedComponent<>( "", String.class, priority, index1 ); - PrioritizedComponent two = new PrioritizedComponent<>( "", String.class, priority, index2 ); - assertEquals( expected, one.compareTo( two ) ); - assertEquals( -expected, two.compareTo( one ) ); + private void assertCompare(int expected, float priority, int index1, int index2) { + PrioritizedComponent one = new PrioritizedComponent<>("", String.class, priority, index1); + PrioritizedComponent two = new PrioritizedComponent<>("", String.class, priority, index2); + assertEquals(expected, one.compareTo(two)); + assertEquals(-expected, two.compareTo(one)); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/PrioritizedComponentsTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/PrioritizedComponentsTest.java index 379fe53be..9a90ea7a0 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/PrioritizedComponentsTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/PrioritizedComponentsTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,10 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +package org.eclipse.aether.internal.impl; import java.util.Collections; import java.util.HashMap; @@ -32,101 +27,101 @@ import org.eclipse.aether.ConfigurationProperties; import org.junit.Test; -public class PrioritizedComponentsTest -{ +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + +public class PrioritizedComponentsTest { @Test - public void testGetConfigKeys() - { - String[] keys = - { ConfigurationProperties.PREFIX_PRIORITY + "java.lang.String", - ConfigurationProperties.PREFIX_PRIORITY + "String" }; - assertArrayEquals( keys, PrioritizedComponents.getConfigKeys( String.class ) ); - - keys = - new String[] { ConfigurationProperties.PREFIX_PRIORITY + "java.util.concurrent.ThreadFactory", - ConfigurationProperties.PREFIX_PRIORITY + "ThreadFactory", - ConfigurationProperties.PREFIX_PRIORITY + "Thread" }; - assertArrayEquals( keys, PrioritizedComponents.getConfigKeys( ThreadFactory.class ) ); + public void testGetConfigKeys() { + String[] keys = { + ConfigurationProperties.PREFIX_PRIORITY + "java.lang.String", + ConfigurationProperties.PREFIX_PRIORITY + "String" + }; + assertArrayEquals(keys, PrioritizedComponents.getConfigKeys(String.class)); + + keys = new String[] { + ConfigurationProperties.PREFIX_PRIORITY + "java.util.concurrent.ThreadFactory", + ConfigurationProperties.PREFIX_PRIORITY + "ThreadFactory", + ConfigurationProperties.PREFIX_PRIORITY + "Thread" + }; + assertArrayEquals(keys, PrioritizedComponents.getConfigKeys(ThreadFactory.class)); } @Test - public void testAdd_PriorityOverride() - { + public void testAdd_PriorityOverride() { Exception comp1 = new IllegalArgumentException(); Exception comp2 = new NullPointerException(); Map config = new HashMap<>(); - config.put( ConfigurationProperties.PREFIX_PRIORITY + comp1.getClass().getName(), 6 ); - config.put( ConfigurationProperties.PREFIX_PRIORITY + comp2.getClass().getName(), 7 ); - PrioritizedComponents components = new PrioritizedComponents<>( config ); - components.add( comp1, 1 ); - components.add( comp2, 0 ); + config.put(ConfigurationProperties.PREFIX_PRIORITY + comp1.getClass().getName(), 6); + config.put(ConfigurationProperties.PREFIX_PRIORITY + comp2.getClass().getName(), 7); + PrioritizedComponents components = new PrioritizedComponents<>(config); + components.add(comp1, 1); + components.add(comp2, 0); List> sorted = components.getEnabled(); - assertEquals( 2, sorted.size() ); - assertSame( comp2, sorted.get( 0 ).getComponent() ); - assertEquals( 7, sorted.get( 0 ).getPriority(), 0.1f ); - assertSame( comp1, sorted.get( 1 ).getComponent() ); - assertEquals( 6, sorted.get( 1 ).getPriority(), 0.1f ); + assertEquals(2, sorted.size()); + assertSame(comp2, sorted.get(0).getComponent()); + assertEquals(7, sorted.get(0).getPriority(), 0.1f); + assertSame(comp1, sorted.get(1).getComponent()); + assertEquals(6, sorted.get(1).getPriority(), 0.1f); } @Test - public void testAdd_ImplicitPriority() - { + public void testAdd_ImplicitPriority() { Exception comp1 = new IllegalArgumentException(); Exception comp2 = new NullPointerException(); Map config = new HashMap<>(); - config.put( ConfigurationProperties.IMPLICIT_PRIORITIES, true ); - PrioritizedComponents components = new PrioritizedComponents<>( config ); - components.add( comp1, 1 ); - components.add( comp2, 2 ); + config.put(ConfigurationProperties.IMPLICIT_PRIORITIES, true); + PrioritizedComponents components = new PrioritizedComponents<>(config); + components.add(comp1, 1); + components.add(comp2, 2); List> sorted = components.getEnabled(); - assertEquals( 2, sorted.size() ); - assertSame( comp1, sorted.get( 0 ).getComponent() ); - assertSame( comp2, sorted.get( 1 ).getComponent() ); + assertEquals(2, sorted.size()); + assertSame(comp1, sorted.get(0).getComponent()); + assertSame(comp2, sorted.get(1).getComponent()); } @Test - public void testAdd_Disabled() - { + public void testAdd_Disabled() { Exception comp1 = new IllegalArgumentException(); Exception comp2 = new NullPointerException(); Map config = new HashMap<>(); - PrioritizedComponents components = new PrioritizedComponents<>( config ); + PrioritizedComponents components = new PrioritizedComponents<>(config); - components.add( new UnsupportedOperationException(), Float.NaN ); + components.add(new UnsupportedOperationException(), Float.NaN); List> sorted = components.getEnabled(); - assertEquals( 0, sorted.size() ); + assertEquals(0, sorted.size()); - components.add( comp1, 1 ); + components.add(comp1, 1); sorted = components.getEnabled(); - assertEquals( 1, sorted.size() ); - assertSame( comp1, sorted.get( 0 ).getComponent() ); + assertEquals(1, sorted.size()); + assertSame(comp1, sorted.get(0).getComponent()); - components.add( new Exception(), Float.NaN ); + components.add(new Exception(), Float.NaN); sorted = components.getEnabled(); - assertEquals( 1, sorted.size() ); - assertSame( comp1, sorted.get( 0 ).getComponent() ); + assertEquals(1, sorted.size()); + assertSame(comp1, sorted.get(0).getComponent()); - components.add( comp2, 0 ); + components.add(comp2, 0); sorted = components.getEnabled(); - assertEquals( 2, sorted.size() ); - assertSame( comp1, sorted.get( 0 ).getComponent() ); - assertSame( comp2, sorted.get( 1 ).getComponent() ); + assertEquals(2, sorted.size()); + assertSame(comp1, sorted.get(0).getComponent()); + assertSame(comp2, sorted.get(1).getComponent()); } @Test - public void testList() - { + public void testList() { Exception comp1 = new IllegalArgumentException(); Exception comp2 = new NullPointerException(); - PrioritizedComponents components = new PrioritizedComponents<>( Collections.emptyMap() ); - components.add( comp1, 1 ); - components.add( comp2, 0 ); + PrioritizedComponents components = new PrioritizedComponents<>(Collections.emptyMap()); + components.add(comp1, 1); + components.add(comp2, 0); StringBuilder stringBuilder = new StringBuilder(); - components.list( stringBuilder ); + components.list(stringBuilder); - assertEquals( "IllegalArgumentException, NullPointerException", stringBuilder.toString() ); + assertEquals("IllegalArgumentException, NullPointerException", stringBuilder.toString()); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/RecordingRepositoryConnector.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/RecordingRepositoryConnector.java index 05d0890ff..e99c23a78 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/RecordingRepositoryConnector.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/RecordingRepositoryConnector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.util.ArrayList; import java.util.Collection; @@ -41,12 +38,12 @@ import org.eclipse.aether.transfer.TransferListener; import org.eclipse.aether.transfer.TransferResource; +import static org.junit.Assert.*; + /** * A repository connector recording all get/put-requests and faking the results. */ -class RecordingRepositoryConnector - implements RepositoryConnector -{ +class RecordingRepositoryConnector implements RepositoryConnector { RepositorySystemSession session; @@ -68,9 +65,12 @@ class RecordingRepositoryConnector private List actualPutMD = new ArrayList<>(); - public RecordingRepositoryConnector( RepositorySystemSession session, Artifact[] expectGet, Artifact[] expectPut, - Metadata[] expectGetMD, Metadata[] expectPutMD ) - { + public RecordingRepositoryConnector( + RepositorySystemSession session, + Artifact[] expectGet, + Artifact[] expectPut, + Metadata[] expectGetMD, + Metadata[] expectPutMD) { this.session = session; this.expectGet = expectGet; this.expectPut = expectPut; @@ -78,220 +78,169 @@ public RecordingRepositoryConnector( RepositorySystemSession session, Artifact[] this.expectPutMD = expectPutMD; } - public RecordingRepositoryConnector( RepositorySystemSession session ) - { + public RecordingRepositoryConnector(RepositorySystemSession session) { this.session = session; } - public RecordingRepositoryConnector() - { - } + public RecordingRepositoryConnector() {} - public void get( Collection artifactDownloads, - Collection metadataDownloads ) - { - try - { - if ( artifactDownloads != null ) - { - for ( ArtifactDownload download : artifactDownloads ) - { - fireInitiated( download ); + public void get( + Collection artifactDownloads, + Collection metadataDownloads) { + try { + if (artifactDownloads != null) { + for (ArtifactDownload download : artifactDownloads) { + fireInitiated(download); Artifact artifact = download.getArtifact(); - this.actualGet.add( artifact ); - if ( fail ) - { - download.setException( new ArtifactTransferException( artifact, null, "forced failure" ) ); - } - else - { - TestFileUtils.writeString( download.getFile(), artifact.toString() ); + this.actualGet.add(artifact); + if (fail) { + download.setException(new ArtifactTransferException(artifact, null, "forced failure")); + } else { + TestFileUtils.writeString(download.getFile(), artifact.toString()); } - fireDone( download ); + fireDone(download); } } - if ( metadataDownloads != null ) - { - for ( MetadataDownload download : metadataDownloads ) - { - fireInitiated( download ); + if (metadataDownloads != null) { + for (MetadataDownload download : metadataDownloads) { + fireInitiated(download); Metadata metadata = download.getMetadata(); - this.actualGetMD.add( metadata ); - if ( fail ) - { - download.setException( new MetadataTransferException( metadata, null, "forced failure" ) ); + this.actualGetMD.add(metadata); + if (fail) { + download.setException(new MetadataTransferException(metadata, null, "forced failure")); + } else { + TestFileUtils.writeString(download.getFile(), metadata.toString()); } - else - { - TestFileUtils.writeString( download.getFile(), metadata.toString() ); - } - fireDone( download ); + fireDone(download); } } - } - catch ( Exception e ) - { - throw new IllegalStateException( e ); + } catch (Exception e) { + throw new IllegalStateException(e); } } - public void put( Collection artifactUploads, - Collection metadataUploads ) - { - try - { - if ( artifactUploads != null ) - { - for ( ArtifactUpload upload : artifactUploads ) - { + public void put( + Collection artifactUploads, + Collection metadataUploads) { + try { + if (artifactUploads != null) { + for (ArtifactUpload upload : artifactUploads) { // mimic "real" connector - fireInitiated( upload ); - if ( upload.getFile() == null ) - { - upload.setException( new ArtifactTransferException( upload.getArtifact(), null, "no file" ) ); + fireInitiated(upload); + if (upload.getFile() == null) { + upload.setException(new ArtifactTransferException(upload.getArtifact(), null, "no file")); + } else if (fail) { + upload.setException( + new ArtifactTransferException(upload.getArtifact(), null, "forced failure")); } - else if ( fail ) - { - upload.setException( new ArtifactTransferException( upload.getArtifact(), null, - "forced failure" ) ); - } - this.actualPut.add( upload.getArtifact() ); - fireDone( upload ); + this.actualPut.add(upload.getArtifact()); + fireDone(upload); } } - if ( metadataUploads != null ) - { - for ( MetadataUpload upload : metadataUploads ) - { + if (metadataUploads != null) { + for (MetadataUpload upload : metadataUploads) { // mimic "real" connector - fireInitiated( upload ); - if ( upload.getFile() == null ) - { - upload.setException( new MetadataTransferException( upload.getMetadata(), null, "no file" ) ); - } - else if ( fail ) - { - upload.setException( new MetadataTransferException( upload.getMetadata(), null, - "forced failure" ) ); + fireInitiated(upload); + if (upload.getFile() == null) { + upload.setException(new MetadataTransferException(upload.getMetadata(), null, "no file")); + } else if (fail) { + upload.setException( + new MetadataTransferException(upload.getMetadata(), null, "forced failure")); } - this.actualPutMD.add( upload.getMetadata() ); - fireDone( upload ); + this.actualPutMD.add(upload.getMetadata()); + fireDone(upload); } } - } - catch ( Exception e ) - { - throw new IllegalStateException( e ); + } catch (Exception e) { + throw new IllegalStateException(e); } } - private void fireInitiated( Transfer transfer ) - throws Exception - { + private void fireInitiated(Transfer transfer) throws Exception { TransferListener listener = transfer.getListener(); - if ( listener == null ) - { + if (listener == null) { return; } TransferEvent.Builder event = - new TransferEvent.Builder( session, new TransferResource( null, null, null, null, transfer.getTrace() ) ); - event.setType( TransferEvent.EventType.INITIATED ); - listener.transferInitiated( event.build() ); + new TransferEvent.Builder(session, new TransferResource(null, null, null, null, transfer.getTrace())); + event.setType(TransferEvent.EventType.INITIATED); + listener.transferInitiated(event.build()); } - private void fireDone( Transfer transfer ) - { + private void fireDone(Transfer transfer) { TransferListener listener = transfer.getListener(); - if ( listener == null ) - { + if (listener == null) { return; } TransferEvent.Builder event = - new TransferEvent.Builder( session, new TransferResource( null, null, null, null, transfer.getTrace() ) ); - event.setException( transfer.getException() ); - if ( transfer.getException() != null ) - { - listener.transferFailed( event.setType( TransferEvent.EventType.FAILED ).build() ); - } - else - { - listener.transferSucceeded( event.setType( TransferEvent.EventType.SUCCEEDED ).build() ); + new TransferEvent.Builder(session, new TransferResource(null, null, null, null, transfer.getTrace())); + event.setException(transfer.getException()); + if (transfer.getException() != null) { + listener.transferFailed( + event.setType(TransferEvent.EventType.FAILED).build()); + } else { + listener.transferSucceeded( + event.setType(TransferEvent.EventType.SUCCEEDED).build()); } } - public void close() - { - } + public void close() {} - public void assertSeenExpected() - { - assertSeenExpected( actualGet, expectGet ); - assertSeenExpected( actualGetMD, expectGetMD ); - assertSeenExpected( actualPut, expectPut ); - assertSeenExpected( actualPutMD, expectPutMD ); + public void assertSeenExpected() { + assertSeenExpected(actualGet, expectGet); + assertSeenExpected(actualGetMD, expectGetMD); + assertSeenExpected(actualPut, expectPut); + assertSeenExpected(actualPutMD, expectPutMD); } - private void assertSeenExpected( List actual, Object[] expected ) - { - if ( expected == null ) - { + private void assertSeenExpected(List actual, Object[] expected) { + if (expected == null) { expected = new Object[0]; } - assertEquals( "different number of expected and actual elements:\n", expected.length, actual.size() ); + assertEquals("different number of expected and actual elements:\n", expected.length, actual.size()); int idx = 0; - for ( Object actualObject : actual ) - { - assertEquals( "seen object differs", expected[idx++], actualObject ); + for (Object actualObject : actual) { + assertEquals("seen object differs", expected[idx++], actualObject); } } - public List getActualArtifactGetRequests() - { + public List getActualArtifactGetRequests() { return actualGet; } - public List getActualMetadataGetRequests() - { + public List getActualMetadataGetRequests() { return actualGetMD; } - public List getActualArtifactPutRequests() - { + public List getActualArtifactPutRequests() { return actualPut; } - public List getActualMetadataPutRequests() - { + public List getActualMetadataPutRequests() { return actualPutMD; } - public void setExpectGet( Artifact... expectGet ) - { + public void setExpectGet(Artifact... expectGet) { this.expectGet = expectGet; } - public void setExpectPut( Artifact... expectPut ) - { + public void setExpectPut(Artifact... expectPut) { this.expectPut = expectPut; } - public void setExpectGet( Metadata... expectGetMD ) - { + public void setExpectGet(Metadata... expectGetMD) { this.expectGetMD = expectGetMD; } - public void setExpectPut( Metadata... expectPutMD ) - { + public void setExpectPut(Metadata... expectPutMD) { this.expectPutMD = expectPutMD; } - public void resetActual() - { + public void resetActual() { this.actualGet = new ArrayList<>(); this.actualGetMD = new ArrayList<>(); this.actualPut = new ArrayList<>(); this.actualPutMD = new ArrayList<>(); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/RecordingRepositoryListener.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/RecordingRepositoryListener.java index a9956da92..cd459e02c 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/RecordingRepositoryListener.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/RecordingRepositoryListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import java.util.ArrayList; import java.util.Collections; @@ -31,134 +30,110 @@ /** * Collects observed repository events for later inspection. */ -class RecordingRepositoryListener - implements RepositoryListener -{ +class RecordingRepositoryListener implements RepositoryListener { - private List events = Collections.synchronizedList( new ArrayList() ); + private List events = Collections.synchronizedList(new ArrayList()); - public List getEvents() - { + public List getEvents() { return events; } - public void clear() - { + public void clear() { events.clear(); } - public void artifactDescriptorInvalid( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void artifactDescriptorInvalid(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void artifactDescriptorMissing( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void artifactDescriptorMissing(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void metadataInvalid( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void metadataInvalid(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void artifactResolving( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void artifactResolving(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void artifactResolved( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void artifactResolved(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void artifactDownloading( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void artifactDownloading(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void artifactDownloaded( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void artifactDownloaded(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void metadataDownloaded( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void metadataDownloaded(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void metadataDownloading( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void metadataDownloading(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void metadataResolving( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void metadataResolving(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void metadataResolved( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void metadataResolved(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void artifactInstalling( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void artifactInstalling(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void artifactInstalled( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void artifactInstalled(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void metadataInstalling( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void metadataInstalling(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void metadataInstalled( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void metadataInstalled(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void artifactDeploying( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void artifactDeploying(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void artifactDeployed( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void artifactDeployed(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void metadataDeploying( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void metadataDeploying(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - public void metadataDeployed( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - events.add( event ); + public void metadataDeployed(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + events.add(event); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/SafeTransferListenerTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/SafeTransferListenerTest.java index 6d7a6fea1..6c56c2094 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/SafeTransferListenerTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/SafeTransferListenerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,28 +16,24 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.lang.reflect.Method; import org.eclipse.aether.transfer.TransferListener; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class SafeTransferListenerTest -{ +public class SafeTransferListenerTest { @Test - public void testAllEventTypesHandled() - throws Exception - { + public void testAllEventTypesHandled() throws Exception { Class type = SafeTransferListener.class; - for ( Method method : TransferListener.class.getMethods() ) - { - assertNotNull( type.getDeclaredMethod( method.getName(), method.getParameterTypes() ) ); + for (Method method : TransferListener.class.getMethods()) { + assertNotNull(type.getDeclaredMethod(method.getName(), method.getParameterTypes())); } } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManagerTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManagerTest.java index a46721efe..83dbd6fa9 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManagerTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/SimpleLocalRepositoryManagerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import java.io.File; import java.io.IOException; @@ -36,10 +33,11 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class SimpleLocalRepositoryManagerTest -{ +public class SimpleLocalRepositoryManagerTest { private File basedir; @@ -48,68 +46,61 @@ public class SimpleLocalRepositoryManagerTest private RepositorySystemSession session; @Before - public void setup() - throws IOException - { - basedir = TestFileUtils.createTempDir( "simple-repo" ); - manager = new SimpleLocalRepositoryManager( basedir, "simple", new DefaultLocalPathComposer() ); + public void setup() throws IOException { + basedir = TestFileUtils.createTempDir("simple-repo"); + manager = new SimpleLocalRepositoryManager(basedir, "simple", new DefaultLocalPathComposer()); session = TestUtils.newSession(); } @After - public void tearDown() - throws Exception - { - TestFileUtils.deleteFile( basedir ); + public void tearDown() throws Exception { + TestFileUtils.deleteFile(basedir); manager = null; session = null; } @Test - public void testGetPathForLocalArtifact() - { - Artifact artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-SNAPSHOT" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact( artifact ) ); - - artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-20110329.221805-4" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact( artifact ) ); - - artifact = new DefaultArtifact( "g.i.d", "a.i.d", "", "", "1.0-SNAPSHOT" ); - assertEquals( "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT", manager.getPathForLocalArtifact( artifact ) ); + public void testGetPathForLocalArtifact() { + Artifact artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-SNAPSHOT"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals("g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact(artifact)); + + artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-20110329.221805-4"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals("g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", manager.getPathForLocalArtifact(artifact)); + + artifact = new DefaultArtifact("g.i.d", "a.i.d", "", "", "1.0-SNAPSHOT"); + assertEquals("g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT", manager.getPathForLocalArtifact(artifact)); } @Test - public void testGetPathForRemoteArtifact() - { - RemoteRepository remoteRepo = new RemoteRepository.Builder( "repo", "default", "ram:/void" ).build(); - - Artifact artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-SNAPSHOT" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", - manager.getPathForRemoteArtifact( artifact, remoteRepo, "" ) ); - - artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-20110329.221805-4" ); - assertEquals( "1.0-SNAPSHOT", artifact.getBaseVersion() ); - assertEquals( "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-20110329.221805-4.jar", - manager.getPathForRemoteArtifact( artifact, remoteRepo, "" ) ); + public void testGetPathForRemoteArtifact() { + RemoteRepository remoteRepo = new RemoteRepository.Builder("repo", "default", "ram:/void").build(); + + Artifact artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-SNAPSHOT"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals( + "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-SNAPSHOT.jar", + manager.getPathForRemoteArtifact(artifact, remoteRepo, "")); + + artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-20110329.221805-4"); + assertEquals("1.0-SNAPSHOT", artifact.getBaseVersion()); + assertEquals( + "g/i/d/a.i.d/1.0-SNAPSHOT/a.i.d-1.0-20110329.221805-4.jar", + manager.getPathForRemoteArtifact(artifact, remoteRepo, "")); } @Test - public void testFindArtifactUsesTimestampedVersion() - throws Exception - { - Artifact artifact = new DefaultArtifact( "g.i.d:a.i.d:1.0-SNAPSHOT" ); - File file = new File( basedir, manager.getPathForLocalArtifact( artifact ) ); - TestFileUtils.writeString( file, "test" ); - - artifact = artifact.setVersion( "1.0-20110329.221805-4" ); + public void testFindArtifactUsesTimestampedVersion() throws Exception { + Artifact artifact = new DefaultArtifact("g.i.d:a.i.d:1.0-SNAPSHOT"); + File file = new File(basedir, manager.getPathForLocalArtifact(artifact)); + TestFileUtils.writeString(file, "test"); + + artifact = artifact.setVersion("1.0-20110329.221805-4"); LocalArtifactRequest request = new LocalArtifactRequest(); - request.setArtifact( artifact ); - LocalArtifactResult result = manager.find( session, request ); - assertNull( result.toString(), result.getFile() ); - assertFalse( result.toString(), result.isAvailable() ); + request.setArtifact(artifact); + LocalArtifactResult result = manager.find(session, request); + assertNull(result.toString(), result.getFile()); + assertFalse(result.toString(), result.isAvailable()); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StaticUpdateCheckManager.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StaticUpdateCheckManager.java index c9889d03d..366b24bd2 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StaticUpdateCheckManager.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StaticUpdateCheckManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -31,67 +30,54 @@ import static java.util.Objects.requireNonNull; -class StaticUpdateCheckManager - implements UpdateCheckManager -{ +class StaticUpdateCheckManager implements UpdateCheckManager { private boolean checkRequired; private boolean localUpToDate; - public StaticUpdateCheckManager( boolean checkRequired ) - { - this( checkRequired, !checkRequired ); + public StaticUpdateCheckManager(boolean checkRequired) { + this(checkRequired, !checkRequired); } - public StaticUpdateCheckManager( boolean checkRequired, boolean localUpToDate ) - { + public StaticUpdateCheckManager(boolean checkRequired, boolean localUpToDate) { this.checkRequired = checkRequired; this.localUpToDate = localUpToDate; } - public void touchMetadata( RepositorySystemSession session, UpdateCheck check ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( check, "check cannot be null" ); + public void touchMetadata(RepositorySystemSession session, UpdateCheck check) { + requireNonNull(session, "session cannot be null"); + requireNonNull(check, "check cannot be null"); } - public void touchArtifact( RepositorySystemSession session, UpdateCheck check ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( check, "check cannot be null" ); + public void touchArtifact(RepositorySystemSession session, UpdateCheck check) { + requireNonNull(session, "session cannot be null"); + requireNonNull(check, "check cannot be null"); } - public void checkMetadata( RepositorySystemSession session, UpdateCheck check ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( check, "check cannot be null" ); - check.setRequired( checkRequired ); + public void checkMetadata(RepositorySystemSession session, UpdateCheck check) { + requireNonNull(session, "session cannot be null"); + requireNonNull(check, "check cannot be null"); + check.setRequired(checkRequired); - if ( check.getLocalLastUpdated() != 0L && localUpToDate ) - { - check.setRequired( false ); + if (check.getLocalLastUpdated() != 0L && localUpToDate) { + check.setRequired(false); } - if ( !check.isRequired() && !check.getFile().isFile() ) - { - check.setException( new MetadataNotFoundException( check.getItem(), check.getRepository() ) ); + if (!check.isRequired() && !check.getFile().isFile()) { + check.setException(new MetadataNotFoundException(check.getItem(), check.getRepository())); } } - public void checkArtifact( RepositorySystemSession session, UpdateCheck check ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( check, "check cannot be null" ); - check.setRequired( checkRequired ); + public void checkArtifact(RepositorySystemSession session, UpdateCheck check) { + requireNonNull(session, "session cannot be null"); + requireNonNull(check, "check cannot be null"); + check.setRequired(checkRequired); - if ( check.getLocalLastUpdated() != 0L && localUpToDate ) - { - check.setRequired( false ); + if (check.getLocalLastUpdated() != 0L && localUpToDate) { + check.setRequired(false); } - if ( !check.isRequired() && !check.getFile().isFile() ) - { - check.setException( new ArtifactNotFoundException( check.getItem(), check.getRepository() ) ); + if (!check.isRequired() && !check.getFile().isFile()) { + check.setException(new ArtifactNotFoundException(check.getItem(), check.getRepository())); } } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubFileTransformerManager.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubFileTransformerManager.java index a079a2ae1..284858bbb 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubFileTransformerManager.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubFileTransformerManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import java.util.Collection; import java.util.HashMap; @@ -28,23 +27,18 @@ import org.eclipse.aether.transform.FileTransformer; import org.eclipse.aether.transform.FileTransformerManager; -public class StubFileTransformerManager implements FileTransformerManager -{ +public class StubFileTransformerManager implements FileTransformerManager { private Map> fileTransformers = new HashMap<>(); - + @Override - public Collection getTransformersForArtifact( Artifact artifact ) - { - return fileTransformers.get( artifact.getExtension() ); + public Collection getTransformersForArtifact(Artifact artifact) { + return fileTransformers.get(artifact.getExtension()); } - - public void addFileTransformer( String extension, FileTransformer fileTransformer ) - { - if ( !fileTransformers.containsKey( extension ) ) - { - fileTransformers.put( extension, new HashSet() ); + + public void addFileTransformer(String extension, FileTransformer fileTransformer) { + if (!fileTransformers.containsKey(extension)) { + fileTransformers.put(extension, new HashSet()); } - fileTransformers.get( extension ).add( fileTransformer ); + fileTransformers.get(extension).add(fileTransformer); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRemoteRepositoryManager.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRemoteRepositoryManager.java index af66f34cc..b04662ce6 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRemoteRepositoryManager.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRemoteRepositoryManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import java.util.List; @@ -29,46 +28,38 @@ import static java.util.Objects.requireNonNull; -public class StubRemoteRepositoryManager - implements RemoteRepositoryManager -{ +public class StubRemoteRepositoryManager implements RemoteRepositoryManager { - public StubRemoteRepositoryManager() - { - } + public StubRemoteRepositoryManager() {} - public List aggregateRepositories( RepositorySystemSession session, - List dominantRepositories, - List recessiveRepositories, - boolean recessiveIsRaw ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( dominantRepositories, "dominantRepositories cannot be null" ); - requireNonNull( recessiveRepositories, "recessiveRepositories cannot be null" ); + public List aggregateRepositories( + RepositorySystemSession session, + List dominantRepositories, + List recessiveRepositories, + boolean recessiveIsRaw) { + requireNonNull(session, "session cannot be null"); + requireNonNull(dominantRepositories, "dominantRepositories cannot be null"); + requireNonNull(recessiveRepositories, "recessiveRepositories cannot be null"); return dominantRepositories; } - public RepositoryPolicy getPolicy( RepositorySystemSession session, RemoteRepository repository, boolean releases, - boolean snapshots ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); - RepositoryPolicy policy = repository.getPolicy( snapshots ); + public RepositoryPolicy getPolicy( + RepositorySystemSession session, RemoteRepository repository, boolean releases, boolean snapshots) { + requireNonNull(session, "session cannot be null"); + requireNonNull(repository, "repository cannot be null"); + RepositoryPolicy policy = repository.getPolicy(snapshots); String checksums = session.getChecksumPolicy(); - if ( StringUtils.isEmpty( checksums ) ) - { + if (StringUtils.isEmpty(checksums)) { checksums = policy.getChecksumPolicy(); } String updates = session.getUpdatePolicy(); - if ( StringUtils.isEmpty( updates ) ) - { + if (StringUtils.isEmpty(updates)) { updates = policy.getUpdatePolicy(); } - policy = new RepositoryPolicy( policy.isEnabled(), updates, checksums ); + policy = new RepositoryPolicy(policy.isEnabled(), updates, checksums); return policy; } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRepositoryConnectorProvider.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRepositoryConnectorProvider.java index 3cb5e38f8..098afabc6 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRepositoryConnectorProvider.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRepositoryConnectorProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.impl.RepositoryConnectorProvider; @@ -25,30 +24,22 @@ import org.eclipse.aether.spi.connector.RepositoryConnector; import org.eclipse.aether.transfer.NoRepositoryConnectorException; -class StubRepositoryConnectorProvider - implements RepositoryConnectorProvider -{ +class StubRepositoryConnectorProvider implements RepositoryConnectorProvider { - public StubRepositoryConnectorProvider( RepositoryConnector connector ) - { - setConnector( connector ); + public StubRepositoryConnectorProvider(RepositoryConnector connector) { + setConnector(connector); } - public StubRepositoryConnectorProvider() - { - } + public StubRepositoryConnectorProvider() {} private RepositoryConnector connector; - public void setConnector( RepositoryConnector connector ) - { + public void setConnector(RepositoryConnector connector) { this.connector = connector; } - public RepositoryConnector newRepositoryConnector( RepositorySystemSession session, RemoteRepository repository ) - throws NoRepositoryConnectorException - { + public RepositoryConnector newRepositoryConnector(RepositorySystemSession session, RemoteRepository repository) + throws NoRepositoryConnectorException { return connector; } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRepositoryEventDispatcher.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRepositoryEventDispatcher.java index b1e9db451..0ed37d966 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRepositoryEventDispatcher.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubRepositoryEventDispatcher.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.RepositoryEvent; import org.eclipse.aether.RepositoryListener; @@ -27,81 +26,75 @@ /** */ -public class StubRepositoryEventDispatcher - implements RepositoryEventDispatcher -{ +public class StubRepositoryEventDispatcher implements RepositoryEventDispatcher { - public void dispatch( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); + public void dispatch(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); RepositoryListener listener = event.getSession().getRepositoryListener(); - if ( listener == null ) - { + if (listener == null) { return; } - switch ( event.getType() ) - { + switch (event.getType()) { case ARTIFACT_DEPLOYED: - listener.artifactDeployed( event ); + listener.artifactDeployed(event); break; case ARTIFACT_DEPLOYING: - listener.artifactDeploying( event ); + listener.artifactDeploying(event); break; case ARTIFACT_DESCRIPTOR_INVALID: - listener.artifactDescriptorInvalid( event ); + listener.artifactDescriptorInvalid(event); break; case ARTIFACT_DESCRIPTOR_MISSING: - listener.artifactDescriptorMissing( event ); + listener.artifactDescriptorMissing(event); break; case ARTIFACT_DOWNLOADED: - listener.artifactDownloaded( event ); + listener.artifactDownloaded(event); break; case ARTIFACT_DOWNLOADING: - listener.artifactDownloading( event ); + listener.artifactDownloading(event); break; case ARTIFACT_INSTALLED: - listener.artifactInstalled( event ); + listener.artifactInstalled(event); break; case ARTIFACT_INSTALLING: - listener.artifactInstalling( event ); + listener.artifactInstalling(event); break; case ARTIFACT_RESOLVED: - listener.artifactResolved( event ); + listener.artifactResolved(event); break; case ARTIFACT_RESOLVING: - listener.artifactResolving( event ); + listener.artifactResolving(event); break; case METADATA_DEPLOYED: - listener.metadataDeployed( event ); + listener.metadataDeployed(event); break; case METADATA_DEPLOYING: - listener.metadataDeploying( event ); + listener.metadataDeploying(event); break; case METADATA_DOWNLOADED: - listener.metadataDownloaded( event ); + listener.metadataDownloaded(event); break; case METADATA_DOWNLOADING: - listener.metadataDownloading( event ); + listener.metadataDownloading(event); break; case METADATA_INSTALLED: - listener.metadataInstalled( event ); + listener.metadataInstalled(event); break; case METADATA_INSTALLING: - listener.metadataInstalling( event ); + listener.metadataInstalling(event); break; case METADATA_INVALID: - listener.metadataInvalid( event ); + listener.metadataInvalid(event); break; case METADATA_RESOLVED: - listener.metadataResolved( event ); + listener.metadataResolved(event); break; case METADATA_RESOLVING: - listener.metadataResolving( event ); + listener.metadataResolving(event); break; default: - throw new IllegalStateException( "unknown repository event type " + event.getType() ); + throw new IllegalStateException("unknown repository event type " + event.getType()); } } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubSyncContextFactory.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubSyncContextFactory.java index 7cea5e6e6..356168f4b 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubSyncContextFactory.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubSyncContextFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,37 +16,29 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import java.util.Collection; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.SyncContext; import org.eclipse.aether.artifact.Artifact; -import org.eclipse.aether.spi.synccontext.SyncContextFactory; import org.eclipse.aether.metadata.Metadata; +import org.eclipse.aether.spi.synccontext.SyncContextFactory; import static java.util.Objects.requireNonNull; /** - * + * */ -public class StubSyncContextFactory - implements SyncContextFactory -{ +public class StubSyncContextFactory implements SyncContextFactory { - public SyncContext newInstance( RepositorySystemSession session, boolean shared ) - { - requireNonNull( session, "session cannot be null" ); - return new SyncContext() - { - public void close() - { - } + public SyncContext newInstance(RepositorySystemSession session, boolean shared) { + requireNonNull(session, "session cannot be null"); + return new SyncContext() { + public void close() {} - public void acquire( Collection artifacts, Collection metadatas ) - { - } + public void acquire(Collection artifacts, Collection metadatas) {} }; } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubVersionRangeResolver.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubVersionRangeResolver.java index 5ace7618a..2c5b1523c 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubVersionRangeResolver.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubVersionRangeResolver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.impl.VersionRangeResolver; @@ -34,49 +33,37 @@ /** */ -public class StubVersionRangeResolver - implements VersionRangeResolver -{ +public class StubVersionRangeResolver implements VersionRangeResolver { private final VersionScheme versionScheme = new GenericVersionScheme(); - public VersionRangeResult resolveVersionRange( RepositorySystemSession session, VersionRangeRequest request ) - throws VersionRangeResolutionException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); - VersionRangeResult result = new VersionRangeResult( request ); - try - { - VersionConstraint constraint = versionScheme.parseVersionConstraint( request.getArtifact().getVersion() ); - result.setVersionConstraint( constraint ); - if ( constraint.getRange() == null ) - { - result.addVersion( constraint.getVersion() ); - } - else - { - for ( int i = 1; i < 10; i++ ) - { - Version ver = versionScheme.parseVersion( Integer.toString( i ) ); - if ( constraint.containsVersion( ver ) ) - { - result.addVersion( ver ); - if ( !request.getRepositories().isEmpty() ) - { - result.setRepository( ver, request.getRepositories().get( 0 ) ); + public VersionRangeResult resolveVersionRange(RepositorySystemSession session, VersionRangeRequest request) + throws VersionRangeResolutionException { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); + VersionRangeResult result = new VersionRangeResult(request); + try { + VersionConstraint constraint = + versionScheme.parseVersionConstraint(request.getArtifact().getVersion()); + result.setVersionConstraint(constraint); + if (constraint.getRange() == null) { + result.addVersion(constraint.getVersion()); + } else { + for (int i = 1; i < 10; i++) { + Version ver = versionScheme.parseVersion(Integer.toString(i)); + if (constraint.containsVersion(ver)) { + result.addVersion(ver); + if (!request.getRepositories().isEmpty()) { + result.setRepository(ver, request.getRepositories().get(0)); } } } } - } - catch ( InvalidVersionSpecificationException e ) - { - result.addException( e ); - throw new VersionRangeResolutionException( result ); + } catch (InvalidVersionSpecificationException e) { + result.addException(e); + throw new VersionRangeResolutionException(result); } return result; } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubVersionResolver.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubVersionResolver.java index 9ef7e7a5f..91ac05f2e 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubVersionResolver.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/StubVersionResolver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.impl.VersionResolver; @@ -28,21 +27,16 @@ /* * */ -class StubVersionResolver - implements VersionResolver -{ +class StubVersionResolver implements VersionResolver { - public VersionResult resolveVersion( RepositorySystemSession session, VersionRequest request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); - VersionResult result = new VersionResult( request ).setVersion( request.getArtifact().getVersion() ); - if ( request.getRepositories().size() > 0 ) - { - result = result.setRepository( request.getRepositories().get( 0 ) ); + public VersionResult resolveVersion(RepositorySystemSession session, VersionRequest request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); + VersionResult result = + new VersionResult(request).setVersion(request.getArtifact().getVersion()); + if (request.getRepositories().size() > 0) { + result = result.setRepository(request.getRepositories().get(0)); } return result; - } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/WarnChecksumPolicyTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/WarnChecksumPolicyTest.java index 6124a022a..e264dc82b 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/WarnChecksumPolicyTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/WarnChecksumPolicyTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.impl; import org.eclipse.aether.spi.connector.checksum.ChecksumPolicy.ChecksumKind; import org.eclipse.aether.transfer.ChecksumFailureException; @@ -27,86 +24,66 @@ import org.junit.Before; import org.junit.Test; -public class WarnChecksumPolicyTest -{ +import static org.junit.Assert.*; + +public class WarnChecksumPolicyTest { private WarnChecksumPolicy policy; private ChecksumFailureException exception; @Before - public void setup() - { - policy = new WarnChecksumPolicy( new TransferResource( "null", "file:/dev/null", "file.txt", null, null ) ); - exception = new ChecksumFailureException( "test" ); + public void setup() { + policy = new WarnChecksumPolicy(new TransferResource("null", "file:/dev/null", "file.txt", null, null)); + exception = new ChecksumFailureException("test"); } @Test - public void testOnTransferChecksumFailure() - { - assertTrue( policy.onTransferChecksumFailure( exception ) ); + public void testOnTransferChecksumFailure() { + assertTrue(policy.onTransferChecksumFailure(exception)); } @Test - public void testOnChecksumMatch() - { - assertTrue( policy.onChecksumMatch( "SHA-1", ChecksumKind.REMOTE_EXTERNAL ) ); - assertTrue( policy.onChecksumMatch( "SHA-1", ChecksumKind.REMOTE_INCLUDED ) ); - assertTrue( policy.onChecksumMatch( "SHA-1", ChecksumKind.PROVIDED ) ); + public void testOnChecksumMatch() { + assertTrue(policy.onChecksumMatch("SHA-1", ChecksumKind.REMOTE_EXTERNAL)); + assertTrue(policy.onChecksumMatch("SHA-1", ChecksumKind.REMOTE_INCLUDED)); + assertTrue(policy.onChecksumMatch("SHA-1", ChecksumKind.PROVIDED)); } @Test - public void testOnChecksumMismatch() - throws Exception - { - try - { - policy.onChecksumMismatch( "SHA-1", ChecksumKind.REMOTE_EXTERNAL, exception ); - fail( "No exception" ); - } - catch ( ChecksumFailureException e ) - { - assertSame( exception, e ); - } - try - { - policy.onChecksumMismatch( "SHA-1", ChecksumKind.REMOTE_INCLUDED, exception ); - fail( "No exception" ); + public void testOnChecksumMismatch() throws Exception { + try { + policy.onChecksumMismatch("SHA-1", ChecksumKind.REMOTE_EXTERNAL, exception); + fail("No exception"); + } catch (ChecksumFailureException e) { + assertSame(exception, e); } - catch ( ChecksumFailureException e ) - { - assertSame( exception, e ); + try { + policy.onChecksumMismatch("SHA-1", ChecksumKind.REMOTE_INCLUDED, exception); + fail("No exception"); + } catch (ChecksumFailureException e) { + assertSame(exception, e); } - try - { + try { policy.onChecksumMismatch("SHA-1", ChecksumKind.PROVIDED, exception); - fail( "No exception" ); - } - catch ( ChecksumFailureException e) - { - assertSame( exception, e ); + fail("No exception"); + } catch (ChecksumFailureException e) { + assertSame(exception, e); } } @Test - public void testOnChecksumError() - throws Exception - { - policy.onChecksumError( "SHA-1", ChecksumKind.REMOTE_EXTERNAL, exception ); + public void testOnChecksumError() throws Exception { + policy.onChecksumError("SHA-1", ChecksumKind.REMOTE_EXTERNAL, exception); } @Test - public void testOnNoMoreChecksums() - { - try - { + public void testOnNoMoreChecksums() { + try { policy.onNoMoreChecksums(); - fail( "No exception" ); - } - catch ( ChecksumFailureException e ) - { - assertTrue( e.getMessage().contains( "no checksums available" ) ); + fail("No exception"); + } catch (ChecksumFailureException e) { + assertTrue(e.getMessage().contains("no checksums available")); } } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/FileTrustedChecksumsSourceTestSupport.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/FileTrustedChecksumsSourceTestSupport.java index d67478ff8..d657ad299 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/FileTrustedChecksumsSourceTestSupport.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/FileTrustedChecksumsSourceTestSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.eclipse.aether.DefaultRepositorySystemSession; -import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.impl.RepositorySystemLifecycle; @@ -44,11 +42,10 @@ import static org.hamcrest.Matchers.nullValue; import static org.junit.Assume.assumeThat; -public abstract class FileTrustedChecksumsSourceTestSupport -{ - private static final Artifact ARTIFACT_WITHOUT_CHECKSUM = new DefaultArtifact( "test:test:1.0" ); +public abstract class FileTrustedChecksumsSourceTestSupport { + private static final Artifact ARTIFACT_WITHOUT_CHECKSUM = new DefaultArtifact("test:test:1.0"); - private static final Artifact ARTIFACT_WITH_CHECKSUM = new DefaultArtifact( "test:test:2.0" ); + private static final Artifact ARTIFACT_WITH_CHECKSUM = new DefaultArtifact("test:test:2.0"); private static final String ARTIFACT_TRUSTED_CHECKSUM = "trustedChecksum"; @@ -63,73 +60,67 @@ public abstract class FileTrustedChecksumsSourceTestSupport private boolean checksumWritten; @Before - public void before() throws Exception - { + public void before() throws Exception { session = TestUtils.newSession(); // populate local repository checksumAlgorithmFactory = new Sha1ChecksumAlgorithmFactory(); repositorySystemLifecycle = new DefaultRepositorySystemLifecycle(); - subject = prepareSubject( repositorySystemLifecycle ); + subject = prepareSubject(repositorySystemLifecycle); checksumWritten = false; - DefaultRepositorySystemSession prepareSession = new DefaultRepositorySystemSession( session ); - enableSource( prepareSession ); - TrustedChecksumsSource.Writer writer = subject.getTrustedArtifactChecksumsWriter( prepareSession ); - if ( writer != null ) - { + DefaultRepositorySystemSession prepareSession = new DefaultRepositorySystemSession(session); + enableSource(prepareSession); + TrustedChecksumsSource.Writer writer = subject.getTrustedArtifactChecksumsWriter(prepareSession); + if (writer != null) { HashMap checksums = new HashMap<>(); - checksums.put( checksumAlgorithmFactory.getName(), ARTIFACT_TRUSTED_CHECKSUM ); - writer.addTrustedArtifactChecksums( ARTIFACT_WITH_CHECKSUM, prepareSession.getLocalRepository(), - Collections.singletonList( checksumAlgorithmFactory ), checksums ); + checksums.put(checksumAlgorithmFactory.getName(), ARTIFACT_TRUSTED_CHECKSUM); + writer.addTrustedArtifactChecksums( + ARTIFACT_WITH_CHECKSUM, + prepareSession.getLocalRepository(), + Collections.singletonList(checksumAlgorithmFactory), + checksums); checksumWritten = true; } } - protected abstract FileTrustedChecksumsSourceSupport prepareSubject( RepositorySystemLifecycle lifecycle ); + protected abstract FileTrustedChecksumsSourceSupport prepareSubject(RepositorySystemLifecycle lifecycle); - protected abstract void enableSource( DefaultRepositorySystemSession session ); + protected abstract void enableSource(DefaultRepositorySystemSession session); @Test - public void notEnabled() - { + public void notEnabled() { assertThat( subject.getTrustedArtifactChecksums( session, ARTIFACT_WITH_CHECKSUM, session.getLocalRepository(), - Collections.singletonList( checksumAlgorithmFactory ) - ), - nullValue() - ); + Collections.singletonList(checksumAlgorithmFactory)), + nullValue()); } @Test - public void noProvidedArtifactChecksum() - { - enableSource( session ); + public void noProvidedArtifactChecksum() { + enableSource(session); Map providedChecksums = subject.getTrustedArtifactChecksums( session, ARTIFACT_WITHOUT_CHECKSUM, session.getLocalRepository(), - Collections.singletonList( checksumAlgorithmFactory ) - ); - assertThat( providedChecksums, notNullValue() ); - assertThat( providedChecksums, anEmptyMap() ); + Collections.singletonList(checksumAlgorithmFactory)); + assertThat(providedChecksums, notNullValue()); + assertThat(providedChecksums, anEmptyMap()); } @Test - public void haveProvidedArtifactChecksum() - { - assumeThat( checksumWritten, is( true ) ); - enableSource( session ); + public void haveProvidedArtifactChecksum() { + assumeThat(checksumWritten, is(true)); + enableSource(session); Map providedChecksums = subject.getTrustedArtifactChecksums( session, ARTIFACT_WITH_CHECKSUM, session.getLocalRepository(), - Collections.singletonList( checksumAlgorithmFactory ) - ); - assertThat( providedChecksums, notNullValue() ); - assertThat( providedChecksums, aMapWithSize( 1 ) ); - assertThat( providedChecksums, hasEntry( checksumAlgorithmFactory.getName(), ARTIFACT_TRUSTED_CHECKSUM ) ); + Collections.singletonList(checksumAlgorithmFactory)); + assertThat(providedChecksums, notNullValue()); + assertThat(providedChecksums, aMapWithSize(1)); + assertThat(providedChecksums, hasEntry(checksumAlgorithmFactory.getName(), ARTIFACT_TRUSTED_CHECKSUM)); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/SparseDirectoryTrustedChecksumsSourceTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/SparseDirectoryTrustedChecksumsSourceTest.java index 36095382c..0dd0a0705 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/SparseDirectoryTrustedChecksumsSourceTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/SparseDirectoryTrustedChecksumsSourceTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,24 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import org.eclipse.aether.DefaultRepositorySystemSession; -import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.impl.RepositorySystemLifecycle; import org.eclipse.aether.internal.impl.DefaultFileProcessor; import org.eclipse.aether.internal.impl.DefaultLocalPathComposer; -public class SparseDirectoryTrustedChecksumsSourceTest extends FileTrustedChecksumsSourceTestSupport -{ +public class SparseDirectoryTrustedChecksumsSourceTest extends FileTrustedChecksumsSourceTestSupport { @Override - protected FileTrustedChecksumsSourceSupport prepareSubject( RepositorySystemLifecycle lifecycle ) - { - return new SparseDirectoryTrustedChecksumsSource( new DefaultFileProcessor(), new DefaultLocalPathComposer() ); + protected FileTrustedChecksumsSourceSupport prepareSubject(RepositorySystemLifecycle lifecycle) { + return new SparseDirectoryTrustedChecksumsSource(new DefaultFileProcessor(), new DefaultLocalPathComposer()); } @Override - protected void enableSource( DefaultRepositorySystemSession session ) - { - session.setConfigProperty( "aether.trustedChecksumsSource.sparseDirectory", Boolean.TRUE.toString() ); + protected void enableSource(DefaultRepositorySystemSession session) { + session.setConfigProperty("aether.trustedChecksumsSource.sparseDirectory", Boolean.TRUE.toString()); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/SummaryFileTrustedChecksumsSourceTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/SummaryFileTrustedChecksumsSourceTest.java index f3e08edad..403f1cb9c 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/SummaryFileTrustedChecksumsSourceTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/checksum/SummaryFileTrustedChecksumsSourceTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,22 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.checksum; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.impl.RepositorySystemLifecycle; import org.eclipse.aether.internal.impl.DefaultLocalPathComposer; -public class SummaryFileTrustedChecksumsSourceTest extends FileTrustedChecksumsSourceTestSupport -{ +public class SummaryFileTrustedChecksumsSourceTest extends FileTrustedChecksumsSourceTestSupport { @Override - protected FileTrustedChecksumsSourceSupport prepareSubject( RepositorySystemLifecycle lifecycle ) - { - return new SummaryFileTrustedChecksumsSource( new DefaultLocalPathComposer(), lifecycle ); + protected FileTrustedChecksumsSourceSupport prepareSubject(RepositorySystemLifecycle lifecycle) { + return new SummaryFileTrustedChecksumsSource(new DefaultLocalPathComposer(), lifecycle); } @Override - protected void enableSource( DefaultRepositorySystemSession session ) - { - session.setConfigProperty( "aether.trustedChecksumsSource.summaryFile", Boolean.TRUE.toString() ); + protected void enableSource(DefaultRepositorySystemSession session) { + session.setConfigProperty("aether.trustedChecksumsSource.summaryFile", Boolean.TRUE.toString()); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DataPoolTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DataPoolTest.java index d8f5524cc..f4295f073 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DataPoolTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DataPoolTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; + +import java.util.Collections; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.artifact.DefaultArtifact; @@ -28,58 +29,51 @@ import org.eclipse.aether.resolution.VersionRangeRequest; import org.junit.Test; -import java.util.Collections; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -public class DataPoolTest -{ +public class DataPoolTest { - private DataPool newDataPool() - { - return new DataPool( new DefaultRepositorySystemSession() ); + private DataPool newDataPool() { + return new DataPool(new DefaultRepositorySystemSession()); } @Test - public void testArtifactDescriptorCaching() - { + public void testArtifactDescriptorCaching() { ArtifactDescriptorRequest request = new ArtifactDescriptorRequest(); - request.setArtifact( new DefaultArtifact( "gid:aid:1" ) ); - ArtifactDescriptorResult result = new ArtifactDescriptorResult( request ); - result.setArtifact( new DefaultArtifact( "gid:aid:2" ) ); - result.addRelocation( request.getArtifact() ); - result.addDependency( new Dependency( new DefaultArtifact( "gid:dep:3" ), "compile" ) ); - result.addManagedDependency( new Dependency( new DefaultArtifact( "gid:mdep:3" ), "runtime" ) ); - result.addRepository( new RemoteRepository.Builder( "test", "default", "http://localhost" ).build() ); - result.addAlias( new DefaultArtifact( "gid:alias:4" ) ); + request.setArtifact(new DefaultArtifact("gid:aid:1")); + ArtifactDescriptorResult result = new ArtifactDescriptorResult(request); + result.setArtifact(new DefaultArtifact("gid:aid:2")); + result.addRelocation(request.getArtifact()); + result.addDependency(new Dependency(new DefaultArtifact("gid:dep:3"), "compile")); + result.addManagedDependency(new Dependency(new DefaultArtifact("gid:mdep:3"), "runtime")); + result.addRepository(new RemoteRepository.Builder("test", "default", "http://localhost").build()); + result.addAlias(new DefaultArtifact("gid:alias:4")); DataPool pool = newDataPool(); - Object key = pool.toKey( request ); - pool.putDescriptor( key, result ); - ArtifactDescriptorResult cached = pool.getDescriptor( key, request ); - assertNotNull( cached ); - assertEquals( result.getArtifact(), cached.getArtifact() ); - assertEquals( result.getRelocations(), cached.getRelocations() ); - assertEquals( result.getDependencies(), cached.getDependencies() ); - assertEquals( result.getManagedDependencies(), cached.getManagedDependencies() ); - assertEquals( result.getRepositories(), cached.getRepositories() ); - assertEquals( result.getAliases(), cached.getAliases() ); + Object key = pool.toKey(request); + pool.putDescriptor(key, result); + ArtifactDescriptorResult cached = pool.getDescriptor(key, request); + assertNotNull(cached); + assertEquals(result.getArtifact(), cached.getArtifact()); + assertEquals(result.getRelocations(), cached.getRelocations()); + assertEquals(result.getDependencies(), cached.getDependencies()); + assertEquals(result.getManagedDependencies(), cached.getManagedDependencies()); + assertEquals(result.getRepositories(), cached.getRepositories()); + assertEquals(result.getAliases(), cached.getAliases()); } @Test - public void testConstraintKey() - { + public void testConstraintKey() { VersionRangeRequest request = new VersionRangeRequest(); - request.setRepositories( - Collections.singletonList( new RemoteRepository.Builder( "some-id", "some-type", "http://www.example.com" ).build() ) - ); - request.setArtifact( new DefaultArtifact("group:artifact:1.0") ); + request.setRepositories(Collections.singletonList( + new RemoteRepository.Builder("some-id", "some-type", "http://www.example.com").build())); + request.setArtifact(new DefaultArtifact("group:artifact:1.0")); DataPool pool = newDataPool(); - Object key1 = pool.toKey( request ); - Object key2 = pool.toKey( request ); + Object key1 = pool.toKey(request); + Object key2 = pool.toKey(request); assertEquals(key1, key2); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCycleTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCycleTest.java index 66dade8c1..5427dc1cd 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCycleTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DefaultDependencyCycleTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; import java.util.ArrayList; import java.util.List; @@ -31,18 +30,16 @@ import static org.junit.Assert.assertEquals; -public class DefaultDependencyCycleTest -{ - private static final Dependency FOO_DEPENDENCY = new Dependency( new DefaultArtifact( "group-id:foo:1.0" ), "test" ); - private static final Dependency BAR_DEPENDENCY = new Dependency( new DefaultArtifact( "group-id:bar:1.0" ), "test" ); +public class DefaultDependencyCycleTest { + private static final Dependency FOO_DEPENDENCY = new Dependency(new DefaultArtifact("group-id:foo:1.0"), "test"); + private static final Dependency BAR_DEPENDENCY = new Dependency(new DefaultArtifact("group-id:bar:1.0"), "test"); @Test - public void testToString() - { + public void testToString() { List nodes = new ArrayList<>(); - nodes.add( new DefaultDependencyNode( FOO_DEPENDENCY ) ); - DependencyCycle cycle = new DefaultDependencyCycle( nodes, 1, BAR_DEPENDENCY ); + nodes.add(new DefaultDependencyNode(FOO_DEPENDENCY)); + DependencyCycle cycle = new DefaultDependencyCycle(nodes, 1, BAR_DEPENDENCY); - assertEquals( "group-id:foo:jar -> group-id:bar:jar", cycle.toString() ); + assertEquals("group-id:foo:jar -> group-id:bar:jar", cycle.toString()); } -} \ No newline at end of file +} diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DefaultVersionFilterContextTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DefaultVersionFilterContextTest.java index b6fbf5fdb..fa045fdbf 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DefaultVersionFilterContextTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DefaultVersionFilterContextTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.NoSuchElementException; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.artifact.DefaultArtifact; @@ -28,76 +32,65 @@ import org.eclipse.aether.version.Version; import org.junit.Test; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.NoSuchElementException; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class DefaultVersionFilterContextTest -{ - private static final Dependency FOO_DEPENDENCY = new Dependency( new DefaultArtifact( "group-id:foo:1.0" ), "test" ); - private static final Dependency BAR_DEPENDENCY = new Dependency( new DefaultArtifact( "group-id:bar:1.0" ), "test" ); +public class DefaultVersionFilterContextTest { + private static final Dependency FOO_DEPENDENCY = new Dependency(new DefaultArtifact("group-id:foo:1.0"), "test"); + private static final Dependency BAR_DEPENDENCY = new Dependency(new DefaultArtifact("group-id:bar:1.0"), "test"); @Test - public void iteratorOneItem() - { - DefaultVersionFilterContext context = new DefaultVersionFilterContext( new DefaultRepositorySystemSession() ); - VersionRangeResult result = new VersionRangeResult( new VersionRangeRequest() ); - result.addVersion( new TestVersion( "1.0" ) ); - context.set( FOO_DEPENDENCY, result ); + public void iteratorOneItem() { + DefaultVersionFilterContext context = new DefaultVersionFilterContext(new DefaultRepositorySystemSession()); + VersionRangeResult result = new VersionRangeResult(new VersionRangeRequest()); + result.addVersion(new TestVersion("1.0")); + context.set(FOO_DEPENDENCY, result); Iterator iterator = context.iterator(); - assertTrue( iterator.hasNext() ); - assertEquals( new TestVersion( "1.0" ), iterator.next() ); + assertTrue(iterator.hasNext()); + assertEquals(new TestVersion("1.0"), iterator.next()); } @Test - public void getCountOneItem() - { - DefaultVersionFilterContext context = new DefaultVersionFilterContext( new DefaultRepositorySystemSession() ); - VersionRangeResult result = new VersionRangeResult( new VersionRangeRequest() ); - result.addVersion( new TestVersion( "1.0" ) ); - context.set( FOO_DEPENDENCY, result ); + public void getCountOneItem() { + DefaultVersionFilterContext context = new DefaultVersionFilterContext(new DefaultRepositorySystemSession()); + VersionRangeResult result = new VersionRangeResult(new VersionRangeRequest()); + result.addVersion(new TestVersion("1.0")); + context.set(FOO_DEPENDENCY, result); assertEquals(1, context.getCount()); } @Test - public void getOneItem() - { - DefaultVersionFilterContext context = new DefaultVersionFilterContext( new DefaultRepositorySystemSession() ); - VersionRangeResult result = new VersionRangeResult( new VersionRangeRequest() ); - result.addVersion( new TestVersion( "1.0" ) ); - context.set( FOO_DEPENDENCY, result ); - - assertEquals( Collections.singletonList( new TestVersion( "1.0") ), context.get() ); + public void getOneItem() { + DefaultVersionFilterContext context = new DefaultVersionFilterContext(new DefaultRepositorySystemSession()); + VersionRangeResult result = new VersionRangeResult(new VersionRangeRequest()); + result.addVersion(new TestVersion("1.0")); + context.set(FOO_DEPENDENCY, result); + + assertEquals(Collections.singletonList(new TestVersion("1.0")), context.get()); } @Test - public void iteratorDelete() - { - DefaultVersionFilterContext context = new DefaultVersionFilterContext( new DefaultRepositorySystemSession() ); - VersionRangeResult result = new VersionRangeResult( new VersionRangeRequest() ); - result.addVersion( new TestVersion( "1.0" ) ); - context.set( FOO_DEPENDENCY, result ); + public void iteratorDelete() { + DefaultVersionFilterContext context = new DefaultVersionFilterContext(new DefaultRepositorySystemSession()); + VersionRangeResult result = new VersionRangeResult(new VersionRangeRequest()); + result.addVersion(new TestVersion("1.0")); + context.set(FOO_DEPENDENCY, result); Iterator iterator = context.iterator(); iterator.next(); iterator.remove(); - assertEquals( 0, context.getCount() ); + assertEquals(0, context.getCount()); } @Test(expected = NoSuchElementException.class) - public void nextBeyondEnd() - { - DefaultVersionFilterContext context = new DefaultVersionFilterContext( new DefaultRepositorySystemSession() ); - VersionRangeResult result = new VersionRangeResult( new VersionRangeRequest() ); - result.addVersion( new TestVersion( "1.0" ) ); - context.set( FOO_DEPENDENCY, result ); + public void nextBeyondEnd() { + DefaultVersionFilterContext context = new DefaultVersionFilterContext(new DefaultRepositorySystemSession()); + VersionRangeResult result = new VersionRangeResult(new VersionRangeRequest()); + result.addVersion(new TestVersion("1.0")); + context.set(FOO_DEPENDENCY, result); Iterator iterator = context.iterator(); iterator.next(); @@ -105,66 +98,62 @@ public void nextBeyondEnd() } @Test - public void removeOneOfOne() - { - DefaultVersionFilterContext context = new DefaultVersionFilterContext( new DefaultRepositorySystemSession() ); - VersionRangeResult result = new VersionRangeResult( new VersionRangeRequest() ); - result.addVersion( new TestVersion( "1.0" ) ); - context.set( FOO_DEPENDENCY, result ); + public void removeOneOfOne() { + DefaultVersionFilterContext context = new DefaultVersionFilterContext(new DefaultRepositorySystemSession()); + VersionRangeResult result = new VersionRangeResult(new VersionRangeRequest()); + result.addVersion(new TestVersion("1.0")); + context.set(FOO_DEPENDENCY, result); Iterator iterator = context.iterator(); iterator.next(); iterator.remove(); - assertEquals( Collections.emptyList(), context.get() ); + assertEquals(Collections.emptyList(), context.get()); } @Test - public void removeOneOfTwo() - { - DefaultVersionFilterContext context = new DefaultVersionFilterContext( new DefaultRepositorySystemSession() ); - VersionRangeResult result = new VersionRangeResult( new VersionRangeRequest() ); - result.addVersion( new TestVersion( "1.0" ) ); - result.addVersion( new TestVersion( "2.0" ) ); - context.set( FOO_DEPENDENCY, result ); + public void removeOneOfTwo() { + DefaultVersionFilterContext context = new DefaultVersionFilterContext(new DefaultRepositorySystemSession()); + VersionRangeResult result = new VersionRangeResult(new VersionRangeRequest()); + result.addVersion(new TestVersion("1.0")); + result.addVersion(new TestVersion("2.0")); + context.set(FOO_DEPENDENCY, result); Iterator iterator = context.iterator(); iterator.next(); iterator.remove(); - assertEquals( Collections.singletonList( new TestVersion( "2.0") ), context.get() ); + assertEquals(Collections.singletonList(new TestVersion("2.0")), context.get()); } @Test - public void removeOneOfThree() - { - DefaultVersionFilterContext context = new DefaultVersionFilterContext( new DefaultRepositorySystemSession() ); - VersionRangeResult result = new VersionRangeResult( new VersionRangeRequest() ); - result.addVersion( new TestVersion( "1.0" ) ); - result.addVersion( new TestVersion( "2.0" ) ); - result.addVersion( new TestVersion( "3.0" ) ); - context.set( FOO_DEPENDENCY, result ); + public void removeOneOfThree() { + DefaultVersionFilterContext context = new DefaultVersionFilterContext(new DefaultRepositorySystemSession()); + VersionRangeResult result = new VersionRangeResult(new VersionRangeRequest()); + result.addVersion(new TestVersion("1.0")); + result.addVersion(new TestVersion("2.0")); + result.addVersion(new TestVersion("3.0")); + context.set(FOO_DEPENDENCY, result); Iterator iterator = context.iterator(); iterator.next(); iterator.remove(); - assertEquals( Arrays.asList( new TestVersion( "2.0" ), new TestVersion( "3.0" ) ), context.get() ); + assertEquals(Arrays.asList(new TestVersion("2.0"), new TestVersion("3.0")), context.get()); } @Test - public void setTwice() - { - DefaultVersionFilterContext context = new DefaultVersionFilterContext( new DefaultRepositorySystemSession() ); - VersionRangeResult fooResult = new VersionRangeResult( new VersionRangeRequest() ); - fooResult.addVersion( new TestVersion( "1.0" ) ); - context.set( FOO_DEPENDENCY, fooResult ); - - VersionRangeResult barResult = new VersionRangeResult( new VersionRangeRequest() ); - barResult.addVersion( new TestVersion( "1.0" ) ); - barResult.addVersion( new TestVersion( "2.0" ) ); - context.set( BAR_DEPENDENCY, barResult ); - - assertEquals( Arrays.asList( new TestVersion( "1.0" ), new TestVersion( "2.0" ) ), context.get() ); + public void setTwice() { + DefaultVersionFilterContext context = new DefaultVersionFilterContext(new DefaultRepositorySystemSession()); + VersionRangeResult fooResult = new VersionRangeResult(new VersionRangeRequest()); + fooResult.addVersion(new TestVersion("1.0")); + context.set(FOO_DEPENDENCY, fooResult); + + VersionRangeResult barResult = new VersionRangeResult(new VersionRangeRequest()); + barResult.addVersion(new TestVersion("1.0")); + barResult.addVersion(new TestVersion("2.0")); + context.set(BAR_DEPENDENCY, barResult); + + assertEquals(Arrays.asList(new TestVersion("1.0"), new TestVersion("2.0")), context.get()); } -} \ No newline at end of file +} diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DependencyCollectorDelegateTestSupport.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DependencyCollectorDelegateTestSupport.java index c7759ced8..5cf4d7f23 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DependencyCollectorDelegateTestSupport.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/DependencyCollectorDelegateTestSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect; import java.io.IOException; import java.util.ArrayList; @@ -81,8 +80,7 @@ /** * Common tests for various {@link DependencyCollectorDelegate} implementations. */ -public abstract class DependencyCollectorDelegateTestSupport -{ +public abstract class DependencyCollectorDelegateTestSupport { protected DefaultRepositorySystemSession session; @@ -92,515 +90,461 @@ public abstract class DependencyCollectorDelegateTestSupport protected DependencyCollectorDelegate collector; - protected IniArtifactDescriptorReader newReader( String prefix ) - { - return new IniArtifactDescriptorReader( "artifact-descriptions/" + prefix ); + protected IniArtifactDescriptorReader newReader(String prefix) { + return new IniArtifactDescriptorReader("artifact-descriptions/" + prefix); } - protected Dependency newDep( String coords ) - { - return newDep( coords, "" ); + protected Dependency newDep(String coords) { + return newDep(coords, ""); } - protected Dependency newDep( String coords, String scope ) - { - return new Dependency( new DefaultArtifact( coords ), scope ); + protected Dependency newDep(String coords, String scope) { + return new Dependency(new DefaultArtifact(coords), scope); } @Before - public void setup() - { + public void setup() { session = TestUtils.newSession(); - parser = new DependencyGraphParser( "artifact-descriptions/" ); - repository = new RemoteRepository.Builder( "id", "default", "file:///" ).build(); + parser = new DependencyGraphParser("artifact-descriptions/"); + repository = new RemoteRepository.Builder("id", "default", "file:///").build(); setupCollector(); } protected abstract void setupCollector(); - private static void assertEqualSubtree( DependencyNode expected, DependencyNode actual ) - { - assertEqualSubtree( expected, actual, new LinkedList<>() ); + private static void assertEqualSubtree(DependencyNode expected, DependencyNode actual) { + assertEqualSubtree(expected, actual, new LinkedList<>()); } - private static void assertEqualSubtree( DependencyNode expected, DependencyNode actual, - LinkedList parents ) - { - assertEquals( "path: " + parents, expected.getDependency(), actual.getDependency() ); + private static void assertEqualSubtree( + DependencyNode expected, DependencyNode actual, LinkedList parents) { + assertEquals("path: " + parents, expected.getDependency(), actual.getDependency()); - if ( actual.getDependency() != null ) - { + if (actual.getDependency() != null) { Artifact artifact = actual.getDependency().getArtifact(); - for ( DependencyNode parent : parents ) - { - if ( parent.getDependency() != null && artifact.equals( parent.getDependency().getArtifact() ) ) - { + for (DependencyNode parent : parents) { + if (parent.getDependency() != null + && artifact.equals(parent.getDependency().getArtifact())) { return; } } } - parents.addLast( expected ); + parents.addLast(expected); - assertEquals( "path: " + parents + ", expected: " + expected.getChildren() + ", actual: " - + actual.getChildren(), expected.getChildren().size(), actual.getChildren().size() ); + assertEquals( + "path: " + parents + ", expected: " + expected.getChildren() + ", actual: " + actual.getChildren(), + expected.getChildren().size(), + actual.getChildren().size()); Iterator iterator1 = expected.getChildren().iterator(); Iterator iterator2 = actual.getChildren().iterator(); - while ( iterator1.hasNext() ) - { - assertEqualSubtree( iterator1.next(), iterator2.next(), parents ); + while (iterator1.hasNext()) { + assertEqualSubtree(iterator1.next(), iterator2.next(), parents); } parents.removeLast(); } - protected Dependency dep( DependencyNode root, int... coords ) - { - return path( root, coords ).getDependency(); + protected Dependency dep(DependencyNode root, int... coords) { + return path(root, coords).getDependency(); } - protected DependencyNode path( DependencyNode root, int... coords ) - { - try - { + protected DependencyNode path(DependencyNode root, int... coords) { + try { DependencyNode node = root; - for ( int coord : coords ) - { - node = node.getChildren().get( coord ); + for (int coord : coords) { + node = node.getChildren().get(coord); } return node; - } - catch ( IndexOutOfBoundsException | NullPointerException e ) - { - throw new IllegalArgumentException( "illegal coordinates for child", e ); + } catch (IndexOutOfBoundsException | NullPointerException e) { + throw new IllegalArgumentException("illegal coordinates for child", e); } } @Test - public void testSimpleCollection() - throws DependencyCollectionException - { - Dependency dependency = newDep( "gid:aid:ext:ver", "compile" ); - CollectRequest request = new CollectRequest( dependency, singletonList( repository ) ); - CollectResult result = collector.collectDependencies( session, request ); + public void testSimpleCollection() throws DependencyCollectionException { + Dependency dependency = newDep("gid:aid:ext:ver", "compile"); + CollectRequest request = new CollectRequest(dependency, singletonList(repository)); + CollectResult result = collector.collectDependencies(session, request); - assertEquals( 0, result.getExceptions().size() ); + assertEquals(0, result.getExceptions().size()); DependencyNode root = result.getRoot(); Dependency newDependency = root.getDependency(); - assertEquals( dependency, newDependency ); - assertEquals( dependency.getArtifact(), newDependency.getArtifact() ); + assertEquals(dependency, newDependency); + assertEquals(dependency.getArtifact(), newDependency.getArtifact()); - assertEquals( 1, root.getChildren().size() ); + assertEquals(1, root.getChildren().size()); - Dependency expect = newDep( "gid:aid2:ext:ver", "compile" ); - assertEquals( expect, root.getChildren().get( 0 ).getDependency() ); + Dependency expect = newDep("gid:aid2:ext:ver", "compile"); + assertEquals(expect, root.getChildren().get(0).getDependency()); } @Test - public void testMissingDependencyDescription() - { - CollectRequest request = - new CollectRequest( newDep( "missing:description:ext:ver" ), singletonList( repository ) ); - try - { - collector.collectDependencies( session, request ); - fail( "expected exception" ); - } - catch ( DependencyCollectionException e ) - { + public void testMissingDependencyDescription() { + CollectRequest request = new CollectRequest(newDep("missing:description:ext:ver"), singletonList(repository)); + try { + collector.collectDependencies(session, request); + fail("expected exception"); + } catch (DependencyCollectionException e) { CollectResult result = e.getResult(); - assertSame( request, result.getRequest() ); - assertNotNull( result.getExceptions() ); - assertEquals( 1, result.getExceptions().size() ); + assertSame(request, result.getRequest()); + assertNotNull(result.getExceptions()); + assertEquals(1, result.getExceptions().size()); - assertTrue( result.getExceptions().get( 0 ) instanceof ArtifactDescriptorException ); + assertTrue(result.getExceptions().get(0) instanceof ArtifactDescriptorException); - assertEquals( request.getRoot(), result.getRoot().getDependency() ); + assertEquals(request.getRoot(), result.getRoot().getDependency()); } } @Test - public void testDuplicates() - throws DependencyCollectionException - { - Dependency dependency = newDep( "duplicate:transitive:ext:dependency" ); - CollectRequest request = new CollectRequest( dependency, singletonList( repository ) ); + public void testDuplicates() throws DependencyCollectionException { + Dependency dependency = newDep("duplicate:transitive:ext:dependency"); + CollectRequest request = new CollectRequest(dependency, singletonList(repository)); - CollectResult result = collector.collectDependencies( session, request ); + CollectResult result = collector.collectDependencies(session, request); - assertEquals( 0, result.getExceptions().size() ); + assertEquals(0, result.getExceptions().size()); DependencyNode root = result.getRoot(); Dependency newDependency = root.getDependency(); - assertEquals( dependency, newDependency ); - assertEquals( dependency.getArtifact(), newDependency.getArtifact() ); + assertEquals(dependency, newDependency); + assertEquals(dependency.getArtifact(), newDependency.getArtifact()); - assertEquals( 2, root.getChildren().size() ); + assertEquals(2, root.getChildren().size()); - Dependency dep = newDep( "gid:aid:ext:ver", "compile" ); - assertEquals( dep, dep( root, 0 ) ); + Dependency dep = newDep("gid:aid:ext:ver", "compile"); + assertEquals(dep, dep(root, 0)); - dep = newDep( "gid:aid2:ext:ver", "compile" ); - assertEquals( dep, dep( root, 1 ) ); - assertEquals( dep, dep( root, 0, 0 ) ); - assertEquals( dep( root, 1 ), dep( root, 0, 0 ) ); + dep = newDep("gid:aid2:ext:ver", "compile"); + assertEquals(dep, dep(root, 1)); + assertEquals(dep, dep(root, 0, 0)); + assertEquals(dep(root, 1), dep(root, 0, 0)); } @Test - public void testEqualSubtree() - throws IOException, DependencyCollectionException - { - DependencyNode root = parser.parseResource( "expectedSubtreeComparisonResult.txt" ); + public void testEqualSubtree() throws IOException, DependencyCollectionException { + DependencyNode root = parser.parseResource("expectedSubtreeComparisonResult.txt"); Dependency dependency = root.getDependency(); - CollectRequest request = new CollectRequest( dependency, singletonList( repository ) ); + CollectRequest request = new CollectRequest(dependency, singletonList(repository)); - CollectResult result = collector.collectDependencies( session, request ); - assertEqualSubtree( root, result.getRoot() ); + CollectResult result = collector.collectDependencies(session, request); + assertEqualSubtree(root, result.getRoot()); } @Test - public void testCyclicDependencies() - throws Exception - { - DependencyNode root = parser.parseResource( "cycle.txt" ); - CollectRequest request = new CollectRequest( root.getDependency(), singletonList( repository ) ); - CollectResult result = collector.collectDependencies( session, request ); - assertEqualSubtree( root, result.getRoot() ); + public void testCyclicDependencies() throws Exception { + DependencyNode root = parser.parseResource("cycle.txt"); + CollectRequest request = new CollectRequest(root.getDependency(), singletonList(repository)); + CollectResult result = collector.collectDependencies(session, request); + assertEqualSubtree(root, result.getRoot()); } @Test - public void testCyclicDependenciesBig() - throws Exception - { - CollectRequest request = new CollectRequest( newDep( "1:2:pom:5.50-SNAPSHOT" ), singletonList( repository ) ); - collector.setArtifactDescriptorReader( newReader( "cycle-big/" ) ); - CollectResult result = collector.collectDependencies( session, request ); - assertNotNull( result.getRoot() ); + public void testCyclicDependenciesBig() throws Exception { + CollectRequest request = new CollectRequest(newDep("1:2:pom:5.50-SNAPSHOT"), singletonList(repository)); + collector.setArtifactDescriptorReader(newReader("cycle-big/")); + CollectResult result = collector.collectDependencies(session, request); + assertNotNull(result.getRoot()); // we only care about the performance here, this test must not hang or run out of mem } @Test - public void testCyclicProjects() - throws Exception - { - CollectRequest request = new CollectRequest( newDep( "test:a:2" ), singletonList( repository ) ); - collector.setArtifactDescriptorReader( newReader( "versionless-cycle/" ) ); - CollectResult result = collector.collectDependencies( session, request ); + public void testCyclicProjects() throws Exception { + CollectRequest request = new CollectRequest(newDep("test:a:2"), singletonList(repository)); + collector.setArtifactDescriptorReader(newReader("versionless-cycle/")); + CollectResult result = collector.collectDependencies(session, request); DependencyNode root = result.getRoot(); - DependencyNode a1 = path( root, 0, 0 ); - assertEquals( "a", a1.getArtifact().getArtifactId() ); - assertEquals( "1", a1.getArtifact().getVersion() ); - for ( DependencyNode child : a1.getChildren() ) - { - assertNotEquals( "1", child.getArtifact().getVersion() ); + DependencyNode a1 = path(root, 0, 0); + assertEquals("a", a1.getArtifact().getArtifactId()); + assertEquals("1", a1.getArtifact().getVersion()); + for (DependencyNode child : a1.getChildren()) { + assertNotEquals("1", child.getArtifact().getVersion()); } - assertEquals( 1, result.getCycles().size() ); - DependencyCycle cycle = result.getCycles().get( 0 ); - assertEquals( Collections.emptyList(), cycle.getPrecedingDependencies() ); - assertEquals( Arrays.asList( root.getDependency(), path( root, 0 ).getDependency(), a1.getDependency() ), - cycle.getCyclicDependencies() ); + assertEquals(1, result.getCycles().size()); + DependencyCycle cycle = result.getCycles().get(0); + assertEquals(Collections.emptyList(), cycle.getPrecedingDependencies()); + assertEquals( + Arrays.asList(root.getDependency(), path(root, 0).getDependency(), a1.getDependency()), + cycle.getCyclicDependencies()); } @Test - public void testCyclicProjects_ConsiderLabelOfRootlessGraph() - throws Exception - { - Dependency dep = newDep( "gid:aid:ver", "compile" ); - CollectRequest request = - new CollectRequest().addDependency( dep ).addRepository( repository ) - .setRootArtifact( dep.getArtifact() ); - CollectResult result = collector.collectDependencies( session, request ); + public void testCyclicProjects_ConsiderLabelOfRootlessGraph() throws Exception { + Dependency dep = newDep("gid:aid:ver", "compile"); + CollectRequest request = new CollectRequest() + .addDependency(dep) + .addRepository(repository) + .setRootArtifact(dep.getArtifact()); + CollectResult result = collector.collectDependencies(session, request); DependencyNode root = result.getRoot(); - DependencyNode a1 = root.getChildren().get( 0 ); - assertEquals( "aid", a1.getArtifact().getArtifactId() ); - assertEquals( "ver", a1.getArtifact().getVersion() ); - DependencyNode a2 = a1.getChildren().get( 0 ); - assertEquals( "aid2", a2.getArtifact().getArtifactId() ); - assertEquals( "ver", a2.getArtifact().getVersion() ); - - assertEquals( 1, result.getCycles().size() ); - DependencyCycle cycle = result.getCycles().get( 0 ); - assertEquals( Collections.emptyList(), cycle.getPrecedingDependencies() ); - assertEquals( Arrays.asList( new Dependency( dep.getArtifact(), null ), a1.getDependency() ), - cycle.getCyclicDependencies() ); + DependencyNode a1 = root.getChildren().get(0); + assertEquals("aid", a1.getArtifact().getArtifactId()); + assertEquals("ver", a1.getArtifact().getVersion()); + DependencyNode a2 = a1.getChildren().get(0); + assertEquals("aid2", a2.getArtifact().getArtifactId()); + assertEquals("ver", a2.getArtifact().getVersion()); + + assertEquals(1, result.getCycles().size()); + DependencyCycle cycle = result.getCycles().get(0); + assertEquals(Collections.emptyList(), cycle.getPrecedingDependencies()); + assertEquals( + Arrays.asList(new Dependency(dep.getArtifact(), null), a1.getDependency()), + cycle.getCyclicDependencies()); } @Test - public void testPartialResultOnError() - throws IOException - { - DependencyNode root = parser.parseResource( "expectedPartialSubtreeOnError.txt" ); + public void testPartialResultOnError() throws IOException { + DependencyNode root = parser.parseResource("expectedPartialSubtreeOnError.txt"); Dependency dependency = root.getDependency(); - CollectRequest request = new CollectRequest( dependency, singletonList( repository ) ); + CollectRequest request = new CollectRequest(dependency, singletonList(repository)); CollectResult result; - try - { - result = collector.collectDependencies( session, request ); - fail( "expected exception " ); - } - catch ( DependencyCollectionException e ) - { + try { + result = collector.collectDependencies(session, request); + fail("expected exception "); + } catch (DependencyCollectionException e) { result = e.getResult(); - assertSame( request, result.getRequest() ); - assertNotNull( result.getExceptions() ); - assertEquals( 1, result.getExceptions().size() ); + assertSame(request, result.getRequest()); + assertNotNull(result.getExceptions()); + assertEquals(1, result.getExceptions().size()); - assertTrue( result.getExceptions().get( 0 ) instanceof ArtifactDescriptorException ); + assertTrue(result.getExceptions().get(0) instanceof ArtifactDescriptorException); - assertEqualSubtree( root, result.getRoot() ); + assertEqualSubtree(root, result.getRoot()); } } @Test - public void testCollectMultipleDependencies() - throws DependencyCollectionException - { - Dependency root1 = newDep( "gid:aid:ext:ver", "compile" ); - Dependency root2 = newDep( "gid:aid2:ext:ver", "compile" ); - List dependencies = Arrays.asList( root1, root2 ); - CollectRequest request = new CollectRequest( dependencies, null, singletonList( repository ) ); - CollectResult result = collector.collectDependencies( session, request ); - - assertEquals( 0, result.getExceptions().size() ); - assertEquals( 2, result.getRoot().getChildren().size() ); - assertEquals( root1, dep( result.getRoot(), 0 ) ); - - assertEquals( 1, path( result.getRoot(), 0 ).getChildren().size() ); - assertEquals( root2, dep( result.getRoot(), 0, 0 ) ); - - assertEquals( 0, path( result.getRoot(), 1 ).getChildren().size() ); - assertEquals( root2, dep( result.getRoot(), 1 ) ); + public void testCollectMultipleDependencies() throws DependencyCollectionException { + Dependency root1 = newDep("gid:aid:ext:ver", "compile"); + Dependency root2 = newDep("gid:aid2:ext:ver", "compile"); + List dependencies = Arrays.asList(root1, root2); + CollectRequest request = new CollectRequest(dependencies, null, singletonList(repository)); + CollectResult result = collector.collectDependencies(session, request); + + assertEquals(0, result.getExceptions().size()); + assertEquals(2, result.getRoot().getChildren().size()); + assertEquals(root1, dep(result.getRoot(), 0)); + + assertEquals(1, path(result.getRoot(), 0).getChildren().size()); + assertEquals(root2, dep(result.getRoot(), 0, 0)); + + assertEquals(0, path(result.getRoot(), 1).getChildren().size()); + assertEquals(root2, dep(result.getRoot(), 1)); } @Test - public void testArtifactDescriptorResolutionNotRestrictedToRepoHostingSelectedVersion() - throws Exception - { - RemoteRepository repo2 = new RemoteRepository.Builder( "test", "default", "file:///" ).build(); + public void testArtifactDescriptorResolutionNotRestrictedToRepoHostingSelectedVersion() throws Exception { + RemoteRepository repo2 = new RemoteRepository.Builder("test", "default", "file:///").build(); final List repos = new ArrayList<>(); - collector.setArtifactDescriptorReader( new ArtifactDescriptorReader() - { - public ArtifactDescriptorResult readArtifactDescriptor( RepositorySystemSession session, - ArtifactDescriptorRequest request ) - { - repos.addAll( request.getRepositories() ); - return new ArtifactDescriptorResult( request ); + collector.setArtifactDescriptorReader(new ArtifactDescriptorReader() { + public ArtifactDescriptorResult readArtifactDescriptor( + RepositorySystemSession session, ArtifactDescriptorRequest request) { + repos.addAll(request.getRepositories()); + return new ArtifactDescriptorResult(request); } - } ); + }); - List dependencies = singletonList( newDep( "verrange:parent:jar:1[1,)", "compile" ) ); - CollectRequest request = new CollectRequest( dependencies, null, Arrays.asList( repository, repo2 ) ); - CollectResult result = collector.collectDependencies( session, request ); + List dependencies = singletonList(newDep("verrange:parent:jar:1[1,)", "compile")); + CollectRequest request = new CollectRequest(dependencies, null, Arrays.asList(repository, repo2)); + CollectResult result = collector.collectDependencies(session, request); - assertEquals( 0, result.getExceptions().size() ); - assertEquals( 2, repos.size() ); - assertEquals( "id", repos.get( 0 ).getId() ); - assertEquals( "test", repos.get( 1 ).getId() ); + assertEquals(0, result.getExceptions().size()); + assertEquals(2, repos.size()); + assertEquals("id", repos.get(0).getId()); + assertEquals("test", repos.get(1).getId()); } @Test - public void testManagedVersionScope() - throws DependencyCollectionException - { - Dependency dependency = newDep( "managed:aid:ext:ver" ); - CollectRequest request = new CollectRequest( dependency, singletonList( repository ) ); + public void testManagedVersionScope() throws DependencyCollectionException { + Dependency dependency = newDep("managed:aid:ext:ver"); + CollectRequest request = new CollectRequest(dependency, singletonList(repository)); - session.setDependencyManager( new ClassicDependencyManager() ); + session.setDependencyManager(new ClassicDependencyManager()); - CollectResult result = collector.collectDependencies( session, request ); + CollectResult result = collector.collectDependencies(session, request); - assertEquals( 0, result.getExceptions().size() ); + assertEquals(0, result.getExceptions().size()); DependencyNode root = result.getRoot(); - assertEquals( dependency, dep( root ) ); - assertEquals( dependency.getArtifact(), dep( root ).getArtifact() ); + assertEquals(dependency, dep(root)); + assertEquals(dependency.getArtifact(), dep(root).getArtifact()); - assertEquals( 1, root.getChildren().size() ); - Dependency expect = newDep( "gid:aid:ext:ver", "compile" ); - assertEquals( expect, dep( root, 0 ) ); + assertEquals(1, root.getChildren().size()); + Dependency expect = newDep("gid:aid:ext:ver", "compile"); + assertEquals(expect, dep(root, 0)); - assertEquals( 1, path( root, 0 ).getChildren().size() ); - expect = newDep( "gid:aid2:ext:managedVersion", "managedScope" ); - assertEquals( expect, dep( root, 0, 0 ) ); + assertEquals(1, path(root, 0).getChildren().size()); + expect = newDep("gid:aid2:ext:managedVersion", "managedScope"); + assertEquals(expect, dep(root, 0, 0)); } @Test - public void testDependencyManagement() - throws IOException, DependencyCollectionException - { - collector.setArtifactDescriptorReader( newReader( "managed/" ) ); + public void testDependencyManagement() throws IOException, DependencyCollectionException { + collector.setArtifactDescriptorReader(newReader("managed/")); - DependencyNode root = parser.parseResource( "expectedSubtreeComparisonResult.txt" ); + DependencyNode root = parser.parseResource("expectedSubtreeComparisonResult.txt"); TestDependencyManager depMgmt = new TestDependencyManager(); - depMgmt.add( dep( root, 0 ), "managed", null, null ); - depMgmt.add( dep( root, 0, 1 ), "managed", "managed", null ); - depMgmt.add( dep( root, 1 ), null, null, "managed" ); - session.setDependencyManager( depMgmt ); + depMgmt.add(dep(root, 0), "managed", null, null); + depMgmt.add(dep(root, 0, 1), "managed", "managed", null); + depMgmt.add(dep(root, 1), null, null, "managed"); + session.setDependencyManager(depMgmt); // collect result will differ from expectedSubtreeComparisonResult.txt // set localPath -> no dependency traversal - CollectRequest request = new CollectRequest( dep( root ), singletonList( repository ) ); - CollectResult result = collector.collectDependencies( session, request ); + CollectRequest request = new CollectRequest(dep(root), singletonList(repository)); + CollectResult result = collector.collectDependencies(session, request); DependencyNode node = result.getRoot(); - assertEquals( "managed", dep( node, 0, 1 ).getArtifact().getVersion() ); - assertEquals( "managed", dep( node, 0, 1 ).getScope() ); + assertEquals("managed", dep(node, 0, 1).getArtifact().getVersion()); + assertEquals("managed", dep(node, 0, 1).getScope()); - assertEquals( "managed", dep( node, 1 ).getArtifact().getProperty( ArtifactProperties.LOCAL_PATH, null ) ); - assertEquals( "managed", dep( node, 0, 0 ).getArtifact().getProperty( ArtifactProperties.LOCAL_PATH, null ) ); + assertEquals("managed", dep(node, 1).getArtifact().getProperty(ArtifactProperties.LOCAL_PATH, null)); + assertEquals("managed", dep(node, 0, 0).getArtifact().getProperty(ArtifactProperties.LOCAL_PATH, null)); } @Test - public void testDependencyManagement_VerboseMode() - throws Exception - { + public void testDependencyManagement_VerboseMode() throws Exception { String depId = "gid:aid2:ext"; TestDependencyManager depMgmt = new TestDependencyManager(); - depMgmt.version( depId, "managedVersion" ); - depMgmt.scope( depId, "managedScope" ); - depMgmt.optional( depId, Boolean.TRUE ); - depMgmt.path( depId, "managedPath" ); - depMgmt.exclusions( depId, new Exclusion( "gid", "aid", "*", "*" ) ); - session.setDependencyManager( depMgmt ); - session.setConfigProperty( DependencyManagerUtils.CONFIG_PROP_VERBOSE, Boolean.TRUE ); - - CollectRequest request = new CollectRequest().setRoot( newDep( "gid:aid:ver" ) ); - CollectResult result = collector.collectDependencies( session, request ); - DependencyNode node = result.getRoot().getChildren().get( 0 ); - assertEquals( DependencyNode.MANAGED_VERSION | DependencyNode.MANAGED_SCOPE | DependencyNode.MANAGED_OPTIONAL - | DependencyNode.MANAGED_PROPERTIES | DependencyNode.MANAGED_EXCLUSIONS, node.getManagedBits() ); - assertEquals( "ver", DependencyManagerUtils.getPremanagedVersion( node ) ); - assertEquals( "compile", DependencyManagerUtils.getPremanagedScope( node ) ); - assertEquals( Boolean.FALSE, DependencyManagerUtils.getPremanagedOptional( node ) ); + depMgmt.version(depId, "managedVersion"); + depMgmt.scope(depId, "managedScope"); + depMgmt.optional(depId, Boolean.TRUE); + depMgmt.path(depId, "managedPath"); + depMgmt.exclusions(depId, new Exclusion("gid", "aid", "*", "*")); + session.setDependencyManager(depMgmt); + session.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, Boolean.TRUE); + + CollectRequest request = new CollectRequest().setRoot(newDep("gid:aid:ver")); + CollectResult result = collector.collectDependencies(session, request); + DependencyNode node = result.getRoot().getChildren().get(0); + assertEquals( + DependencyNode.MANAGED_VERSION + | DependencyNode.MANAGED_SCOPE + | DependencyNode.MANAGED_OPTIONAL + | DependencyNode.MANAGED_PROPERTIES + | DependencyNode.MANAGED_EXCLUSIONS, + node.getManagedBits()); + assertEquals("ver", DependencyManagerUtils.getPremanagedVersion(node)); + assertEquals("compile", DependencyManagerUtils.getPremanagedScope(node)); + assertEquals(Boolean.FALSE, DependencyManagerUtils.getPremanagedOptional(node)); } @Test public void testDependencyManagement_TransitiveDependencyManager() - throws DependencyCollectionException, IOException - { - collector.setArtifactDescriptorReader( newReader( "managed/" ) ); - parser = new DependencyGraphParser( "artifact-descriptions/managed/" ); - session.setDependencyManager( new TransitiveDependencyManager() ); - final Dependency root = newDep( "gid:root:ext:ver", "compile" ); - CollectRequest request = new CollectRequest( root, singletonList( repository ) ); - request.addManagedDependency( newDep( "gid:root:ext:must-retain-core-management" ) ); - CollectResult result = collector.collectDependencies( session, request ); - - final DependencyNode expectedTree = parser.parseResource( "management-tree.txt" ); - assertEqualSubtree( expectedTree, result.getRoot() ); + throws DependencyCollectionException, IOException { + collector.setArtifactDescriptorReader(newReader("managed/")); + parser = new DependencyGraphParser("artifact-descriptions/managed/"); + session.setDependencyManager(new TransitiveDependencyManager()); + final Dependency root = newDep("gid:root:ext:ver", "compile"); + CollectRequest request = new CollectRequest(root, singletonList(repository)); + request.addManagedDependency(newDep("gid:root:ext:must-retain-core-management")); + CollectResult result = collector.collectDependencies(session, request); + + final DependencyNode expectedTree = parser.parseResource("management-tree.txt"); + assertEqualSubtree(expectedTree, result.getRoot()); // Same test for root artifact (POM) request. final CollectRequest rootArtifactRequest = new CollectRequest(); - rootArtifactRequest.setRepositories( singletonList( repository ) ); - rootArtifactRequest.setRootArtifact( new DefaultArtifact( "gid:root:ext:ver" ) ); - rootArtifactRequest.addDependency( newDep( "gid:direct:ext:ver", "compile" ) ); - rootArtifactRequest.addManagedDependency( newDep( "gid:root:ext:must-retain-core-management" ) ); - rootArtifactRequest.addManagedDependency( newDep( "gid:direct:ext:must-retain-core-management" ) ); - rootArtifactRequest.addManagedDependency( newDep( "gid:transitive-1:ext:managed-by-root" ) ); - session.setDependencyManager( new TransitiveDependencyManager() ); - result = collector.collectDependencies( session, rootArtifactRequest ); - assertEqualSubtree( expectedTree, toDependencyResult( result.getRoot(), "compile", null ) ); + rootArtifactRequest.setRepositories(singletonList(repository)); + rootArtifactRequest.setRootArtifact(new DefaultArtifact("gid:root:ext:ver")); + rootArtifactRequest.addDependency(newDep("gid:direct:ext:ver", "compile")); + rootArtifactRequest.addManagedDependency(newDep("gid:root:ext:must-retain-core-management")); + rootArtifactRequest.addManagedDependency(newDep("gid:direct:ext:must-retain-core-management")); + rootArtifactRequest.addManagedDependency(newDep("gid:transitive-1:ext:managed-by-root")); + session.setDependencyManager(new TransitiveDependencyManager()); + result = collector.collectDependencies(session, rootArtifactRequest); + assertEqualSubtree(expectedTree, toDependencyResult(result.getRoot(), "compile", null)); } @Test - public void testDependencyManagement_DefaultDependencyManager() - throws DependencyCollectionException, IOException - { - collector.setArtifactDescriptorReader( newReader( "managed/" ) ); - parser = new DependencyGraphParser( "artifact-descriptions/managed/" ); - session.setDependencyManager( new DefaultDependencyManager() ); - final Dependency root = newDep( "gid:root:ext:ver", "compile" ); - CollectRequest request = new CollectRequest( root, singletonList( repository ) ); - request.addManagedDependency( newDep( "gid:root:ext:must-not-manage-root" ) ); - request.addManagedDependency( newDep( "gid:direct:ext:managed-by-dominant-request" ) ); - CollectResult result = collector.collectDependencies( session, request ); - - final DependencyNode expectedTree = parser.parseResource( "default-management-tree.txt" ); - assertEqualSubtree( expectedTree, result.getRoot() ); + public void testDependencyManagement_DefaultDependencyManager() throws DependencyCollectionException, IOException { + collector.setArtifactDescriptorReader(newReader("managed/")); + parser = new DependencyGraphParser("artifact-descriptions/managed/"); + session.setDependencyManager(new DefaultDependencyManager()); + final Dependency root = newDep("gid:root:ext:ver", "compile"); + CollectRequest request = new CollectRequest(root, singletonList(repository)); + request.addManagedDependency(newDep("gid:root:ext:must-not-manage-root")); + request.addManagedDependency(newDep("gid:direct:ext:managed-by-dominant-request")); + CollectResult result = collector.collectDependencies(session, request); + + final DependencyNode expectedTree = parser.parseResource("default-management-tree.txt"); + assertEqualSubtree(expectedTree, result.getRoot()); // Same test for root artifact (POM) request. final CollectRequest rootArtifactRequest = new CollectRequest(); - rootArtifactRequest.setRepositories( singletonList( repository ) ); - rootArtifactRequest.setRootArtifact( new DefaultArtifact( "gid:root:ext:ver" ) ); - rootArtifactRequest.addDependency( newDep( "gid:direct:ext:ver", "compile" ) ); - rootArtifactRequest.addManagedDependency( newDep( "gid:root:ext:must-not-manage-root" ) ); - rootArtifactRequest.addManagedDependency( newDep( "gid:direct:ext:managed-by-dominant-request" ) ); - rootArtifactRequest.addManagedDependency( newDep( "gid:transitive-1:ext:managed-by-root" ) ); - session.setDependencyManager( new DefaultDependencyManager() ); - result = collector.collectDependencies( session, rootArtifactRequest ); - assertEqualSubtree( expectedTree, toDependencyResult( result.getRoot(), "compile", null ) ); + rootArtifactRequest.setRepositories(singletonList(repository)); + rootArtifactRequest.setRootArtifact(new DefaultArtifact("gid:root:ext:ver")); + rootArtifactRequest.addDependency(newDep("gid:direct:ext:ver", "compile")); + rootArtifactRequest.addManagedDependency(newDep("gid:root:ext:must-not-manage-root")); + rootArtifactRequest.addManagedDependency(newDep("gid:direct:ext:managed-by-dominant-request")); + rootArtifactRequest.addManagedDependency(newDep("gid:transitive-1:ext:managed-by-root")); + session.setDependencyManager(new DefaultDependencyManager()); + result = collector.collectDependencies(session, rootArtifactRequest); + assertEqualSubtree(expectedTree, toDependencyResult(result.getRoot(), "compile", null)); } - private DependencyNode toDependencyResult( final DependencyNode root, final String rootScope, - final Boolean optional ) - { + private DependencyNode toDependencyResult( + final DependencyNode root, final String rootScope, final Boolean optional) { // Make the root artifact resultion result a dependency resolution result for the subtree check. - assertNull( "Expected root artifact resolution result.", root.getDependency() ); + assertNull("Expected root artifact resolution result.", root.getDependency()); final DefaultDependencyNode defaultNode = - new DefaultDependencyNode( new Dependency( root.getArtifact(), rootScope ) ); + new DefaultDependencyNode(new Dependency(root.getArtifact(), rootScope)); - defaultNode.setChildren( root.getChildren() ); + defaultNode.setChildren(root.getChildren()); - if ( optional != null ) - { - defaultNode.setOptional( optional ); + if (optional != null) { + defaultNode.setOptional(optional); } return defaultNode; } @Test - public void testVersionFilter() - throws Exception - { - session.setVersionFilter( new HighestVersionFilter() ); - CollectRequest request = new CollectRequest().setRoot( newDep( "gid:aid:1" ) ); - CollectResult result = collector.collectDependencies( session, request ); - assertEquals( 1, result.getRoot().getChildren().size() ); + public void testVersionFilter() throws Exception { + session.setVersionFilter(new HighestVersionFilter()); + CollectRequest request = new CollectRequest().setRoot(newDep("gid:aid:1")); + CollectResult result = collector.collectDependencies(session, request); + assertEquals(1, result.getRoot().getChildren().size()); } - @Test - public void testDescriptorDependenciesEmpty() - throws Exception - { - collector.setArtifactDescriptorReader( newReader( "dependencies-empty/" ) ); - - session.setDependencyGraphTransformer( new ConflictResolver( - new NearestVersionSelector(), new JavaScopeSelector(), new SimpleOptionalitySelector(), - new JavaScopeDeriver() - ) ); + public void testDescriptorDependenciesEmpty() throws Exception { + collector.setArtifactDescriptorReader(newReader("dependencies-empty/")); + session.setDependencyGraphTransformer(new ConflictResolver( + new NearestVersionSelector(), + new JavaScopeSelector(), + new SimpleOptionalitySelector(), + new JavaScopeDeriver())); - DependencyNode root = parser.parseResource( "expectedSubtreeOnDescriptorDependenciesEmptyLeft.txt" ); + DependencyNode root = parser.parseResource("expectedSubtreeOnDescriptorDependenciesEmptyLeft.txt"); Dependency dependency = root.getDependency(); - CollectRequest request = new CollectRequest( dependency, singletonList( repository ) ); - CollectResult result = collector.collectDependencies( session, request ); - assertEqualSubtree( root, result.getRoot() ); + CollectRequest request = new CollectRequest(dependency, singletonList(repository)); + CollectResult result = collector.collectDependencies(session, request); + assertEqualSubtree(root, result.getRoot()); - root = parser.parseResource( "expectedSubtreeOnDescriptorDependenciesEmptyRight.txt" ); + root = parser.parseResource("expectedSubtreeOnDescriptorDependenciesEmptyRight.txt"); dependency = root.getDependency(); - request = new CollectRequest( dependency, singletonList( repository ) ); - result = collector.collectDependencies( session, request ); - assertEqualSubtree( root, result.getRoot() ); + request = new CollectRequest(dependency, singletonList(repository)); + result = collector.collectDependencies(session, request); + assertEqualSubtree(root, result.getRoot()); } - static class TestDependencyManager - implements DependencyManager - { + static class TestDependencyManager implements DependencyManager { private final Map versions = new HashMap<>(); @@ -612,69 +556,57 @@ static class TestDependencyManager private final Map> exclusions = new HashMap<>(); - public void add( Dependency d, String version, String scope, String localPath ) - { - String id = toKey( d ); - version( id, version ); - scope( id, scope ); - path( id, localPath ); + public void add(Dependency d, String version, String scope, String localPath) { + String id = toKey(d); + version(id, version); + scope(id, scope); + path(id, localPath); } - public void version( String id, String version ) - { - versions.put( id, version ); + public void version(String id, String version) { + versions.put(id, version); } - public void scope( String id, String scope ) - { - scopes.put( id, scope ); + public void scope(String id, String scope) { + scopes.put(id, scope); } - public void optional( String id, Boolean optional ) - { - optionals.put( id, optional ); + public void optional(String id, Boolean optional) { + optionals.put(id, optional); } - public void path( String id, String path ) - { - paths.put( id, path ); + public void path(String id, String path) { + paths.put(id, path); } - public void exclusions( String id, Exclusion... exclusions ) - { - this.exclusions.put( id, exclusions != null ? Arrays.asList( exclusions ) : null ); + public void exclusions(String id, Exclusion... exclusions) { + this.exclusions.put(id, exclusions != null ? Arrays.asList(exclusions) : null); } @Override - public DependencyManagement manageDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); - String id = toKey( dependency ); + public DependencyManagement manageDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); + String id = toKey(dependency); DependencyManagement mgmt = new DependencyManagement(); - mgmt.setVersion( versions.get( id ) ); - mgmt.setScope( scopes.get( id ) ); - mgmt.setOptional( optionals.get( id ) ); - String path = paths.get( id ); - if ( path != null ) - { - mgmt.setProperties( Collections.singletonMap( ArtifactProperties.LOCAL_PATH, path ) ); + mgmt.setVersion(versions.get(id)); + mgmt.setScope(scopes.get(id)); + mgmt.setOptional(optionals.get(id)); + String path = paths.get(id); + if (path != null) { + mgmt.setProperties(Collections.singletonMap(ArtifactProperties.LOCAL_PATH, path)); } - mgmt.setExclusions( exclusions.get( id ) ); + mgmt.setExclusions(exclusions.get(id)); return mgmt; } - private String toKey( Dependency dependency ) - { - return ArtifactIdUtils.toVersionlessId( dependency.getArtifact() ); + private String toKey(Dependency dependency) { + return ArtifactIdUtils.toVersionlessId(dependency.getArtifact()); } @Override - public DependencyManager deriveChildManager( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencyManager deriveChildManager(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); return this; } - } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/bf/BfDependencyCollectorTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/bf/BfDependencyCollectorTest.java index cd6aa1532..353030fdd 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/bf/BfDependencyCollectorTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/bf/BfDependencyCollectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect.bf; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect.bf; import java.util.Arrays; import java.util.Collection; @@ -46,66 +45,60 @@ /** * UT for {@link BfDependencyCollector}. */ -@RunWith( Parameterized.class ) -public class BfDependencyCollectorTest extends DependencyCollectorDelegateTestSupport -{ +@RunWith(Parameterized.class) +public class BfDependencyCollectorTest extends DependencyCollectorDelegateTestSupport { @Parameterized.Parameters - public static List parameters() - { - return Arrays.asList( Boolean.TRUE, Boolean.FALSE ); + public static List parameters() { + return Arrays.asList(Boolean.TRUE, Boolean.FALSE); } @Parameterized.Parameter public boolean useSkipper; @Override - protected void setupCollector() - { - session.setConfigProperty( BfDependencyCollector.CONFIG_PROP_SKIPPER, useSkipper ); + protected void setupCollector() { + session.setConfigProperty(BfDependencyCollector.CONFIG_PROP_SKIPPER, useSkipper); collector = new BfDependencyCollector(); - collector.setArtifactDescriptorReader( newReader( "" ) ); - collector.setVersionRangeResolver( new StubVersionRangeResolver() ); - collector.setRemoteRepositoryManager( new StubRemoteRepositoryManager() ); + collector.setArtifactDescriptorReader(newReader("")); + collector.setVersionRangeResolver(new StubVersionRangeResolver()); + collector.setRemoteRepositoryManager(new StubRemoteRepositoryManager()); } - private Dependency newDep( String coords, String scope, Collection exclusions ) - { - Dependency d = new Dependency( new DefaultArtifact( coords ), scope ); - return d.setExclusions( exclusions ); + private Dependency newDep(String coords, String scope, Collection exclusions) { + Dependency d = new Dependency(new DefaultArtifact(coords), scope); + return d.setExclusions(exclusions); } @Test - public void testSkipperWithDifferentExclusion() throws DependencyCollectionException - { - Assume.assumeTrue( useSkipper ); - collector.setArtifactDescriptorReader( newReader( "managed/" ) ); - parser = new DependencyGraphParser( "artifact-descriptions/managed/" ); - session.setDependencyManager( new TransitiveDependencyManager() ); + public void testSkipperWithDifferentExclusion() throws DependencyCollectionException { + Assume.assumeTrue(useSkipper); + collector.setArtifactDescriptorReader(newReader("managed/")); + parser = new DependencyGraphParser("artifact-descriptions/managed/"); + session.setDependencyManager(new TransitiveDependencyManager()); ExclusionDependencySelector exclSel1 = new ExclusionDependencySelector(); - session.setDependencySelector( exclSel1 ); + session.setDependencySelector(exclSel1); - Dependency root1 = newDep( "gid:root:ext:ver", "compile", - Collections.singleton( new Exclusion( "gid", "transitive-1", "", "ext" ) ) ); - Dependency root2 = newDep( "gid:root:ext:ver", "compile", - Collections.singleton( new Exclusion( "gid", "transitive-2", "", "ext" ) ) ); - List dependencies = Arrays.asList( root1, root2 ); + Dependency root1 = newDep( + "gid:root:ext:ver", "compile", Collections.singleton(new Exclusion("gid", "transitive-1", "", "ext"))); + Dependency root2 = newDep( + "gid:root:ext:ver", "compile", Collections.singleton(new Exclusion("gid", "transitive-2", "", "ext"))); + List dependencies = Arrays.asList(root1, root2); - CollectRequest request = new CollectRequest( dependencies, null, Arrays.asList( repository ) ); - request.addManagedDependency( newDep( "gid:direct:ext:managed-by-dominant-request" ) ); - request.addManagedDependency( newDep( "gid:transitive-1:ext:managed-by-root" ) ); + CollectRequest request = new CollectRequest(dependencies, null, Arrays.asList(repository)); + request.addManagedDependency(newDep("gid:direct:ext:managed-by-dominant-request")); + request.addManagedDependency(newDep("gid:transitive-1:ext:managed-by-root")); - CollectResult result = collector.collectDependencies( session, request ); - assertEquals( 0, result.getExceptions().size() ); - assertEquals( 2, result.getRoot().getChildren().size() ); - assertEquals( root1, dep( result.getRoot(), 0 ) ); - assertEquals( root2, dep( result.getRoot(), 1 ) ); - //the winner has transitive-1 excluded - assertEquals( 1, path( result.getRoot(), 0 ).getChildren().size() ); - assertEquals( 0, path( result.getRoot(), 0, 0 ).getChildren().size() ); - //skipped - assertEquals( 0, path( result.getRoot(), 1 ).getChildren().size() ); + CollectResult result = collector.collectDependencies(session, request); + assertEquals(0, result.getExceptions().size()); + assertEquals(2, result.getRoot().getChildren().size()); + assertEquals(root1, dep(result.getRoot(), 0)); + assertEquals(root2, dep(result.getRoot(), 1)); + // the winner has transitive-1 excluded + assertEquals(1, path(result.getRoot(), 0).getChildren().size()); + assertEquals(0, path(result.getRoot(), 0, 0).getChildren().size()); + // skipped + assertEquals(0, path(result.getRoot(), 1).getChildren().size()); } - } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/bf/DependencyResolutionSkipperTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/bf/DependencyResolutionSkipperTest.java index eeb0a02d7..97ad3eebb 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/bf/DependencyResolutionSkipperTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/bf/DependencyResolutionSkipperTest.java @@ -1,4 +1,3 @@ -package org.eclipse.aether.internal.impl.collect.bf; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,7 +7,7 @@ * "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 + * 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 @@ -17,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect.bf; import java.util.ArrayList; import java.util.Arrays; @@ -36,178 +36,169 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; - -public class DependencyResolutionSkipperTest -{ - private static DependencyNode makeDependencyNode( String groupId, String artifactId, String version ) - { - return makeDependencyNode( groupId, artifactId, version, "compile" ); +public class DependencyResolutionSkipperTest { + private static DependencyNode makeDependencyNode(String groupId, String artifactId, String version) { + return makeDependencyNode(groupId, artifactId, version, "compile"); } - private static List mutableList( DependencyNode... nodes ) - { - return new ArrayList<>( Arrays.asList( nodes ) ); + private static List mutableList(DependencyNode... nodes) { + return new ArrayList<>(Arrays.asList(nodes)); } - private static DependencyNode makeDependencyNode( String groupId, String artifactId, String version, String scope ) - { + private static DependencyNode makeDependencyNode(String groupId, String artifactId, String version, String scope) { DefaultDependencyNode node = new DefaultDependencyNode( - new Dependency( new DefaultArtifact( groupId + ':' + artifactId + ':' + version ), scope ) - ); - node.setVersion( new TestVersion( version ) ); - node.setVersionConstraint( new TestVersionConstraint( node.getVersion() ) ); + new Dependency(new DefaultArtifact(groupId + ':' + artifactId + ':' + version), scope)); + node.setVersion(new TestVersion(version)); + node.setVersionConstraint(new TestVersionConstraint(node.getVersion())); return node; } @Test - public void testSkipVersionConflict() - { + public void testSkipVersionConflict() { // A -> B -> C 3.0 -> D => C3.0 SHOULD BE SKIPPED // | -> E -> F -> G // | -> C 2.0 -> H => C2.0 is the winner - DependencyNode aNode = makeDependencyNode( "some-group", "A", "1.0" ); - DependencyNode bNode = makeDependencyNode( "some-group", "B", "1.0" ); - DependencyNode c3Node = makeDependencyNode( "some-group", "C", "3.0" ); - DependencyNode dNode = makeDependencyNode( "some-group", "D", "1.0" ); - DependencyNode eNode = makeDependencyNode( "some-group", "E", "1.0" ); - DependencyNode fNode = makeDependencyNode( "some-group", "F", "1.0" ); - DependencyNode c2Node = makeDependencyNode( "some-group", "C", "2.0" ); - DependencyNode gNode = makeDependencyNode( "some-group", "G", "1.0" ); - DependencyNode hNode = makeDependencyNode( "some-group", "H", "1.0" ); - - aNode.setChildren( mutableList( bNode, eNode, c2Node ) ); - bNode.setChildren( mutableList( c3Node ) ); - c3Node.setChildren( mutableList( dNode ) ); - eNode.setChildren( mutableList( fNode ) ); - fNode.setChildren( mutableList( gNode ) ); - c2Node.setChildren( mutableList( hNode ) ); - - //follow the BFS resolve sequence - DependencyResolutionSkipper.DefaultDependencyResolutionSkipper skipper = DependencyResolutionSkipper.defaultSkipper(); - assertFalse( skipper.skipResolution( aNode, new ArrayList<>() ) ); - skipper.cache( aNode, new ArrayList<>() ); - assertFalse( skipper.skipResolution( bNode, mutableList( aNode ) ) ); - skipper.cache( bNode, mutableList( aNode ) ); - assertFalse( skipper.skipResolution( eNode, mutableList( aNode ) ) ); - skipper.cache( eNode, mutableList( aNode ) ); - assertFalse( skipper.skipResolution( c2Node, mutableList( aNode ) ) ); - skipper.cache( c2Node, mutableList( aNode ) ); - assertTrue( skipper.skipResolution( c3Node, mutableList( aNode, bNode ) ) );//version conflict - assertFalse( skipper.skipResolution( fNode, mutableList( aNode, eNode ) ) ); - skipper.cache( fNode, mutableList( aNode, eNode ) ); - assertFalse( skipper.skipResolution( gNode, mutableList( aNode, eNode, fNode ) ) ); - skipper.cache( gNode, mutableList( aNode, eNode, fNode ) ); + DependencyNode aNode = makeDependencyNode("some-group", "A", "1.0"); + DependencyNode bNode = makeDependencyNode("some-group", "B", "1.0"); + DependencyNode c3Node = makeDependencyNode("some-group", "C", "3.0"); + DependencyNode dNode = makeDependencyNode("some-group", "D", "1.0"); + DependencyNode eNode = makeDependencyNode("some-group", "E", "1.0"); + DependencyNode fNode = makeDependencyNode("some-group", "F", "1.0"); + DependencyNode c2Node = makeDependencyNode("some-group", "C", "2.0"); + DependencyNode gNode = makeDependencyNode("some-group", "G", "1.0"); + DependencyNode hNode = makeDependencyNode("some-group", "H", "1.0"); + + aNode.setChildren(mutableList(bNode, eNode, c2Node)); + bNode.setChildren(mutableList(c3Node)); + c3Node.setChildren(mutableList(dNode)); + eNode.setChildren(mutableList(fNode)); + fNode.setChildren(mutableList(gNode)); + c2Node.setChildren(mutableList(hNode)); + + // follow the BFS resolve sequence + DependencyResolutionSkipper.DefaultDependencyResolutionSkipper skipper = + DependencyResolutionSkipper.defaultSkipper(); + assertFalse(skipper.skipResolution(aNode, new ArrayList<>())); + skipper.cache(aNode, new ArrayList<>()); + assertFalse(skipper.skipResolution(bNode, mutableList(aNode))); + skipper.cache(bNode, mutableList(aNode)); + assertFalse(skipper.skipResolution(eNode, mutableList(aNode))); + skipper.cache(eNode, mutableList(aNode)); + assertFalse(skipper.skipResolution(c2Node, mutableList(aNode))); + skipper.cache(c2Node, mutableList(aNode)); + assertTrue(skipper.skipResolution(c3Node, mutableList(aNode, bNode))); // version conflict + assertFalse(skipper.skipResolution(fNode, mutableList(aNode, eNode))); + skipper.cache(fNode, mutableList(aNode, eNode)); + assertFalse(skipper.skipResolution(gNode, mutableList(aNode, eNode, fNode))); + skipper.cache(gNode, mutableList(aNode, eNode, fNode)); Map results = skipper.getResults(); - assertEquals( results.size(), 7 ); + assertEquals(results.size(), 7); - List skipped = - results.values().stream() - .filter( dependencyResolutionResult -> dependencyResolutionResult.skippedAsVersionConflict ) - .collect( Collectors.toList() ); - assertEquals( skipped.size(), 1 ); - assertTrue( skipped.get( 0 ).current == c3Node ); + List skipped = results.values().stream() + .filter(dependencyResolutionResult -> dependencyResolutionResult.skippedAsVersionConflict) + .collect(Collectors.toList()); + assertEquals(skipped.size(), 1); + assertTrue(skipped.get(0).current == c3Node); } @Test - public void testSkipDeeperDuplicateNode() - { + public void testSkipDeeperDuplicateNode() { // A -> B // |--> C -> B => B here will be skipped // |--> D -> C => C here will be skipped - DependencyNode aNode = makeDependencyNode( "some-group", "A", "1.0" ); - DependencyNode bNode = makeDependencyNode( "some-group", "B", "1.0" ); - DependencyNode cNode = makeDependencyNode( "some-group", "C", "1.0" ); - DependencyNode dNode = makeDependencyNode( "some-group", "D", "1.0" ); - DependencyNode b1Node = new DefaultDependencyNode( bNode ); - DependencyNode c1Node = new DefaultDependencyNode( cNode ); - - aNode.setChildren( mutableList( bNode, cNode, dNode ) ); - bNode.setChildren( new ArrayList<>() ); - cNode.setChildren( mutableList( b1Node ) ); - dNode.setChildren( mutableList( c1Node ) ); - - //follow the BFS resolve sequence - DependencyResolutionSkipper.DefaultDependencyResolutionSkipper skipper = DependencyResolutionSkipper.defaultSkipper(); - assertFalse( skipper.skipResolution( aNode, new ArrayList<>() ) ); - skipper.cache( aNode, new ArrayList<>() ); - assertFalse( skipper.skipResolution( bNode, mutableList( aNode ) ) ); - skipper.cache( bNode, mutableList( aNode ) ); - assertFalse( skipper.skipResolution( cNode, mutableList( aNode ) ) ); - skipper.cache( cNode, mutableList( aNode ) ); - assertFalse( skipper.skipResolution( dNode, mutableList( aNode ) ) ); - skipper.cache( dNode, mutableList( aNode ) ); - - assertTrue( skipper.skipResolution( b1Node, mutableList( aNode, cNode ) ) ); - skipper.cache( b1Node, mutableList( aNode, cNode ) ); - - assertTrue( skipper.skipResolution( c1Node, mutableList( aNode, dNode ) ) ); - skipper.cache( c1Node, mutableList( aNode, dNode ) ); + DependencyNode aNode = makeDependencyNode("some-group", "A", "1.0"); + DependencyNode bNode = makeDependencyNode("some-group", "B", "1.0"); + DependencyNode cNode = makeDependencyNode("some-group", "C", "1.0"); + DependencyNode dNode = makeDependencyNode("some-group", "D", "1.0"); + DependencyNode b1Node = new DefaultDependencyNode(bNode); + DependencyNode c1Node = new DefaultDependencyNode(cNode); + + aNode.setChildren(mutableList(bNode, cNode, dNode)); + bNode.setChildren(new ArrayList<>()); + cNode.setChildren(mutableList(b1Node)); + dNode.setChildren(mutableList(c1Node)); + + // follow the BFS resolve sequence + DependencyResolutionSkipper.DefaultDependencyResolutionSkipper skipper = + DependencyResolutionSkipper.defaultSkipper(); + assertFalse(skipper.skipResolution(aNode, new ArrayList<>())); + skipper.cache(aNode, new ArrayList<>()); + assertFalse(skipper.skipResolution(bNode, mutableList(aNode))); + skipper.cache(bNode, mutableList(aNode)); + assertFalse(skipper.skipResolution(cNode, mutableList(aNode))); + skipper.cache(cNode, mutableList(aNode)); + assertFalse(skipper.skipResolution(dNode, mutableList(aNode))); + skipper.cache(dNode, mutableList(aNode)); + + assertTrue(skipper.skipResolution(b1Node, mutableList(aNode, cNode))); + skipper.cache(b1Node, mutableList(aNode, cNode)); + + assertTrue(skipper.skipResolution(c1Node, mutableList(aNode, dNode))); + skipper.cache(c1Node, mutableList(aNode, dNode)); Map results = skipper.getResults(); - assertEquals( results.size(), 6 ); + assertEquals(results.size(), 6); List skipped = results.values().stream() - .filter( dependencyResolutionResult -> dependencyResolutionResult.skippedAsDuplicate ) - .collect( Collectors.toList() ); - assertEquals( skipped.size(), 2 ); - assertTrue( skipped.get( 0 ).current == b1Node ); - assertTrue( skipped.get( 1 ).current == c1Node ); + .filter(dependencyResolutionResult -> dependencyResolutionResult.skippedAsDuplicate) + .collect(Collectors.toList()); + assertEquals(skipped.size(), 2); + assertTrue(skipped.get(0).current == b1Node); + assertTrue(skipped.get(1).current == c1Node); } - @Test - public void testForceResolution() - { + public void testForceResolution() { // A -> B -> C -> D => 3rd D here will be force-resolved // |--> C -> D => 2nd D will be force-resolved // |--> D => 1st D to resolve - DependencyNode aNode = makeDependencyNode( "some-group", "A", "1.0" ); - DependencyNode bNode = makeDependencyNode( "some-group", "B", "1.0" ); - DependencyNode cNode = makeDependencyNode( "some-group", "C", "1.0" ); - DependencyNode dNode = makeDependencyNode( "some-group", "D", "1.0" ); - DependencyNode c1Node = new DefaultDependencyNode( cNode ); - DependencyNode d1Node = new DefaultDependencyNode( dNode ); - DependencyNode d2Node = new DefaultDependencyNode( dNode ); - - aNode.setChildren( mutableList( bNode, cNode, dNode ) ); - bNode.setChildren( mutableList( c1Node ) ); - c1Node.setChildren( mutableList( d2Node ) ); - cNode.setChildren( mutableList( d1Node ) ); - dNode.setChildren( new ArrayList<>() ); - - //follow the BFS resolve sequence - DependencyResolutionSkipper.DefaultDependencyResolutionSkipper skipper = DependencyResolutionSkipper.defaultSkipper(); - assertFalse( skipper.skipResolution( aNode, new ArrayList<>() ) ); - skipper.cache( aNode, new ArrayList<>() ); - assertFalse( skipper.skipResolution( bNode, mutableList( aNode ) ) ); - skipper.cache( bNode, mutableList( aNode ) ); - assertFalse( skipper.skipResolution( cNode, mutableList( aNode ) ) ); - skipper.cache( cNode, mutableList( aNode ) ); - assertFalse( skipper.skipResolution( dNode, mutableList( aNode ) ) ); - skipper.cache( dNode, mutableList( aNode ) ); - - assertFalse( skipper.skipResolution( c1Node, mutableList( aNode, bNode ) ) ); - skipper.cache( c1Node, mutableList( aNode, bNode ) ); - - assertFalse( skipper.skipResolution( d1Node, mutableList( aNode, cNode ) ) ); - skipper.cache( d1Node, mutableList( aNode, cNode ) ); - - assertFalse( skipper.skipResolution( d2Node, mutableList( aNode, bNode, c1Node ) ) ); - skipper.cache( d2Node, mutableList( aNode, bNode, c1Node ) ); + DependencyNode aNode = makeDependencyNode("some-group", "A", "1.0"); + DependencyNode bNode = makeDependencyNode("some-group", "B", "1.0"); + DependencyNode cNode = makeDependencyNode("some-group", "C", "1.0"); + DependencyNode dNode = makeDependencyNode("some-group", "D", "1.0"); + DependencyNode c1Node = new DefaultDependencyNode(cNode); + DependencyNode d1Node = new DefaultDependencyNode(dNode); + DependencyNode d2Node = new DefaultDependencyNode(dNode); + + aNode.setChildren(mutableList(bNode, cNode, dNode)); + bNode.setChildren(mutableList(c1Node)); + c1Node.setChildren(mutableList(d2Node)); + cNode.setChildren(mutableList(d1Node)); + dNode.setChildren(new ArrayList<>()); + + // follow the BFS resolve sequence + DependencyResolutionSkipper.DefaultDependencyResolutionSkipper skipper = + DependencyResolutionSkipper.defaultSkipper(); + assertFalse(skipper.skipResolution(aNode, new ArrayList<>())); + skipper.cache(aNode, new ArrayList<>()); + assertFalse(skipper.skipResolution(bNode, mutableList(aNode))); + skipper.cache(bNode, mutableList(aNode)); + assertFalse(skipper.skipResolution(cNode, mutableList(aNode))); + skipper.cache(cNode, mutableList(aNode)); + assertFalse(skipper.skipResolution(dNode, mutableList(aNode))); + skipper.cache(dNode, mutableList(aNode)); + + assertFalse(skipper.skipResolution(c1Node, mutableList(aNode, bNode))); + skipper.cache(c1Node, mutableList(aNode, bNode)); + + assertFalse(skipper.skipResolution(d1Node, mutableList(aNode, cNode))); + skipper.cache(d1Node, mutableList(aNode, cNode)); + + assertFalse(skipper.skipResolution(d2Node, mutableList(aNode, bNode, c1Node))); + skipper.cache(d2Node, mutableList(aNode, bNode, c1Node)); Map results = skipper.getResults(); - assertEquals( results.size(), 7 ); + assertEquals(results.size(), 7); List forceResolved = results.values().stream() - .filter( dependencyResolutionResult -> dependencyResolutionResult.forceResolution ) - .collect( Collectors.toList() ); - assertEquals( forceResolved.size(), 3 ); - assertTrue( forceResolved.get( 0 ).current == c1Node ); - assertTrue( forceResolved.get( 1 ).current == d1Node ); - assertTrue( forceResolved.get( 2 ).current == d2Node ); + .filter(dependencyResolutionResult -> dependencyResolutionResult.forceResolution) + .collect(Collectors.toList()); + assertEquals(forceResolved.size(), 3); + assertTrue(forceResolved.get(0).current == c1Node); + assertTrue(forceResolved.get(1).current == d1Node); + assertTrue(forceResolved.get(2).current == d2Node); } - -} \ No newline at end of file +} diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/df/DfDependencyCollectorTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/df/DfDependencyCollectorTest.java index 131e24c41..f5e808b66 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/df/DfDependencyCollectorTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/collect/df/DfDependencyCollectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.collect.df; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.collect.df; import org.eclipse.aether.internal.impl.StubRemoteRepositoryManager; import org.eclipse.aether.internal.impl.StubVersionRangeResolver; @@ -26,14 +25,12 @@ /** * UT for {@link DfDependencyCollector}. */ -public class DfDependencyCollectorTest extends DependencyCollectorDelegateTestSupport -{ +public class DfDependencyCollectorTest extends DependencyCollectorDelegateTestSupport { @Override - protected void setupCollector() - { + protected void setupCollector() { collector = new DfDependencyCollector(); - collector.setArtifactDescriptorReader( newReader( "" ) ); - collector.setVersionRangeResolver( new StubVersionRangeResolver() ); - collector.setRemoteRepositoryManager( new StubRemoteRepositoryManager() ); + collector.setArtifactDescriptorReader(newReader("")); + collector.setVersionRangeResolver(new StubVersionRangeResolver()); + collector.setRemoteRepositoryManager(new StubRemoteRepositoryManager()); } -} \ No newline at end of file +} diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/Filters.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/Filters.java index d6a1a818d..d9de53608 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/Filters.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/Filters.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.filter; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -29,37 +28,29 @@ /** * Some filters used in UTs. */ -public final class Filters -{ +public final class Filters { /** * Returns a filter that always accepts. */ - public static RemoteRepositoryFilterSource alwaysAccept() - { - return new RemoteRepositoryFilterSource() - { - public String getName() - { + public static RemoteRepositoryFilterSource alwaysAccept() { + return new RemoteRepositoryFilterSource() { + public String getName() { return "always-accept"; } private final RemoteRepositoryFilter.Result RESULT = - new RemoteRepositoryFilterSourceSupport.SimpleResult( true, getName() ); + new RemoteRepositoryFilterSourceSupport.SimpleResult(true, getName()); @Override - public RemoteRepositoryFilter getRemoteRepositoryFilter( RepositorySystemSession session ) - { - return new RemoteRepositoryFilter() - { + public RemoteRepositoryFilter getRemoteRepositoryFilter(RepositorySystemSession session) { + return new RemoteRepositoryFilter() { @Override - public Result acceptArtifact( RemoteRepository remoteRepository, Artifact artifact ) - { + public Result acceptArtifact(RemoteRepository remoteRepository, Artifact artifact) { return RESULT; } @Override - public Result acceptMetadata( RemoteRepository remoteRepository, Metadata metadata ) - { + public Result acceptMetadata(RemoteRepository remoteRepository, Metadata metadata) { return RESULT; } }; @@ -70,36 +61,29 @@ public Result acceptMetadata( RemoteRepository remoteRepository, Metadata metada /** * Returns a filter that always accepts from given repo. */ - public static RemoteRepositoryFilterSource alwaysAcceptFrom( String repoId ) - { - return new RemoteRepositoryFilterSource() - { - public String getName() - { + public static RemoteRepositoryFilterSource alwaysAcceptFrom(String repoId) { + return new RemoteRepositoryFilterSource() { + public String getName() { return "always-accept-" + repoId; } private final RemoteRepositoryFilter.Result MATCHED = - new RemoteRepositoryFilterSourceSupport.SimpleResult( true, getName() ); + new RemoteRepositoryFilterSourceSupport.SimpleResult(true, getName()); private final RemoteRepositoryFilter.Result UNMATCHED = - new RemoteRepositoryFilterSourceSupport.SimpleResult( false, getName() ); + new RemoteRepositoryFilterSourceSupport.SimpleResult(false, getName()); @Override - public RemoteRepositoryFilter getRemoteRepositoryFilter( RepositorySystemSession session ) - { - return new RemoteRepositoryFilter() - { + public RemoteRepositoryFilter getRemoteRepositoryFilter(RepositorySystemSession session) { + return new RemoteRepositoryFilter() { @Override - public Result acceptArtifact( RemoteRepository remoteRepository, Artifact artifact ) - { - return repoId.equals( remoteRepository.getId() ) ? MATCHED : UNMATCHED; + public Result acceptArtifact(RemoteRepository remoteRepository, Artifact artifact) { + return repoId.equals(remoteRepository.getId()) ? MATCHED : UNMATCHED; } @Override - public Result acceptMetadata( RemoteRepository remoteRepository, Metadata metadata ) - { - return repoId.equals( remoteRepository.getId() ) ? MATCHED : UNMATCHED; + public Result acceptMetadata(RemoteRepository remoteRepository, Metadata metadata) { + return repoId.equals(remoteRepository.getId()) ? MATCHED : UNMATCHED; } }; } @@ -109,32 +93,25 @@ public Result acceptMetadata( RemoteRepository remoteRepository, Metadata metada /** * Returns a filter that never accepts. */ - public static RemoteRepositoryFilterSource neverAccept() - { - return new RemoteRepositoryFilterSource() - { - public String getName() - { + public static RemoteRepositoryFilterSource neverAccept() { + return new RemoteRepositoryFilterSource() { + public String getName() { return "never-accept"; } private final RemoteRepositoryFilter.Result RESULT = - new RemoteRepositoryFilterSourceSupport.SimpleResult( false, getName() ); + new RemoteRepositoryFilterSourceSupport.SimpleResult(false, getName()); @Override - public RemoteRepositoryFilter getRemoteRepositoryFilter( RepositorySystemSession session ) - { - return new RemoteRepositoryFilter() - { + public RemoteRepositoryFilter getRemoteRepositoryFilter(RepositorySystemSession session) { + return new RemoteRepositoryFilter() { @Override - public Result acceptArtifact( RemoteRepository remoteRepository, Artifact artifact ) - { + public Result acceptArtifact(RemoteRepository remoteRepository, Artifact artifact) { return RESULT; } @Override - public Result acceptMetadata( RemoteRepository remoteRepository, Metadata metadata ) - { + public Result acceptMetadata(RemoteRepository remoteRepository, Metadata metadata) { return RESULT; } }; @@ -145,36 +122,29 @@ public Result acceptMetadata( RemoteRepository remoteRepository, Metadata metada /** * Returns a filter that never accepts from given repo. */ - public static RemoteRepositoryFilterSource neverAcceptFrom( String repoId ) - { - return new RemoteRepositoryFilterSource() - { - public String getName() - { + public static RemoteRepositoryFilterSource neverAcceptFrom(String repoId) { + return new RemoteRepositoryFilterSource() { + public String getName() { return "never-accept-" + repoId; } private final RemoteRepositoryFilter.Result MATCHED = - new RemoteRepositoryFilterSourceSupport.SimpleResult( false, getName() ); + new RemoteRepositoryFilterSourceSupport.SimpleResult(false, getName()); private final RemoteRepositoryFilter.Result UNMATCHED = - new RemoteRepositoryFilterSourceSupport.SimpleResult( true, getName() ); + new RemoteRepositoryFilterSourceSupport.SimpleResult(true, getName()); @Override - public RemoteRepositoryFilter getRemoteRepositoryFilter( RepositorySystemSession session ) - { - return new RemoteRepositoryFilter() - { + public RemoteRepositoryFilter getRemoteRepositoryFilter(RepositorySystemSession session) { + return new RemoteRepositoryFilter() { @Override - public Result acceptArtifact( RemoteRepository remoteRepository, Artifact artifact ) - { - return repoId.equals( remoteRepository.getId() ) ? MATCHED : UNMATCHED; + public Result acceptArtifact(RemoteRepository remoteRepository, Artifact artifact) { + return repoId.equals(remoteRepository.getId()) ? MATCHED : UNMATCHED; } @Override - public Result acceptMetadata( RemoteRepository remoteRepository, Metadata metadata ) - { - return repoId.equals( remoteRepository.getId() ) ? MATCHED : UNMATCHED; + public Result acceptMetadata(RemoteRepository remoteRepository, Metadata metadata) { + return repoId.equals(remoteRepository.getId()) ? MATCHED : UNMATCHED; } }; } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/GroupIdRemoteRepositoryFilterSourceTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/GroupIdRemoteRepositoryFilterSourceTest.java index 236d5c880..6802f9362 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/GroupIdRemoteRepositoryFilterSourceTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/GroupIdRemoteRepositoryFilterSourceTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.filter; import java.io.IOException; import java.io.UncheckedIOException; @@ -35,46 +34,40 @@ /** * UT for {@link GroupIdRemoteRepositoryFilterSource}. */ -public class GroupIdRemoteRepositoryFilterSourceTest extends RemoteRepositoryFilterSourceTestSupport -{ +public class GroupIdRemoteRepositoryFilterSourceTest extends RemoteRepositoryFilterSourceTestSupport { private GroupIdRemoteRepositoryFilterSource groupIdRemoteRepositoryFilterSource; @Override protected GroupIdRemoteRepositoryFilterSource getRemoteRepositoryFilterSource( - DefaultRepositorySystemSession session, RemoteRepository remoteRepository ) - { + DefaultRepositorySystemSession session, RemoteRepository remoteRepository) { return groupIdRemoteRepositoryFilterSource = - new GroupIdRemoteRepositoryFilterSource( new DefaultRepositorySystemLifecycle() ); + new GroupIdRemoteRepositoryFilterSource(new DefaultRepositorySystemLifecycle()); } @Override - protected void enableSource( DefaultRepositorySystemSession session ) - { - session.setConfigProperty( "aether.remoteRepositoryFilter." + GroupIdRemoteRepositoryFilterSource.NAME, - Boolean.TRUE.toString() ); + protected void enableSource(DefaultRepositorySystemSession session) { + session.setConfigProperty( + "aether.remoteRepositoryFilter." + GroupIdRemoteRepositoryFilterSource.NAME, Boolean.TRUE.toString()); } - protected void allowArtifact( DefaultRepositorySystemSession session, RemoteRepository remoteRepository, - Artifact artifact ) - { - DefaultRepositorySystemSession newSession = new DefaultRepositorySystemSession( session ); - try - { - Artifact resolvedArtifact = artifact.setFile( Files.createTempFile( "test", "tmp" ).toFile() ); - ArtifactResult artifactResult = new ArtifactResult( new ArtifactRequest( resolvedArtifact, - Collections.singletonList( remoteRepository ), "context" ) ); - artifactResult.setArtifact( resolvedArtifact ); - artifactResult.setRepository( remoteRepository ); - List artifactResults = Collections.singletonList( artifactResult ); - enableSource( newSession ); - newSession.setConfigProperty( "aether.remoteRepositoryFilter." + GroupIdRemoteRepositoryFilterSource.NAME - + ".record", Boolean.TRUE.toString() ); - groupIdRemoteRepositoryFilterSource.postProcess( newSession, artifactResults ); + protected void allowArtifact( + DefaultRepositorySystemSession session, RemoteRepository remoteRepository, Artifact artifact) { + DefaultRepositorySystemSession newSession = new DefaultRepositorySystemSession(session); + try { + Artifact resolvedArtifact = + artifact.setFile(Files.createTempFile("test", "tmp").toFile()); + ArtifactResult artifactResult = new ArtifactResult( + new ArtifactRequest(resolvedArtifact, Collections.singletonList(remoteRepository), "context")); + artifactResult.setArtifact(resolvedArtifact); + artifactResult.setRepository(remoteRepository); + List artifactResults = Collections.singletonList(artifactResult); + enableSource(newSession); + newSession.setConfigProperty( + "aether.remoteRepositoryFilter." + GroupIdRemoteRepositoryFilterSource.NAME + ".record", + Boolean.TRUE.toString()); + groupIdRemoteRepositoryFilterSource.postProcess(newSession, artifactResults); + } catch (IOException e) { + throw new UncheckedIOException(e); } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); - } - } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/PrefixesRemoteRepositoryFilterSourceTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/PrefixesRemoteRepositoryFilterSourceTest.java index 305face26..1a9d14b12 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/PrefixesRemoteRepositoryFilterSourceTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/PrefixesRemoteRepositoryFilterSourceTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.filter; import java.io.IOException; import java.io.UncheckedIOException; @@ -35,41 +34,36 @@ /** * UT for {@link PrefixesRemoteRepositoryFilterSource}. */ -public class PrefixesRemoteRepositoryFilterSourceTest extends RemoteRepositoryFilterSourceTestSupport -{ +public class PrefixesRemoteRepositoryFilterSourceTest extends RemoteRepositoryFilterSourceTestSupport { @Override protected RemoteRepositoryFilterSource getRemoteRepositoryFilterSource( - DefaultRepositorySystemSession session, RemoteRepository remoteRepository ) - { + DefaultRepositorySystemSession session, RemoteRepository remoteRepository) { DefaultRepositoryLayoutProvider layoutProvider = new DefaultRepositoryLayoutProvider(); - layoutProvider.addRepositoryLayoutFactory( new Maven2RepositoryLayoutFactory() ); - return new PrefixesRemoteRepositoryFilterSource( layoutProvider ); + layoutProvider.addRepositoryLayoutFactory(new Maven2RepositoryLayoutFactory()); + return new PrefixesRemoteRepositoryFilterSource(layoutProvider); } @Override - protected void enableSource( DefaultRepositorySystemSession session ) - { - session.setConfigProperty( "aether.remoteRepositoryFilter." + PrefixesRemoteRepositoryFilterSource.NAME, - Boolean.TRUE.toString() ); + protected void enableSource(DefaultRepositorySystemSession session) { + session.setConfigProperty( + "aether.remoteRepositoryFilter." + PrefixesRemoteRepositoryFilterSource.NAME, Boolean.TRUE.toString()); } @Override - protected void allowArtifact( DefaultRepositorySystemSession session, RemoteRepository remoteRepository, - Artifact artifact ) - { - try - { - Path baseDir = session.getLocalRepository().getBasedir().toPath() - .resolve( PrefixesRemoteRepositoryFilterSource.LOCAL_REPO_PREFIX_DIR ); - Path groupId = baseDir - .resolve( PrefixesRemoteRepositoryFilterSource.PREFIXES_FILE_PREFIX + remoteRepository.getId() - + PrefixesRemoteRepositoryFilterSource.PREFIXES_FILE_SUFFIX ); - Files.createDirectories( groupId.getParent() ); - Files.write( groupId, artifact.getGroupId().replaceAll( "\\.", "/" ).getBytes( StandardCharsets.UTF_8 ) ); - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + protected void allowArtifact( + DefaultRepositorySystemSession session, RemoteRepository remoteRepository, Artifact artifact) { + try { + Path baseDir = session.getLocalRepository() + .getBasedir() + .toPath() + .resolve(PrefixesRemoteRepositoryFilterSource.LOCAL_REPO_PREFIX_DIR); + Path groupId = baseDir.resolve(PrefixesRemoteRepositoryFilterSource.PREFIXES_FILE_PREFIX + + remoteRepository.getId() + + PrefixesRemoteRepositoryFilterSource.PREFIXES_FILE_SUFFIX); + Files.createDirectories(groupId.getParent()); + Files.write(groupId, artifact.getGroupId().replaceAll("\\.", "/").getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new UncheckedIOException(e); } } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/RemoteRepositoryFilterSourceTestSupport.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/RemoteRepositoryFilterSourceTestSupport.java index c13b6b14b..d78ee9f31 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/RemoteRepositoryFilterSourceTestSupport.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/filter/RemoteRepositoryFilterSourceTestSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.filter; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -38,11 +37,10 @@ /** * UT helper for {@link RemoteRepositoryFilterSource} UTs. */ -public abstract class RemoteRepositoryFilterSourceTestSupport -{ - private final Artifact acceptedArtifact = new DefaultArtifact( "org.one:aid:1.0" ); +public abstract class RemoteRepositoryFilterSourceTestSupport { + private final Artifact acceptedArtifact = new DefaultArtifact("org.one:aid:1.0"); - private final Artifact notAcceptedArtifact = new DefaultArtifact( "org.two:aid:1.0" ); + private final Artifact notAcceptedArtifact = new DefaultArtifact("org.two:aid:1.0"); private DefaultRepositorySystemSession session; @@ -51,55 +49,51 @@ public abstract class RemoteRepositoryFilterSourceTestSupport private RemoteRepositoryFilterSource subject; @Before - public void setup() - { - remoteRepository = new RemoteRepository.Builder( "test", "default", "https://irrelevant.com" ).build(); + public void setup() { + remoteRepository = new RemoteRepository.Builder("test", "default", "https://irrelevant.com").build(); session = TestUtils.newSession(); - subject = getRemoteRepositoryFilterSource( session, remoteRepository ); + subject = getRemoteRepositoryFilterSource(session, remoteRepository); } protected abstract RemoteRepositoryFilterSource getRemoteRepositoryFilterSource( - DefaultRepositorySystemSession session, RemoteRepository remoteRepository ); + DefaultRepositorySystemSession session, RemoteRepository remoteRepository); - protected abstract void enableSource( DefaultRepositorySystemSession session ); + protected abstract void enableSource(DefaultRepositorySystemSession session); protected abstract void allowArtifact( - DefaultRepositorySystemSession session, RemoteRepository remoteRepository, Artifact artifact ); + DefaultRepositorySystemSession session, RemoteRepository remoteRepository, Artifact artifact); @Test - public void notEnabled() - { - RemoteRepositoryFilter filter = subject.getRemoteRepositoryFilter( session ); - assertThat( filter, nullValue() ); + public void notEnabled() { + RemoteRepositoryFilter filter = subject.getRemoteRepositoryFilter(session); + assertThat(filter, nullValue()); } @Test - public void acceptedArtifact() - { - allowArtifact( session, remoteRepository, acceptedArtifact ); - enableSource( session ); + public void acceptedArtifact() { + allowArtifact(session, remoteRepository, acceptedArtifact); + enableSource(session); - RemoteRepositoryFilter filter = subject.getRemoteRepositoryFilter( session ); - assertThat( filter, notNullValue() ); + RemoteRepositoryFilter filter = subject.getRemoteRepositoryFilter(session); + assertThat(filter, notNullValue()); - RemoteRepositoryFilter.Result result = filter.acceptArtifact( remoteRepository, acceptedArtifact ); + RemoteRepositoryFilter.Result result = filter.acceptArtifact(remoteRepository, acceptedArtifact); - assertThat( result.isAccepted(), equalTo( true ) ); - assertThat( result.reasoning(), containsString( "allowed from test" ) ); + assertThat(result.isAccepted(), equalTo(true)); + assertThat(result.reasoning(), containsString("allowed from test")); } @Test - public void notAcceptedArtifact() - { - allowArtifact( session, remoteRepository, acceptedArtifact ); - enableSource( session ); + public void notAcceptedArtifact() { + allowArtifact(session, remoteRepository, acceptedArtifact); + enableSource(session); - RemoteRepositoryFilter filter = subject.getRemoteRepositoryFilter( session ); - assertThat( filter, notNullValue() ); + RemoteRepositoryFilter filter = subject.getRemoteRepositoryFilter(session); + assertThat(filter, notNullValue()); - RemoteRepositoryFilter.Result result = filter.acceptArtifact( remoteRepository, notAcceptedArtifact ); + RemoteRepositoryFilter.Result result = filter.acceptArtifact(remoteRepository, notAcceptedArtifact); - assertThat( result.isAccepted(), equalTo( false ) ); - assertThat( result.reasoning(), containsString( "NOT allowed from test" ) ); + assertThat(result.isAccepted(), equalTo(false)); + assertThat(result.reasoning(), containsString("NOT allowed from test")); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/resolution/TrustedChecksumsArtifactResolverPostProcessorTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/resolution/TrustedChecksumsArtifactResolverPostProcessorTest.java index 393cc4bc3..64db73f55 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/resolution/TrustedChecksumsArtifactResolverPostProcessorTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/resolution/TrustedChecksumsArtifactResolverPostProcessorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.resolution; import java.io.File; import java.io.IOException; @@ -55,8 +54,7 @@ /** * UT for {@link TrustedChecksumsArtifactResolverPostProcessor}. */ -public class TrustedChecksumsArtifactResolverPostProcessorTest implements TrustedChecksumsSource -{ +public class TrustedChecksumsArtifactResolverPostProcessorTest implements TrustedChecksumsSource { private static final String TRUSTED_SOURCE_NAME = "test"; private Artifact artifactWithoutTrustedChecksum; @@ -74,162 +72,145 @@ public class TrustedChecksumsArtifactResolverPostProcessorTest implements Truste private TrustedChecksumsSource.Writer trustedChecksumsWriter; @Before - public void prepareSubject() throws IOException - { + public void prepareSubject() throws IOException { // make the two artifacts, BOTH as resolved - File tmp = Files.createTempFile( "artifact", "tmp" ).toFile(); - artifactWithoutTrustedChecksum = new DefaultArtifact( "test:test:1.0" ).setFile( tmp ); - artifactWithTrustedChecksum = new DefaultArtifact( "test:test:2.0" ).setFile( tmp ); + File tmp = Files.createTempFile("artifact", "tmp").toFile(); + artifactWithoutTrustedChecksum = new DefaultArtifact("test:test:1.0").setFile(tmp); + artifactWithTrustedChecksum = new DefaultArtifact("test:test:2.0").setFile(tmp); artifactTrustedChecksum = "da39a3ee5e6b4b0d3255bfef95601890afd80709"; // empty file session = TestUtils.newSession(); - ChecksumAlgorithmFactorySelector selector = new ChecksumAlgorithmFactorySelector() - { + ChecksumAlgorithmFactorySelector selector = new ChecksumAlgorithmFactorySelector() { @Override - public ChecksumAlgorithmFactory select( String algorithmName ) - { - if ( checksumAlgorithmFactory.getName().equals( algorithmName ) ) - { + public ChecksumAlgorithmFactory select(String algorithmName) { + if (checksumAlgorithmFactory.getName().equals(algorithmName)) { return checksumAlgorithmFactory; } throw new IllegalArgumentException("no alg factory for " + algorithmName); } @Override - public List selectList( Collection algorithmNames ) - { - return algorithmNames.stream() - .map( this::select ) - .collect( toList() ); + public List selectList(Collection algorithmNames) { + return algorithmNames.stream().map(this::select).collect(toList()); } @Override - public Collection getChecksumAlgorithmFactories() - { - return Collections.singletonList( checksumAlgorithmFactory ); + public Collection getChecksumAlgorithmFactories() { + return Collections.singletonList(checksumAlgorithmFactory); } @Override - public boolean isChecksumExtension( String extension ) - { - throw new RuntimeException( "not implemented" ); + public boolean isChecksumExtension(String extension) { + throw new RuntimeException("not implemented"); } }; - subject = new TrustedChecksumsArtifactResolverPostProcessor( selector, - Collections.singletonMap( TRUSTED_SOURCE_NAME, this ) ); + subject = new TrustedChecksumsArtifactResolverPostProcessor( + selector, Collections.singletonMap(TRUSTED_SOURCE_NAME, this)); trustedChecksumsWriter = null; - session.setConfigProperty( "aether.artifactResolver.postProcessor.trustedChecksums", Boolean.TRUE.toString() ); + session.setConfigProperty("aether.artifactResolver.postProcessor.trustedChecksums", Boolean.TRUE.toString()); } // -- TrustedChecksumsSource interface BEGIN @Override - public Map getTrustedArtifactChecksums( RepositorySystemSession session, Artifact artifact, - ArtifactRepository artifactRepository, - List checksumAlgorithmFactories ) - { - if ( ArtifactIdUtils.toId( artifactWithTrustedChecksum ).equals( ArtifactIdUtils.toId( artifact ) ) ) - { - return Collections.singletonMap( checksumAlgorithmFactory.getName(), artifactTrustedChecksum ); - } - else - { + public Map getTrustedArtifactChecksums( + RepositorySystemSession session, + Artifact artifact, + ArtifactRepository artifactRepository, + List checksumAlgorithmFactories) { + if (ArtifactIdUtils.toId(artifactWithTrustedChecksum).equals(ArtifactIdUtils.toId(artifact))) { + return Collections.singletonMap(checksumAlgorithmFactory.getName(), artifactTrustedChecksum); + } else { return Collections.emptyMap(); } } @Override - public Writer getTrustedArtifactChecksumsWriter( RepositorySystemSession session ) - { + public Writer getTrustedArtifactChecksumsWriter(RepositorySystemSession session) { return trustedChecksumsWriter; } // -- TrustedChecksumsSource interface END - private ArtifactResult createArtifactResult( Artifact artifact ) - { - ArtifactResult artifactResult = new ArtifactResult( new ArtifactRequest().setArtifact( artifact ) ); - artifactResult.setArtifact( artifact ); + private ArtifactResult createArtifactResult(Artifact artifact) { + ArtifactResult artifactResult = new ArtifactResult(new ArtifactRequest().setArtifact(artifact)); + artifactResult.setArtifact(artifact); return artifactResult; } // UTs below @Test - public void haveMatchingChecksumPass() - { - ArtifactResult artifactResult = createArtifactResult( artifactWithTrustedChecksum ); - assertThat( artifactResult.isResolved(), equalTo( true ) ); + public void haveMatchingChecksumPass() { + ArtifactResult artifactResult = createArtifactResult(artifactWithTrustedChecksum); + assertThat(artifactResult.isResolved(), equalTo(true)); - subject.postProcess( session, Collections.singletonList( artifactResult ) ); - assertThat( artifactResult.isResolved(), equalTo( true ) ); + subject.postProcess(session, Collections.singletonList(artifactResult)); + assertThat(artifactResult.isResolved(), equalTo(true)); } @Test - public void haveNoChecksumPass() - { - ArtifactResult artifactResult = createArtifactResult( artifactWithoutTrustedChecksum ); - assertThat( artifactResult.isResolved(), equalTo( true ) ); + public void haveNoChecksumPass() { + ArtifactResult artifactResult = createArtifactResult(artifactWithoutTrustedChecksum); + assertThat(artifactResult.isResolved(), equalTo(true)); - subject.postProcess( session, Collections.singletonList( artifactResult ) ); - assertThat( artifactResult.isResolved(), equalTo( true ) ); + subject.postProcess(session, Collections.singletonList(artifactResult)); + assertThat(artifactResult.isResolved(), equalTo(true)); } @Test - public void haveNoChecksumFailIfMissingEnabledFail() - { - session.setConfigProperty( "aether.artifactResolver.postProcessor.trustedChecksums.failIfMissing", - Boolean.TRUE.toString() ); - ArtifactResult artifactResult = createArtifactResult( artifactWithoutTrustedChecksum ); - assertThat( artifactResult.isResolved(), equalTo( true ) ); - - subject.postProcess( session, Collections.singletonList( artifactResult ) ); - assertThat( artifactResult.isResolved(), equalTo( false ) ); - assertThat( artifactResult.getExceptions(), not( empty() ) ); - assertThat( artifactResult.getExceptions().get( 0 ).getMessage(), - containsString( "Missing from " + TRUSTED_SOURCE_NAME + " trusted" ) ); + public void haveNoChecksumFailIfMissingEnabledFail() { + session.setConfigProperty( + "aether.artifactResolver.postProcessor.trustedChecksums.failIfMissing", Boolean.TRUE.toString()); + ArtifactResult artifactResult = createArtifactResult(artifactWithoutTrustedChecksum); + assertThat(artifactResult.isResolved(), equalTo(true)); + + subject.postProcess(session, Collections.singletonList(artifactResult)); + assertThat(artifactResult.isResolved(), equalTo(false)); + assertThat(artifactResult.getExceptions(), not(empty())); + assertThat( + artifactResult.getExceptions().get(0).getMessage(), + containsString("Missing from " + TRUSTED_SOURCE_NAME + " trusted")); } @Test - public void haveMismatchingChecksumFail() - { + public void haveMismatchingChecksumFail() { artifactTrustedChecksum = "foobar"; - ArtifactResult artifactResult = createArtifactResult( artifactWithTrustedChecksum ); - assertThat( artifactResult.isResolved(), equalTo( true ) ); - - subject.postProcess( session, Collections.singletonList( artifactResult ) ); - assertThat( artifactResult.isResolved(), equalTo( false ) ); - assertThat( artifactResult.getExceptions(), not( empty() ) ); - assertThat( artifactResult.getExceptions().get( 0 ).getMessage(), - containsString( "trusted checksum mismatch" ) ); - assertThat( artifactResult.getExceptions().get( 0 ).getMessage(), - containsString( TRUSTED_SOURCE_NAME + "=" + artifactTrustedChecksum ) ); + ArtifactResult artifactResult = createArtifactResult(artifactWithTrustedChecksum); + assertThat(artifactResult.isResolved(), equalTo(true)); + + subject.postProcess(session, Collections.singletonList(artifactResult)); + assertThat(artifactResult.isResolved(), equalTo(false)); + assertThat(artifactResult.getExceptions(), not(empty())); + assertThat(artifactResult.getExceptions().get(0).getMessage(), containsString("trusted checksum mismatch")); + assertThat( + artifactResult.getExceptions().get(0).getMessage(), + containsString(TRUSTED_SOURCE_NAME + "=" + artifactTrustedChecksum)); } @Test - public void recordCalculatedChecksum() - { + public void recordCalculatedChecksum() { AtomicReference recordedChecksum = new AtomicReference<>(null); - this.trustedChecksumsWriter = new Writer() - { + this.trustedChecksumsWriter = new Writer() { @Override - public void addTrustedArtifactChecksums( Artifact artifact, ArtifactRepository artifactRepository, - List checksumAlgorithmFactories, - Map trustedArtifactChecksums ) - { - recordedChecksum.set( trustedArtifactChecksums.get( checksumAlgorithmFactory.getName() ) ); + public void addTrustedArtifactChecksums( + Artifact artifact, + ArtifactRepository artifactRepository, + List checksumAlgorithmFactories, + Map trustedArtifactChecksums) { + recordedChecksum.set(trustedArtifactChecksums.get(checksumAlgorithmFactory.getName())); } }; - session.setConfigProperty( "aether.artifactResolver.postProcessor.trustedChecksums.record", - Boolean.TRUE.toString() ); - ArtifactResult artifactResult = createArtifactResult( artifactWithTrustedChecksum ); - assertThat( artifactResult.isResolved(), equalTo( true ) ); + session.setConfigProperty( + "aether.artifactResolver.postProcessor.trustedChecksums.record", Boolean.TRUE.toString()); + ArtifactResult artifactResult = createArtifactResult(artifactWithTrustedChecksum); + assertThat(artifactResult.isResolved(), equalTo(true)); - subject.postProcess( session, Collections.singletonList( artifactResult ) ); - assertThat( artifactResult.isResolved(), equalTo( true ) ); + subject.postProcess(session, Collections.singletonList(artifactResult)); + assertThat(artifactResult.isResolved(), equalTo(true)); String checksum = recordedChecksum.get(); - assertThat( checksum, notNullValue() ); - assertThat( checksum, equalTo( artifactTrustedChecksum ) ); + assertThat(checksum, notNullValue()); + assertThat(checksum, equalTo(artifactTrustedChecksum)); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/FileLockAdapterTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/FileLockAdapterTest.java index 218af4c1b..a199b83c8 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/FileLockAdapterTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/FileLockAdapterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext; import org.eclipse.aether.internal.impl.synccontext.named.BasedirNameMapper; import org.eclipse.aether.internal.impl.synccontext.named.GAVNameMapper; import org.eclipse.aether.named.providers.FileLockNamedLockFactory; import org.junit.BeforeClass; -public class FileLockAdapterTest - extends NamedLockFactoryAdapterTestSupport -{ +public class FileLockAdapterTest extends NamedLockFactoryAdapterTestSupport { @BeforeClass - public static void createNamedLockFactory() - { - nameMapper = new BasedirNameMapper( GAVNameMapper.fileGav() ); + public static void createNamedLockFactory() { + nameMapper = new BasedirNameMapper(GAVNameMapper.fileGav()); namedLockFactory = new FileLockNamedLockFactory(); createAdapter(); } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/LocalReadWriteLockAdapterTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/LocalReadWriteLockAdapterTest.java index 82a2f019e..cce345ff6 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/LocalReadWriteLockAdapterTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/LocalReadWriteLockAdapterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext; import org.eclipse.aether.named.providers.LocalReadWriteLockNamedLockFactory; import org.junit.BeforeClass; -public class LocalReadWriteLockAdapterTest - extends NamedLockFactoryAdapterTestSupport -{ +public class LocalReadWriteLockAdapterTest extends NamedLockFactoryAdapterTestSupport { @BeforeClass public static void createNamedLockFactory() { namedLockFactory = new LocalReadWriteLockNamedLockFactory(); diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/LocalSemaphoreAdapterTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/LocalSemaphoreAdapterTest.java index adf88fbbb..c2a001891 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/LocalSemaphoreAdapterTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/LocalSemaphoreAdapterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext; import org.eclipse.aether.named.providers.LocalSemaphoreNamedLockFactory; import org.junit.BeforeClass; -public class LocalSemaphoreAdapterTest - extends NamedLockFactoryAdapterTestSupport -{ +public class LocalSemaphoreAdapterTest extends NamedLockFactoryAdapterTestSupport { @BeforeClass public static void createNamedLockFactory() { namedLockFactory = new LocalSemaphoreNamedLockFactory(); diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/NamedLockFactoryAdapterTestSupport.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/NamedLockFactoryAdapterTestSupport.java index 9b87e2cc0..7487d9bab 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/NamedLockFactoryAdapterTestSupport.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/NamedLockFactoryAdapterTestSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Objects; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.SyncContext; @@ -31,15 +39,6 @@ import org.junit.Before; import org.junit.Test; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Objects; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.mockito.Mockito.mock; @@ -48,8 +47,7 @@ /** * UT support for {@link SyncContextFactory}. */ -public abstract class NamedLockFactoryAdapterTestSupport -{ +public abstract class NamedLockFactoryAdapterTestSupport { private static final long ADAPTER_TIME = 1000L; private static final TimeUnit ADAPTER_TIME_UNIT = TimeUnit.MILLISECONDS; @@ -57,7 +55,7 @@ public abstract class NamedLockFactoryAdapterTestSupport /** * Subclass MAY populate this field but subclass must take care of proper cleanup as well, if needed! */ - protected static NameMapper nameMapper = new DiscriminatingNameMapper( GAVNameMapper.gav() ); + protected static NameMapper nameMapper = new DiscriminatingNameMapper(GAVNameMapper.gav()); /** * Subclass MUST populate this field but subclass must take care of proper cleanup as well, if needed! Once set, @@ -84,7 +82,8 @@ public static void cleanupAdapter() { @Before public void before() throws IOException { Files.createDirectories(Paths.get(System.getProperty("java.io.tmpdir"))); // hack for Surefire - LocalRepository localRepository = new LocalRepository(Files.createTempDirectory("test").toFile()); + LocalRepository localRepository = + new LocalRepository(Files.createTempDirectory("test").toFile()); session = mock(RepositorySystemSession.class); when(session.getLocalRepository()).thenReturn(localRepository); HashMap config = new HashMap<>(); @@ -102,9 +101,10 @@ public void justCreateAndClose() { public void justAcquire() { try (SyncContext syncContext = adapter.newInstance(session, false)) { syncContext.acquire( - Arrays.asList(new DefaultArtifact("groupId:artifactId:1.0"), new DefaultArtifact("groupId:artifactId:1.1")), - null - ); + Arrays.asList( + new DefaultArtifact("groupId:artifactId:1.0"), + new DefaultArtifact("groupId:artifactId:1.1")), + null); } } @@ -154,11 +154,8 @@ public void mixedAccess() throws InterruptedException { public void nestedSharedShared() throws InterruptedException { CountDownLatch winners = new CountDownLatch(2); // we expect 2 winners CountDownLatch losers = new CountDownLatch(0); // we expect 0 losers - Thread t1 = new Thread( - new Access(true, winners, losers, adapter, session, - new Access(true, winners, losers, adapter, session, null) - ) - ); + Thread t1 = new Thread(new Access( + true, winners, losers, adapter, session, new Access(true, winners, losers, adapter, session, null))); t1.start(); t1.join(); winners.await(); @@ -169,11 +166,8 @@ public void nestedSharedShared() throws InterruptedException { public void nestedExclusiveShared() throws InterruptedException { CountDownLatch winners = new CountDownLatch(2); // we expect 2 winners CountDownLatch losers = new CountDownLatch(0); // we expect 0 losers - Thread t1 = new Thread( - new Access(false, winners, losers, adapter, session, - new Access(true, winners, losers, adapter, session, null) - ) - ); + Thread t1 = new Thread(new Access( + false, winners, losers, adapter, session, new Access(true, winners, losers, adapter, session, null))); t1.start(); t1.join(); winners.await(); @@ -184,11 +178,8 @@ public void nestedExclusiveShared() throws InterruptedException { public void nestedExclusiveExclusive() throws InterruptedException { CountDownLatch winners = new CountDownLatch(2); // we expect 2 winners CountDownLatch losers = new CountDownLatch(0); // we expect 0 losers - Thread t1 = new Thread( - new Access(false, winners, losers, adapter, session, - new Access(false, winners, losers, adapter, session, null) - ) - ); + Thread t1 = new Thread(new Access( + false, winners, losers, adapter, session, new Access(false, winners, losers, adapter, session, null))); t1.start(); t1.join(); winners.await(); @@ -199,11 +190,8 @@ public void nestedExclusiveExclusive() throws InterruptedException { public void nestedSharedExclusive() throws InterruptedException { CountDownLatch winners = new CountDownLatch(1); // we expect 1 winner (outer) CountDownLatch losers = new CountDownLatch(1); // we expect 1 loser (inner) - Thread t1 = new Thread( - new Access(true, winners, losers, adapter, session, - new Access(false, winners, losers, adapter, session, null) - ) - ); + Thread t1 = new Thread(new Access( + true, winners, losers, adapter, session, new Access(false, winners, losers, adapter, session, null))); t1.start(); t1.join(); winners.await(); @@ -249,12 +237,13 @@ private static class Access implements Runnable { final RepositorySystemSession session; final Access chained; - public Access(boolean shared, - CountDownLatch winner, - CountDownLatch loser, - NamedLockFactoryAdapter adapter, - RepositorySystemSession session, - Access chained) { + public Access( + boolean shared, + CountDownLatch winner, + CountDownLatch loser, + NamedLockFactoryAdapter adapter, + RepositorySystemSession session, + Access chained) { this.shared = shared; this.winner = winner; this.loser = loser; @@ -268,9 +257,10 @@ public void run() { try { try (SyncContext syncContext = adapter.newInstance(session, shared)) { syncContext.acquire( - Arrays.asList(new DefaultArtifact("groupId:artifactId:1.0"), new DefaultArtifact("groupId:artifactId:1.1")), - null - ); + Arrays.asList( + new DefaultArtifact("groupId:artifactId:1.0"), + new DefaultArtifact("groupId:artifactId:1.1")), + null); winner.countDown(); if (chained != null) { chained.run(); diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/BasedirNameMapperTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/BasedirNameMapperTest.java index 3f8dfc5df..2123e258b 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/BasedirNameMapperTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/BasedirNameMapperTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; import java.io.File; import java.io.IOException; @@ -36,113 +35,112 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -public class BasedirNameMapperTest extends NameMapperTestSupport -{ +public class BasedirNameMapperTest extends NameMapperTestSupport { private final String PS = File.separator; - BasedirNameMapper mapper = new BasedirNameMapper( new HashingNameMapper( GAVNameMapper.gav() ) ); + BasedirNameMapper mapper = new BasedirNameMapper(new HashingNameMapper(GAVNameMapper.gav())); @Test - public void nullsAndEmptyInputs() - { + public void nullsAndEmptyInputs() { Collection names; - names = mapper.nameLocks( session, null, null ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, null, null); + assertThat(names, Matchers.empty()); - names = mapper.nameLocks( session, null, emptyList() ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, null, emptyList()); + assertThat(names, Matchers.empty()); - names = mapper.nameLocks( session, emptyList(), null ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, emptyList(), null); + assertThat(names, Matchers.empty()); - names = mapper.nameLocks( session, emptyList(), emptyList() ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, emptyList(), emptyList()); + assertThat(names, Matchers.empty()); } @Test - public void defaultLocksDir() - { - configProperties.put( "aether.syncContext.named.hashing.depth", "0" ); - configProperties.put( "aether.syncContext.named.basedir.locksDir", null ); - DefaultArtifact artifact = new DefaultArtifact( "group:artifact:1.0" ); - Collection names = mapper.nameLocks( session, singletonList( artifact ), null ); - assertThat( names, hasSize( 1 ) ); - assertThat( names.iterator().next(), - equalTo( basedir + PS + ".locks" + PS + "46e98183d232f1e16f863025080c7f2b9797fd10" ) ); + public void defaultLocksDir() { + configProperties.put("aether.syncContext.named.hashing.depth", "0"); + configProperties.put("aether.syncContext.named.basedir.locksDir", null); + DefaultArtifact artifact = new DefaultArtifact("group:artifact:1.0"); + Collection names = mapper.nameLocks(session, singletonList(artifact), null); + assertThat(names, hasSize(1)); + assertThat( + names.iterator().next(), + equalTo(basedir + PS + ".locks" + PS + "46e98183d232f1e16f863025080c7f2b9797fd10")); } @Test - public void relativeLocksDir() - { - configProperties.put( "aether.syncContext.named.hashing.depth", "0" ); - configProperties.put( "aether.syncContext.named.basedir.locksDir", "my/locks" ); - DefaultArtifact artifact = new DefaultArtifact( "group:artifact:1.0" ); - Collection names = mapper.nameLocks( session, singletonList( artifact ), null ); - assertThat( names, hasSize( 1 ) ); - assertThat( names.iterator().next(), - equalTo( basedir + PS + "my" + PS + "locks" + PS + "46e98183d232f1e16f863025080c7f2b9797fd10" ) ); + public void relativeLocksDir() { + configProperties.put("aether.syncContext.named.hashing.depth", "0"); + configProperties.put("aether.syncContext.named.basedir.locksDir", "my/locks"); + DefaultArtifact artifact = new DefaultArtifact("group:artifact:1.0"); + Collection names = mapper.nameLocks(session, singletonList(artifact), null); + assertThat(names, hasSize(1)); + assertThat( + names.iterator().next(), + equalTo(basedir + PS + "my" + PS + "locks" + PS + "46e98183d232f1e16f863025080c7f2b9797fd10")); } @Test - public void absoluteLocksDir() throws IOException - { + public void absoluteLocksDir() throws IOException { String absoluteLocksDir = "/my/locks"; - String customBaseDir = new File( absoluteLocksDir ).getCanonicalPath(); - - configProperties.put( "aether.syncContext.named.hashing.depth", "0" ); - configProperties.put( "aether.syncContext.named.basedir.locksDir", absoluteLocksDir ); - DefaultArtifact artifact = new DefaultArtifact( "group:artifact:1.0" ); - Collection names = mapper.nameLocks( session, singletonList( artifact ), null ); - assertThat( names, hasSize( 1 ) ); - assertThat( names.iterator().next(), // ends with as we do not test drive letter on non-Win plaf - equalTo( customBaseDir + PS + "46e98183d232f1e16f863025080c7f2b9797fd10" ) ); + String customBaseDir = new File(absoluteLocksDir).getCanonicalPath(); + + configProperties.put("aether.syncContext.named.hashing.depth", "0"); + configProperties.put("aether.syncContext.named.basedir.locksDir", absoluteLocksDir); + DefaultArtifact artifact = new DefaultArtifact("group:artifact:1.0"); + Collection names = mapper.nameLocks(session, singletonList(artifact), null); + assertThat(names, hasSize(1)); + assertThat( + names.iterator().next(), // ends with as we do not test drive letter on non-Win plaf + equalTo(customBaseDir + PS + "46e98183d232f1e16f863025080c7f2b9797fd10")); } @Test - public void singleArtifact() - { - configProperties.put( "aether.syncContext.named.hashing.depth", "0" ); + public void singleArtifact() { + configProperties.put("aether.syncContext.named.hashing.depth", "0"); - DefaultArtifact artifact = new DefaultArtifact( "group:artifact:1.0" ); - Collection names = mapper.nameLocks( session, singletonList( artifact ), null ); + DefaultArtifact artifact = new DefaultArtifact("group:artifact:1.0"); + Collection names = mapper.nameLocks(session, singletonList(artifact), null); - assertThat( names, hasSize( 1 ) ); - assertThat( names.iterator().next(), - equalTo( basedir + PS + ".locks" + PS + "46e98183d232f1e16f863025080c7f2b9797fd10" ) ); + assertThat(names, hasSize(1)); + assertThat( + names.iterator().next(), + equalTo(basedir + PS + ".locks" + PS + "46e98183d232f1e16f863025080c7f2b9797fd10")); } @Test - public void singleMetadata() - { - configProperties.put( "aether.syncContext.named.hashing.depth", "0" ); + public void singleMetadata() { + configProperties.put("aether.syncContext.named.hashing.depth", "0"); DefaultMetadata metadata = - new DefaultMetadata( "group", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); - Collection names = mapper.nameLocks( session, null, singletonList( metadata ) ); + new DefaultMetadata("group", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); + Collection names = mapper.nameLocks(session, null, singletonList(metadata)); - assertThat( names, hasSize( 1 ) ); - assertThat( names.iterator().next(), - equalTo( basedir + PS + ".locks" + PS + "293b3990971f4b4b02b220620d2538eaac5f221b" ) ); + assertThat(names, hasSize(1)); + assertThat( + names.iterator().next(), + equalTo(basedir + PS + ".locks" + PS + "293b3990971f4b4b02b220620d2538eaac5f221b")); } @Test - public void oneAndOne() - { - configProperties.put( "aether.syncContext.named.hashing.depth", "0" ); + public void oneAndOne() { + configProperties.put("aether.syncContext.named.hashing.depth", "0"); - DefaultArtifact artifact = new DefaultArtifact( "agroup:artifact:1.0" ); + DefaultArtifact artifact = new DefaultArtifact("agroup:artifact:1.0"); DefaultMetadata metadata = - new DefaultMetadata( "bgroup", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); - Collection names = mapper.nameLocks( session, singletonList( artifact ), singletonList( metadata ) ); + new DefaultMetadata("bgroup", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); + Collection names = mapper.nameLocks(session, singletonList(artifact), singletonList(metadata)); - assertThat( names, hasSize( 2 ) ); + assertThat(names, hasSize(2)); Iterator namesIterator = names.iterator(); // they are sorted as well - assertThat( namesIterator.next(), - equalTo( basedir + PS + ".locks" + PS + "d36504431d00d1c6e4d1c34258f2bf0a004de085" ) ); - assertThat( namesIterator.next(), - equalTo( basedir + PS + ".locks" + PS + "fbcebba60d7eb931eca634f6ca494a8a1701b638" ) ); + assertThat( + namesIterator.next(), + equalTo(basedir + PS + ".locks" + PS + "d36504431d00d1c6e4d1c34258f2bf0a004de085")); + assertThat( + namesIterator.next(), + equalTo(basedir + PS + ".locks" + PS + "fbcebba60d7eb931eca634f6ca494a8a1701b638")); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/GAVNameMapperTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/GAVNameMapperTest.java index a943bca69..54d00b43e 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/GAVNameMapperTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/GAVNameMapperTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; import java.util.Collection; import java.util.Iterator; @@ -34,62 +33,57 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -public class GAVNameMapperTest extends NameMapperTestSupport -{ +public class GAVNameMapperTest extends NameMapperTestSupport { NameMapper mapper = GAVNameMapper.fileGav(); @Test - public void nullsAndEmptyInputs() - { + public void nullsAndEmptyInputs() { Collection names; - names = mapper.nameLocks( session, null, null ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, null, null); + assertThat(names, Matchers.empty()); - names = mapper.nameLocks( session, null, emptyList() ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, null, emptyList()); + assertThat(names, Matchers.empty()); - names = mapper.nameLocks( session, emptyList(), null ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, emptyList(), null); + assertThat(names, Matchers.empty()); - names = mapper.nameLocks( session, emptyList(), emptyList() ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, emptyList(), emptyList()); + assertThat(names, Matchers.empty()); } @Test - public void singleArtifact() - { - DefaultArtifact artifact = new DefaultArtifact( "group:artifact:1.0" ); - Collection names = mapper.nameLocks( session, singletonList( artifact ), null ); + public void singleArtifact() { + DefaultArtifact artifact = new DefaultArtifact("group:artifact:1.0"); + Collection names = mapper.nameLocks(session, singletonList(artifact), null); - assertThat( names, hasSize( 1 ) ); - assertThat( names.iterator().next(), equalTo( "group~artifact~1.0.lock" ) ); + assertThat(names, hasSize(1)); + assertThat(names.iterator().next(), equalTo("group~artifact~1.0.lock")); } @Test - public void singleMetadata() - { + public void singleMetadata() { DefaultMetadata metadata = - new DefaultMetadata( "group", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); - Collection names = mapper.nameLocks( session, null, singletonList( metadata ) ); + new DefaultMetadata("group", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); + Collection names = mapper.nameLocks(session, null, singletonList(metadata)); - assertThat( names, hasSize( 1 ) ); - assertThat( names.iterator().next(), equalTo( "group~artifact.lock" ) ); + assertThat(names, hasSize(1)); + assertThat(names.iterator().next(), equalTo("group~artifact.lock")); } @Test - public void oneAndOne() - { - DefaultArtifact artifact = new DefaultArtifact( "agroup:artifact:1.0" ); + public void oneAndOne() { + DefaultArtifact artifact = new DefaultArtifact("agroup:artifact:1.0"); DefaultMetadata metadata = - new DefaultMetadata( "bgroup", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); - Collection names = mapper.nameLocks( session, singletonList( artifact ), singletonList( metadata ) ); + new DefaultMetadata("bgroup", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); + Collection names = mapper.nameLocks(session, singletonList(artifact), singletonList(metadata)); - assertThat( names, hasSize( 2 ) ); + assertThat(names, hasSize(2)); Iterator namesIterator = names.iterator(); // they are sorted as well - assertThat( namesIterator.next(), equalTo( "agroup~artifact~1.0.lock" ) ); - assertThat( namesIterator.next(), equalTo( "bgroup~artifact.lock" ) ); + assertThat(namesIterator.next(), equalTo("agroup~artifact~1.0.lock")); + assertThat(namesIterator.next(), equalTo("bgroup~artifact.lock")); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/HashingNameMapperTest.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/HashingNameMapperTest.java index 12356ec5a..e3285868a 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/HashingNameMapperTest.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/HashingNameMapperTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; import java.util.Collection; import java.util.Iterator; @@ -34,113 +33,97 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -public class HashingNameMapperTest extends NameMapperTestSupport -{ - HashingNameMapper mapper = new HashingNameMapper( GAVNameMapper.gav() ); +public class HashingNameMapperTest extends NameMapperTestSupport { + HashingNameMapper mapper = new HashingNameMapper(GAVNameMapper.gav()); @Test - public void nullsAndEmptyInputs() - { + public void nullsAndEmptyInputs() { Collection names; - names = mapper.nameLocks( session, null, null ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, null, null); + assertThat(names, Matchers.empty()); - names = mapper.nameLocks( session, null, emptyList() ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, null, emptyList()); + assertThat(names, Matchers.empty()); - names = mapper.nameLocks( session, emptyList(), null ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, emptyList(), null); + assertThat(names, Matchers.empty()); - names = mapper.nameLocks( session, emptyList(), emptyList() ); - assertThat( names, Matchers.empty() ); + names = mapper.nameLocks(session, emptyList(), emptyList()); + assertThat(names, Matchers.empty()); } @Test - public void singleArtifact_depth0() - { - configProperties.put( "aether.syncContext.named.hashing.depth", "0" ); - DefaultArtifact artifact = new DefaultArtifact( "group:artifact:1.0" ); - Collection names = mapper.nameLocks( session, singletonList( artifact ), null ); - - assertThat( names, hasSize( 1 ) ); - assertThat( names.iterator().next(), - equalTo( "46e98183d232f1e16f863025080c7f2b9797fd10" ) ); + public void singleArtifact_depth0() { + configProperties.put("aether.syncContext.named.hashing.depth", "0"); + DefaultArtifact artifact = new DefaultArtifact("group:artifact:1.0"); + Collection names = mapper.nameLocks(session, singletonList(artifact), null); + + assertThat(names, hasSize(1)); + assertThat(names.iterator().next(), equalTo("46e98183d232f1e16f863025080c7f2b9797fd10")); } @Test - public void singleMetadata_depth0() - { - configProperties.put( "aether.syncContext.named.hashing.depth", "0" ); + public void singleMetadata_depth0() { + configProperties.put("aether.syncContext.named.hashing.depth", "0"); DefaultMetadata metadata = - new DefaultMetadata( "group", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); - Collection names = mapper.nameLocks( session, null, singletonList( metadata ) ); + new DefaultMetadata("group", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); + Collection names = mapper.nameLocks(session, null, singletonList(metadata)); - assertThat( names, hasSize( 1 ) ); - assertThat( names.iterator().next(), - equalTo( "293b3990971f4b4b02b220620d2538eaac5f221b" ) ); + assertThat(names, hasSize(1)); + assertThat(names.iterator().next(), equalTo("293b3990971f4b4b02b220620d2538eaac5f221b")); } @Test - public void oneAndOne_depth0() - { - configProperties.put( "aether.syncContext.named.hashing.depth", "0" ); - DefaultArtifact artifact = new DefaultArtifact( "agroup:artifact:1.0" ); + public void oneAndOne_depth0() { + configProperties.put("aether.syncContext.named.hashing.depth", "0"); + DefaultArtifact artifact = new DefaultArtifact("agroup:artifact:1.0"); DefaultMetadata metadata = - new DefaultMetadata( "bgroup", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); - Collection names = mapper.nameLocks( session, singletonList( artifact ), singletonList( metadata ) ); + new DefaultMetadata("bgroup", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); + Collection names = mapper.nameLocks(session, singletonList(artifact), singletonList(metadata)); - assertThat( names, hasSize( 2 ) ); + assertThat(names, hasSize(2)); Iterator namesIterator = names.iterator(); // they are sorted as well - assertThat( namesIterator.next(), - equalTo( "d36504431d00d1c6e4d1c34258f2bf0a004de085" ) ); - assertThat( namesIterator.next(), - equalTo( "fbcebba60d7eb931eca634f6ca494a8a1701b638" ) ); + assertThat(namesIterator.next(), equalTo("d36504431d00d1c6e4d1c34258f2bf0a004de085")); + assertThat(namesIterator.next(), equalTo("fbcebba60d7eb931eca634f6ca494a8a1701b638")); } @Test - public void singleArtifact_depth2() - { - configProperties.put( "aether.syncContext.named.hashing.depth", "2" ); - DefaultArtifact artifact = new DefaultArtifact( "group:artifact:1.0" ); - Collection names = mapper.nameLocks( session, singletonList( artifact ), null ); - - assertThat( names, hasSize( 1 ) ); - assertThat( names.iterator().next(), - equalTo( "46/e9/46e98183d232f1e16f863025080c7f2b9797fd10" ) ); + public void singleArtifact_depth2() { + configProperties.put("aether.syncContext.named.hashing.depth", "2"); + DefaultArtifact artifact = new DefaultArtifact("group:artifact:1.0"); + Collection names = mapper.nameLocks(session, singletonList(artifact), null); + + assertThat(names, hasSize(1)); + assertThat(names.iterator().next(), equalTo("46/e9/46e98183d232f1e16f863025080c7f2b9797fd10")); } @Test - public void singleMetadata_depth2() - { - configProperties.put( "aether.syncContext.named.hashing.depth", "2" ); + public void singleMetadata_depth2() { + configProperties.put("aether.syncContext.named.hashing.depth", "2"); DefaultMetadata metadata = - new DefaultMetadata( "group", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); - Collection names = mapper.nameLocks( session, null, singletonList( metadata ) ); + new DefaultMetadata("group", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); + Collection names = mapper.nameLocks(session, null, singletonList(metadata)); - assertThat( names, hasSize( 1 ) ); - assertThat( names.iterator().next(), - equalTo( "29/3b/293b3990971f4b4b02b220620d2538eaac5f221b" ) ); + assertThat(names, hasSize(1)); + assertThat(names.iterator().next(), equalTo("29/3b/293b3990971f4b4b02b220620d2538eaac5f221b")); } @Test - public void oneAndOne_depth2() - { - configProperties.put( "aether.syncContext.named.hashing.depth", "2" ); - DefaultArtifact artifact = new DefaultArtifact( "agroup:artifact:1.0" ); + public void oneAndOne_depth2() { + configProperties.put("aether.syncContext.named.hashing.depth", "2"); + DefaultArtifact artifact = new DefaultArtifact("agroup:artifact:1.0"); DefaultMetadata metadata = - new DefaultMetadata( "bgroup", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT ); - Collection names = mapper.nameLocks( session, singletonList( artifact ), singletonList( metadata ) ); + new DefaultMetadata("bgroup", "artifact", "maven-metadata.xml", Metadata.Nature.RELEASE_OR_SNAPSHOT); + Collection names = mapper.nameLocks(session, singletonList(artifact), singletonList(metadata)); - assertThat( names, hasSize( 2 ) ); + assertThat(names, hasSize(2)); Iterator namesIterator = names.iterator(); // they are sorted as well - assertThat( namesIterator.next(), - equalTo( "d3/65/d36504431d00d1c6e4d1c34258f2bf0a004de085" ) ); - assertThat( namesIterator.next(), - equalTo( "fb/ce/fbcebba60d7eb931eca634f6ca494a8a1701b638" ) ); + assertThat(namesIterator.next(), equalTo("d3/65/d36504431d00d1c6e4d1c34258f2bf0a004de085")); + assertThat(namesIterator.next(), equalTo("fb/ce/fbcebba60d7eb931eca634f6ca494a8a1701b638")); } } diff --git a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/NameMapperTestSupport.java b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/NameMapperTestSupport.java index 4a3a60e56..ffe3ffddd 100644 --- a/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/NameMapperTestSupport.java +++ b/maven-resolver-impl/src/test/java/org/eclipse/aether/internal/impl/synccontext/named/NameMapperTestSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.impl.synccontext.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.impl.synccontext.named; import java.io.File; import java.io.IOException; @@ -33,8 +32,7 @@ /** * Simple support class for {@link NameMapper} implementation UTs. */ -public abstract class NameMapperTestSupport -{ +public abstract class NameMapperTestSupport { protected String basedir; protected HashMap configProperties; @@ -42,14 +40,13 @@ public abstract class NameMapperTestSupport protected RepositorySystemSession session; @Before - public void before() throws IOException - { + public void before() throws IOException { basedir = new File("/home/maven/.m2/repository").getCanonicalPath(); configProperties = new HashMap<>(); - LocalRepository localRepository = new LocalRepository( new File( basedir ) ); - session = mock( RepositorySystemSession.class ); - when( session.getConfigProperties() ).thenReturn( configProperties ); - when( session.getLocalRepository() ).thenReturn( localRepository ); + LocalRepository localRepository = new LocalRepository(new File(basedir)); + session = mock(RepositorySystemSession.class); + when(session.getConfigProperties()).thenReturn(configProperties); + when(session.getLocalRepository()).thenReturn(localRepository); } } diff --git a/maven-resolver-named-locks-hazelcast/pom.xml b/maven-resolver-named-locks-hazelcast/pom.xml index 2383efa85..1f86c6a41 100644 --- a/maven-resolver-named-locks-hazelcast/pom.xml +++ b/maven-resolver-named-locks-hazelcast/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-named-locks-hazelcast Maven Artifact Resolver Named Locks using Hazelcast - - A synchronization utility implementation using Hazelcast. - + A synchronization utility implementation using Hazelcast. org.apache.maven.resolver.named.hazelcast diff --git a/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/DirectHazelcastSemaphoreProvider.java b/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/DirectHazelcastSemaphoreProvider.java index 6901dafe5..68c1b6648 100644 --- a/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/DirectHazelcastSemaphoreProvider.java +++ b/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/DirectHazelcastSemaphoreProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.cp.ISemaphore; @@ -27,17 +26,14 @@ * of it. This implies, that as many lock names are requested from it, this class will create as many semaphores in * Hazelcast. */ -public class DirectHazelcastSemaphoreProvider extends HazelcastSemaphoreProvider -{ +public class DirectHazelcastSemaphoreProvider extends HazelcastSemaphoreProvider { @Override - public ISemaphore acquireSemaphore( HazelcastInstance hazelcastInstance, String name ) - { - return hazelcastInstance.getCPSubsystem().getSemaphore( NAME_PREFIX + name ); + public ISemaphore acquireSemaphore(HazelcastInstance hazelcastInstance, String name) { + return hazelcastInstance.getCPSubsystem().getSemaphore(NAME_PREFIX + name); } @Override - public void releaseSemaphore( HazelcastInstance hazelcastInstance, String name, ISemaphore semaphore ) - { + public void releaseSemaphore(HazelcastInstance hazelcastInstance, String name, ISemaphore semaphore) { // nothing } } diff --git a/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreNamedLockFactory.java b/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreNamedLockFactory.java index 3f110eadb..8ad42f2e1 100644 --- a/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreNamedLockFactory.java +++ b/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreNamedLockFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import javax.inject.Inject; import javax.inject.Named; @@ -30,26 +29,22 @@ * {@link HazelcastSemaphoreNamedLockFactory} using {@link DirectHazelcastSemaphoreProvider} full Hazelcast member. */ @Singleton -@Named( HazelcastCPSemaphoreNamedLockFactory.NAME ) -public class HazelcastCPSemaphoreNamedLockFactory extends HazelcastSemaphoreNamedLockFactory -{ +@Named(HazelcastCPSemaphoreNamedLockFactory.NAME) +public class HazelcastCPSemaphoreNamedLockFactory extends HazelcastSemaphoreNamedLockFactory { public static final String NAME = "semaphore-hazelcast"; /** * The default constructor: creates own instance of Hazelcast using standard Hazelcast configuration discovery. */ @Inject - public HazelcastCPSemaphoreNamedLockFactory() - { - this( Hazelcast.newHazelcastInstance(), true ); + public HazelcastCPSemaphoreNamedLockFactory() { + this(Hazelcast.newHazelcastInstance(), true); } /** * Constructor for customization. */ - public HazelcastCPSemaphoreNamedLockFactory( HazelcastInstance hazelcastInstance, - boolean manageHazelcast ) - { - super( hazelcastInstance, manageHazelcast, new DirectHazelcastSemaphoreProvider() ); + public HazelcastCPSemaphoreNamedLockFactory(HazelcastInstance hazelcastInstance, boolean manageHazelcast) { + super(hazelcastInstance, manageHazelcast, new DirectHazelcastSemaphoreProvider()); } } diff --git a/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreNamedLockFactory.java b/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreNamedLockFactory.java index 138f7bb2d..7cb86ade0 100644 --- a/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreNamedLockFactory.java +++ b/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreNamedLockFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import javax.inject.Inject; import javax.inject.Named; @@ -31,26 +30,22 @@ * client must be configured to connect to some existing cluster (w/ proper configuration applied). */ @Singleton -@Named( HazelcastClientCPSemaphoreNamedLockFactory.NAME ) -public class HazelcastClientCPSemaphoreNamedLockFactory extends HazelcastSemaphoreNamedLockFactory -{ +@Named(HazelcastClientCPSemaphoreNamedLockFactory.NAME) +public class HazelcastClientCPSemaphoreNamedLockFactory extends HazelcastSemaphoreNamedLockFactory { public static final String NAME = "semaphore-hazelcast-client"; /** * The default constructor: creates own instance of Hazelcast using standard Hazelcast configuration discovery. */ @Inject - public HazelcastClientCPSemaphoreNamedLockFactory() - { - this( HazelcastClient.newHazelcastClient(), true ); + public HazelcastClientCPSemaphoreNamedLockFactory() { + this(HazelcastClient.newHazelcastClient(), true); } /** * Constructor for customization. */ - public HazelcastClientCPSemaphoreNamedLockFactory( HazelcastInstance hazelcastInstance, - boolean manageHazelcast ) - { - super( hazelcastInstance, manageHazelcast, new DirectHazelcastSemaphoreProvider() ); + public HazelcastClientCPSemaphoreNamedLockFactory(HazelcastInstance hazelcastInstance, boolean manageHazelcast) { + super(hazelcastInstance, manageHazelcast, new DirectHazelcastSemaphoreProvider()); } } diff --git a/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastSemaphoreNamedLockFactory.java b/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastSemaphoreNamedLockFactory.java index 18a30fa63..25b60a5d8 100644 --- a/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastSemaphoreNamedLockFactory.java +++ b/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastSemaphoreNamedLockFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -36,9 +35,7 @@ * most the work to {@link HazelcastSemaphoreProvider} and this class just adapts the returned semaphore to named lock * and caches {@link ISemaphore} instances, as recommended by Hazelcast. */ -public class HazelcastSemaphoreNamedLockFactory - extends NamedLockFactorySupport -{ +public class HazelcastSemaphoreNamedLockFactory extends NamedLockFactorySupport { protected final HazelcastInstance hazelcastInstance; protected final boolean manageHazelcast; @@ -50,58 +47,47 @@ public class HazelcastSemaphoreNamedLockFactory public HazelcastSemaphoreNamedLockFactory( final HazelcastInstance hazelcastInstance, final boolean manageHazelcast, - final HazelcastSemaphoreProvider hazelcastSemaphoreProvider - ) - { - this.hazelcastInstance = requireNonNull( hazelcastInstance ); + final HazelcastSemaphoreProvider hazelcastSemaphoreProvider) { + this.hazelcastInstance = requireNonNull(hazelcastInstance); this.manageHazelcast = manageHazelcast; - this.hazelcastSemaphoreProvider = requireNonNull( hazelcastSemaphoreProvider ); + this.hazelcastSemaphoreProvider = requireNonNull(hazelcastSemaphoreProvider); this.semaphores = new ConcurrentHashMap<>(); } @Override - protected AdaptedSemaphoreNamedLock createLock( final String name ) - { - ISemaphore semaphore = semaphores.computeIfAbsent( name, - k -> hazelcastSemaphoreProvider.acquireSemaphore( hazelcastInstance, name ) ); - return new AdaptedSemaphoreNamedLock( name, this, new HazelcastSemaphore( semaphore ) ); + protected AdaptedSemaphoreNamedLock createLock(final String name) { + ISemaphore semaphore = semaphores.computeIfAbsent( + name, k -> hazelcastSemaphoreProvider.acquireSemaphore(hazelcastInstance, name)); + return new AdaptedSemaphoreNamedLock(name, this, new HazelcastSemaphore(semaphore)); } @Override - protected void destroyLock( final String name ) - { - hazelcastSemaphoreProvider.releaseSemaphore( hazelcastInstance, name, semaphores.remove( name ) ); + protected void destroyLock(final String name) { + hazelcastSemaphoreProvider.releaseSemaphore(hazelcastInstance, name, semaphores.remove(name)); } @Override - public void shutdown() - { - if ( manageHazelcast ) - { + public void shutdown() { + if (manageHazelcast) { hazelcastInstance.shutdown(); } } - private static final class HazelcastSemaphore implements AdaptedSemaphore - { + private static final class HazelcastSemaphore implements AdaptedSemaphore { private final ISemaphore semaphore; - private HazelcastSemaphore( final ISemaphore semaphore ) - { + private HazelcastSemaphore(final ISemaphore semaphore) { this.semaphore = semaphore; } @Override - public boolean tryAcquire( final int perms, final long time, final TimeUnit unit ) - throws InterruptedException - { - return semaphore.tryAcquire( perms, time, unit ); + public boolean tryAcquire(final int perms, final long time, final TimeUnit unit) throws InterruptedException { + return semaphore.tryAcquire(perms, time, unit); } @Override - public void release( final int perms ) - { - semaphore.release( perms ); + public void release(final int perms) { + semaphore.release(perms); } } } diff --git a/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastSemaphoreProvider.java b/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastSemaphoreProvider.java index 7ffc98072..51107af24 100644 --- a/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastSemaphoreProvider.java +++ b/maven-resolver-named-locks-hazelcast/src/main/java/org/eclipse/aether/named/hazelcast/HazelcastSemaphoreProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.cp.ISemaphore; @@ -25,8 +24,7 @@ /** * Support class for providers of {@link ISemaphore} instances. */ -public abstract class HazelcastSemaphoreProvider -{ +public abstract class HazelcastSemaphoreProvider { /** * Name prefix recommended using for simpler configuration of Hazelcast. */ @@ -35,10 +33,10 @@ public abstract class HazelcastSemaphoreProvider /** * Invoked when new instance of semaphore needed for given name. must not return {@code null}. */ - public abstract ISemaphore acquireSemaphore( HazelcastInstance hazelcastInstance, String name ); + public abstract ISemaphore acquireSemaphore(HazelcastInstance hazelcastInstance, String name); /** * Invoked when passed in semaphore associated with passed in name is not to be used anymore. */ - public abstract void releaseSemaphore( HazelcastInstance hazelcastInstance, String name, ISemaphore semaphore ); + public abstract void releaseSemaphore(HazelcastInstance hazelcastInstance, String name, ISemaphore semaphore); } diff --git a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreAdapterIT.java b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreAdapterIT.java index 8f69655ca..fbd31c7a5 100644 --- a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreAdapterIT.java +++ b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreAdapterIT.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,18 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import org.junit.BeforeClass; -public class HazelcastCPSemaphoreAdapterIT - extends NamedLockFactoryAdapterTestSupport -{ +public class HazelcastCPSemaphoreAdapterIT extends NamedLockFactoryAdapterTestSupport { @BeforeClass - public static void createNamedLockFactory() - { - String clusterName = utils.clusterName( HazelcastCPSemaphoreAdapterIT.class ); - setNamedLockFactory( - new HazelcastCPSemaphoreNamedLockFactory( utils.createMember( clusterName ), true ) ); + public static void createNamedLockFactory() { + String clusterName = utils.clusterName(HazelcastCPSemaphoreAdapterIT.class); + setNamedLockFactory(new HazelcastCPSemaphoreNamedLockFactory(utils.createMember(clusterName), true)); } } diff --git a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreNamedLockFactoryIT.java b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreNamedLockFactoryIT.java index cd1a091e3..cf9807fba 100644 --- a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreNamedLockFactoryIT.java +++ b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastCPSemaphoreNamedLockFactoryIT.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,17 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import org.junit.BeforeClass; -public class HazelcastCPSemaphoreNamedLockFactoryIT - extends NamedLockFactoryTestSupport -{ +public class HazelcastCPSemaphoreNamedLockFactoryIT extends NamedLockFactoryTestSupport { @BeforeClass - public static void createNamedLockFactory() - { - String clusterName = utils.clusterName( HazelcastCPSemaphoreNamedLockFactoryIT.class ); - namedLockFactory = new HazelcastCPSemaphoreNamedLockFactory( utils.createMember( clusterName ), true ); + public static void createNamedLockFactory() { + String clusterName = utils.clusterName(HazelcastCPSemaphoreNamedLockFactoryIT.class); + namedLockFactory = new HazelcastCPSemaphoreNamedLockFactory(utils.createMember(clusterName), true); } } diff --git a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreAdapterIT.java b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreAdapterIT.java index c770b7a39..863b7e87d 100644 --- a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreAdapterIT.java +++ b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreAdapterIT.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,18 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import org.junit.BeforeClass; -public class HazelcastClientCPSemaphoreAdapterIT - extends NamedLockFactoryAdapterTestSupport -{ +public class HazelcastClientCPSemaphoreAdapterIT extends NamedLockFactoryAdapterTestSupport { @BeforeClass - public static void createNamedLockFactory() - { - String clusterName = utils.clusterName( HazelcastClientCPSemaphoreAdapterIT.class ); - utils.createMember( clusterName ); - setNamedLockFactory( - new HazelcastClientCPSemaphoreNamedLockFactory( utils.createClient( clusterName ), true ) ); + public static void createNamedLockFactory() { + String clusterName = utils.clusterName(HazelcastClientCPSemaphoreAdapterIT.class); + utils.createMember(clusterName); + setNamedLockFactory(new HazelcastClientCPSemaphoreNamedLockFactory(utils.createClient(clusterName), true)); } } diff --git a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreNamedLockFactoryIT.java b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreNamedLockFactoryIT.java index be50ed5be..3ac2f6dde 100644 --- a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreNamedLockFactoryIT.java +++ b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientCPSemaphoreNamedLockFactoryIT.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,18 +16,15 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import org.junit.BeforeClass; -public class HazelcastClientCPSemaphoreNamedLockFactoryIT - extends NamedLockFactoryTestSupport -{ +public class HazelcastClientCPSemaphoreNamedLockFactoryIT extends NamedLockFactoryTestSupport { @BeforeClass - public static void createNamedLockFactory() - { - String clusterName = utils.clusterName( HazelcastClientCPSemaphoreNamedLockFactoryIT.class ); - utils.createMember( clusterName ); - namedLockFactory = - new HazelcastClientCPSemaphoreNamedLockFactory( utils.createClient( clusterName ), true ); + public static void createNamedLockFactory() { + String clusterName = utils.clusterName(HazelcastClientCPSemaphoreNamedLockFactoryIT.class); + utils.createMember(clusterName); + namedLockFactory = new HazelcastClientCPSemaphoreNamedLockFactory(utils.createClient(clusterName), true); } } diff --git a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientUtils.java b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientUtils.java index ec547069c..367341d21 100644 --- a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientUtils.java +++ b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/HazelcastClientUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import java.util.ArrayList; import java.util.List; @@ -33,60 +32,53 @@ /** * Hazelcast test utilities. */ -public final class HazelcastClientUtils -{ +public final class HazelcastClientUtils { private final List servers = new ArrayList<>(); /** * Creates similar but still randomized name. */ - public String clusterName( Class klazz ) - { - return String.format( "%s-%s", klazz.getSimpleName(), UUID.randomUUID() ); + public String clusterName(Class klazz) { + return String.format("%s-%s", klazz.getSimpleName(), UUID.randomUUID()); } /** * Creates single Hazelcast client instance. */ - public synchronized HazelcastInstance createClient( String clusterName ) - { + public synchronized HazelcastInstance createClient(String clusterName) { ClientConfig config = ClientConfig.load(); - config.setClusterName( clusterName ); - return HazelcastClient.newHazelcastClient( config ); + config.setClusterName(clusterName); + return HazelcastClient.newHazelcastClient(config); } /** * Creates single Hazelcast member instance. */ - public synchronized HazelcastInstance createMember( String clusterName ) - { - return createMembers( 1, clusterName ).get( 0 ); + public synchronized HazelcastInstance createMember(String clusterName) { + return createMembers(1, clusterName).get(0); } /** * Creates given count of Hazelcast member instances. */ - public synchronized List createMembers( int memberCount, String clusterName ) - { + public synchronized List createMembers(int memberCount, String clusterName) { Config config = Config.load(); - config.setClusterName( clusterName ); - ArrayList result = new ArrayList<>( memberCount ); - IntStream.range( 0, memberCount ).forEach( i -> { - config.setInstanceName( "node-" + i ); - HazelcastInstance instance = Hazelcast.newHazelcastInstance( config ); - result.add( instance ); - servers.add( instance ); - } - ); + config.setClusterName(clusterName); + ArrayList result = new ArrayList<>(memberCount); + IntStream.range(0, memberCount).forEach(i -> { + config.setInstanceName("node-" + i); + HazelcastInstance instance = Hazelcast.newHazelcastInstance(config); + result.add(instance); + servers.add(instance); + }); return result; } /** * Shuts down the created instances. */ - public synchronized void cleanup() - { - servers.forEach( HazelcastInstance::shutdown ); + public synchronized void cleanup() { + servers.forEach(HazelcastInstance::shutdown); servers.clear(); } } diff --git a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/NamedLockFactoryAdapterTestSupport.java b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/NamedLockFactoryAdapterTestSupport.java index 1450604c3..f7e031b02 100644 --- a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/NamedLockFactoryAdapterTestSupport.java +++ b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/NamedLockFactoryAdapterTestSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import java.io.IOException; import java.nio.file.Files; @@ -47,8 +46,7 @@ /** * UT support for {@link SyncContextFactory}. */ -public abstract class NamedLockFactoryAdapterTestSupport -{ +public abstract class NamedLockFactoryAdapterTestSupport { protected static final HazelcastClientUtils utils = new HazelcastClientUtils(); private static final long ADAPTER_TIME = 100L; @@ -63,18 +61,13 @@ public abstract class NamedLockFactoryAdapterTestSupport private RepositorySystemSession session; - protected static void setNamedLockFactory( final NamedLockFactory namedLockFactory ) - { - adapter = new NamedLockFactoryAdapter( - new DiscriminatingNameMapper( GAVNameMapper.gav() ), namedLockFactory - ); + protected static void setNamedLockFactory(final NamedLockFactory namedLockFactory) { + adapter = new NamedLockFactoryAdapter(new DiscriminatingNameMapper(GAVNameMapper.gav()), namedLockFactory); } @AfterClass - public static void cleanup() - { - if ( adapter != null ) - { + public static void cleanup() { + if (adapter != null) { adapter.getNamedLockFactory().shutdown(); } @@ -82,44 +75,40 @@ public static void cleanup() } @Before - public void before() throws IOException - { - Files.createDirectories( Paths.get( System.getProperty( "java.io.tmpdir" ) ) ); // hack for Surefire - LocalRepository localRepository = new LocalRepository( Files.createTempDirectory( "test" ).toFile() ); - session = mock( RepositorySystemSession.class ); - when( session.getLocalRepository() ).thenReturn( localRepository ); + public void before() throws IOException { + Files.createDirectories(Paths.get(System.getProperty("java.io.tmpdir"))); // hack for Surefire + LocalRepository localRepository = + new LocalRepository(Files.createTempDirectory("test").toFile()); + session = mock(RepositorySystemSession.class); + when(session.getLocalRepository()).thenReturn(localRepository); HashMap config = new HashMap<>(); - config.put( NamedLockFactoryAdapter.TIME_KEY, String.valueOf( ADAPTER_TIME ) ); - config.put( NamedLockFactoryAdapter.TIME_UNIT_KEY, ADAPTER_TIME_UNIT.name() ); - when( session.getConfigProperties() ).thenReturn( config ); + config.put(NamedLockFactoryAdapter.TIME_KEY, String.valueOf(ADAPTER_TIME)); + config.put(NamedLockFactoryAdapter.TIME_UNIT_KEY, ADAPTER_TIME_UNIT.name()); + when(session.getConfigProperties()).thenReturn(config); } @Test - public void justCreateAndClose() - { - adapter.newInstance( session, false ).close(); + public void justCreateAndClose() { + adapter.newInstance(session, false).close(); } @Test - public void justAcquire() - { - try ( SyncContext syncContext = adapter.newInstance( session, false ) ) - { + public void justAcquire() { + try (SyncContext syncContext = adapter.newInstance(session, false)) { syncContext.acquire( - Arrays.asList( new DefaultArtifact( "groupId:artifactId:1.0" ), - new DefaultArtifact( "groupId:artifactId:1.1" ) ), - null - ); + Arrays.asList( + new DefaultArtifact("groupId:artifactId:1.0"), + new DefaultArtifact("groupId:artifactId:1.1")), + null); } } - @Test( timeout = 5000 ) - public void sharedAccess() throws InterruptedException - { - CountDownLatch winners = new CountDownLatch( 2 ); // we expect 2 winners - CountDownLatch losers = new CountDownLatch( 0 ); // we expect 0 losers - Thread t1 = new Thread( new Access( true, winners, losers, adapter, session, null ) ); - Thread t2 = new Thread( new Access( true, winners, losers, adapter, session, null ) ); + @Test(timeout = 5000) + public void sharedAccess() throws InterruptedException { + CountDownLatch winners = new CountDownLatch(2); // we expect 2 winners + CountDownLatch losers = new CountDownLatch(0); // we expect 0 losers + Thread t1 = new Thread(new Access(true, winners, losers, adapter, session, null)); + Thread t2 = new Thread(new Access(true, winners, losers, adapter, session, null)); t1.start(); t2.start(); t1.join(); @@ -128,13 +117,12 @@ public void sharedAccess() throws InterruptedException losers.await(); } - @Test( timeout = 5000 ) - public void exclusiveAccess() throws InterruptedException - { - CountDownLatch winners = new CountDownLatch( 1 ); // we expect 1 winner - CountDownLatch losers = new CountDownLatch( 1 ); // we expect 1 loser - Thread t1 = new Thread( new Access( false, winners, losers, adapter, session, null ) ); - Thread t2 = new Thread( new Access( false, winners, losers, adapter, session, null ) ); + @Test(timeout = 5000) + public void exclusiveAccess() throws InterruptedException { + CountDownLatch winners = new CountDownLatch(1); // we expect 1 winner + CountDownLatch losers = new CountDownLatch(1); // we expect 1 loser + Thread t1 = new Thread(new Access(false, winners, losers, adapter, session, null)); + Thread t2 = new Thread(new Access(false, winners, losers, adapter, session, null)); t1.start(); t2.start(); t1.join(); @@ -143,13 +131,12 @@ public void exclusiveAccess() throws InterruptedException losers.await(); } - @Test( timeout = 5000 ) - public void mixedAccess() throws InterruptedException - { - CountDownLatch winners = new CountDownLatch( 1 ); // we expect 1 winner - CountDownLatch losers = new CountDownLatch( 1 ); // we expect 1 loser - Thread t1 = new Thread( new Access( true, winners, losers, adapter, session, null ) ); - Thread t2 = new Thread( new Access( false, winners, losers, adapter, session, null ) ); + @Test(timeout = 5000) + public void mixedAccess() throws InterruptedException { + CountDownLatch winners = new CountDownLatch(1); // we expect 1 winner + CountDownLatch losers = new CountDownLatch(1); // we expect 1 loser + Thread t1 = new Thread(new Access(true, winners, losers, adapter, session, null)); + Thread t2 = new Thread(new Access(false, winners, losers, adapter, session, null)); t1.start(); t2.start(); t1.join(); @@ -158,72 +145,55 @@ public void mixedAccess() throws InterruptedException losers.await(); } - @Test( timeout = 5000 ) - public void nestedSharedShared() throws InterruptedException - { - CountDownLatch winners = new CountDownLatch( 2 ); // we expect 2 winners - CountDownLatch losers = new CountDownLatch( 0 ); // we expect 0 losers - Thread t1 = new Thread( - new Access( true, winners, losers, adapter, session, - new Access( true, winners, losers, adapter, session, null ) - ) - ); + @Test(timeout = 5000) + public void nestedSharedShared() throws InterruptedException { + CountDownLatch winners = new CountDownLatch(2); // we expect 2 winners + CountDownLatch losers = new CountDownLatch(0); // we expect 0 losers + Thread t1 = new Thread(new Access( + true, winners, losers, adapter, session, new Access(true, winners, losers, adapter, session, null))); t1.start(); t1.join(); winners.await(); losers.await(); } - @Test( timeout = 5000 ) - public void nestedExclusiveShared() throws InterruptedException - { - CountDownLatch winners = new CountDownLatch( 2 ); // we expect 2 winners - CountDownLatch losers = new CountDownLatch( 0 ); // we expect 0 losers - Thread t1 = new Thread( - new Access( false, winners, losers, adapter, session, - new Access( true, winners, losers, adapter, session, null ) - ) - ); + @Test(timeout = 5000) + public void nestedExclusiveShared() throws InterruptedException { + CountDownLatch winners = new CountDownLatch(2); // we expect 2 winners + CountDownLatch losers = new CountDownLatch(0); // we expect 0 losers + Thread t1 = new Thread(new Access( + false, winners, losers, adapter, session, new Access(true, winners, losers, adapter, session, null))); t1.start(); t1.join(); winners.await(); losers.await(); } - @Test( timeout = 5000 ) - public void nestedExclusiveExclusive() throws InterruptedException - { - CountDownLatch winners = new CountDownLatch( 2 ); // we expect 2 winners - CountDownLatch losers = new CountDownLatch( 0 ); // we expect 0 losers - Thread t1 = new Thread( - new Access( false, winners, losers, adapter, session, - new Access( false, winners, losers, adapter, session, null ) - ) - ); + @Test(timeout = 5000) + public void nestedExclusiveExclusive() throws InterruptedException { + CountDownLatch winners = new CountDownLatch(2); // we expect 2 winners + CountDownLatch losers = new CountDownLatch(0); // we expect 0 losers + Thread t1 = new Thread(new Access( + false, winners, losers, adapter, session, new Access(false, winners, losers, adapter, session, null))); t1.start(); t1.join(); winners.await(); losers.await(); } - @Test( timeout = 5000 ) - public void nestedSharedExclusive() throws InterruptedException - { - CountDownLatch winners = new CountDownLatch( 1 ); // we expect 1 winner (outer) - CountDownLatch losers = new CountDownLatch( 1 ); // we expect 1 loser (inner) - Thread t1 = new Thread( - new Access( true, winners, losers, adapter, session, - new Access( false, winners, losers, adapter, session, null ) - ) - ); + @Test(timeout = 5000) + public void nestedSharedExclusive() throws InterruptedException { + CountDownLatch winners = new CountDownLatch(1); // we expect 1 winner (outer) + CountDownLatch losers = new CountDownLatch(1); // we expect 1 loser (inner) + Thread t1 = new Thread(new Access( + true, winners, losers, adapter, session, new Access(false, winners, losers, adapter, session, null))); t1.start(); t1.join(); winners.await(); losers.await(); } - private static class Access implements Runnable - { + private static class Access implements Runnable { final boolean shared; final CountDownLatch winner; final CountDownLatch loser; @@ -231,13 +201,13 @@ private static class Access implements Runnable final RepositorySystemSession session; final Access chained; - public Access( boolean shared, - CountDownLatch winner, - CountDownLatch loser, - NamedLockFactoryAdapter adapter, - RepositorySystemSession session, - Access chained ) - { + public Access( + boolean shared, + CountDownLatch winner, + CountDownLatch loser, + NamedLockFactoryAdapter adapter, + RepositorySystemSession session, + Access chained) { this.shared = shared; this.winner = winner; this.loser = loser; @@ -247,33 +217,25 @@ public Access( boolean shared, } @Override - public void run() - { - try - { - try ( SyncContext syncContext = adapter.newInstance( session, shared ) ) - { + public void run() { + try { + try (SyncContext syncContext = adapter.newInstance(session, shared)) { syncContext.acquire( - Arrays.asList( new DefaultArtifact( "groupId:artifactId:1.0" ), - new DefaultArtifact( "groupId:artifactId:1.1" ) ), - null - ); + Arrays.asList( + new DefaultArtifact("groupId:artifactId:1.0"), + new DefaultArtifact("groupId:artifactId:1.1")), + null); winner.countDown(); - if ( chained != null ) - { + if (chained != null) { chained.run(); } loser.await(); - } - catch ( IllegalStateException e ) - { + } catch (IllegalStateException e) { loser.countDown(); winner.await(); } - } - catch ( InterruptedException e ) - { - Assert.fail( "interrupted" ); + } catch (InterruptedException e) { + Assert.fail("interrupted"); } } } diff --git a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/NamedLockFactoryTestSupport.java b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/NamedLockFactoryTestSupport.java index 04b009c8a..ad11bddc3 100644 --- a/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/NamedLockFactoryTestSupport.java +++ b/maven-resolver-named-locks-hazelcast/src/test/java/org/eclipse/aether/named/hazelcast/NamedLockFactoryTestSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.hazelcast; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.hazelcast; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -38,8 +37,7 @@ /** * UT support for {@link NamedLockFactory}. */ -public abstract class NamedLockFactoryTestSupport -{ +public abstract class NamedLockFactoryTestSupport { protected static final HazelcastClientUtils utils = new HazelcastClientUtils(); protected static NamedLockFactory namedLockFactory; @@ -48,102 +46,86 @@ public abstract class NamedLockFactoryTestSupport public TestName testName = new TestName(); @AfterClass - public static void cleanup() - { - if ( namedLockFactory != null ) - { + public static void cleanup() { + if (namedLockFactory != null) { namedLockFactory.shutdown(); } utils.cleanup(); } @Test - public void refCounting() - { + public void refCounting() { final String name = testName.getMethodName(); - try ( NamedLock one = namedLockFactory.getLock( name ); - NamedLock two = namedLockFactory.getLock( name ) ) - { - assertThat( one, sameInstance( two ) ); + try (NamedLock one = namedLockFactory.getLock(name); + NamedLock two = namedLockFactory.getLock(name)) { + assertThat(one, sameInstance(two)); one.close(); two.close(); - try ( NamedLock three = namedLockFactory.getLock( name ) ) - { - assertThat( three, not( sameInstance( two ) ) ); + try (NamedLock three = namedLockFactory.getLock(name)) { + assertThat(three, not(sameInstance(two))); } } } - @Test( expected = IllegalStateException.class ) - public void unlockWoLock() - { + @Test(expected = IllegalStateException.class) + public void unlockWoLock() { final String name = testName.getMethodName(); - try ( NamedLock one = namedLockFactory.getLock( name ) ) - { + try (NamedLock one = namedLockFactory.getLock(name)) { one.unlock(); } } @Test - public void wwBoxing() throws InterruptedException - { + public void wwBoxing() throws InterruptedException { final String name = testName.getMethodName(); - try ( NamedLock one = namedLockFactory.getLock( name ) ) - { - assertThat( one.lockExclusively( 1L, TimeUnit.MILLISECONDS ), is( true ) ); - assertThat( one.lockExclusively( 1L, TimeUnit.MILLISECONDS ), is( true ) ); + try (NamedLock one = namedLockFactory.getLock(name)) { + assertThat(one.lockExclusively(1L, TimeUnit.MILLISECONDS), is(true)); + assertThat(one.lockExclusively(1L, TimeUnit.MILLISECONDS), is(true)); one.unlock(); one.unlock(); } } @Test - public void rrBoxing() throws InterruptedException - { + public void rrBoxing() throws InterruptedException { final String name = testName.getMethodName(); - try ( NamedLock one = namedLockFactory.getLock( name ) ) - { - assertThat( one.lockShared( 1L, TimeUnit.MILLISECONDS ), is( true ) ); - assertThat( one.lockShared( 1L, TimeUnit.MILLISECONDS ), is( true ) ); + try (NamedLock one = namedLockFactory.getLock(name)) { + assertThat(one.lockShared(1L, TimeUnit.MILLISECONDS), is(true)); + assertThat(one.lockShared(1L, TimeUnit.MILLISECONDS), is(true)); one.unlock(); one.unlock(); } } @Test - public void wrBoxing() throws InterruptedException - { + public void wrBoxing() throws InterruptedException { final String name = testName.getMethodName(); - try ( NamedLock one = namedLockFactory.getLock( name ) ) - { - assertThat( one.lockExclusively( 1L, TimeUnit.MILLISECONDS ), is( true ) ); - assertThat( one.lockShared( 1L, TimeUnit.MILLISECONDS ), is( true ) ); + try (NamedLock one = namedLockFactory.getLock(name)) { + assertThat(one.lockExclusively(1L, TimeUnit.MILLISECONDS), is(true)); + assertThat(one.lockShared(1L, TimeUnit.MILLISECONDS), is(true)); one.unlock(); one.unlock(); } } @Test - public void rwBoxing() throws InterruptedException - { + public void rwBoxing() throws InterruptedException { final String name = testName.getMethodName(); - try ( NamedLock one = namedLockFactory.getLock( name ) ) - { - assertThat( one.lockShared( 1L, TimeUnit.MILLISECONDS ), is( true ) ); - assertThat( one.lockExclusively( 1L, TimeUnit.MILLISECONDS ), is( false ) ); + try (NamedLock one = namedLockFactory.getLock(name)) { + assertThat(one.lockShared(1L, TimeUnit.MILLISECONDS), is(true)); + assertThat(one.lockExclusively(1L, TimeUnit.MILLISECONDS), is(false)); one.unlock(); } } - @Test( timeout = 5000 ) - public void sharedAccess() throws InterruptedException - { + @Test(timeout = 5000) + public void sharedAccess() throws InterruptedException { final String name = testName.getMethodName(); - CountDownLatch winners = new CountDownLatch( 2 ); // we expect 2 winner - CountDownLatch losers = new CountDownLatch( 0 ); // we expect 0 loser - Thread t1 = new Thread( new Access( namedLockFactory, name, true, winners, losers ) ); - Thread t2 = new Thread( new Access( namedLockFactory, name, true, winners, losers ) ); + CountDownLatch winners = new CountDownLatch(2); // we expect 2 winner + CountDownLatch losers = new CountDownLatch(0); // we expect 0 loser + Thread t1 = new Thread(new Access(namedLockFactory, name, true, winners, losers)); + Thread t2 = new Thread(new Access(namedLockFactory, name, true, winners, losers)); t1.start(); t2.start(); t1.join(); @@ -152,14 +134,13 @@ public void sharedAccess() throws InterruptedException losers.await(); } - @Test( timeout = 5000 ) - public void exclusiveAccess() throws InterruptedException - { + @Test(timeout = 5000) + public void exclusiveAccess() throws InterruptedException { final String name = testName.getMethodName(); - CountDownLatch winners = new CountDownLatch( 1 ); // we expect 1 winner - CountDownLatch losers = new CountDownLatch( 1 ); // we expect 1 loser - Thread t1 = new Thread( new Access( namedLockFactory, name, false, winners, losers ) ); - Thread t2 = new Thread( new Access( namedLockFactory, name, false, winners, losers ) ); + CountDownLatch winners = new CountDownLatch(1); // we expect 1 winner + CountDownLatch losers = new CountDownLatch(1); // we expect 1 loser + Thread t1 = new Thread(new Access(namedLockFactory, name, false, winners, losers)); + Thread t2 = new Thread(new Access(namedLockFactory, name, false, winners, losers)); t1.start(); t2.start(); t1.join(); @@ -168,14 +149,13 @@ public void exclusiveAccess() throws InterruptedException losers.await(); } - @Test( timeout = 5000 ) - public void mixedAccess() throws InterruptedException - { + @Test(timeout = 5000) + public void mixedAccess() throws InterruptedException { final String name = testName.getMethodName(); - CountDownLatch winners = new CountDownLatch( 1 ); // we expect 1 winner - CountDownLatch losers = new CountDownLatch( 1 ); // we expect 1 loser - Thread t1 = new Thread( new Access( namedLockFactory, name, true, winners, losers ) ); - Thread t2 = new Thread( new Access( namedLockFactory, name, false, winners, losers ) ); + CountDownLatch winners = new CountDownLatch(1); // we expect 1 winner + CountDownLatch losers = new CountDownLatch(1); // we expect 1 loser + Thread t1 = new Thread(new Access(namedLockFactory, name, true, winners, losers)); + Thread t2 = new Thread(new Access(namedLockFactory, name, false, winners, losers)); t1.start(); t2.start(); t1.join(); @@ -184,20 +164,19 @@ public void mixedAccess() throws InterruptedException losers.await(); } - private static class Access implements Runnable - { + private static class Access implements Runnable { final NamedLockFactory namedLockFactory; final String name; final boolean shared; final CountDownLatch winner; final CountDownLatch loser; - public Access( NamedLockFactory namedLockFactory, - String name, - boolean shared, - CountDownLatch winner, - CountDownLatch loser ) - { + public Access( + NamedLockFactory namedLockFactory, + String name, + boolean shared, + CountDownLatch winner, + CountDownLatch loser) { this.namedLockFactory = namedLockFactory; this.name = name; this.shared = shared; @@ -206,32 +185,23 @@ public Access( NamedLockFactory namedLockFactory, } @Override - public void run() - { - try ( NamedLock lock = namedLockFactory.getLock( name ) ) - { - if ( shared ? lock.lockShared( 100L, TimeUnit.MILLISECONDS ) : - lock.lockExclusively( 100L, TimeUnit.MILLISECONDS ) ) - { - try - { + public void run() { + try (NamedLock lock = namedLockFactory.getLock(name)) { + if (shared + ? lock.lockShared(100L, TimeUnit.MILLISECONDS) + : lock.lockExclusively(100L, TimeUnit.MILLISECONDS)) { + try { winner.countDown(); loser.await(); - } - finally - { + } finally { lock.unlock(); } - } - else - { + } else { loser.countDown(); winner.await(); } - } - catch ( InterruptedException e ) - { - Assert.fail( e.getMessage() ); + } catch (InterruptedException e) { + Assert.fail(e.getMessage()); } } } diff --git a/maven-resolver-named-locks-redisson/pom.xml b/maven-resolver-named-locks-redisson/pom.xml index af434b38b..90c008be8 100644 --- a/maven-resolver-named-locks-redisson/pom.xml +++ b/maven-resolver-named-locks-redisson/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-named-locks-redisson Maven Artifact Resolver Named Locks using Redisson - - A synchronization utility implementation using Redisson. - + A synchronization utility implementation using Redisson. org.apache.maven.resolver.named.redisson diff --git a/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonNamedLockFactorySupport.java b/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonNamedLockFactorySupport.java index d49c19e4e..4396f4755 100644 --- a/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonNamedLockFactorySupport.java +++ b/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonNamedLockFactorySupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.redisson; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,11 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.eclipse.aether.named.support.NamedLockFactorySupport; -import org.redisson.Redisson; -import org.redisson.api.RedissonClient; -import org.redisson.config.Config; +package org.eclipse.aether.named.redisson; import java.io.IOException; import java.io.InputStream; @@ -30,12 +24,15 @@ import java.nio.file.Path; import java.nio.file.Paths; +import org.eclipse.aether.named.support.NamedLockFactorySupport; +import org.redisson.Redisson; +import org.redisson.api.RedissonClient; +import org.redisson.config.Config; + /** * Support class for factories using {@link RedissonClient}. */ -public abstract class RedissonNamedLockFactorySupport - extends NamedLockFactorySupport -{ +public abstract class RedissonNamedLockFactorySupport extends NamedLockFactorySupport { protected static final String NAME_PREFIX = "maven:resolver:"; private static final String DEFAULT_CONFIG_FILE_NAME = "maven-resolver-redisson.yaml"; @@ -48,41 +45,33 @@ public abstract class RedissonNamedLockFactorySupport protected final RedissonClient redissonClient; - public RedissonNamedLockFactorySupport() - { + public RedissonNamedLockFactorySupport() { this.redissonClient = createRedissonClient(); } @Override - public void shutdown() - { - logger.trace( "Shutting down Redisson client with id '{}'", redissonClient.getId() ); + public void shutdown() { + logger.trace("Shutting down Redisson client with id '{}'", redissonClient.getId()); redissonClient.shutdown(); } - private RedissonClient createRedissonClient() - { + private RedissonClient createRedissonClient() { Path configFilePath = null; - String configFile = System.getProperty( CONFIG_PROP_CONFIG_FILE ); - if ( configFile != null && !configFile.isEmpty() ) - { - configFilePath = Paths.get( configFile ); - if ( Files.notExists( configFilePath ) ) - { - throw new IllegalArgumentException( "The specified Redisson config file does not exist: " - + configFilePath ); + String configFile = System.getProperty(CONFIG_PROP_CONFIG_FILE); + if (configFile != null && !configFile.isEmpty()) { + configFilePath = Paths.get(configFile); + if (Files.notExists(configFilePath)) { + throw new IllegalArgumentException( + "The specified Redisson config file does not exist: " + configFilePath); } } - if ( configFilePath == null ) - { - String mavenConf = System.getProperty( "maven.conf" ); - if ( mavenConf != null && !mavenConf.isEmpty() ) - { - configFilePath = Paths.get( mavenConf, DEFAULT_CONFIG_FILE_NAME ); - if ( Files.notExists( configFilePath ) ) - { + if (configFilePath == null) { + String mavenConf = System.getProperty("maven.conf"); + if (mavenConf != null && !mavenConf.isEmpty()) { + configFilePath = Paths.get(mavenConf, DEFAULT_CONFIG_FILE_NAME); + if (Files.notExists(configFilePath)) { configFilePath = null; } } @@ -90,28 +79,20 @@ private RedissonClient createRedissonClient() Config config; - if ( configFilePath != null ) - { - logger.trace( "Reading Redisson config file from '{}'", configFilePath ); - try ( InputStream is = Files.newInputStream( configFilePath ) ) - { - config = Config.fromYAML( is ); - } - catch ( IOException e ) - { - throw new IllegalStateException( "Failed to read Redisson config file: " + configFilePath, e ); + if (configFilePath != null) { + logger.trace("Reading Redisson config file from '{}'", configFilePath); + try (InputStream is = Files.newInputStream(configFilePath)) { + config = Config.fromYAML(is); + } catch (IOException e) { + throw new IllegalStateException("Failed to read Redisson config file: " + configFilePath, e); } - } - else - { + } else { config = new Config(); - config.useSingleServer() - .setAddress( DEFAULT_REDIS_ADDRESS ) - .setClientName( DEFAULT_CLIENT_NAME ); + config.useSingleServer().setAddress(DEFAULT_REDIS_ADDRESS).setClientName(DEFAULT_CLIENT_NAME); } - RedissonClient redissonClient = Redisson.create( config ); - logger.trace( "Created Redisson client with id '{}'", redissonClient.getId() ); + RedissonClient redissonClient = Redisson.create(config); + logger.trace("Created Redisson client with id '{}'", redissonClient.getId()); return redissonClient; } diff --git a/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonReadWriteLockNamedLockFactory.java b/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonReadWriteLockNamedLockFactory.java index 30b7a93db..bcb418479 100644 --- a/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonReadWriteLockNamedLockFactory.java +++ b/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonReadWriteLockNamedLockFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.redisson; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,29 +16,27 @@ * specific language governing permissions and limitations * under the License. */ - -import org.eclipse.aether.named.support.ReadWriteLockNamedLock; -import org.redisson.api.RReadWriteLock; +package org.eclipse.aether.named.redisson; import javax.inject.Named; import javax.inject.Singleton; +import org.eclipse.aether.named.support.ReadWriteLockNamedLock; +import org.redisson.api.RReadWriteLock; + /** * Provider of {@link RedissonReadWriteLockNamedLockFactory} using Redisson and {@link org.redisson.api.RReadWriteLock}. */ @Singleton -@Named( RedissonReadWriteLockNamedLockFactory.NAME ) -public class RedissonReadWriteLockNamedLockFactory - extends RedissonNamedLockFactorySupport -{ +@Named(RedissonReadWriteLockNamedLockFactory.NAME) +public class RedissonReadWriteLockNamedLockFactory extends RedissonNamedLockFactorySupport { public static final String NAME = "rwlock-redisson"; private static final String TYPED_NAME_PREFIX = NAME_PREFIX + NAME + ":"; @Override - protected ReadWriteLockNamedLock createLock( final String name ) - { - RReadWriteLock readWriteLock = redissonClient.getReadWriteLock( TYPED_NAME_PREFIX + name ); - return new ReadWriteLockNamedLock( name, this, readWriteLock ); + protected ReadWriteLockNamedLock createLock(final String name) { + RReadWriteLock readWriteLock = redissonClient.getReadWriteLock(TYPED_NAME_PREFIX + name); + return new ReadWriteLockNamedLock(name, this, readWriteLock); } } diff --git a/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonSemaphoreNamedLockFactory.java b/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonSemaphoreNamedLockFactory.java index 80156b578..44e8a136e 100644 --- a/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonSemaphoreNamedLockFactory.java +++ b/maven-resolver-named-locks-redisson/src/main/java/org/eclipse/aether/named/redisson/RedissonSemaphoreNamedLockFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.redisson; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,79 +16,70 @@ * specific language governing permissions and limitations * under the License. */ - -import org.eclipse.aether.named.support.AdaptedSemaphoreNamedLock; -import org.redisson.api.RSemaphore; +package org.eclipse.aether.named.redisson; import javax.inject.Named; import javax.inject.Singleton; + import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; +import org.eclipse.aether.named.support.AdaptedSemaphoreNamedLock; +import org.redisson.api.RSemaphore; + /** * Provider of {@link RedissonSemaphoreNamedLockFactory} using Redisson and {@link org.redisson.api.RSemaphore}. */ @Singleton -@Named( RedissonSemaphoreNamedLockFactory.NAME ) -public class RedissonSemaphoreNamedLockFactory - extends RedissonNamedLockFactorySupport -{ +@Named(RedissonSemaphoreNamedLockFactory.NAME) +public class RedissonSemaphoreNamedLockFactory extends RedissonNamedLockFactorySupport { public static final String NAME = "semaphore-redisson"; private static final String TYPED_NAME_PREFIX = NAME_PREFIX + NAME + ":"; private final ConcurrentMap semaphores; - public RedissonSemaphoreNamedLockFactory() - { + public RedissonSemaphoreNamedLockFactory() { this.semaphores = new ConcurrentHashMap<>(); } @Override - protected AdaptedSemaphoreNamedLock createLock( final String name ) - { - RSemaphore semaphore = semaphores.computeIfAbsent( name, k -> - { - RSemaphore result = redissonClient.getSemaphore( TYPED_NAME_PREFIX + k ); - result.trySetPermits( Integer.MAX_VALUE ); + protected AdaptedSemaphoreNamedLock createLock(final String name) { + RSemaphore semaphore = semaphores.computeIfAbsent(name, k -> { + RSemaphore result = redissonClient.getSemaphore(TYPED_NAME_PREFIX + k); + result.trySetPermits(Integer.MAX_VALUE); return result; - } ); - return new AdaptedSemaphoreNamedLock( name, this, new RedissonSemaphore( semaphore ) ); + }); + return new AdaptedSemaphoreNamedLock(name, this, new RedissonSemaphore(semaphore)); } @Override - protected void destroyLock( final String name ) - { - RSemaphore semaphore = semaphores.remove( name ); - if ( semaphore == null ) - { - throw new IllegalStateException( "Semaphore expected, but does not exist: " + name ); + protected void destroyLock(final String name) { + RSemaphore semaphore = semaphores.remove(name); + if (semaphore == null) { + throw new IllegalStateException("Semaphore expected, but does not exist: " + name); } /* Threre is no reasonable way to destroy the semaphore in Redis because we cannot know * when the last process has stopped using it. */ } - private static final class RedissonSemaphore implements AdaptedSemaphoreNamedLock.AdaptedSemaphore - { + private static final class RedissonSemaphore implements AdaptedSemaphoreNamedLock.AdaptedSemaphore { private final RSemaphore semaphore; - private RedissonSemaphore( final RSemaphore semaphore ) - { + private RedissonSemaphore(final RSemaphore semaphore) { this.semaphore = semaphore; } @Override - public boolean tryAcquire( final int perms, final long time, final TimeUnit unit ) throws InterruptedException - { - return semaphore.tryAcquire( perms, time, unit ); + public boolean tryAcquire(final int perms, final long time, final TimeUnit unit) throws InterruptedException { + return semaphore.tryAcquire(perms, time, unit); } @Override - public void release( final int perms ) - { - semaphore.release( perms ); + public void release(final int perms) { + semaphore.release(perms); } } } diff --git a/maven-resolver-named-locks/pom.xml b/maven-resolver-named-locks/pom.xml index c81965e0d..5359a9520 100644 --- a/maven-resolver-named-locks/pom.xml +++ b/maven-resolver-named-locks/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-named-locks Maven Artifact Resolver Named Locks - - A synchronization utility implementation using Named locks. - + A synchronization utility implementation using Named locks. org.apache.maven.resolver.named diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/NamedLock.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/NamedLock.java index 81ebe5e16..724a839a6 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/NamedLock.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/NamedLock.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named; import java.util.concurrent.TimeUnit; @@ -41,8 +40,7 @@ * } * */ -public interface NamedLock extends AutoCloseable -{ +public interface NamedLock extends AutoCloseable { /** * Returns this instance name, never null */ @@ -51,12 +49,12 @@ public interface NamedLock extends AutoCloseable /** * Tries to lock shared, may block for given time. If successful, returns {@code true}. */ - boolean lockShared( long time, TimeUnit unit ) throws InterruptedException; + boolean lockShared(long time, TimeUnit unit) throws InterruptedException; /** * Tries to lock exclusively, may block for given time. If successful, returns {@code true}. */ - boolean lockExclusively( long time, TimeUnit unit ) throws InterruptedException; + boolean lockExclusively(long time, TimeUnit unit) throws InterruptedException; /** * Unlocks the lock, must be invoked by caller after one of the {@link #lockShared(long, TimeUnit)} or {@link diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/NamedLockFactory.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/NamedLockFactory.java index 5b7490974..56935637b 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/NamedLockFactory.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/NamedLockFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named; /** * A factory of {@link NamedLock}s. */ -public interface NamedLockFactory -{ +public interface NamedLockFactory { /** * Creates or reuses existing {@link NamedLock}. Returns instance MUST BE treated as "resource", best in * try-with-resource block. @@ -31,7 +29,7 @@ public interface NamedLockFactory * @param name the lock name, must not be {@code null}. * @return named lock instance, never {@code null}. */ - NamedLock getLock( String name ); + NamedLock getLock(String name); /** * Performs a clean shut down of the factory. diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/FileLockNamedLockFactory.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/FileLockNamedLockFactory.java index 5f1b9da4b..a89c05cf3 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/FileLockNamedLockFactory.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/FileLockNamedLockFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.providers; + +import javax.inject.Named; +import javax.inject.Singleton; import java.io.IOException; import java.io.UncheckedIOException; @@ -30,9 +32,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import javax.inject.Named; -import javax.inject.Singleton; - import org.eclipse.aether.named.support.FileLockNamedLock; import org.eclipse.aether.named.support.NamedLockFactorySupport; import org.eclipse.aether.named.support.NamedLockSupport; @@ -46,10 +45,8 @@ * @since 1.7.3 */ @Singleton -@Named( FileLockNamedLockFactory.NAME ) -public class FileLockNamedLockFactory - extends NamedLockFactorySupport -{ +@Named(FileLockNamedLockFactory.NAME) +public class FileLockNamedLockFactory extends NamedLockFactorySupport { public static final String NAME = "file-lock"; /** @@ -59,8 +56,8 @@ public class FileLockNamedLockFactory * * @see JDK-8252883 */ - private static final boolean DELETE_LOCK_FILES = Boolean.parseBoolean( - System.getProperty( "aether.named.file-lock.deleteLockFiles", Boolean.TRUE.toString() ) ); + private static final boolean DELETE_LOCK_FILES = + Boolean.parseBoolean(System.getProperty("aether.named.file-lock.deleteLockFiles", Boolean.TRUE.toString())); /** * Tweak: on Windows, the presence of {@link StandardOpenOption#DELETE_ON_CLOSE} causes concurrency issues. This @@ -69,98 +66,79 @@ public class FileLockNamedLockFactory * * @see JDK-8252883 */ - private static final int ATTEMPTS = Integer.parseInt( - System.getProperty( "aether.named.file-lock.attempts", "5" ) ); + private static final int ATTEMPTS = Integer.parseInt(System.getProperty("aether.named.file-lock.attempts", "5")); /** * Tweak: When {@link #ATTEMPTS} used, the amount of milliseconds to sleep between subsequent retries. Default * value is 50 milliseconds. */ - private static final long SLEEP_MILLIS = Long.parseLong( - System.getProperty( "aether.named.file-lock.sleepMillis", "50" ) ); + private static final long SLEEP_MILLIS = + Long.parseLong(System.getProperty("aether.named.file-lock.sleepMillis", "50")); private final ConcurrentMap fileChannels; - public FileLockNamedLockFactory() - { + public FileLockNamedLockFactory() { this.fileChannels = new ConcurrentHashMap<>(); } @Override - protected NamedLockSupport createLock( final String name ) - { - Path path = Paths.get( name ); - FileChannel fileChannel = fileChannels.computeIfAbsent( name, k -> - { - try - { - Files.createDirectories( path.getParent() ); - FileChannel channel = retry( ATTEMPTS, SLEEP_MILLIS, () -> - { - try - { - if ( DELETE_LOCK_FILES ) - { - return FileChannel.open( - path, - StandardOpenOption.READ, StandardOpenOption.WRITE, - StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE - ); - } - else - { - return FileChannel.open( - path, - StandardOpenOption.READ, StandardOpenOption.WRITE, - StandardOpenOption.CREATE - ); - } - } - catch ( AccessDeniedException e ) - { - return null; - } - }, null, null ); + protected NamedLockSupport createLock(final String name) { + Path path = Paths.get(name); + FileChannel fileChannel = fileChannels.computeIfAbsent(name, k -> { + try { + Files.createDirectories(path.getParent()); + FileChannel channel = retry( + ATTEMPTS, + SLEEP_MILLIS, + () -> { + try { + if (DELETE_LOCK_FILES) { + return FileChannel.open( + path, + StandardOpenOption.READ, + StandardOpenOption.WRITE, + StandardOpenOption.CREATE, + StandardOpenOption.DELETE_ON_CLOSE); + } else { + return FileChannel.open( + path, + StandardOpenOption.READ, + StandardOpenOption.WRITE, + StandardOpenOption.CREATE); + } + } catch (AccessDeniedException e) { + return null; + } + }, + null, + null); - if ( channel == null ) - { - throw new IllegalStateException( "Could not open file channel for '" - + name + "' after " + ATTEMPTS + " attempts; giving up" ); + if (channel == null) { + throw new IllegalStateException("Could not open file channel for '" + name + "' after " + ATTEMPTS + + " attempts; giving up"); } return channel; - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); - throw new RuntimeException( "Interrupted while opening file channel for '" - + name + "'", e ); - } - catch ( IOException e ) - { - throw new UncheckedIOException( "Failed to open file channel for '" - + name + "'", e ); + throw new RuntimeException("Interrupted while opening file channel for '" + name + "'", e); + } catch (IOException e) { + throw new UncheckedIOException("Failed to open file channel for '" + name + "'", e); } - } ); - return new FileLockNamedLock( name, fileChannel, this ); + }); + return new FileLockNamedLock(name, fileChannel, this); } @Override - protected void destroyLock( final String name ) - { - FileChannel fileChannel = fileChannels.remove( name ); - if ( fileChannel == null ) - { - throw new IllegalStateException( "File channel expected, but does not exist: " + name ); + protected void destroyLock(final String name) { + FileChannel fileChannel = fileChannels.remove(name); + if (fileChannel == null) { + throw new IllegalStateException("File channel expected, but does not exist: " + name); } - try - { + try { fileChannel.close(); - } - catch ( IOException e ) - { - throw new UncheckedIOException( "Failed to close file channel for '" - + name + "'", e ); + } catch (IOException e) { + throw new UncheckedIOException("Failed to close file channel for '" + name + "'", e); } } } diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/LocalReadWriteLockNamedLockFactory.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/LocalReadWriteLockNamedLockFactory.java index 34b242ac1..952fd8327 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/LocalReadWriteLockNamedLockFactory.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/LocalReadWriteLockNamedLockFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,27 +16,26 @@ * specific language governing permissions and limitations * under the License. */ - -import org.eclipse.aether.named.support.NamedLockFactorySupport; -import org.eclipse.aether.named.support.ReadWriteLockNamedLock; +package org.eclipse.aether.named.providers; import javax.inject.Named; import javax.inject.Singleton; + import java.util.concurrent.locks.ReentrantReadWriteLock; +import org.eclipse.aether.named.support.NamedLockFactorySupport; +import org.eclipse.aether.named.support.ReadWriteLockNamedLock; + /** * A JVM-local named lock factory that uses named {@link ReentrantReadWriteLock}s. */ @Singleton -@Named( LocalReadWriteLockNamedLockFactory.NAME ) -public class LocalReadWriteLockNamedLockFactory - extends NamedLockFactorySupport -{ +@Named(LocalReadWriteLockNamedLockFactory.NAME) +public class LocalReadWriteLockNamedLockFactory extends NamedLockFactorySupport { public static final String NAME = "rwlock-local"; @Override - protected ReadWriteLockNamedLock createLock( final String name ) - { - return new ReadWriteLockNamedLock( name, this, new ReentrantReadWriteLock() ); + protected ReadWriteLockNamedLock createLock(final String name) { + return new ReadWriteLockNamedLock(name, this, new ReentrantReadWriteLock()); } } diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/LocalSemaphoreNamedLockFactory.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/LocalSemaphoreNamedLockFactory.java index 3be7f4ea3..ab46c506a 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/LocalSemaphoreNamedLockFactory.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/LocalSemaphoreNamedLockFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; +package org.eclipse.aether.named.providers; import javax.inject.Named; import javax.inject.Singleton; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + import org.eclipse.aether.named.support.AdaptedSemaphoreNamedLock; import org.eclipse.aether.named.support.NamedLockFactorySupport; @@ -32,42 +31,34 @@ * A JVM-local named lock factory that uses named {@link Semaphore}s. */ @Singleton -@Named( LocalSemaphoreNamedLockFactory.NAME ) -public class LocalSemaphoreNamedLockFactory - extends NamedLockFactorySupport -{ +@Named(LocalSemaphoreNamedLockFactory.NAME) +public class LocalSemaphoreNamedLockFactory extends NamedLockFactorySupport { public static final String NAME = "semaphore-local"; @Override - protected AdaptedSemaphoreNamedLock createLock( final String name ) - { - Semaphore semaphore = new Semaphore( Integer.MAX_VALUE ); - return new AdaptedSemaphoreNamedLock( name, this, new JVMSemaphore( semaphore ) ); + protected AdaptedSemaphoreNamedLock createLock(final String name) { + Semaphore semaphore = new Semaphore(Integer.MAX_VALUE); + return new AdaptedSemaphoreNamedLock(name, this, new JVMSemaphore(semaphore)); } /** * Adapted JVM {@link java.util.concurrent.Semaphore}. */ - private static final class JVMSemaphore - implements AdaptedSemaphoreNamedLock.AdaptedSemaphore - { + private static final class JVMSemaphore implements AdaptedSemaphoreNamedLock.AdaptedSemaphore { private final Semaphore semaphore; - private JVMSemaphore( final Semaphore semaphore ) - { - this.semaphore = semaphore; + private JVMSemaphore(final Semaphore semaphore) { + this.semaphore = semaphore; } @Override - public boolean tryAcquire( final int perms, final long time, final TimeUnit unit ) throws InterruptedException - { - return semaphore.tryAcquire( perms, time, unit ); + public boolean tryAcquire(final int perms, final long time, final TimeUnit unit) throws InterruptedException { + return semaphore.tryAcquire(perms, time, unit); } @Override - public void release( final int perms ) - { - semaphore.release( perms ); + public void release(final int perms) { + semaphore.release(perms); } } } diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/NoopNamedLockFactory.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/NoopNamedLockFactory.java index 66b45ed6c..67e0b14e0 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/NoopNamedLockFactory.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/providers/NoopNamedLockFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.providers; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,13 @@ * specific language governing permissions and limitations * under the License. */ - -import java.util.concurrent.TimeUnit; +package org.eclipse.aether.named.providers; import javax.inject.Named; import javax.inject.Singleton; +import java.util.concurrent.TimeUnit; + import org.eclipse.aether.named.support.NamedLockFactorySupport; import org.eclipse.aether.named.support.NamedLockSupport; @@ -31,41 +30,33 @@ * A no-op lock factory, that creates no-op locks. */ @Singleton -@Named( NoopNamedLockFactory.NAME ) -public class NoopNamedLockFactory - extends NamedLockFactorySupport -{ - public static final String NAME = "noop"; - - @Override - protected NoopNamedLock createLock( final String name ) - { - return new NoopNamedLock( name, this ); - } - - private static final class NoopNamedLock extends NamedLockSupport - { - private NoopNamedLock( final String name, final NamedLockFactorySupport factory ) - { - super( name, factory ); - } +@Named(NoopNamedLockFactory.NAME) +public class NoopNamedLockFactory extends NamedLockFactorySupport { + public static final String NAME = "noop"; @Override - public boolean lockShared( final long time, final TimeUnit unit ) - { - return true; + protected NoopNamedLock createLock(final String name) { + return new NoopNamedLock(name, this); } - @Override - public boolean lockExclusively( final long time, final TimeUnit unit ) - { - return true; - } - - @Override - public void unlock() - { - // no-op + private static final class NoopNamedLock extends NamedLockSupport { + private NoopNamedLock(final String name, final NamedLockFactorySupport factory) { + super(name, factory); + } + + @Override + public boolean lockShared(final long time, final TimeUnit unit) { + return true; + } + + @Override + public boolean lockExclusively(final long time, final TimeUnit unit) { + return true; + } + + @Override + public void unlock() { + // no-op + } } - } } diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/AdaptedSemaphoreNamedLock.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/AdaptedSemaphoreNamedLock.java index 2f4a0b803..348d29681 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/AdaptedSemaphoreNamedLock.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/AdaptedSemaphoreNamedLock.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.support; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.support; import java.util.ArrayDeque; import java.util.Deque; @@ -27,18 +26,15 @@ * Named lock support implementation that is using "adapted" semaphore (to be able to use semaphores not sharing common * API). */ -public class AdaptedSemaphoreNamedLock - extends NamedLockSupport -{ +public class AdaptedSemaphoreNamedLock extends NamedLockSupport { /** * Wrapper for semaphore-like stuff, that do not share common ancestor. Semaphore must be created to support {@link * Integer#MAX_VALUE} permissions. */ - public interface AdaptedSemaphore - { - boolean tryAcquire( int perms, long time, TimeUnit unit ) throws InterruptedException; + public interface AdaptedSemaphore { + boolean tryAcquire(int perms, long time, TimeUnit unit) throws InterruptedException; - void release( int perms ); + void release(int perms); } /** @@ -62,68 +58,54 @@ public interface AdaptedSemaphore private final AdaptedSemaphore semaphore; - public AdaptedSemaphoreNamedLock( final String name, - final NamedLockFactorySupport factory, - final AdaptedSemaphore semaphore ) - { - super( name, factory ); - this.threadPerms = ThreadLocal.withInitial( ArrayDeque::new ); + public AdaptedSemaphoreNamedLock( + final String name, final NamedLockFactorySupport factory, final AdaptedSemaphore semaphore) { + super(name, factory); + this.threadPerms = ThreadLocal.withInitial(ArrayDeque::new); this.semaphore = semaphore; } @Override - public boolean lockShared( final long time, final TimeUnit unit ) throws InterruptedException - { + public boolean lockShared(final long time, final TimeUnit unit) throws InterruptedException { Deque perms = threadPerms.get(); - if ( !perms.isEmpty() ) - { // we already own shared or exclusive lock - perms.push( NONE ); + if (!perms.isEmpty()) { // we already own shared or exclusive lock + perms.push(NONE); return true; } - if ( semaphore.tryAcquire( SHARED, time, unit ) ) - { - perms.push( SHARED ); + if (semaphore.tryAcquire(SHARED, time, unit)) { + perms.push(SHARED); return true; } return false; } @Override - public boolean lockExclusively( final long time, final TimeUnit unit ) throws InterruptedException - { + public boolean lockExclusively(final long time, final TimeUnit unit) throws InterruptedException { Deque perms = threadPerms.get(); - if ( !perms.isEmpty() ) - { // we already own shared or exclusive lock - if ( perms.contains( EXCLUSIVE ) ) - { - perms.push( NONE ); + if (!perms.isEmpty()) { // we already own shared or exclusive lock + if (perms.contains(EXCLUSIVE)) { + perms.push(NONE); return true; - } - else - { + } else { return false; // Lock upgrade not supported } } - if ( semaphore.tryAcquire( EXCLUSIVE, time, unit ) ) - { - perms.push( EXCLUSIVE ); + if (semaphore.tryAcquire(EXCLUSIVE, time, unit)) { + perms.push(EXCLUSIVE); return true; } return false; } @Override - public void unlock() - { + public void unlock() { Deque steps = threadPerms.get(); - if ( steps.isEmpty() ) - { - throw new IllegalStateException( "Wrong API usage: unlock without lock" ); + if (steps.isEmpty()) { + throw new IllegalStateException("Wrong API usage: unlock without lock"); } int step = steps.pop(); - if ( step > NONE ) - { - semaphore.release( step ); + if (step > NONE) { + semaphore.release(step); } } } diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/FileLockNamedLock.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/FileLockNamedLock.java index 557a16643..957e4666e 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/FileLockNamedLock.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/FileLockNamedLock.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.support; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.support; import java.io.IOException; import java.io.UncheckedIOException; @@ -47,9 +46,7 @@ * * @since 1.7.3 */ -public final class FileLockNamedLock - extends NamedLockSupport -{ +public final class FileLockNamedLock extends NamedLockSupport { private static final long RETRY_SLEEP_MILLIS = 100L; private static final long LOCK_POSITION = 0L; @@ -77,128 +74,94 @@ public final class FileLockNamedLock */ private final ReentrantLock criticalRegion; - public FileLockNamedLock( final String name, - final FileChannel fileChannel, - final NamedLockFactorySupport factory ) - { - super( name, factory ); + public FileLockNamedLock(final String name, final FileChannel fileChannel, final NamedLockFactorySupport factory) { + super(name, factory); this.threadSteps = new HashMap<>(); this.fileChannel = fileChannel; - this.fileLockRef = new AtomicReference<>( null ); + this.fileLockRef = new AtomicReference<>(null); this.criticalRegion = new ReentrantLock(); } @Override - public boolean lockShared( final long time, final TimeUnit unit ) throws InterruptedException - { - return retry( time, unit, RETRY_SLEEP_MILLIS, this::doLockShared, null, false ); + public boolean lockShared(final long time, final TimeUnit unit) throws InterruptedException { + return retry(time, unit, RETRY_SLEEP_MILLIS, this::doLockShared, null, false); } @Override - public boolean lockExclusively( final long time, final TimeUnit unit ) throws InterruptedException - { - return retry( time, unit, RETRY_SLEEP_MILLIS, this::doLockExclusively, null, false ); + public boolean lockExclusively(final long time, final TimeUnit unit) throws InterruptedException { + return retry(time, unit, RETRY_SLEEP_MILLIS, this::doLockExclusively, null, false); } - private Boolean doLockShared() - { - if ( criticalRegion.tryLock() ) - { - try - { - Deque steps = threadSteps.computeIfAbsent( Thread.currentThread(), k -> new ArrayDeque<>() ); + private Boolean doLockShared() { + if (criticalRegion.tryLock()) { + try { + Deque steps = threadSteps.computeIfAbsent(Thread.currentThread(), k -> new ArrayDeque<>()); FileLock obtainedLock = fileLockRef.get(); - if ( obtainedLock != null ) - { - if ( obtainedLock.isShared() ) - { - steps.push( Boolean.TRUE ); + if (obtainedLock != null) { + if (obtainedLock.isShared()) { + steps.push(Boolean.TRUE); return true; - } - else - { + } else { // if we own exclusive, that's still fine - boolean weOwnExclusive = steps.contains( Boolean.FALSE ); - if ( weOwnExclusive ) - { - steps.push( Boolean.TRUE ); + boolean weOwnExclusive = steps.contains(Boolean.FALSE); + if (weOwnExclusive) { + steps.push(Boolean.TRUE); return true; - } - else - { + } else { // someone else owns exclusive, let's wait return null; } } } - FileLock fileLock = obtainFileLock( true ); - if ( fileLock != null ) - { - fileLockRef.set( fileLock ); - steps.push( Boolean.TRUE ); + FileLock fileLock = obtainFileLock(true); + if (fileLock != null) { + fileLockRef.set(fileLock); + steps.push(Boolean.TRUE); return true; } - } - finally - { + } finally { criticalRegion.unlock(); } } return null; } - private Boolean doLockExclusively() - { - if ( criticalRegion.tryLock() ) - { - try - { - Deque steps = threadSteps.computeIfAbsent( Thread.currentThread(), k -> new ArrayDeque<>() ); + private Boolean doLockExclusively() { + if (criticalRegion.tryLock()) { + try { + Deque steps = threadSteps.computeIfAbsent(Thread.currentThread(), k -> new ArrayDeque<>()); FileLock obtainedLock = fileLockRef.get(); - if ( obtainedLock != null ) - { - if ( obtainedLock.isShared() ) - { + if (obtainedLock != null) { + if (obtainedLock.isShared()) { // if we own shared, that's attempted upgrade - boolean weOwnShared = steps.contains( Boolean.TRUE ); - if ( weOwnShared ) - { + boolean weOwnShared = steps.contains(Boolean.TRUE); + if (weOwnShared) { return false; // Lock upgrade not supported - } - else - { + } else { // someone else owns shared, let's wait return null; } - } - else - { + } else { // if we own exclusive, that's fine - boolean weOwnExclusive = steps.contains( Boolean.FALSE ); - if ( weOwnExclusive ) - { - steps.push( Boolean.FALSE ); + boolean weOwnExclusive = steps.contains(Boolean.FALSE); + if (weOwnExclusive) { + steps.push(Boolean.FALSE); return true; - } - else - { + } else { // someone else owns exclusive, let's wait return null; } } } - FileLock fileLock = obtainFileLock( false ); - if ( fileLock != null ) - { - fileLockRef.set( fileLock ); - steps.push( Boolean.FALSE ); + FileLock fileLock = obtainFileLock(false); + if (fileLock != null) { + fileLockRef.set(fileLock); + steps.push(Boolean.FALSE); return true; } - } - finally - { + } finally { criticalRegion.unlock(); } } @@ -206,31 +169,22 @@ private Boolean doLockExclusively() } @Override - public void unlock() - { + public void unlock() { criticalRegion.lock(); - try - { - Deque steps = threadSteps.computeIfAbsent( Thread.currentThread(), k -> new ArrayDeque<>() ); - if ( steps.isEmpty() ) - { - throw new IllegalStateException( "Wrong API usage: unlock without lock" ); + try { + Deque steps = threadSteps.computeIfAbsent(Thread.currentThread(), k -> new ArrayDeque<>()); + if (steps.isEmpty()) { + throw new IllegalStateException("Wrong API usage: unlock without lock"); } steps.pop(); - if ( steps.isEmpty() && !anyOtherThreadHasSteps() ) - { - try - { - fileLockRef.getAndSet( null ).release(); - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + if (steps.isEmpty() && !anyOtherThreadHasSteps()) { + try { + fileLockRef.getAndSet(null).release(); + } catch (IOException e) { + throw new UncheckedIOException(e); } } - } - finally - { + } finally { criticalRegion.unlock(); } } @@ -238,33 +192,26 @@ public void unlock() /** * Returns {@code true} if any other than this thread using this instance has any step recorded. */ - private boolean anyOtherThreadHasSteps() - { + private boolean anyOtherThreadHasSteps() { return threadSteps.entrySet().stream() - .filter( e -> !Thread.currentThread().equals( e.getKey() ) ) - .map( Map.Entry::getValue ) - .anyMatch( d -> !d.isEmpty() ); + .filter(e -> !Thread.currentThread().equals(e.getKey())) + .map(Map.Entry::getValue) + .anyMatch(d -> !d.isEmpty()); } /** * Attempts to obtain real {@link FileLock}, returns non-null value is succeeds, or {@code null} if cannot. */ - private FileLock obtainFileLock( final boolean shared ) - { + private FileLock obtainFileLock(final boolean shared) { FileLock result; - try - { - result = fileChannel.tryLock( LOCK_POSITION, LOCK_SIZE, shared ); - } - catch ( OverlappingFileLockException e ) - { - logger.trace( "File lock overlap on '{}'", name(), e ); + try { + result = fileChannel.tryLock(LOCK_POSITION, LOCK_SIZE, shared); + } catch (OverlappingFileLockException e) { + logger.trace("File lock overlap on '{}'", name(), e); return null; - } - catch ( IOException e ) - { - logger.trace( "Failure on acquire of file lock for '{}'", name(), e ); - throw new UncheckedIOException( "Failed to acquire lock file channel for '" + name() + "'", e ); + } catch (IOException e) { + logger.trace("Failure on acquire of file lock for '{}'", name(), e); + throw new UncheckedIOException("Failed to acquire lock file channel for '" + name() + "'", e); } return result; } diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/NamedLockFactorySupport.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/NamedLockFactorySupport.java index f1ae82cdb..531472844 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/NamedLockFactorySupport.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/NamedLockFactorySupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.support; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,104 +16,90 @@ * specific language governing permissions and limitations * under the License. */ - -import org.eclipse.aether.named.NamedLockFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +package org.eclipse.aether.named.support; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; +import org.eclipse.aether.named.NamedLockFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Support class for {@link NamedLockFactory} implementations providing reference counting. */ -public abstract class NamedLockFactorySupport - implements NamedLockFactory -{ - protected final Logger logger = LoggerFactory.getLogger( getClass() ); +public abstract class NamedLockFactorySupport implements NamedLockFactory { + protected final Logger logger = LoggerFactory.getLogger(getClass()); private final ConcurrentMap locks; - public NamedLockFactorySupport() - { + public NamedLockFactorySupport() { this.locks = new ConcurrentHashMap<>(); } @Override - public NamedLockSupport getLock( final String name ) - { - return locks.compute( name, ( k, v ) -> - { - if ( v == null ) - { - v = new NamedLockHolder( createLock( k ) ); - } - v.incRef(); - return v; - } ).namedLock; + public NamedLockSupport getLock(final String name) { + return locks.compute(name, (k, v) -> { + if (v == null) { + v = new NamedLockHolder(createLock(k)); + } + v.incRef(); + return v; + }) + .namedLock; } @Override - public void shutdown() - { + public void shutdown() { // override if needed } - public void closeLock( final String name ) - { - locks.compute( name, ( k, v ) -> - { - if ( v != null && v.decRef() == 0 ) - { - destroyLock( v.namedLock.name() ); + public void closeLock(final String name) { + locks.compute(name, (k, v) -> { + if (v != null && v.decRef() == 0) { + destroyLock(v.namedLock.name()); return null; } return v; - } ); + }); } /** * Implementations shall create and return {@link NamedLockSupport} for given {@code name}, this method must never * return {@code null}. */ - protected abstract NamedLockSupport createLock( final String name ); + protected abstract NamedLockSupport createLock(String name); /** * Implementation may override this (empty) method to perform some sort of implementation specific cleanup for * given lock name. Invoked when reference count for given name drops to zero and named lock was removed. */ - protected void destroyLock( final String name ) - { + protected void destroyLock(final String name) { // override if needed } - private static final class NamedLockHolder - { + private static final class NamedLockHolder { private final NamedLockSupport namedLock; private final AtomicInteger referenceCount; - private NamedLockHolder( final NamedLockSupport namedLock ) - { - this.namedLock = Objects.requireNonNull( namedLock ); - this.referenceCount = new AtomicInteger( 0 ); + private NamedLockHolder(final NamedLockSupport namedLock) { + this.namedLock = Objects.requireNonNull(namedLock); + this.referenceCount = new AtomicInteger(0); } - private int incRef() - { + private int incRef() { return referenceCount.incrementAndGet(); } - private int decRef() - { + private int decRef() { return referenceCount.decrementAndGet(); } @Override - public String toString() - { + public String toString() { return "[refCount=" + referenceCount.get() + ", lock=" + namedLock + "]"; } } diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/NamedLockSupport.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/NamedLockSupport.java index 38915b200..9bd966df1 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/NamedLockSupport.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/NamedLockSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.support; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.support; import org.eclipse.aether.named.NamedLock; import org.slf4j.Logger; @@ -26,30 +25,25 @@ /** * Support class for {@link NamedLock} implementations providing reference counting. */ -public abstract class NamedLockSupport - implements NamedLock -{ - protected final Logger logger = LoggerFactory.getLogger( getClass() ); +public abstract class NamedLockSupport implements NamedLock { + protected final Logger logger = LoggerFactory.getLogger(getClass()); private final String name; private final NamedLockFactorySupport factory; - public NamedLockSupport( final String name, final NamedLockFactorySupport factory ) - { + public NamedLockSupport(final String name, final NamedLockFactorySupport factory) { this.name = name; this.factory = factory; } @Override - public String name() - { + public String name() { return name; } @Override - public void close() - { - factory.closeLock( name ); + public void close() { + factory.closeLock(name); } } diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/ReadWriteLockNamedLock.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/ReadWriteLockNamedLock.java index 2168832d0..54b1f61e2 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/ReadWriteLockNamedLock.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/ReadWriteLockNamedLock.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.support; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.support; import java.util.ArrayDeque; import java.util.Deque; @@ -29,11 +28,8 @@ * reentrancy, non re-entrant locks will NOT work. It is the responsibility of an adapting lock, to ensure that * above lock requirement stands. */ -public class ReadWriteLockNamedLock - extends NamedLockSupport -{ - private enum Step - { +public class ReadWriteLockNamedLock extends NamedLockSupport { + private enum Step { /** * Step when {@link ReadWriteLock#readLock()} was locked */ @@ -49,61 +45,48 @@ private enum Step private final ReadWriteLock readWriteLock; - public ReadWriteLockNamedLock( final String name, - final NamedLockFactorySupport factory, - final ReadWriteLock readWriteLock ) - { - super( name, factory ); - this.threadSteps = ThreadLocal.withInitial( ArrayDeque::new ); + public ReadWriteLockNamedLock( + final String name, final NamedLockFactorySupport factory, final ReadWriteLock readWriteLock) { + super(name, factory); + this.threadSteps = ThreadLocal.withInitial(ArrayDeque::new); this.readWriteLock = readWriteLock; } @Override - public boolean lockShared( final long time, final TimeUnit unit ) throws InterruptedException - { + public boolean lockShared(final long time, final TimeUnit unit) throws InterruptedException { Deque steps = threadSteps.get(); - if ( readWriteLock.readLock().tryLock( time, unit ) ) - { - steps.push( Step.SHARED ); + if (readWriteLock.readLock().tryLock(time, unit)) { + steps.push(Step.SHARED); return true; } return false; } @Override - public boolean lockExclusively( final long time, final TimeUnit unit ) throws InterruptedException - { + public boolean lockExclusively(final long time, final TimeUnit unit) throws InterruptedException { Deque steps = threadSteps.get(); - if ( !steps.isEmpty() ) - { // we already own shared or exclusive lock - if ( !steps.contains( Step.EXCLUSIVE ) ) - { + if (!steps.isEmpty()) { // we already own shared or exclusive lock + if (!steps.contains(Step.EXCLUSIVE)) { return false; // Lock upgrade not supported } } - if ( readWriteLock.writeLock().tryLock( time, unit ) ) - { - steps.push( Step.EXCLUSIVE ); + if (readWriteLock.writeLock().tryLock(time, unit)) { + steps.push(Step.EXCLUSIVE); return true; } return false; } @Override - public void unlock() - { + public void unlock() { Deque steps = threadSteps.get(); - if ( steps.isEmpty() ) - { - throw new IllegalStateException( "Wrong API usage: unlock without lock" ); + if (steps.isEmpty()) { + throw new IllegalStateException("Wrong API usage: unlock without lock"); } Step step = steps.pop(); - if ( Step.SHARED == step ) - { + if (Step.SHARED == step) { readWriteLock.readLock().unlock(); - } - else if ( Step.EXCLUSIVE == step ) - { + } else if (Step.EXCLUSIVE == step) { readWriteLock.writeLock().unlock(); } } diff --git a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/Retry.java b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/Retry.java index 595166ac2..7cc6a9c4a 100644 --- a/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/Retry.java +++ b/maven-resolver-named-locks/src/main/java/org/eclipse/aether/named/support/Retry.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named.support; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named.support; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; @@ -35,13 +34,11 @@ * * @since 1.7.3 */ -public final class Retry -{ - private static final Logger LOGGER = LoggerFactory.getLogger( Retry.class ); +public final class Retry { + private static final Logger LOGGER = LoggerFactory.getLogger(Retry.class); - private Retry() - { - // no instances + private Retry() { + // no instances } /** @@ -51,42 +48,35 @@ private Retry() * passes, and still {@code null} ("is not done yet") is returned from operation, the * {@code defaultResult} is returned. */ - public static R retry( final long time, - final TimeUnit unit, - final long sleepMillis, - final Callable operation, - final Predicate retryPredicate, - final R defaultResult ) throws InterruptedException - { + public static R retry( + final long time, + final TimeUnit unit, + final long sleepMillis, + final Callable operation, + final Predicate retryPredicate, + final R defaultResult) + throws InterruptedException { long now = System.nanoTime(); - final long barrier = now + unit.toNanos( time ); + final long barrier = now + unit.toNanos(time); int attempt = 1; R result = null; - while ( now < barrier && result == null ) - { - try - { - result = operation.call(); - if ( result == null ) - { - LOGGER.trace( "Retry attempt {}: no result", attempt ); - Thread.sleep( sleepMillis ); - } - } - catch ( InterruptedException e ) - { - throw e; - } - catch ( Exception e ) - { - LOGGER.trace( "Retry attempt {}: operation failure", attempt, e ); - if ( retryPredicate != null && !retryPredicate.test( e ) ) - { - throw new IllegalStateException( e ); + while (now < barrier && result == null) { + try { + result = operation.call(); + if (result == null) { + LOGGER.trace("Retry attempt {}: no result", attempt); + Thread.sleep(sleepMillis); + } + } catch (InterruptedException e) { + throw e; + } catch (Exception e) { + LOGGER.trace("Retry attempt {}: operation failure", attempt, e); + if (retryPredicate != null && !retryPredicate.test(e)) { + throw new IllegalStateException(e); + } } - } - now = System.nanoTime(); - attempt++; + now = System.nanoTime(); + attempt++; } return result == null ? defaultResult : result; } @@ -101,35 +91,28 @@ public static R retry( final long time, * Just to clear things up: 5 attempts is really 4 retries (once do it and retry 4 times). 0 attempts means * "do not even try it", and this method returns without doing anything. */ - public static R retry( final int attempts, - final long sleepMillis, - final Callable operation, - final Predicate retryPredicate, - final R defaultResult ) throws InterruptedException - { + public static R retry( + final int attempts, + final long sleepMillis, + final Callable operation, + final Predicate retryPredicate, + final R defaultResult) + throws InterruptedException { int attempt = 1; R result = null; - while ( attempt <= attempts && result == null ) - { - try - { + while (attempt <= attempts && result == null) { + try { result = operation.call(); - if ( result == null ) - { - LOGGER.trace( "Retry attempt {}: no result", attempt ); - Thread.sleep( sleepMillis ); + if (result == null) { + LOGGER.trace("Retry attempt {}: no result", attempt); + Thread.sleep(sleepMillis); } - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { throw e; - } - catch ( Exception e ) - { - LOGGER.trace( "Retry attempt {}: operation failure", attempt, e ); - if ( retryPredicate != null && !retryPredicate.test( e ) ) - { - throw new IllegalStateException( e ); + } catch (Exception e) { + LOGGER.trace("Retry attempt {}: operation failure", attempt, e); + if (retryPredicate != null && !retryPredicate.test(e)) { + throw new IllegalStateException(e); } } attempt++; diff --git a/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/FileLockNamedLockFactorySupportTest.java b/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/FileLockNamedLockFactorySupportTest.java index 03f08569d..76a4c3870 100644 --- a/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/FileLockNamedLockFactorySupportTest.java +++ b/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/FileLockNamedLockFactorySupportTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named; import java.io.IOException; import java.nio.file.Files; @@ -27,28 +26,23 @@ import org.eclipse.aether.named.providers.FileLockNamedLockFactory; import org.junit.BeforeClass; -public class FileLockNamedLockFactorySupportTest - extends NamedLockFactoryTestSupport - { +public class FileLockNamedLockFactorySupportTest extends NamedLockFactoryTestSupport { private final Path baseDir; - public FileLockNamedLockFactorySupportTest() throws IOException - { - String path = System.getProperty( "java.io.tmpdir" ); - Files.createDirectories( Paths.get (path) ); // hack for surefire: sets the property but directory does not exist - this.baseDir = Files.createTempDirectory( null ); + public FileLockNamedLockFactorySupportTest() throws IOException { + String path = System.getProperty("java.io.tmpdir"); + Files.createDirectories(Paths.get(path)); // hack for surefire: sets the property but directory does not exist + this.baseDir = Files.createTempDirectory(null); } @Override - protected String lockName() - { - return baseDir.resolve( testName.getMethodName() ).toAbsolutePath().toString(); + protected String lockName() { + return baseDir.resolve(testName.getMethodName()).toAbsolutePath().toString(); } @BeforeClass - public static void createNamedLockFactory() throws IOException - { + public static void createNamedLockFactory() throws IOException { namedLockFactory = new FileLockNamedLockFactory(); } } diff --git a/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/LocalReadWriteLockNamedLockFactoryTest.java b/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/LocalReadWriteLockNamedLockFactoryTest.java index 3fb6ca21c..e3ff12710 100644 --- a/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/LocalReadWriteLockNamedLockFactoryTest.java +++ b/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/LocalReadWriteLockNamedLockFactoryTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named; import org.eclipse.aether.named.providers.LocalReadWriteLockNamedLockFactory; import org.junit.BeforeClass; -public class LocalReadWriteLockNamedLockFactoryTest - extends NamedLockFactoryTestSupport { +public class LocalReadWriteLockNamedLockFactoryTest extends NamedLockFactoryTestSupport { @BeforeClass public static void createNamedLockFactory() { diff --git a/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/LocalSemaphoreNamedLockFactoryTest.java b/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/LocalSemaphoreNamedLockFactoryTest.java index df8c247e7..eef7291cb 100644 --- a/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/LocalSemaphoreNamedLockFactoryTest.java +++ b/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/LocalSemaphoreNamedLockFactoryTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named; import org.eclipse.aether.named.providers.LocalSemaphoreNamedLockFactory; import org.junit.BeforeClass; -public class LocalSemaphoreNamedLockFactoryTest - extends NamedLockFactoryTestSupport { +public class LocalSemaphoreNamedLockFactoryTest extends NamedLockFactoryTestSupport { @BeforeClass public static void createNamedLockFactory() { diff --git a/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/NamedLockFactoryTestSupport.java b/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/NamedLockFactoryTestSupport.java index de4a8fe12..471d308a8 100644 --- a/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/NamedLockFactoryTestSupport.java +++ b/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/NamedLockFactoryTestSupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,15 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -40,8 +39,7 @@ public abstract class NamedLockFactoryTestSupport { @Rule public TestName testName = new TestName(); - protected String lockName() - { + protected String lockName() { return testName.getMethodName(); } @@ -49,7 +47,7 @@ protected String lockName() public void refCounting() { final String name = lockName(); try (NamedLock one = namedLockFactory.getLock(name); - NamedLock two = namedLockFactory.getLock(name)) { + NamedLock two = namedLockFactory.getLock(name)) { assertThat(one, sameInstance(two)); one.close(); two.close(); @@ -172,7 +170,7 @@ public void fullyConsumeLockTime() throws InterruptedException { losers.await(); long end = System.nanoTime(); long duration = end - start; - long expectedDuration = TimeUnit.MILLISECONDS.toNanos( ACCESS_WAIT_MILLIS ); + long expectedDuration = TimeUnit.MILLISECONDS.toNanos(ACCESS_WAIT_MILLIS); assertThat(duration, greaterThanOrEqualTo(expectedDuration)); // equal in ideal case } @@ -182,15 +180,12 @@ public void releasedExclusiveAllowAccess() throws InterruptedException { CountDownLatch winners = new CountDownLatch(1); // we expect 1 winner CountDownLatch losers = new CountDownLatch(0); // we expect 0 loser Thread t1 = new Thread(new Access(namedLockFactory, name, true, winners, losers)); - try (NamedLock namedLock = namedLockFactory.getLock(name)) - { - assertThat( namedLock.lockExclusively( 50L, TimeUnit.MILLISECONDS ), is( true )); + try (NamedLock namedLock = namedLockFactory.getLock(name)) { + assertThat(namedLock.lockExclusively(50L, TimeUnit.MILLISECONDS), is(true)); try { t1.start(); - Thread.sleep(50L ); - } - finally - { + Thread.sleep(50L); + } finally { namedLock.unlock(); } } @@ -208,11 +203,12 @@ private static class Access implements Runnable { final CountDownLatch winner; final CountDownLatch loser; - public Access(NamedLockFactory namedLockFactory, - String name, - boolean shared, - CountDownLatch winner, - CountDownLatch loser) { + public Access( + NamedLockFactory namedLockFactory, + String name, + boolean shared, + CountDownLatch winner, + CountDownLatch loser) { this.namedLockFactory = namedLockFactory; this.name = name; this.shared = shared; @@ -223,7 +219,9 @@ public Access(NamedLockFactory namedLockFactory, @Override public void run() { try (NamedLock lock = namedLockFactory.getLock(name)) { - if (shared ? lock.lockShared(ACCESS_WAIT_MILLIS, TimeUnit.MILLISECONDS) : lock.lockExclusively(ACCESS_WAIT_MILLIS, TimeUnit.MILLISECONDS)) { + if (shared + ? lock.lockShared(ACCESS_WAIT_MILLIS, TimeUnit.MILLISECONDS) + : lock.lockExclusively(ACCESS_WAIT_MILLIS, TimeUnit.MILLISECONDS)) { try { winner.countDown(); loser.await(); diff --git a/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/RetryTest.java b/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/RetryTest.java index bdd5cdb96..5f5b1bd31 100644 --- a/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/RetryTest.java +++ b/maven-resolver-named-locks/src/test/java/org/eclipse/aether/named/RetryTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.named; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.named; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.LongAdder; @@ -34,64 +33,108 @@ /** * UT for {@link org.eclipse.aether.named.support.Retry}. */ -public class RetryTest -{ +public class RetryTest { private static final long RETRY_SLEEP_MILLIS = 250L; @Rule public TestName testName = new TestName(); @Test - public void happy() throws InterruptedException - { + public void happy() throws InterruptedException { LongAdder retries = new LongAdder(); - String result = retry( 1L, TimeUnit.SECONDS, RETRY_SLEEP_MILLIS, () -> { retries.increment(); return "happy"; }, null, "notHappy" ); - assertThat( result, equalTo( "happy" ) ); - assertThat( retries.sum(), equalTo( 1L ) ); + String result = retry( + 1L, + TimeUnit.SECONDS, + RETRY_SLEEP_MILLIS, + () -> { + retries.increment(); + return "happy"; + }, + null, + "notHappy"); + assertThat(result, equalTo("happy")); + assertThat(retries.sum(), equalTo(1L)); } @Test - public void notHappy() throws InterruptedException - { + public void notHappy() throws InterruptedException { LongAdder retries = new LongAdder(); - String result = retry( 1L, TimeUnit.SECONDS, RETRY_SLEEP_MILLIS, () -> { retries.increment(); return null; }, null, "notHappy" ); - assertThat( result, equalTo( "notHappy" ) ); - assertThat( retries.sum(), greaterThan( 1L ) ); + String result = retry( + 1L, + TimeUnit.SECONDS, + RETRY_SLEEP_MILLIS, + () -> { + retries.increment(); + return null; + }, + null, + "notHappy"); + assertThat(result, equalTo("notHappy")); + assertThat(retries.sum(), greaterThan(1L)); } @Test - public void happyAfterSomeTime() throws InterruptedException - { + public void happyAfterSomeTime() throws InterruptedException { LongAdder retries = new LongAdder(); - String result = retry( 1L, TimeUnit.SECONDS, RETRY_SLEEP_MILLIS, () -> { retries.increment(); return retries.sum() == 2 ? "got it" : null; }, null, "notHappy" ); - assertThat( result, equalTo( "got it" ) ); - assertThat( retries.sum(), equalTo( 2L ) ); + String result = retry( + 1L, + TimeUnit.SECONDS, + RETRY_SLEEP_MILLIS, + () -> { + retries.increment(); + return retries.sum() == 2 ? "got it" : null; + }, + null, + "notHappy"); + assertThat(result, equalTo("got it")); + assertThat(retries.sum(), equalTo(2L)); } @Test - public void happyFirstAttempt() throws InterruptedException - { + public void happyFirstAttempt() throws InterruptedException { LongAdder retries = new LongAdder(); - String result = retry( 5, RETRY_SLEEP_MILLIS, () -> { retries.increment(); return "happy"; }, null, "notHappy" ); - assertThat( result, equalTo( "happy" ) ); - assertThat( retries.sum(), equalTo( 1L ) ); + String result = retry( + 5, + RETRY_SLEEP_MILLIS, + () -> { + retries.increment(); + return "happy"; + }, + null, + "notHappy"); + assertThat(result, equalTo("happy")); + assertThat(retries.sum(), equalTo(1L)); } @Test - public void notHappyAnyAttempt() throws InterruptedException - { + public void notHappyAnyAttempt() throws InterruptedException { LongAdder retries = new LongAdder(); - String result = retry( 5, RETRY_SLEEP_MILLIS, () -> { retries.increment(); return null; }, null, "notHappy" ); - assertThat( result, equalTo( "notHappy" ) ); - assertThat( retries.sum(), equalTo( 5L ) ); + String result = retry( + 5, + RETRY_SLEEP_MILLIS, + () -> { + retries.increment(); + return null; + }, + null, + "notHappy"); + assertThat(result, equalTo("notHappy")); + assertThat(retries.sum(), equalTo(5L)); } @Test - public void happyAfterSomeAttempt() throws InterruptedException - { + public void happyAfterSomeAttempt() throws InterruptedException { LongAdder retries = new LongAdder(); - String result = retry( 5, RETRY_SLEEP_MILLIS, () -> { retries.increment(); return retries.sum() == 3 ? "got it" : null; }, null, "notHappy" ); - assertThat( result, equalTo( "got it" ) ); - assertThat( retries.sum(), equalTo( 3L ) ); + String result = retry( + 5, + RETRY_SLEEP_MILLIS, + () -> { + retries.increment(); + return retries.sum() == 3 ? "got it" : null; + }, + null, + "notHappy"); + assertThat(result, equalTo("got it")); + assertThat(retries.sum(), equalTo(3L)); } } diff --git a/maven-resolver-spi/pom.xml b/maven-resolver-spi/pom.xml index 61a352e7a..e2e53106b 100644 --- a/maven-resolver-spi/pom.xml +++ b/maven-resolver-spi/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-spi Maven Artifact Resolver SPI - - The service provider interface for repository system implementations and repository connectors. - + The service provider interface for repository system implementations and repository connectors. org.apache.maven.resolver.spi diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/checksums/TrustedChecksumsSource.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/checksums/TrustedChecksumsSource.java index 8c909ec56..2af3590cc 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/checksums/TrustedChecksumsSource.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/checksums/TrustedChecksumsSource.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.checksums; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.checksums; import java.io.IOException; import java.util.List; @@ -37,8 +36,7 @@ * * @since 1.9.0 */ -public interface TrustedChecksumsSource -{ +public interface TrustedChecksumsSource { /** * May return the trusted checksums (for given artifact) from trusted source, or {@code null} if not enabled. * Enabled trusted checksum source SHOULD return non-null (empty map) result, when it has no data for given @@ -51,30 +49,32 @@ public interface TrustedChecksumsSource * @param checksumAlgorithmFactories The checksum algorithms that are expected, never {@code null}. * @return Map of expected checksums, or {@code null} if not enabled. */ - Map getTrustedArtifactChecksums( RepositorySystemSession session, - Artifact artifact, - ArtifactRepository artifactRepository, - List checksumAlgorithmFactories ); + Map getTrustedArtifactChecksums( + RepositorySystemSession session, + Artifact artifact, + ArtifactRepository artifactRepository, + List checksumAlgorithmFactories); /** * A writer that is able to write/add trusted checksums to this implementation. */ - interface Writer - { + interface Writer { /** * Performs whatever implementation requires to "set" (write/add/append) given map of trusted checksums. * The passed in list of checksum algorithm factories and the map must have equal size and mapping must * contain all algorithm names in list. */ - void addTrustedArtifactChecksums( Artifact artifact, - ArtifactRepository artifactRepository, - List checksumAlgorithmFactories, - Map trustedArtifactChecksums ) throws IOException; + void addTrustedArtifactChecksums( + Artifact artifact, + ArtifactRepository artifactRepository, + List checksumAlgorithmFactories, + Map trustedArtifactChecksums) + throws IOException; } /** * Some trusted checksums sources may implement this optional method: ability to write/add checksums to them. * If source does not support this feature, method should return {@code null}. */ - Writer getTrustedArtifactChecksumsWriter( RepositorySystemSession session ); + Writer getTrustedArtifactChecksumsWriter(RepositorySystemSession session); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactDownload.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactDownload.java index 5c1fe7f1d..36eb4c03b 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactDownload.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactDownload.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector; import java.io.File; import java.util.Collection; @@ -35,9 +34,7 @@ * {@link #setException(ArtifactTransferException)} and {@link #setSupportedContexts(Collection)} (if applicable) to * report the results of the transfer. */ -public final class ArtifactDownload - extends ArtifactTransfer -{ +public final class ArtifactDownload extends ArtifactTransfer { private boolean existenceCheck; @@ -52,38 +49,34 @@ public final class ArtifactDownload /** * Creates a new uninitialized download. */ - public ArtifactDownload() - { + public ArtifactDownload() { // enables default constructor } /** * Creates a new download with the specified properties. - * + * * @param artifact The artifact to download, may be {@code null}. * @param context The context in which this download is performed, may be {@code null}. * @param file The local file to download the artifact to, may be {@code null}. * @param checksumPolicy The checksum policy, may be {@code null}. */ - public ArtifactDownload( Artifact artifact, String context, File file, String checksumPolicy ) - { - setArtifact( artifact ); - setRequestContext( context ); - setFile( file ); - setChecksumPolicy( checksumPolicy ); + public ArtifactDownload(Artifact artifact, String context, File file, String checksumPolicy) { + setArtifact(artifact); + setRequestContext(context); + setFile(file); + setChecksumPolicy(checksumPolicy); } @Override - public ArtifactDownload setArtifact( Artifact artifact ) - { - super.setArtifact( artifact ); + public ArtifactDownload setArtifact(Artifact artifact) { + super.setArtifact(artifact); return this; } @Override - public ArtifactDownload setFile( File file ) - { - super.setFile( file ); + public ArtifactDownload setFile(File file) { + super.setFile(file); return this; } @@ -93,70 +86,64 @@ public ArtifactDownload setFile( File file ) * non-existence of the artifact by associating an {@link org.eclipse.aether.transfer.ArtifactNotFoundException * ArtifactNotFoundException} with this download. Note: If an existence check is requested, * {@link #getFile()} may be {@code null}, i.e. the connector must not try to access the local file. - * + * * @return {@code true} if only the artifact existence shall be verified, {@code false} to actually download the * artifact. */ - public boolean isExistenceCheck() - { + public boolean isExistenceCheck() { return existenceCheck; } /** * Controls whether this transfer shall only verify the existence of the artifact in the remote repository rather * than actually downloading the file. - * + * * @param existenceCheck {@code true} if only the artifact existence shall be verified, {@code false} to actually * download the artifact. * @return This transfer for chaining, never {@code null}. */ - public ArtifactDownload setExistenceCheck( boolean existenceCheck ) - { + public ArtifactDownload setExistenceCheck(boolean existenceCheck) { this.existenceCheck = existenceCheck; return this; } /** * Gets the checksum policy for this transfer. - * + * * @return The checksum policy, never {@code null}. */ - public String getChecksumPolicy() - { + public String getChecksumPolicy() { return checksumPolicy; } /** * Sets the checksum policy for this transfer. - * + * * @param checksumPolicy The checksum policy, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - public ArtifactDownload setChecksumPolicy( String checksumPolicy ) - { - this.checksumPolicy = ( checksumPolicy != null ) ? checksumPolicy : ""; + public ArtifactDownload setChecksumPolicy(String checksumPolicy) { + this.checksumPolicy = (checksumPolicy != null) ? checksumPolicy : ""; return this; } /** * Gets the context of this transfer. - * + * * @return The context id, never {@code null}. */ - public String getRequestContext() - { + public String getRequestContext() { return context; } /** * Sets the context of this transfer. - * + * * @param context The context id, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - public ArtifactDownload setRequestContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public ArtifactDownload setRequestContext(String context) { + this.context = (context != null) ? context : ""; return this; } @@ -164,12 +151,11 @@ public ArtifactDownload setRequestContext( String context ) * Gets the set of request contexts in which the artifact is generally available. Repository managers can indicate * that an artifact is available in more than the requested context to avoid future remote trips for the same * artifact in a different context. - * + * * @return The set of requests context in which the artifact is available, never {@code null}. */ - public Collection getSupportedContexts() - { - return ( contexts != null ) ? contexts : Collections.singleton( context ); + public Collection getSupportedContexts() { + return (contexts != null) ? contexts : Collections.singleton(context); } /** @@ -177,18 +163,14 @@ public Collection getSupportedContexts() * that an artifact is available in more than the requested context to avoid future remote trips for the same * artifact in a different context. The set of supported contexts defaults to the original request context if not * overridden by the repository connector. - * + * * @param contexts The set of requests context in which the artifact is available, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - public ArtifactDownload setSupportedContexts( Collection contexts ) - { - if ( contexts == null || contexts.isEmpty() ) - { - this.contexts = Collections.singleton( context ); - } - else - { + public ArtifactDownload setSupportedContexts(Collection contexts) { + if (contexts == null || contexts.isEmpty()) { + this.contexts = Collections.singleton(context); + } else { this.contexts = contexts; } return this; @@ -197,59 +179,49 @@ public ArtifactDownload setSupportedContexts( Collection contexts ) /** * Gets the remote repositories that are being aggregated by the physically contacted remote repository (i.e. a * repository manager). - * + * * @return The remote repositories being aggregated, never {@code null}. */ - public List getRepositories() - { + public List getRepositories() { return repositories; } /** * Sets the remote repositories that are being aggregated by the physically contacted remote repository (i.e. a * repository manager). - * + * * @param repositories The remote repositories being aggregated, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - public ArtifactDownload setRepositories( List repositories ) - { - if ( repositories == null ) - { + public ArtifactDownload setRepositories(List repositories) { + if (repositories == null) { this.repositories = Collections.emptyList(); - } - else - { + } else { this.repositories = repositories; } return this; } @Override - public ArtifactDownload setException( ArtifactTransferException exception ) - { - super.setException( exception ); + public ArtifactDownload setException(ArtifactTransferException exception) { + super.setException(exception); return this; } @Override - public ArtifactDownload setListener( TransferListener listener ) - { - super.setListener( listener ); + public ArtifactDownload setListener(TransferListener listener) { + super.setListener(listener); return this; } @Override - public ArtifactDownload setTrace( RequestTrace trace ) - { - super.setTrace( trace ); + public ArtifactDownload setTrace(RequestTrace trace) { + super.setTrace(trace); return this; } @Override - public String toString() - { - return getArtifact() + " - " + ( isExistenceCheck() ? "?" : "" ) + getFile(); + public String toString() { + return getArtifact() + " - " + (isExistenceCheck() ? "?" : "") + getFile(); } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactTransfer.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactTransfer.java index 83995121e..979098b61 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactTransfer.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactTransfer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector; import java.io.File; @@ -26,12 +25,10 @@ /** * A download/upload of an artifact. - * + * * @noextend This class is not intended to be extended by clients. */ -public abstract class ArtifactTransfer - extends Transfer -{ +public abstract class ArtifactTransfer extends Transfer { private Artifact artifact; @@ -39,29 +36,26 @@ public abstract class ArtifactTransfer private ArtifactTransferException exception; - ArtifactTransfer() - { + ArtifactTransfer() { // hide } /** * Gets the artifact being transferred. - * + * * @return The artifact being transferred or {@code null} if not set. */ - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } /** * Sets the artifact to transfer. - * + * * @param artifact The artifact, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - public ArtifactTransfer setArtifact( Artifact artifact ) - { + public ArtifactTransfer setArtifact(Artifact artifact) { this.artifact = artifact; return this; } @@ -70,46 +64,41 @@ public ArtifactTransfer setArtifact( Artifact artifact ) * Gets the local file the artifact is downloaded to or uploaded from. In case of a download, a connector should * first transfer the bytes to a temporary file and only overwrite the target file once the entire download is * completed such that an interrupted/failed download does not corrupt the current file contents. - * + * * @return The local file or {@code null} if not set. */ - public File getFile() - { + public File getFile() { return file; } /** * Sets the local file the artifact is downloaded to or uploaded from. - * + * * @param file The local file, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - public ArtifactTransfer setFile( File file ) - { + public ArtifactTransfer setFile(File file) { this.file = file; return this; } /** * Gets the exception that occurred during the transfer (if any). - * + * * @return The exception or {@code null} if the transfer was successful. */ - public ArtifactTransferException getException() - { + public ArtifactTransferException getException() { return exception; } /** * Sets the exception that occurred during the transfer. - * + * * @param exception The exception, may be {@code null} to denote a successful transfer. * @return This transfer for chaining, never {@code null}. */ - public ArtifactTransfer setException( ArtifactTransferException exception ) - { + public ArtifactTransfer setException(ArtifactTransferException exception) { this.exception = exception; return this; } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactUpload.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactUpload.java index 90323b17d..8c1fa7950 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactUpload.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/ArtifactUpload.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector; import java.io.File; @@ -31,107 +30,89 @@ * An upload of an artifact to a remote repository. A repository connector processing this upload has to use * {@link #setException(ArtifactTransferException)} to report the results of the transfer. */ -public final class ArtifactUpload - extends ArtifactTransfer -{ +public final class ArtifactUpload extends ArtifactTransfer { private FileTransformer fileTransformer; /** * Creates a new uninitialized upload. */ - public ArtifactUpload() - { + public ArtifactUpload() { // enables default constructor } /** * Creates a new upload with the specified properties. - * + * * @param artifact The artifact to upload, may be {@code null}. * @param file The local file to upload the artifact from, may be {@code null}. */ - public ArtifactUpload( Artifact artifact, File file ) - { - setArtifact( artifact ); - setFile( file ); + public ArtifactUpload(Artifact artifact, File file) { + setArtifact(artifact); + setFile(file); } /** - *

    Creates a new upload with the specified properties.

    - * + *

    Creates a new upload with the specified properties.

    + * *

    IMPORTANT When using a fileTransformer, the * content of the file is stored in memory to ensure that file content and checksums stay in sync! *

    - * + * * @param artifact The artifact to upload, may be {@code null}. * @param file The local file to upload the artifact from, may be {@code null}. * @param fileTransformer The file transformer, may be {@code null}. */ - public ArtifactUpload( Artifact artifact, File file, FileTransformer fileTransformer ) - { - setArtifact( artifact ); - setFile( file ); - setFileTransformer( fileTransformer ); + public ArtifactUpload(Artifact artifact, File file, FileTransformer fileTransformer) { + setArtifact(artifact); + setFile(file); + setFileTransformer(fileTransformer); } @Override - public ArtifactUpload setArtifact( Artifact artifact ) - { - super.setArtifact( artifact ); + public ArtifactUpload setArtifact(Artifact artifact) { + super.setArtifact(artifact); return this; } @Override - public ArtifactUpload setFile( File file ) - { - super.setFile( file ); + public ArtifactUpload setFile(File file) { + super.setFile(file); return this; } @Override - public ArtifactUpload setException( ArtifactTransferException exception ) - { - super.setException( exception ); + public ArtifactUpload setException(ArtifactTransferException exception) { + super.setException(exception); return this; } @Override - public ArtifactUpload setListener( TransferListener listener ) - { - super.setListener( listener ); + public ArtifactUpload setListener(TransferListener listener) { + super.setListener(listener); return this; } @Override - public ArtifactUpload setTrace( RequestTrace trace ) - { - super.setTrace( trace ); + public ArtifactUpload setTrace(RequestTrace trace) { + super.setTrace(trace); return this; } - - public ArtifactUpload setFileTransformer( FileTransformer fileTransformer ) - { + + public ArtifactUpload setFileTransformer(FileTransformer fileTransformer) { this.fileTransformer = fileTransformer; return this; } - - public FileTransformer getFileTransformer() - { + + public FileTransformer getFileTransformer() { return fileTransformer; } @Override - public String toString() - { - if ( getFileTransformer() != null ) - { - return getArtifact() + " >>> " + getFileTransformer().transformArtifact( getArtifact() ) - + " - " + getFile(); - } - else - { + public String toString() { + if (getFileTransformer() != null) { + return getArtifact() + " >>> " + getFileTransformer().transformArtifact(getArtifact()) + " - " + getFile(); + } else { return getArtifact() + " - " + getFile(); } } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataDownload.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataDownload.java index be3a2d0d7..cc77497fe 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataDownload.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataDownload.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector; import java.io.File; import java.util.Collections; @@ -33,9 +32,7 @@ * A download of metadata from a remote repository. A repository connector processing this download has to use * {@link #setException(MetadataTransferException)} to report the results of the transfer. */ -public final class MetadataDownload - extends MetadataTransfer -{ +public final class MetadataDownload extends MetadataTransfer { private String checksumPolicy = ""; @@ -46,141 +43,123 @@ public final class MetadataDownload /** * Creates a new uninitialized download. */ - public MetadataDownload() - { + public MetadataDownload() { // enables default constructor } /** * Creates a new download with the specified properties. - * + * * @param metadata The metadata to download, may be {@code null}. * @param context The context in which this download is performed, may be {@code null}. * @param file The local file to download the metadata to, may be {@code null}. * @param checksumPolicy The checksum policy, may be {@code null}. */ - public MetadataDownload( Metadata metadata, String context, File file, String checksumPolicy ) - { - setMetadata( metadata ); - setFile( file ); - setChecksumPolicy( checksumPolicy ); - setRequestContext( context ); + public MetadataDownload(Metadata metadata, String context, File file, String checksumPolicy) { + setMetadata(metadata); + setFile(file); + setChecksumPolicy(checksumPolicy); + setRequestContext(context); } @Override - public MetadataDownload setMetadata( Metadata metadata ) - { - super.setMetadata( metadata ); + public MetadataDownload setMetadata(Metadata metadata) { + super.setMetadata(metadata); return this; } @Override - public MetadataDownload setFile( File file ) - { - super.setFile( file ); + public MetadataDownload setFile(File file) { + super.setFile(file); return this; } /** * Gets the checksum policy for this transfer. - * + * * @return The checksum policy, never {@code null}. */ - public String getChecksumPolicy() - { + public String getChecksumPolicy() { return checksumPolicy; } /** * Sets the checksum policy for this transfer. - * + * * @param checksumPolicy The checksum policy, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - public MetadataDownload setChecksumPolicy( String checksumPolicy ) - { - this.checksumPolicy = ( checksumPolicy != null ) ? checksumPolicy : ""; + public MetadataDownload setChecksumPolicy(String checksumPolicy) { + this.checksumPolicy = (checksumPolicy != null) ? checksumPolicy : ""; return this; } /** * Gets the context of this transfer. - * + * * @return The context id, never {@code null}. */ - public String getRequestContext() - { + public String getRequestContext() { return context; } /** * Sets the request context of this transfer. - * + * * @param context The context id, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - public MetadataDownload setRequestContext( String context ) - { - this.context = ( context != null ) ? context : ""; + public MetadataDownload setRequestContext(String context) { + this.context = (context != null) ? context : ""; return this; } /** * Gets the remote repositories that are being aggregated by the physically contacted remote repository (i.e. a * repository manager). - * + * * @return The remote repositories being aggregated, never {@code null}. */ - public List getRepositories() - { + public List getRepositories() { return repositories; } /** * Sets the remote repositories that are being aggregated by the physically contacted remote repository (i.e. a * repository manager). - * + * * @param repositories The remote repositories being aggregated, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - public MetadataDownload setRepositories( List repositories ) - { - if ( repositories == null ) - { + public MetadataDownload setRepositories(List repositories) { + if (repositories == null) { this.repositories = Collections.emptyList(); - } - else - { + } else { this.repositories = repositories; } return this; } @Override - public MetadataDownload setException( MetadataTransferException exception ) - { - super.setException( exception ); + public MetadataDownload setException(MetadataTransferException exception) { + super.setException(exception); return this; } @Override - public MetadataDownload setListener( TransferListener listener ) - { - super.setListener( listener ); + public MetadataDownload setListener(TransferListener listener) { + super.setListener(listener); return this; } @Override - public MetadataDownload setTrace( RequestTrace trace ) - { - super.setTrace( trace ); + public MetadataDownload setTrace(RequestTrace trace) { + super.setTrace(trace); return this; } @Override - public String toString() - { + public String toString() { return getMetadata() + " - " + getFile(); } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataTransfer.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataTransfer.java index 94eb46e79..b1be3fab2 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataTransfer.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataTransfer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector; import java.io.File; @@ -26,12 +25,10 @@ /** * A download/upload of metadata. - * + * * @noextend This class is not intended to be extended by clients. */ -public abstract class MetadataTransfer - extends Transfer -{ +public abstract class MetadataTransfer extends Transfer { private Metadata metadata; @@ -39,29 +36,26 @@ public abstract class MetadataTransfer private MetadataTransferException exception; - MetadataTransfer() - { + MetadataTransfer() { // hide } /** * Gets the metadata being transferred. - * + * * @return The metadata being transferred or {@code null} if not set. */ - public Metadata getMetadata() - { + public Metadata getMetadata() { return metadata; } /** * Sets the metadata to transfer. - * + * * @param metadata The metadata, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - public MetadataTransfer setMetadata( Metadata metadata ) - { + public MetadataTransfer setMetadata(Metadata metadata) { this.metadata = metadata; return this; } @@ -70,46 +64,41 @@ public MetadataTransfer setMetadata( Metadata metadata ) * Gets the local file the metadata is downloaded to or uploaded from. In case of a download, a connector should * first transfer the bytes to a temporary file and only overwrite the target file once the entire download is * completed such that an interrupted/failed download does not corrupt the current file contents. - * + * * @return The local file or {@code null} if not set. */ - public File getFile() - { + public File getFile() { return file; } /** * Sets the local file the metadata is downloaded to or uploaded from. - * + * * @param file The local file, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - public MetadataTransfer setFile( File file ) - { + public MetadataTransfer setFile(File file) { this.file = file; return this; } /** * Gets the exception that occurred during the transfer (if any). - * + * * @return The exception or {@code null} if the transfer was successful. */ - public MetadataTransferException getException() - { + public MetadataTransferException getException() { return exception; } /** * Sets the exception that occurred during the transfer. - * + * * @param exception The exception, may be {@code null} to denote a successful transfer. * @return This transfer for chaining, never {@code null}. */ - public MetadataTransfer setException( MetadataTransferException exception ) - { + public MetadataTransfer setException(MetadataTransferException exception) { this.exception = exception; return this; } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataUpload.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataUpload.java index d992757c7..d549f7ac6 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataUpload.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/MetadataUpload.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector; import java.io.File; @@ -30,69 +29,58 @@ * An upload of metadata to a remote repository. A repository connector processing this upload has to use * {@link #setException(MetadataTransferException)} to report the results of the transfer. */ -public final class MetadataUpload - extends MetadataTransfer -{ +public final class MetadataUpload extends MetadataTransfer { /** * Creates a new uninitialized upload. */ - public MetadataUpload() - { + public MetadataUpload() { // enables default constructor } /** * Creates a new upload with the specified properties. - * + * * @param metadata The metadata to upload, may be {@code null}. * @param file The local file to upload the metadata from, may be {@code null}. */ - public MetadataUpload( Metadata metadata, File file ) - { - setMetadata( metadata ); - setFile( file ); + public MetadataUpload(Metadata metadata, File file) { + setMetadata(metadata); + setFile(file); } @Override - public MetadataUpload setMetadata( Metadata metadata ) - { - super.setMetadata( metadata ); + public MetadataUpload setMetadata(Metadata metadata) { + super.setMetadata(metadata); return this; } @Override - public MetadataUpload setFile( File file ) - { - super.setFile( file ); + public MetadataUpload setFile(File file) { + super.setFile(file); return this; } @Override - public MetadataUpload setException( MetadataTransferException exception ) - { - super.setException( exception ); + public MetadataUpload setException(MetadataTransferException exception) { + super.setException(exception); return this; } @Override - public MetadataUpload setListener( TransferListener listener ) - { - super.setListener( listener ); + public MetadataUpload setListener(TransferListener listener) { + super.setListener(listener); return this; } @Override - public MetadataUpload setTrace( RequestTrace trace ) - { - super.setTrace( trace ); + public MetadataUpload setTrace(RequestTrace trace) { + super.setTrace(trace); return this; } @Override - public String toString() - { + public String toString() { return getMetadata() + " - " + getFile(); } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/RepositoryConnector.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/RepositoryConnector.java index 059262304..fee4a30c8 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/RepositoryConnector.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/RepositoryConnector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector; import java.io.Closeable; import java.util.Collection; @@ -34,14 +33,12 @@ *

    * Note: While a connector itself can use multiple threads internally to performs the transfers, * clients must not call a connector concurrently, i.e. connectors are generally not thread-safe. - * + * * @see org.eclipse.aether.spi.connector.transport.TransporterProvider * @see org.eclipse.aether.spi.connector.layout.RepositoryLayoutProvider * @see org.eclipse.aether.spi.connector.checksum.ChecksumPolicyProvider */ -public interface RepositoryConnector - extends Closeable -{ +public interface RepositoryConnector extends Closeable { /** * Performs the specified downloads. If a download fails, the connector stores the underlying exception in the @@ -49,24 +46,25 @@ public interface RepositoryConnector * {@link MetadataDownload#getException()}, respectively. If reasonable, a connector should continue to process the * remaining downloads after an error to retrieve as many items as possible. The connector may perform the transfers * concurrently and in any order. - * + * * @param artifactDownloads The artifact downloads to perform, may be {@code null} or empty. * @param metadataDownloads The metadata downloads to perform, may be {@code null} or empty. */ - void get( Collection artifactDownloads, - Collection metadataDownloads ); + void get( + Collection artifactDownloads, + Collection metadataDownloads); /** * Performs the specified uploads. If an upload fails, the connector stores the underlying exception in the upload * object such that callers can inspect the result via {@link ArtifactUpload#getException()} and * {@link MetadataUpload#getException()}, respectively. The connector may perform the transfers concurrently and in * any order. - * + * * @param artifactUploads The artifact uploads to perform, may be {@code null} or empty. * @param metadataUploads The metadata uploads to perform, may be {@code null} or empty. */ - void put( Collection artifactUploads, - Collection metadataUploads ); + void put( + Collection artifactUploads, Collection metadataUploads); /** * Closes this connector and frees any network resources associated with it. Once closed, a connector must not be @@ -74,5 +72,4 @@ void put( Collection artifactUploads, * an already closed connector is harmless and has no effect. */ void close(); - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/RepositoryConnectorFactory.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/RepositoryConnectorFactory.java index 0d401c448..3662b817a 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/RepositoryConnectorFactory.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/RepositoryConnectorFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; @@ -30,14 +29,13 @@ * {@link #newInstance(RepositorySystemSession, RemoteRepository)} on them. The first connector returned by a factory * will then be used for the transfer. */ -public interface RepositoryConnectorFactory -{ +public interface RepositoryConnectorFactory { /** * Tries to create a repository connector for the specified remote repository. Typically, a factory will inspect * {@link RemoteRepository#getProtocol()} and {@link RemoteRepository#getContentType()} to determine whether it can * handle a repository. - * + * * @param session The repository system session from which to configure the connector, must not be {@code null}. In * particular, a connector must notify any {@link RepositorySystemSession#getTransferListener()} set for * the session and should obey the timeouts configured for the session. @@ -46,15 +44,14 @@ public interface RepositoryConnectorFactory * @throws NoRepositoryConnectorException If the factory cannot create a connector for the specified remote * repository. */ - RepositoryConnector newInstance( RepositorySystemSession session, RemoteRepository repository ) - throws NoRepositoryConnectorException; + RepositoryConnector newInstance(RepositorySystemSession session, RemoteRepository repository) + throws NoRepositoryConnectorException; /** * The priority of this factory. When multiple factories can handle a given repository, factories with higher * priority are preferred over those with lower priority. - * + * * @return The priority of this factory. */ float getPriority(); - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/Transfer.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/Transfer.java index fc77011bc..6200ace20 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/Transfer.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/Transfer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,76 +16,70 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector; import org.eclipse.aether.RequestTrace; import org.eclipse.aether.transfer.TransferListener; /** * An artifact/metadata transfer. - * + * * @noextend This class is not intended to be extended by clients. */ -public abstract class Transfer -{ +public abstract class Transfer { private TransferListener listener; private RequestTrace trace; - Transfer() - { + Transfer() { // hide from public } /** * Gets the exception that occurred during the transfer (if any). - * + * * @return The exception or {@code null} if the transfer was successful. */ public abstract Exception getException(); /** * Gets the listener that is to be notified during the transfer. - * + * * @return The transfer listener or {@code null} if none. */ - public TransferListener getListener() - { + public TransferListener getListener() { return listener; } /** * Sets the listener that is to be notified during the transfer. - * + * * @param listener The transfer listener to notify, may be {@code null} if none. * @return This transfer for chaining, never {@code null}. */ - Transfer setListener( TransferListener listener ) - { + Transfer setListener(TransferListener listener) { this.listener = listener; return this; } /** * Gets the trace information that describes the higher level request/operation in which this transfer is issued. - * + * * @return The trace information about the higher level operation or {@code null} if none. */ - public RequestTrace getTrace() - { + public RequestTrace getTrace() { return trace; } /** * Sets the trace information that describes the higher level request/operation in which this transfer is issued. - * + * * @param trace The trace information about the higher level operation, may be {@code null}. * @return This transfer for chaining, never {@code null}. */ - Transfer setTrace( RequestTrace trace ) - { + Transfer setTrace(RequestTrace trace) { this.trace = trace; return this; } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithm.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithm.java index ade3c6212..19bfc225c 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithm.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithm.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.checksum; import java.nio.ByteBuffer; @@ -27,12 +26,11 @@ * * @since 1.8.0 */ -public interface ChecksumAlgorithm -{ +public interface ChecksumAlgorithm { /** * Updates the checksum algorithm inner state with input. */ - void update( ByteBuffer input ); + void update(ByteBuffer input); /** * Returns the algorithm end result as string, never {@code null}. After invoking this method, this instance should diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactory.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactory.java index f11f6c6e2..b517a52fb 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactory.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.checksum; /** * A component representing a checksum factory: provides {@link ChecksumAlgorithm} instances, name and extension to be @@ -26,8 +25,7 @@ * * @since 1.8.0 */ -public interface ChecksumAlgorithmFactory -{ +public interface ChecksumAlgorithmFactory { /** * Returns the algorithm name, usually used as key, never {@code null} value. The name is a standard name of * algorithm (if applicable) or any other designator that is algorithm commonly referred with. Example: "SHA-1". diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactorySelector.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactorySelector.java index 371357e2e..cc96ddabb 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactorySelector.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactorySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.checksum; import java.util.Collection; import java.util.List; @@ -31,14 +30,13 @@ * @noextend This interface is not intended to be extended by clients. * @since 1.8.0 */ -public interface ChecksumAlgorithmFactorySelector -{ +public interface ChecksumAlgorithmFactorySelector { /** * Returns factory for given algorithm name, or throws if algorithm not supported. * * @throws IllegalArgumentException if asked algorithm name is not supported. */ - ChecksumAlgorithmFactory select( String algorithmName ); + ChecksumAlgorithmFactory select(String algorithmName); /** * Returns a list of factories in same order as algorithm names are ordered, or throws if any of the @@ -49,7 +47,7 @@ public interface ChecksumAlgorithmFactorySelector * @throws NullPointerException if passed in list of names is {@code null}. * @since 1.9.0 */ - List selectList( Collection algorithmNames ); + List selectList(Collection algorithmNames); /** * Returns immutable collection of all supported algorithms. This set represents ALL the algorithms supported by @@ -66,5 +64,5 @@ public interface ChecksumAlgorithmFactorySelector * * @since 1.9.3 */ - boolean isChecksumExtension( String extension ); + boolean isChecksumExtension(String extension); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactorySupport.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactorySupport.java index 7fd398e60..0045451c7 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactorySupport.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmFactorySupport.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.checksum; import static java.util.Objects.requireNonNull; @@ -26,25 +25,21 @@ * * @since 1.8.0 */ -public abstract class ChecksumAlgorithmFactorySupport - implements ChecksumAlgorithmFactory -{ +public abstract class ChecksumAlgorithmFactorySupport implements ChecksumAlgorithmFactory { private final String name; private final String fileExtension; - public ChecksumAlgorithmFactorySupport( String name, String fileExtension ) - { - this.name = requireNonNull( name ); - this.fileExtension = requireNonNull( fileExtension ); + public ChecksumAlgorithmFactorySupport(String name, String fileExtension) { + this.name = requireNonNull(name); + this.fileExtension = requireNonNull(fileExtension); } /** * Returns the algorithm name, usually used as key, never {@code null} value. */ @Override - public String getName() - { + public String getName() { return name; } @@ -52,8 +47,7 @@ public String getName() * Returns the file extension to be used for given checksum algorithm (without leading dot), never {@code null}. */ @Override - public String getFileExtension() - { + public String getFileExtension() { return fileExtension; } } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmHelper.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmHelper.java index df4be0e7f..ebcc3131f 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmHelper.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumAlgorithmHelper.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.checksum; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; @@ -35,10 +34,8 @@ * * @since 1.8.0 */ -public final class ChecksumAlgorithmHelper -{ - private ChecksumAlgorithmHelper() - { +public final class ChecksumAlgorithmHelper { + private ChecksumAlgorithmHelper() { // nop } @@ -51,12 +48,10 @@ private ChecksumAlgorithmHelper() * calculate it, never {@code null}. * @throws IOException In case of any problem. */ - public static Map calculate( byte[] data, List factories ) - throws IOException - { - try ( InputStream inputStream = new ByteArrayInputStream( data ) ) - { - return calculate( inputStream, factories ); + public static Map calculate(byte[] data, List factories) + throws IOException { + try (InputStream inputStream = new ByteArrayInputStream(data)) { + return calculate(inputStream, factories); } } @@ -69,35 +64,29 @@ public static Map calculate( byte[] data, List calculate( File file, List factories ) - throws IOException - { - try ( InputStream inputStream = new BufferedInputStream( Files.newInputStream( file.toPath() ) ) ) - { - return calculate( inputStream, factories ); + public static Map calculate(File file, List factories) + throws IOException { + try (InputStream inputStream = new BufferedInputStream(Files.newInputStream(file.toPath()))) { + return calculate(inputStream, factories); } } - private static Map calculate( InputStream inputStream, List factories ) - throws IOException - { + private static Map calculate(InputStream inputStream, List factories) + throws IOException { LinkedHashMap algorithms = new LinkedHashMap<>(); - factories.forEach( f -> algorithms.put( f.getName(), f.getAlgorithm() ) ); - final byte[] buffer = new byte[ 1024 * 32 ]; - for ( ; ; ) - { - int read = inputStream.read( buffer ); - if ( read < 0 ) - { + factories.forEach(f -> algorithms.put(f.getName(), f.getAlgorithm())); + final byte[] buffer = new byte[1024 * 32]; + for (; ; ) { + int read = inputStream.read(buffer); + if (read < 0) { break; } - for ( ChecksumAlgorithm checksumAlgorithm : algorithms.values() ) - { - checksumAlgorithm.update( ByteBuffer.wrap( buffer, 0, read ) ); + for (ChecksumAlgorithm checksumAlgorithm : algorithms.values()) { + checksumAlgorithm.update(ByteBuffer.wrap(buffer, 0, read)); } } LinkedHashMap result = new LinkedHashMap<>(); - algorithms.forEach( ( k, v ) -> result.put( k, v.checksum() ) ); + algorithms.forEach((k, v) -> result.put(k, v.checksum())); return result; } } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumPolicy.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumPolicy.java index 065fe429c..056b6e538 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumPolicy.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumPolicy.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.checksum; import org.eclipse.aether.transfer.ChecksumFailureException; @@ -62,15 +61,13 @@ *

    * Checksum policies might be stateful and are generally not thread-safe. */ -public interface ChecksumPolicy -{ +public interface ChecksumPolicy { /** * Enum denoting origin of checksum. * * @since 1.8.0 */ - enum ChecksumKind - { + enum ChecksumKind { /** * Remote external kind of checksum are retrieved from remote doing extra transport round-trip (usually by * getting "file.jar.sha1" for corresponding "file.jar" file). This kind of checksum is part of layout, and @@ -103,7 +100,7 @@ enum ChecksumKind * @return {@code true} to accept the download as valid and stop further validation, {@code false} to continue * validation with the next checksum. */ - boolean onChecksumMatch( String algorithm, ChecksumKind kind ); + boolean onChecksumMatch(String algorithm, ChecksumKind kind); /** * Signals a mismatch between the locally computed checksum value and the checksum value declared by the remote @@ -116,7 +113,7 @@ enum ChecksumKind * @throws ChecksumFailureException If the checksum validation is to be failed. If the method returns normally, * validation continues with the next checksum. */ - void onChecksumMismatch( String algorithm, ChecksumKind kind, ChecksumFailureException exception ) + void onChecksumMismatch(String algorithm, ChecksumKind kind, ChecksumFailureException exception) throws ChecksumFailureException; /** @@ -129,7 +126,7 @@ void onChecksumMismatch( String algorithm, ChecksumKind kind, ChecksumFailureExc * @throws ChecksumFailureException If the checksum validation is to be failed. If the method returns normally, * validation continues with the next checksum. */ - void onChecksumError( String algorithm, ChecksumKind kind, ChecksumFailureException exception ) + void onChecksumError(String algorithm, ChecksumKind kind, ChecksumFailureException exception) throws ChecksumFailureException; /** @@ -138,8 +135,7 @@ void onChecksumError( String algorithm, ChecksumKind kind, ChecksumFailureExcept * @throws ChecksumFailureException If the checksum validation is to be failed. If the method returns normally, the * download is assumed to be valid. */ - void onNoMoreChecksums() - throws ChecksumFailureException; + void onNoMoreChecksums() throws ChecksumFailureException; /** * Signals that the download is being retried after a previously thrown {@link ChecksumFailureException} that is @@ -159,6 +155,5 @@ void onNoMoreChecksums() * @return {@code true} to accept the download nevertheless and let artifact resolution succeed, {@code false} to * reject the transferred file as unusable. */ - boolean onTransferChecksumFailure( ChecksumFailureException exception ); - + boolean onTransferChecksumFailure(ChecksumFailureException exception); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumPolicyProvider.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumPolicyProvider.java index f50230063..1e2c4837d 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumPolicyProvider.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ChecksumPolicyProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.checksum; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; @@ -25,34 +24,32 @@ /** * Assists repository connectors in applying checksum policies to downloaded resources. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface ChecksumPolicyProvider -{ +public interface ChecksumPolicyProvider { /** * Retrieves the checksum policy with the specified identifier for use on the given remote resource. - * + * * @param session The repository system session during which the request is made, must not be {@code null}. * @param repository The repository hosting the resource being transferred, must not be {@code null}. * @param resource The transfer resource on which the policy will be applied, must not be {@code null}. * @param policy The identifier of the policy to apply, must not be {@code null}. * @return The policy to apply or {@code null} if checksums should be ignored. */ - ChecksumPolicy newChecksumPolicy( RepositorySystemSession session, RemoteRepository repository, - TransferResource resource, String policy ); + ChecksumPolicy newChecksumPolicy( + RepositorySystemSession session, RemoteRepository repository, TransferResource resource, String policy); /** * Returns the least strict policy. A checksum policy is said to be less strict than another policy if it would * accept a downloaded resource in all cases where the other policy would reject the resource. - * + * * @param session The repository system session during which the request is made, must not be {@code null}. * @param policy1 A policy to compare, must not be {@code null}. * @param policy2 A policy to compare, must not be {@code null}. * @return The least strict policy among the two input policies. */ - String getEffectiveChecksumPolicy( RepositorySystemSession session, String policy1, String policy2 ); - + String getEffectiveChecksumPolicy(RepositorySystemSession session, String policy1, String policy2); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ProvidedChecksumsSource.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ProvidedChecksumsSource.java index 809fedee6..9f3323e03 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ProvidedChecksumsSource.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/ProvidedChecksumsSource.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.checksum; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.checksum; import java.util.List; import java.util.Map; @@ -31,8 +30,7 @@ * * @since 1.8.0 */ -public interface ProvidedChecksumsSource -{ +public interface ProvidedChecksumsSource { /** * May return the provided checksums (for given artifact transfer) from source other than remote repository, or * {@code null} if it have no checksums available for given transfer. Provided checksums are "opt-in" for @@ -47,7 +45,8 @@ public interface ProvidedChecksumsSource * @param checksumAlgorithmFactories The checksum algorithms that are expected. * @return Map of expected checksums, or {@code null}. */ - Map getProvidedArtifactChecksums( RepositorySystemSession session, - ArtifactDownload transfer, - List checksumAlgorithmFactories ); + Map getProvidedArtifactChecksums( + RepositorySystemSession session, + ArtifactDownload transfer, + List checksumAlgorithmFactories); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/package-info.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/package-info.java index 94d0653ea..e84bc856a 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/package-info.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/checksum/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -19,7 +19,6 @@ */ /** * The support infrastructure for repository connectors to apply checksum policies when validating the integrity of - * downloaded files. + * downloaded files. */ package org.eclipse.aether.spi.connector.checksum; - diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/filter/RemoteRepositoryFilter.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/filter/RemoteRepositoryFilter.java index b966609b8..9332a52f6 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/filter/RemoteRepositoryFilter.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/filter/RemoteRepositoryFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.filter; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.metadata.Metadata; @@ -29,13 +28,11 @@ * * @since 1.9.0 */ -public interface RemoteRepositoryFilter -{ +public interface RemoteRepositoryFilter { /** * The check result, is immutable. */ - interface Result - { + interface Result { /** * Returns {@code true} if accepted. */ @@ -54,7 +51,7 @@ interface Result * @param artifact The artifact, not {@code null}. * @return the result, never {@code null}. */ - Result acceptArtifact( RemoteRepository remoteRepository, Artifact artifact ); + Result acceptArtifact(RemoteRepository remoteRepository, Artifact artifact); /** * Decides should metadata be accepted from given remote repository. @@ -63,5 +60,5 @@ interface Result * @param metadata The artifact, not {@code null}. * @return the result, never {@code null}. */ - Result acceptMetadata( RemoteRepository remoteRepository, Metadata metadata ); + Result acceptMetadata(RemoteRepository remoteRepository, Metadata metadata); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/filter/RemoteRepositoryFilterSource.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/filter/RemoteRepositoryFilterSource.java index b457584e5..ad1adb52d 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/filter/RemoteRepositoryFilterSource.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/filter/RemoteRepositoryFilterSource.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.filter; import org.eclipse.aether.RepositorySystemSession; @@ -26,13 +25,12 @@ * * @since 1.9.0 */ -public interface RemoteRepositoryFilterSource -{ +public interface RemoteRepositoryFilterSource { /** * Provides the filter instance for given session, or {@code null} if this instance wants to abstain from * participating in filtering. * * @return The filter for given session or {@code null}. */ - RemoteRepositoryFilter getRemoteRepositoryFilter( RepositorySystemSession session ); + RemoteRepositoryFilter getRemoteRepositoryFilter(RepositorySystemSession session); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayout.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayout.java index 83b43528c..90069debf 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayout.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayout.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.layout; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,30 +16,29 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.layout; import java.net.URI; import java.util.List; -import static java.util.Objects.requireNonNull; - import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.metadata.Metadata; import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactory; +import static java.util.Objects.requireNonNull; + /** * The layout for a remote repository whose artifacts/metadata can be addressed via URIs. *

    * Note: Implementations must be stateless. */ -public interface RepositoryLayout -{ +public interface RepositoryLayout { /** * A descriptor for a checksum location. This descriptor simply associates the location of a checksum file with the * underlying checksum algorithm used to calculate/verify it. */ - final class ChecksumLocation - { + final class ChecksumLocation { private final URI location; private final ChecksumAlgorithmFactory checksumAlgorithmFactory; @@ -54,9 +51,8 @@ final class ChecksumLocation * null}. * @param checksumAlgorithmFactory The checksum type used to calculate the checksum, must not be {@code null}. */ - public ChecksumLocation( URI location, ChecksumAlgorithmFactory checksumAlgorithmFactory ) - { - verify( location, checksumAlgorithmFactory ); + public ChecksumLocation(URI location, ChecksumAlgorithmFactory checksumAlgorithmFactory) { + verify(location, checksumAlgorithmFactory); this.location = location; this.checksumAlgorithmFactory = checksumAlgorithmFactory; } @@ -72,29 +68,24 @@ public ChecksumLocation( URI location, ChecksumAlgorithmFactory checksumAlgorith * @param checksumAlgorithmFactory The algorithm used to calculate the checksum, must not be {@code null}. * @return The checksum file descriptor, never {@code null}. */ - public static ChecksumLocation forLocation( URI location, ChecksumAlgorithmFactory checksumAlgorithmFactory ) - { - verify( location, checksumAlgorithmFactory ); - if ( location.getRawQuery() != null ) - { - throw new IllegalArgumentException( "resource location must not have query parameters: " + location ); + public static ChecksumLocation forLocation(URI location, ChecksumAlgorithmFactory checksumAlgorithmFactory) { + verify(location, checksumAlgorithmFactory); + if (location.getRawQuery() != null) { + throw new IllegalArgumentException("resource location must not have query parameters: " + location); } - if ( location.getRawFragment() != null ) - { - throw new IllegalArgumentException( "resource location must not have a fragment: " + location ); + if (location.getRawFragment() != null) { + throw new IllegalArgumentException("resource location must not have a fragment: " + location); } - return new ChecksumLocation( URI.create( location + "." + checksumAlgorithmFactory.getFileExtension() ), - checksumAlgorithmFactory ); + return new ChecksumLocation( + URI.create(location + "." + checksumAlgorithmFactory.getFileExtension()), checksumAlgorithmFactory); } - private static void verify( URI location, ChecksumAlgorithmFactory checksumAlgorithmFactory ) - { - requireNonNull( location, "checksum location cannot be null" ); - if ( location.isAbsolute() ) - { - throw new IllegalArgumentException( "checksum location must be relative" ); + private static void verify(URI location, ChecksumAlgorithmFactory checksumAlgorithmFactory) { + requireNonNull(location, "checksum location cannot be null"); + if (location.isAbsolute()) { + throw new IllegalArgumentException("checksum location must be relative"); } - requireNonNull( checksumAlgorithmFactory, "checksum algorithm factory cannot be null" ); + requireNonNull(checksumAlgorithmFactory, "checksum algorithm factory cannot be null"); } /** @@ -102,8 +93,7 @@ private static void verify( URI location, ChecksumAlgorithmFactory checksumAlgor * * @return The checksum factory, never {@code null}. */ - public ChecksumAlgorithmFactory getChecksumAlgorithmFactory() - { + public ChecksumAlgorithmFactory getChecksumAlgorithmFactory() { return checksumAlgorithmFactory; } @@ -113,14 +103,12 @@ public ChecksumAlgorithmFactory getChecksumAlgorithmFactory() * * @return The relative URI to the checksum file, never {@code null}. */ - public URI getLocation() - { + public URI getLocation() { return location; } @Override - public String toString() - { + public String toString() { return location + " (" + checksumAlgorithmFactory.getName() + ")"; } } @@ -154,7 +142,7 @@ public String toString() * @see #getChecksumAlgorithmFactories() * @since 1.8.0 */ - boolean hasChecksums( Artifact artifact ); + boolean hasChecksums(Artifact artifact); /** * Gets the location within a remote repository where the specified artifact resides. The URI is relative to the @@ -165,7 +153,7 @@ public String toString() * uploaded. * @return The relative URI to the artifact, never {@code null}. */ - URI getLocation( Artifact artifact, boolean upload ); + URI getLocation(Artifact artifact, boolean upload); /** * Gets the location within a remote repository where the specified metadata resides. The URI is relative to the @@ -176,7 +164,7 @@ public String toString() * uploaded. * @return The relative URI to the metadata, never {@code null}. */ - URI getLocation( Metadata metadata, boolean upload ); + URI getLocation(Metadata metadata, boolean upload); /** * Gets the checksums files that a remote repository keeps to help detect data corruption during transfers of the @@ -190,7 +178,7 @@ public String toString() * @return The checksum files for the given artifact, possibly empty but never {@code null}. If empty, that means * that this layout does not provide checksums for given artifact. */ - List getChecksumLocations( Artifact artifact, boolean upload, URI location ); + List getChecksumLocations(Artifact artifact, boolean upload, URI location); /** * Gets the checksums files that a remote repository keeps to help detect data corruption during transfers of the @@ -204,6 +192,5 @@ public String toString() * @return The checksum files for the given metadata, possibly empty but never {@code null}. If empty, that means * that this layout does not provide checksums for given artifact. */ - List getChecksumLocations( Metadata metadata, boolean upload, URI location ); - + List getChecksumLocations(Metadata metadata, boolean upload, URI location); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayoutFactory.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayoutFactory.java index 8aa71d7ab..6d419cb72 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayoutFactory.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayoutFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.layout; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.layout; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; @@ -30,28 +29,26 @@ * {@link #newInstance(RepositorySystemSession, RemoteRepository)} on them. The first layout returned by a factory will * then be used for transferring artifacts/metadata. */ -public interface RepositoryLayoutFactory -{ +public interface RepositoryLayoutFactory { /** * Tries to create a repository layout for the specified remote repository. Typically, a factory will inspect * {@link RemoteRepository#getContentType()} to determine whether it can handle a repository. - * + * * @param session The repository system session from which to configure the layout, must not be {@code null}. * @param repository The remote repository to create a layout for, must not be {@code null}. * @return The layout for the given repository, never {@code null}. * @throws NoRepositoryLayoutException If the factory cannot create a repository layout for the specified remote * repository. */ - RepositoryLayout newInstance( RepositorySystemSession session, RemoteRepository repository ) - throws NoRepositoryLayoutException; + RepositoryLayout newInstance(RepositorySystemSession session, RemoteRepository repository) + throws NoRepositoryLayoutException; /** * The priority of this factory. When multiple factories can handle a given repository, factories with higher * priority are preferred over those with lower priority. - * + * * @return The priority of this factory. */ float getPriority(); - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayoutProvider.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayoutProvider.java index 5cdf53b1b..65f20d1ee 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayoutProvider.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/RepositoryLayoutProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.layout; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.layout; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; @@ -25,23 +24,21 @@ /** * Retrieves a repository layout from the installed layout factories. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface RepositoryLayoutProvider -{ +public interface RepositoryLayoutProvider { /** * Tries to retrieve a repository layout for the specified remote repository. - * + * * @param session The repository system session from which to configure the layout, must not be {@code null}. * @param repository The remote repository to create a layout for, must not be {@code null}. * @return The layout for the given repository, never {@code null}. * @throws NoRepositoryLayoutException If none of the installed layout factories can provide a repository layout for * the specified remote repository. */ - RepositoryLayout newRepositoryLayout( RepositorySystemSession session, RemoteRepository repository ) - throws NoRepositoryLayoutException; - + RepositoryLayout newRepositoryLayout(RepositorySystemSession session, RemoteRepository repository) + throws NoRepositoryLayoutException; } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/package-info.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/package-info.java index 2b36f7cd3..3f529bfe2 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/package-info.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/layout/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -20,7 +20,6 @@ /** * The contract to locate URI-based resources using custom repository layouts. By implementing a * {@link org.eclipse.aether.spi.connector.layout.RepositoryLayoutFactory} and registering it with the repository - * system, an application enables access to remote repositories that use new content types/layouts. + * system, an application enables access to remote repositories that use new content types/layouts. */ package org.eclipse.aether.spi.connector.layout; - diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/package-info.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/package-info.java index f31a2a8aa..cdf913385 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/package-info.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,10 +21,9 @@ * The contract to access artifacts/metadata in remote repositories. By implementing a * {@link org.eclipse.aether.spi.connector.RepositoryConnectorFactory} and registering it with the repository system, * an application can enable access to arbitrary remote repositories. It should be noted that a repository connector is - * powerful yet burdensome to implement. In many cases, implementing a - * {@link org.eclipse.aether.spi.connector.transport.TransporterFactory} or + * powerful yet burdensome to implement. In many cases, implementing a + * {@link org.eclipse.aether.spi.connector.transport.TransporterFactory} or * {@link org.eclipse.aether.spi.connector.layout.RepositoryLayoutFactory} will be sufficient and easier to access a * custom remote repository. */ package org.eclipse.aether.spi.connector; - diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/AbstractTransporter.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/AbstractTransporter.java index c8205f200..0c08bdffe 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/AbstractTransporter.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/AbstractTransporter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.transport; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.transport; import java.io.IOException; import java.io.InputStream; @@ -31,27 +30,22 @@ /** * A skeleton implementation for custom transporters. */ -public abstract class AbstractTransporter - implements Transporter -{ +public abstract class AbstractTransporter implements Transporter { private final AtomicBoolean closed; /** * Enables subclassing. */ - protected AbstractTransporter() - { + protected AbstractTransporter() { closed = new AtomicBoolean(); } - public void peek( PeekTask task ) - throws Exception - { - Objects.requireNonNull( task, "task cannot be null" ); + public void peek(PeekTask task) throws Exception { + Objects.requireNonNull(task, "task cannot be null"); - failIfClosed( task ); - implPeek( task ); + failIfClosed(task); + implPeek(task); } /** @@ -60,16 +54,13 @@ public void peek( PeekTask task ) * @param task The existence check to perform, must not be {@code null}. * @throws Exception If the existence of the specified resource could not be confirmed. */ - protected abstract void implPeek( PeekTask task ) - throws Exception; + protected abstract void implPeek(PeekTask task) throws Exception; - public void get( GetTask task ) - throws Exception - { - Objects.requireNonNull( task, "task cannot be null" ); + public void get(GetTask task) throws Exception { + Objects.requireNonNull(task, "task cannot be null"); - failIfClosed( task ); - implGet( task ); + failIfClosed(task); + implGet(task); } /** @@ -78,8 +69,7 @@ public void get( GetTask task ) * @param task The download to perform, must not be {@code null}. * @throws Exception If the transfer failed. */ - protected abstract void implGet( GetTask task ) - throws Exception; + protected abstract void implGet(GetTask task) throws Exception; /** * Performs stream-based I/O for the specified download task and notifies the configured transport listener. @@ -97,30 +87,23 @@ protected abstract void implGet( GetTask task ) * @throws IOException If the transfer encountered an I/O error. * @throws TransferCancelledException If the transfer was cancelled. */ - protected void utilGet( GetTask task, InputStream is, boolean close, long length, boolean resume ) - throws IOException, TransferCancelledException - { - try ( OutputStream os = task.newOutputStream( resume ) ) - { - task.getListener().transportStarted( resume ? task.getResumeOffset() : 0L, length ); - copy( os, is, task.getListener() ); - } - finally - { - if ( close ) - { + protected void utilGet(GetTask task, InputStream is, boolean close, long length, boolean resume) + throws IOException, TransferCancelledException { + try (OutputStream os = task.newOutputStream(resume)) { + task.getListener().transportStarted(resume ? task.getResumeOffset() : 0L, length); + copy(os, is, task.getListener()); + } finally { + if (close) { is.close(); } } } - public void put( PutTask task ) - throws Exception - { - Objects.requireNonNull( task, "task cannot be null" ); + public void put(PutTask task) throws Exception { + Objects.requireNonNull(task, "task cannot be null"); - failIfClosed( task ); - implPut( task ); + failIfClosed(task); + implPut(task); } /** @@ -129,8 +112,7 @@ public void put( PutTask task ) * @param task The upload to perform, must not be {@code null}. * @throws Exception If the transfer failed. */ - protected abstract void implPut( PutTask task ) - throws Exception; + protected abstract void implPut(PutTask task) throws Exception; /** * Performs stream-based I/O for the specified upload task and notifies the configured transport listener. @@ -144,31 +126,22 @@ protected abstract void implPut( PutTask task ) * @throws IOException If the transfer encountered an I/O error. * @throws TransferCancelledException If the transfer was cancelled. */ - protected void utilPut( PutTask task, OutputStream os, boolean close ) - throws IOException, TransferCancelledException - { - try ( InputStream is = task.newInputStream() ) - { - task.getListener().transportStarted( 0, task.getDataLength() ); - copy( os, is, task.getListener() ); - } - finally - { - if ( close ) - { + protected void utilPut(PutTask task, OutputStream os, boolean close) + throws IOException, TransferCancelledException { + try (InputStream is = task.newInputStream()) { + task.getListener().transportStarted(0, task.getDataLength()); + copy(os, is, task.getListener()); + } finally { + if (close) { os.close(); - } - else - { + } else { os.flush(); } } } - public void close() - { - if ( closed.compareAndSet( false, true ) ) - { + public void close() { + if (closed.compareAndSet(false, true)) { implClose(); } } @@ -178,23 +151,18 @@ public void close() */ protected abstract void implClose(); - private void failIfClosed( TransportTask task ) - { - if ( closed.get() ) - { - throw new IllegalStateException( "transporter closed, cannot execute task " + task ); + private void failIfClosed(TransportTask task) { + if (closed.get()) { + throw new IllegalStateException("transporter closed, cannot execute task " + task); } } - private static void copy( OutputStream os, InputStream is, TransportListener listener ) - throws IOException, TransferCancelledException - { - byte[] buffer = new byte[ 1024 * 32 ]; - for ( int read = is.read( buffer ); read >= 0; read = is.read( buffer ) ) - { - os.write( buffer, 0, read ); - listener.transportProgressed( ByteBuffer.wrap( buffer, 0, read ) ); + private static void copy(OutputStream os, InputStream is, TransportListener listener) + throws IOException, TransferCancelledException { + byte[] buffer = new byte[1024 * 32]; + for (int read = is.read(buffer); read >= 0; read = is.read(buffer)) { + os.write(buffer, 0, read); + listener.transportProgressed(ByteBuffer.wrap(buffer, 0, read)); } } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/GetTask.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/GetTask.java index 9d68dc01e..60d4d1594 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/GetTask.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/GetTask.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.transport; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.transport; import java.io.ByteArrayOutputStream; import java.io.File; @@ -36,9 +35,7 @@ * * @see Transporter#get(GetTask) */ -public final class GetTask - extends TransportTask -{ +public final class GetTask extends TransportTask { private File dataFile; @@ -50,61 +47,55 @@ public final class GetTask /** * Creates a new task for the specified remote resource. - * + * * @param location The relative location of the resource in the remote repository, must not be {@code null}. */ - public GetTask( URI location ) - { + public GetTask(URI location) { checksums = Collections.emptyMap(); - setLocation( location ); + setLocation(location); } /** * Opens an output stream to store the downloaded data. Depending on {@link #getDataFile()}, this stream writes * either to a file on disk or a growable buffer in memory. It's the responsibility of the caller to close the * provided stream. - * + * * @return The output stream for the data, never {@code null}. The stream is unbuffered. * @throws IOException If the stream could not be opened. */ - public OutputStream newOutputStream() - throws IOException - { - return newOutputStream( false ); + public OutputStream newOutputStream() throws IOException { + return newOutputStream(false); } /** * Opens an output stream to store the downloaded data. Depending on {@link #getDataFile()}, this stream writes * either to a file on disk or a growable buffer in memory. It's the responsibility of the caller to close the * provided stream. - * + * * @param resume {@code true} if the download resumes from the byte offset given by {@link #getResumeOffset()}, * {@code false} if the download starts at the first byte of the resource. * @return The output stream for the data, never {@code null}. The stream is unbuffered. * @throws IOException If the stream could not be opened. */ - public OutputStream newOutputStream( boolean resume ) - throws IOException - { - if ( dataFile != null ) - { - if ( this.resume && resume ) - { - return Files.newOutputStream( dataFile.toPath(), - StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND ); + public OutputStream newOutputStream(boolean resume) throws IOException { + if (dataFile != null) { + if (this.resume && resume) { + return Files.newOutputStream( + dataFile.toPath(), + StandardOpenOption.CREATE, + StandardOpenOption.WRITE, + StandardOpenOption.APPEND); + } else { + return Files.newOutputStream( + dataFile.toPath(), + StandardOpenOption.CREATE, + StandardOpenOption.WRITE, + StandardOpenOption.TRUNCATE_EXISTING); } - else - { - return Files.newOutputStream( dataFile.toPath(), - StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING ); - } - } - if ( dataBytes == null ) - { - dataBytes = new ByteArrayOutputStream( 1024 ); } - else if ( !resume ) - { + if (dataBytes == null) { + dataBytes = new ByteArrayOutputStream(1024); + } else if (!resume) { dataBytes.reset(); } return dataBytes; @@ -113,11 +104,10 @@ else if ( !resume ) /** * Gets the file (if any) where the downloaded data should be stored. If the specified file already exists, it will * be overwritten. - * + * * @return The data file or {@code null} if the data will be buffered in memory. */ - public File getDataFile() - { + public File getDataFile() { return dataFile; } @@ -125,13 +115,12 @@ public File getDataFile() * Sets the file where the downloaded data should be stored. If the specified file already exists, it will be * overwritten. Unless the caller can reasonably expect the resource to be small, use of a data file is strongly * recommended to avoid exhausting heap memory during the download. - * + * * @param dataFile The file to store the downloaded data, may be {@code null} to store the data in memory. * @return This task for chaining, never {@code null}. */ - public GetTask setDataFile( File dataFile ) - { - return setDataFile( dataFile, false ); + public GetTask setDataFile(File dataFile) { + return setDataFile(dataFile, false); } /** @@ -139,14 +128,13 @@ public GetTask setDataFile( File dataFile ) * overwritten or appended to, depending on the {@code resume} argument and the capabilities of the transporter. * Unless the caller can reasonably expect the resource to be small, use of a data file is strongly recommended to * avoid exhausting heap memory during the download. - * + * * @param dataFile The file to store the downloaded data, may be {@code null} to store the data in memory. * @param resume {@code true} to request resuming a previous download attempt, starting from the current length of * the data file, {@code false} to download the resource from its beginning. * @return This task for chaining, never {@code null}. */ - public GetTask setDataFile( File dataFile, boolean resume ) - { + public GetTask setDataFile(File dataFile, boolean resume) { this.dataFile = dataFile; this.resume = resume; return this; @@ -154,20 +142,16 @@ public GetTask setDataFile( File dataFile, boolean resume ) /** * Gets the byte offset within the resource from which the download should resume if supported. - * + * * @return The zero-based index of the first byte to download or {@code 0} for a full download from the start of the * resource, never negative. */ - public long getResumeOffset() - { - if ( resume ) - { - if ( dataFile != null ) - { + public long getResumeOffset() { + if (resume) { + if (dataFile != null) { return dataFile.length(); } - if ( dataBytes != null ) - { + if (dataBytes != null) { return dataBytes.size(); } } @@ -177,13 +161,11 @@ public long getResumeOffset() /** * Gets the data that was downloaded into memory. Note: This method may only be called if * {@link #getDataFile()} is {@code null} as otherwise the downloaded data has been written directly to disk. - * + * * @return The possibly empty data bytes, never {@code null}. */ - public byte[] getDataBytes() - { - if ( dataFile != null || dataBytes == null ) - { + public byte[] getDataBytes() { + if (dataFile != null || dataBytes == null) { return EMPTY; } return dataBytes.toByteArray(); @@ -193,16 +175,14 @@ public byte[] getDataBytes() * Gets the data that was downloaded into memory as a string. The downloaded data is assumed to be encoded using * UTF-8. Note: This method may only be called if {@link #getDataFile()} is {@code null} as * otherwise the downloaded data has been written directly to disk. - * + * * @return The possibly empty data string, never {@code null}. */ - public String getDataString() - { - if ( dataFile != null || dataBytes == null ) - { + public String getDataString() { + if (dataFile != null || dataBytes == null) { return ""; } - return new String( dataBytes.toByteArray(), StandardCharsets.UTF_8 ); + return new String(dataBytes.toByteArray(), StandardCharsets.UTF_8); } /** @@ -211,9 +191,8 @@ public String getDataString() * @param listener The listener to notify of progress, may be {@code null}. * @return This task for chaining, never {@code null}. */ - public GetTask setListener( TransportListener listener ) - { - super.setListener( listener ); + public GetTask setListener(TransportListener listener) { + super.setListener(listener); return this; } @@ -223,11 +202,10 @@ public GetTask setListener( TransportListener listener ) * data that a transporter may return if the underlying transport protocol provides metadata (e.g. HTTP headers) * along with the actual resource data. Checksums returned by this method have kind of * {@link org.eclipse.aether.spi.connector.checksum.ChecksumPolicy.ChecksumKind#REMOTE_INCLUDED}. - * + * * @return The (read-only) checksums advertised for the downloaded resource, possibly empty but never {@code null}. */ - public Map getChecksums() - { + public Map getChecksums() { return checksums; } @@ -235,35 +213,27 @@ public Map getChecksums() * Sets a checksum which the remote repository advertises for the resource. Note: Transporters should only * use this method to record checksum information which is readily available while performing the actual download, * they should not perform additional transfers to gather this data. - * + * * @param algorithm The name of the checksum algorithm (e.g. {@code "SHA-1"}, may be {@code null}. * @param value The hexadecimal representation of the checksum, may be {@code null}. * @return This task for chaining, never {@code null}. */ - public GetTask setChecksum( String algorithm, String value ) - { - if ( algorithm != null ) - { - if ( checksums.isEmpty() ) - { + public GetTask setChecksum(String algorithm, String value) { + if (algorithm != null) { + if (checksums.isEmpty()) { checksums = new HashMap<>(); } - if ( value != null && value.length() > 0 ) - { - checksums.put( algorithm, value ); - } - else - { - checksums.remove( algorithm ); + if (value != null && value.length() > 0) { + checksums.put(algorithm, value); + } else { + checksums.remove(algorithm); } } return this; } @Override - public String toString() - { + public String toString() { return "<< " + getLocation(); } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/PeekTask.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/PeekTask.java index d1fb9056d..00edc9f17 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/PeekTask.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/PeekTask.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.transport; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,33 +16,29 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.transport; import java.net.URI; /** * A task to check the existence of a resource in the remote repository. Note: The listener returned from * {@link #getListener()} is always a noop given that none of its event methods are relevant in context of this task. - * + * * @see Transporter#peek(PeekTask) */ -public final class PeekTask - extends TransportTask -{ +public final class PeekTask extends TransportTask { /** * Creates a new task for the specified remote resource. - * + * * @param location The relative location of the resource in the remote repository, must not be {@code null}. */ - public PeekTask( URI location ) - { - setLocation( location ); + public PeekTask(URI location) { + setLocation(location); } @Override - public String toString() - { + public String toString() { return "?? " + getLocation(); } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/PutTask.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/PutTask.java index 5ba659a5b..273ab1135 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/PutTask.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/PutTask.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.transport; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.transport; import java.io.ByteArrayInputStream; import java.io.File; @@ -32,9 +31,7 @@ * * @see Transporter#put(PutTask) */ -public final class PutTask - extends TransportTask -{ +public final class PutTask extends TransportTask { private File dataFile; @@ -42,40 +39,34 @@ public final class PutTask /** * Creates a new task for the specified remote resource. - * + * * @param location The relative location of the resource in the remote repository, must not be {@code null}. */ - public PutTask( URI location ) - { - setLocation( location ); + public PutTask(URI location) { + setLocation(location); } /** * Opens an input stream for the data to be uploaded. The length of the stream can be queried via * {@link #getDataLength()}. It's the responsibility of the caller to close the provided stream. - * + * * @return The input stream for the data, never {@code null}. The stream is unbuffered. * @throws IOException If the stream could not be opened. */ - public InputStream newInputStream() - throws IOException - { - if ( dataFile != null ) - { - return Files.newInputStream( dataFile.toPath() ); + public InputStream newInputStream() throws IOException { + if (dataFile != null) { + return Files.newInputStream(dataFile.toPath()); } - return new ByteArrayInputStream( dataBytes ); + return new ByteArrayInputStream(dataBytes); } /** * Gets the total number of bytes to be uploaded. - * + * * @return The total number of bytes to be uploaded. */ - public long getDataLength() - { - if ( dataFile != null ) - { + public long getDataLength() { + if (dataFile != null) { return dataFile.length(); } return dataBytes.length; @@ -83,23 +74,21 @@ public long getDataLength() /** * Gets the file (if any) with the data to be uploaded. - * + * * @return The data file or {@code null} if the data resides in memory. */ - public File getDataFile() - { + public File getDataFile() { return dataFile; } /** * Sets the file with the data to be uploaded. To upload some data residing already in memory, use * {@link #setDataString(String)} or {@link #setDataBytes(byte[])}. - * + * * @param dataFile The data file, may be {@code null} if the resource data is provided directly from memory. * @return This task for chaining, never {@code null}. */ - public PutTask setDataFile( File dataFile ) - { + public PutTask setDataFile(File dataFile) { this.dataFile = dataFile; dataBytes = EMPTY; return this; @@ -107,13 +96,12 @@ public PutTask setDataFile( File dataFile ) /** * Sets the binary data to be uploaded. - * + * * @param bytes The binary data, may be {@code null}. * @return This task for chaining, never {@code null}. */ - public PutTask setDataBytes( byte[] bytes ) - { - this.dataBytes = ( bytes != null ) ? bytes : EMPTY; + public PutTask setDataBytes(byte[] bytes) { + this.dataBytes = (bytes != null) ? bytes : EMPTY; dataFile = null; return this; } @@ -124,9 +112,8 @@ public PutTask setDataBytes( byte[] bytes ) * @param str The textual data, may be {@code null}. * @return This task for chaining, never {@code null}. */ - public PutTask setDataString( String str ) - { - return setDataBytes( ( str != null ) ? str.getBytes( StandardCharsets.UTF_8 ) : null ); + public PutTask setDataString(String str) { + return setDataBytes((str != null) ? str.getBytes(StandardCharsets.UTF_8) : null); } /** @@ -135,16 +122,13 @@ public PutTask setDataString( String str ) * @param listener The listener to notify of progress, may be {@code null}. * @return This task for chaining, never {@code null}. */ - public PutTask setListener( TransportListener listener ) - { - super.setListener( listener ); + public PutTask setListener(TransportListener listener) { + super.setListener(listener); return this; } @Override - public String toString() - { + public String toString() { return ">> " + getLocation(); } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransportListener.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransportListener.java index 473036b0a..b6e60645a 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransportListener.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransportListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.transport; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.transport; import java.nio.ByteBuffer; @@ -26,46 +25,36 @@ /** * A skeleton class for listeners used to monitor transport operations. Reusing common regular expression syntax, the * sequence of events is generally as follows: - * + * *

      * ( STARTED PROGRESSED* )*
      * 
    - * + * * The methods in this class do nothing. */ -public abstract class TransportListener -{ +public abstract class TransportListener { /** * Enables subclassing. */ - protected TransportListener() - { - } + protected TransportListener() {} /** * Notifies the listener about the start of the data transfer. This event may arise more than once if the transfer * needs to be restarted (e.g. after an authentication failure). - * + * * @param dataOffset The byte offset in the resource at which the transfer starts, must not be negative. * @param dataLength The total number of bytes in the resource or {@code -1} if the length is unknown. * @throws TransferCancelledException If the transfer should be aborted. */ - public void transportStarted( long dataOffset, long dataLength ) - throws TransferCancelledException - { - } + public void transportStarted(long dataOffset, long dataLength) throws TransferCancelledException {} /** * Notifies the listener about some progress in the data transfer. This event may even be fired if actually zero * bytes have been transferred since the last event, for instance to enable cancellation. - * + * * @param data The (read-only) buffer holding the bytes that have just been tranferred, must not be {@code null}. * @throws TransferCancelledException If the transfer should be aborted. */ - public void transportProgressed( ByteBuffer data ) - throws TransferCancelledException - { - } - + public void transportProgressed(ByteBuffer data) throws TransferCancelledException {} } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransportTask.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransportTask.java index 05525b108..22eb21f8f 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransportTask.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransportTask.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.transport; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.transport; import java.net.URI; + import static java.util.Objects.requireNonNull; /** @@ -27,12 +27,9 @@ * * @noextend This class is not intended to be extended by clients. */ -public abstract class TransportTask -{ +public abstract class TransportTask { - static final TransportListener NOOP = new TransportListener() - { - }; + static final TransportListener NOOP = new TransportListener() {}; static final byte[] EMPTY = {}; @@ -40,24 +37,21 @@ public abstract class TransportTask private TransportListener listener = NOOP; - TransportTask() - { + TransportTask() { // hide } /** * Gets the relative location of the affected resource in the remote repository. - * + * * @return The relative location of the resource, never {@code null}. */ - public URI getLocation() - { + public URI getLocation() { return location; } - TransportTask setLocation( URI location ) - { - this.location = requireNonNull( location, "location type cannot be null" ); + TransportTask setLocation(URI location) { + this.location = requireNonNull(location, "location type cannot be null"); return this; } @@ -66,21 +60,18 @@ TransportTask setLocation( URI location ) * * @return The listener to notify of progress, never {@code null}. */ - public TransportListener getListener() - { + public TransportListener getListener() { return listener; } /** * Sets the listener that is to be notified during the transfer. - * + * * @param listener The listener to notify of progress, may be {@code null}. * @return This task for chaining, never {@code null}. */ - TransportTask setListener( TransportListener listener ) - { - this.listener = ( listener != null ) ? listener : NOOP; + TransportTask setListener(TransportListener listener) { + this.listener = (listener != null) ? listener : NOOP; return this; } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/Transporter.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/Transporter.java index b8d221c05..cb790f87c 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/Transporter.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/Transporter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.transport; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.transport; import java.io.Closeable; @@ -33,14 +32,12 @@ * Note: Implementations must be thread-safe such that a given transporter instance can safely be used * for concurrent requests. */ -public interface Transporter - extends Closeable -{ +public interface Transporter extends Closeable { /** * Classification for exceptions that denote connectivity or authentication issues and any other kind of error that * is not mapped to another classification code. - * + * * @see #classify(Throwable) */ int ERROR_OTHER = 0; @@ -48,7 +45,7 @@ public interface Transporter /** * Classification for exceptions that denote a requested resource does not exist in the remote repository. Note that * cases where a remote repository is completely inaccessible should be classified as {@link #ERROR_OTHER}. - * + * * @see #classify(Throwable) */ int ERROR_NOT_FOUND = 1; @@ -57,42 +54,39 @@ public interface Transporter * Classifies the type of exception that has been thrown from a previous request to the transporter. The exception * types employed by a transporter are generally unknown to its caller. Where a caller needs to distinguish between * certain error cases, it employs this method to detect which error case corresponds to the exception. - * + * * @param error The exception to classify, must not be {@code null}. * @return The classification of the error, either {@link #ERROR_NOT_FOUND} or {@link #ERROR_OTHER}. */ - int classify( Throwable error ); + int classify(Throwable error); /** * Checks the existence of a resource in the repository. If the remote repository can be contacted successfully but * indicates the resource specified in the request does not exist, an exception is thrown such that invoking * {@link #classify(Throwable)} with that exception yields {@link #ERROR_NOT_FOUND}. - * + * * @param task The existence check to perform, must not be {@code null}. * @throws Exception If the existence of the specified resource could not be confirmed. */ - void peek( PeekTask task ) - throws Exception; + void peek(PeekTask task) throws Exception; /** * Downloads a resource from the repository. If the resource is downloaded to a file as given by * {@link GetTask#getDataFile()} and the operation fails midway, the transporter should not delete the partial file * but leave its management to the caller. - * + * * @param task The download to perform, must not be {@code null}. * @throws Exception If the transfer failed. */ - void get( GetTask task ) - throws Exception; + void get(GetTask task) throws Exception; /** * Uploads a resource to the repository. - * + * * @param task The upload to perform, must not be {@code null}. * @throws Exception If the transfer failed. */ - void put( PutTask task ) - throws Exception; + void put(PutTask task) throws Exception; /** * Closes this transporter and frees any network resources associated with it. Once closed, a transporter must not @@ -100,5 +94,4 @@ void put( PutTask task ) * Closing an already closed transporter is harmless and has no effect. */ void close(); - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransporterFactory.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransporterFactory.java index 999908af5..ca87a0c84 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransporterFactory.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransporterFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.transport; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.transport; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; @@ -30,28 +29,25 @@ * {@link #newInstance(RepositorySystemSession, RemoteRepository)} on them. The first transporter returned by a factory * will then be used for the transfer. */ -public interface TransporterFactory -{ +public interface TransporterFactory { /** * Tries to create a transporter for the specified remote repository. Typically, a factory will inspect * {@link RemoteRepository#getProtocol()} to determine whether it can handle a repository. - * + * * @param session The repository system session from which to configure the transporter, must not be {@code null}. * In particular, a transporter should obey the timeouts configured for the session. * @param repository The remote repository to create a transporter for, must not be {@code null}. * @return The transporter for the given repository, never {@code null}. * @throws NoTransporterException If the factory cannot create a transporter for the specified remote repository. */ - Transporter newInstance( RepositorySystemSession session, RemoteRepository repository ) - throws NoTransporterException; + Transporter newInstance(RepositorySystemSession session, RemoteRepository repository) throws NoTransporterException; /** * The priority of this factory. When multiple factories can handle a given repository, factories with higher * priority are preferred over those with lower priority. - * + * * @return The priority of this factory. */ float getPriority(); - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransporterProvider.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransporterProvider.java index b855042d9..e8d4b25a4 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransporterProvider.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/TransporterProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.transport; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.transport; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; @@ -25,23 +24,21 @@ /** * Retrieves a transporter from the installed transporter factories. - * + * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ -public interface TransporterProvider -{ +public interface TransporterProvider { /** * Tries to create a transporter for the specified remote repository. - * + * * @param session The repository system session from which to configure the transporter, must not be {@code null}. * @param repository The remote repository to create a transporter for, must not be {@code null}. * @return The transporter for the given repository, never {@code null}. * @throws NoTransporterException If none of the installed transporter factories can provide a transporter for the * specified remote repository. */ - Transporter newTransporter( RepositorySystemSession session, RemoteRepository repository ) - throws NoTransporterException; - + Transporter newTransporter(RepositorySystemSession session, RemoteRepository repository) + throws NoTransporterException; } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/package-info.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/package-info.java index 26796ba1f..e934a44f7 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/package-info.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/connector/transport/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -20,7 +20,6 @@ /** * The contract to download/upload URI-based resources using custom transport protocols. By implementing a * {@link org.eclipse.aether.spi.connector.transport.TransporterFactory} and registering it with the repository system, - * an application enables access to remote repositories that use new URI schemes. + * an application enables access to remote repositories that use new URI schemes. */ package org.eclipse.aether.spi.connector.transport; - diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/io/FileProcessor.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/io/FileProcessor.java index 0a84eb1e8..98a60658c 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/io/FileProcessor.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/io/FileProcessor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.io; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.io; import java.io.File; import java.io.IOException; @@ -27,89 +26,80 @@ /** * A utility component to perform file-based operations. */ -public interface FileProcessor -{ +public interface FileProcessor { /** * Creates the directory named by the given abstract pathname, including any necessary but nonexistent parent * directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent * directories. - * + * * @param directory The directory to create, may be {@code null}. * @return {@code true} if and only if the directory was created, along with all necessary parent directories; * {@code false} otherwise */ - boolean mkdirs( File directory ); + boolean mkdirs(File directory); /** * Writes the given data to a file. UTF-8 is assumed as encoding for the data. Creates the necessary directories for * the target file. In case of an error, the created directories will be left on the file system. - * + * * @param target The file to write to, must not be {@code null}. This file will be overwritten. * @param data The data to write, may be {@code null}. * @throws IOException If an I/O error occurs. */ - void write( File target, String data ) - throws IOException; + void write(File target, String data) throws IOException; /** * Writes the given stream to a file. Creates the necessary directories for the target file. In case of an error, * the created directories will be left on the file system. - * + * * @param target The file to write to, must not be {@code null}. This file will be overwritten. * @param source The stream to write to the file, must not be {@code null}. * @throws IOException If an I/O error occurs. */ - void write( File target, InputStream source ) - throws IOException; + void write(File target, InputStream source) throws IOException; /** * Moves the specified source file to the given target file. If the target file already exists, it is overwritten. * Creates the necessary directories for the target file. In case of an error, the created directories will be left * on the file system. - * + * * @param source The file to move from, must not be {@code null}. * @param target The file to move to, must not be {@code null}. * @throws IOException If an I/O error occurs. */ - void move( File source, File target ) - throws IOException; + void move(File source, File target) throws IOException; /** * Copies the specified source file to the given target file. Creates the necessary directories for the target file. * In case of an error, the created directories will be left on the file system. - * + * * @param source The file to copy from, must not be {@code null}. * @param target The file to copy to, must not be {@code null}. * @throws IOException If an I/O error occurs. */ - void copy( File source, File target ) - throws IOException; + void copy(File source, File target) throws IOException; /** * Copies the specified source file to the given target file. Creates the necessary directories for the target file. * In case of an error, the created directories will be left on the file system. - * + * * @param source The file to copy from, must not be {@code null}. * @param target The file to copy to, must not be {@code null}. * @param listener The listener to notify about the copy progress, may be {@code null}. * @return The number of copied bytes. * @throws IOException If an I/O error occurs. */ - long copy( File source, File target, ProgressListener listener ) - throws IOException; + long copy(File source, File target, ProgressListener listener) throws IOException; /** * A listener object that is notified for every progress made while copying files. - * + * * @see FileProcessor#copy(File, File, ProgressListener) */ - interface ProgressListener - { - - void progressed( ByteBuffer buffer ) - throws IOException; + interface ProgressListener { + void progressed(ByteBuffer buffer) throws IOException; } /** @@ -118,7 +108,7 @@ void progressed( ByteBuffer buffer ) * @throws IOException in case of any IO error. * @since 1.8.0 */ - String readChecksum( File checksumFile ) throws IOException; + String readChecksum(File checksumFile) throws IOException; /** * Writes checksum to specified file. @@ -126,6 +116,5 @@ void progressed( ByteBuffer buffer ) * @throws IOException in case of any IO error. * @since 1.8.0 */ - void writeChecksum( File checksumFile, String checksum ) throws IOException; - + void writeChecksum(File checksumFile, String checksum) throws IOException; } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/io/package-info.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/io/package-info.java index ec5c12214..1a4b0f6c6 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/io/package-info.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/io/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -18,7 +18,6 @@ * under the License. */ /** - * I/O related support infrastructure for components. + * I/O related support infrastructure for components. */ package org.eclipse.aether.spi.io; - diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/localrepo/LocalRepositoryManagerFactory.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/localrepo/LocalRepositoryManagerFactory.java index 518f90e2a..55830e87a 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/localrepo/LocalRepositoryManagerFactory.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/localrepo/LocalRepositoryManagerFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.localrepo; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.localrepo; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.LocalRepository; @@ -31,28 +30,26 @@ * {@link #newInstance(RepositorySystemSession, LocalRepository)} on them. The first manager returned by a factory will * then be used for the local repository. */ -public interface LocalRepositoryManagerFactory -{ +public interface LocalRepositoryManagerFactory { /** * Tries to create a repository manager for the specified local repository. The distinguishing property of a local * repository is its {@link LocalRepository#getContentType() type}, which may for example denote the used directory * structure. - * + * * @param session The repository system session from which to configure the manager, must not be {@code null}. * @param repository The local repository to create a manager for, must not be {@code null}. * @return The manager for the given repository, never {@code null}. * @throws NoLocalRepositoryManagerException If the factory cannot create a manager for the specified local * repository. */ - LocalRepositoryManager newInstance( RepositorySystemSession session, LocalRepository repository ) - throws NoLocalRepositoryManagerException; + LocalRepositoryManager newInstance(RepositorySystemSession session, LocalRepository repository) + throws NoLocalRepositoryManagerException; /** * The priority of this factory. Factories with higher priority are preferred over those with lower priority. - * + * * @return The priority of this factory. */ float getPriority(); - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/localrepo/package-info.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/localrepo/package-info.java index afd64cf2f..391097ed7 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/localrepo/package-info.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/localrepo/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -18,7 +18,6 @@ * under the License. */ /** - * The contract for custom local repository implementations. + * The contract for custom local repository implementations. */ package org.eclipse.aether.spi.localrepo; - diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/Service.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/Service.java index bbd6713fb..dcdf2c503 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/Service.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/Service.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.locator; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.locator; /** * A stateless component of the repository system. The primary purpose of this interface is to provide a convenient @@ -27,15 +26,13 @@ * @deprecated Use some out-of-the-box DI implementation instead. */ @Deprecated -public interface Service -{ +public interface Service { /** * Provides the opportunity to initialize this service and to acquire other services for its operation from the * locator. A service must not save the reference to the provided service locator. - * + * * @param locator The service locator, must not be {@code null}. */ - void initService( ServiceLocator locator ); - + void initService(ServiceLocator locator); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/ServiceLocator.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/ServiceLocator.java index bb376b6d6..5de51268a 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/ServiceLocator.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/ServiceLocator.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.locator; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.locator; import java.util.List; @@ -25,36 +24,34 @@ * A simple infrastructure to programmatically wire the various components of the repository system together when it is * used outside of an IoC container. Once a concrete implementation of a service locator has been setup, clients could * use - * + * *
      * RepositorySystem repoSystem = serviceLocator.getService( RepositorySystem.class );
      * 
    - * + * * to acquire the repository system. Components that implement {@link Service} will be given an opportunity to acquire * further components from the locator, thereby allowing to create the complete object graph of the repository system. * * @deprecated Use some out-of-the-box DI implementation instead. */ @Deprecated -public interface ServiceLocator -{ +public interface ServiceLocator { /** * Gets an instance of the specified service. - * + * * @param The service type. * @param type The interface describing the service, must not be {@code null}. * @return The service instance or {@code null} if the service could not be located/initialized. */ - T getService( Class type ); + T getService(Class type); /** * Gets all available instances of the specified service. - * + * * @param The service type. * @param type The interface describing the service, must not be {@code null}. * @return The (read-only) list of available service instances, never {@code null}. */ - List getServices( Class type ); - + List getServices(Class type); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/package-info.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/package-info.java index 32e48874d..e3d149387 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/package-info.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/locator/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -30,4 +30,3 @@ * @deprecated Use some out-of-the-box DI implementation instead. */ package org.eclipse.aether.spi.locator; - diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/Logger.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/Logger.java index dbe67782a..270e715d3 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/Logger.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/Logger.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.log; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.log; /** * A simple logger to facilitate emission of diagnostic messages. In general, unrecoverable errors should be reported @@ -27,8 +26,7 @@ * @deprecated Use SLF4J instead */ @Deprecated -public interface Logger -{ +public interface Logger { /** * Indicates whether debug logging is enabled. @@ -42,7 +40,7 @@ public interface Logger * * @param msg The message to log, must not be {@code null}. */ - void debug( String msg ); + void debug(String msg); /** * Emits the specified message along with a stack trace of the given exception. @@ -50,7 +48,7 @@ public interface Logger * @param msg The message to log, must not be {@code null}. * @param error The exception to log, may be {@code null}. */ - void debug( String msg, Throwable error ); + void debug(String msg, Throwable error); /** * Indicates whether warn logging is enabled. @@ -64,7 +62,7 @@ public interface Logger * * @param msg The message to log, must not be {@code null}. */ - void warn( String msg ); + void warn(String msg); /** * Emits the specified message along with a stack trace of the given exception. @@ -72,6 +70,5 @@ public interface Logger * @param msg The message to log, must not be {@code null}. * @param error The exception to log, may be {@code null}. */ - void warn( String msg, Throwable error ); - + void warn(String msg, Throwable error); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/LoggerFactory.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/LoggerFactory.java index 3258e04cb..d5beb56ab 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/LoggerFactory.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/LoggerFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.log; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.log; /** * A factory to create loggers. @@ -25,8 +24,7 @@ * @deprecated Use SLF4J instead */ @Deprecated -public interface LoggerFactory -{ +public interface LoggerFactory { /** * Gets a logger for a class with the specified name. @@ -34,6 +32,5 @@ public interface LoggerFactory * @param name The name of the class requesting a logger, must not be {@code null}. * @return The requested logger, never {@code null}. */ - Logger getLogger( String name ); - + Logger getLogger(String name); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/NullLogger.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/NullLogger.java index c1bacbac6..f3029a3b8 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/NullLogger.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/NullLogger.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.log; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.log; /** * A logger that disables any logging. @@ -25,34 +24,21 @@ * @deprecated Use SLF4J instead */ @Deprecated -final class NullLogger - implements Logger -{ +final class NullLogger implements Logger { - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return false; } - public void debug( String msg ) - { - } + public void debug(String msg) {} - public void debug( String msg, Throwable error ) - { - } + public void debug(String msg, Throwable error) {} - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return false; } - public void warn( String msg ) - { - } - - public void warn( String msg, Throwable error ) - { - } + public void warn(String msg) {} + public void warn(String msg, Throwable error) {} } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/NullLoggerFactory.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/NullLoggerFactory.java index 8bf8a242c..6e896fc4a 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/NullLoggerFactory.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/NullLoggerFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.log; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.log; /** * A logger factory that disables any logging. @@ -25,9 +24,7 @@ * @deprecated Use SLF4J instead */ @Deprecated -public final class NullLoggerFactory - implements LoggerFactory -{ +public final class NullLoggerFactory implements LoggerFactory { /** * The singleton instance of this factory. @@ -39,13 +36,11 @@ public final class NullLoggerFactory */ public static final Logger LOGGER = new NullLogger(); - public Logger getLogger( String name ) - { + public Logger getLogger(String name) { return LOGGER; } - private NullLoggerFactory() - { + private NullLoggerFactory() { // hide constructor } @@ -57,18 +52,14 @@ private NullLoggerFactory() * @param type The class for which to get the logger, must not be {@code null}. * @return The requested logger, never {@code null}. */ - public static Logger getSafeLogger( LoggerFactory loggerFactory, Class type ) - { - if ( loggerFactory == null ) - { + public static Logger getSafeLogger(LoggerFactory loggerFactory, Class type) { + if (loggerFactory == null) { return LOGGER; } - Logger logger = loggerFactory.getLogger( type.getName() ); - if ( logger == null ) - { + Logger logger = loggerFactory.getLogger(type.getName()); + if (logger == null) { return LOGGER; } return logger; } - } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/package-info.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/package-info.java index 9584292b9..84ed6c621 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/package-info.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/log/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -22,7 +22,6 @@ * {@link org.eclipse.aether.spi.log.LoggerFactory} defined here is to avoid a mandatory dependency on a 3rd party * logging system/facade. Some applications might find the events fired by the repository system sufficient and prefer * a small footprint. Components that do not share this concern are free to ignore this package and directly employ - * whatever logging system they desire. + * whatever logging system they desire. */ package org.eclipse.aether.spi.log; - diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/resolution/ArtifactResolverPostProcessor.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/resolution/ArtifactResolverPostProcessor.java index 5e90df606..919ecd517 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/resolution/ArtifactResolverPostProcessor.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/resolution/ArtifactResolverPostProcessor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.resolution; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.resolution; import java.util.List; @@ -31,8 +30,7 @@ * * @since 1.9.0 */ -public interface ArtifactResolverPostProcessor -{ +public interface ArtifactResolverPostProcessor { /** * Receives resolver results just before it would return it to caller. Is able to generate "resolution failure" * by augmenting passed in {@link ArtifactResult}s (artifacts should be "unresolved" and exceptions added). @@ -43,5 +41,5 @@ public interface ArtifactResolverPostProcessor * The implementations must be aware that this call may be "hot", so it directly affects the performance of * resolver in general. */ - void postProcess( RepositorySystemSession session, List artifactResults ); + void postProcess(RepositorySystemSession session, List artifactResults); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/synccontext/SyncContextFactory.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/synccontext/SyncContextFactory.java index bb2628209..8de4e3ab0 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/synccontext/SyncContextFactory.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/synccontext/SyncContextFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.synccontext; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.synccontext; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; @@ -27,18 +26,16 @@ * A factory to create synchronization contexts. A synchronization context is used to coordinate concurrent access to * artifacts or metadata. */ -public interface SyncContextFactory -{ +public interface SyncContextFactory { /** * Creates a new synchronization context. - * + * * @param session The repository session during which the context will be used, must not be {@code null}. * @param shared A flag indicating whether access to the artifacts/metadata associated with the new context can be * shared among concurrent readers or whether access needs to be exclusive to the calling thread. * @return The synchronization context, never {@code null}. * @see RepositorySystem#newSyncContext(RepositorySystemSession, boolean) */ - SyncContext newInstance( RepositorySystemSession session, boolean shared ); - + SyncContext newInstance(RepositorySystemSession session, boolean shared); } diff --git a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/synccontext/package-info.java b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/synccontext/package-info.java index 268aa3caa..96dd5f788 100644 --- a/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/synccontext/package-info.java +++ b/maven-resolver-spi/src/main/java/org/eclipse/aether/spi/synccontext/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * The contract for synchronization context implementations. */ package org.eclipse.aether.spi.synccontext; - diff --git a/maven-resolver-spi/src/test/java/org/eclipse/aether/spi/connector/layout/ChecksumLocationTest.java b/maven-resolver-spi/src/test/java/org/eclipse/aether/spi/connector/layout/ChecksumLocationTest.java index c8b53fa9e..73b746ce9 100644 --- a/maven-resolver-spi/src/test/java/org/eclipse/aether/spi/connector/layout/ChecksumLocationTest.java +++ b/maven-resolver-spi/src/test/java/org/eclipse/aether/spi/connector/layout/ChecksumLocationTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.spi.connector.layout; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,20 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.spi.connector.layout; import java.net.URI; import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithm; import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactory; import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmFactorySupport; -import org.junit.Test; - import org.eclipse.aether.spi.connector.layout.RepositoryLayout.ChecksumLocation; +import org.junit.Test; import static org.junit.Assert.assertEquals; -public class ChecksumLocationTest -{ +public class ChecksumLocationTest { private ChecksumAlgorithmFactory SHA512 = new ChecksumAlgorithmFactorySupport("SHA-512", "sha512") { @Override public ChecksumAlgorithm getAlgorithm() { @@ -61,35 +58,31 @@ public ChecksumAlgorithm getAlgorithm() { }; @Test - public void testForLocation() - { - ChecksumLocation cs = ChecksumLocation.forLocation( URI.create( "dir/sub%20dir/file.txt" ), SHA512 ); - assertEquals( SHA512, cs.getChecksumAlgorithmFactory() ); - assertEquals( "dir/sub%20dir/file.txt.sha512", cs.getLocation().toString() ); - - cs = ChecksumLocation.forLocation( URI.create( "dir/sub%20dir/file.txt" ), SHA256 ); - assertEquals( SHA256, cs.getChecksumAlgorithmFactory() ); - assertEquals( "dir/sub%20dir/file.txt.sha256", cs.getLocation().toString() ); - - cs = ChecksumLocation.forLocation( URI.create( "dir/sub%20dir/file.txt" ), SHA1 ); - assertEquals( SHA1, cs.getChecksumAlgorithmFactory() ); - assertEquals( "dir/sub%20dir/file.txt.sha1", cs.getLocation().toString() ); - - cs = ChecksumLocation.forLocation( URI.create( "dir/sub%20dir/file.txt" ), MD5 ); - assertEquals( MD5, cs.getChecksumAlgorithmFactory() ); - assertEquals( "dir/sub%20dir/file.txt.md5", cs.getLocation().toString() ); + public void testForLocation() { + ChecksumLocation cs = ChecksumLocation.forLocation(URI.create("dir/sub%20dir/file.txt"), SHA512); + assertEquals(SHA512, cs.getChecksumAlgorithmFactory()); + assertEquals("dir/sub%20dir/file.txt.sha512", cs.getLocation().toString()); + + cs = ChecksumLocation.forLocation(URI.create("dir/sub%20dir/file.txt"), SHA256); + assertEquals(SHA256, cs.getChecksumAlgorithmFactory()); + assertEquals("dir/sub%20dir/file.txt.sha256", cs.getLocation().toString()); + + cs = ChecksumLocation.forLocation(URI.create("dir/sub%20dir/file.txt"), SHA1); + assertEquals(SHA1, cs.getChecksumAlgorithmFactory()); + assertEquals("dir/sub%20dir/file.txt.sha1", cs.getLocation().toString()); + + cs = ChecksumLocation.forLocation(URI.create("dir/sub%20dir/file.txt"), MD5); + assertEquals(MD5, cs.getChecksumAlgorithmFactory()); + assertEquals("dir/sub%20dir/file.txt.md5", cs.getLocation().toString()); } - @Test( expected = IllegalArgumentException.class ) - public void testForLocation_WithQueryParams() - { - ChecksumLocation.forLocation( URI.create( "file.php?param=1" ), SHA1 ); + @Test(expected = IllegalArgumentException.class) + public void testForLocation_WithQueryParams() { + ChecksumLocation.forLocation(URI.create("file.php?param=1"), SHA1); } - @Test( expected = IllegalArgumentException.class ) - public void testForLocation_WithFragment() - { - ChecksumLocation.forLocation( URI.create( "file.html#fragment" ), SHA1 ); + @Test(expected = IllegalArgumentException.class) + public void testForLocation_WithFragment() { + ChecksumLocation.forLocation(URI.create("file.html#fragment"), SHA1); } - } diff --git a/maven-resolver-test-util/pom.xml b/maven-resolver-test-util/pom.xml index 703cbd1fa..a3f5c3131 100644 --- a/maven-resolver-test-util/pom.xml +++ b/maven-resolver-test-util/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-test-util Maven Artifact Resolver Test Utilities - - A collection of utility classes to ease testing of the repository system. - + A collection of utility classes to ease testing of the repository system. org.apache.maven.resolver.testutil diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/ArtifactDefinition.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/ArtifactDefinition.java index 00dac9293..5d192f1d4 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/ArtifactDefinition.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/ArtifactDefinition.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,9 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; -class ArtifactDefinition -{ +class ArtifactDefinition { private String groupId; private String artifactId; @@ -39,102 +37,81 @@ class ArtifactDefinition private Boolean optional; - ArtifactDefinition( String def ) - { + ArtifactDefinition(String def) { this.definition = def.trim(); - if ( definition.startsWith( "(" ) ) - { - int idx = definition.indexOf( ')' ); - this.id = definition.substring( 1, idx ); - this.definition = definition.substring( idx + 1 ); - } - else if ( definition.startsWith( "^" ) ) - { - this.reference = definition.substring( 1 ); + if (definition.startsWith("(")) { + int idx = definition.indexOf(')'); + this.id = definition.substring(1, idx); + this.definition = definition.substring(idx + 1); + } else if (definition.startsWith("^")) { + this.reference = definition.substring(1); return; } - String[] split = definition.split( ":" ); - if ( split.length < 4 ) - { - throw new IllegalArgumentException( "Need definition like 'gid:aid:ext:ver[:scope]', but was: " - + definition ); + String[] split = definition.split(":"); + if (split.length < 4) { + throw new IllegalArgumentException( + "Need definition like 'gid:aid:ext:ver[:scope]', but was: " + definition); } groupId = split[0]; artifactId = split[1]; extension = split[2]; version = split[3]; - if ( split.length > 4 ) - { + if (split.length > 4) { scope = split[4]; } - if ( split.length > 5 ) - { - if ( "optional".equalsIgnoreCase( split[5] ) ) - { + if (split.length > 5) { + if ("optional".equalsIgnoreCase(split[5])) { optional = true; - } - else if ( "!optional".equalsIgnoreCase( split[5] ) ) - { + } else if ("!optional".equalsIgnoreCase(split[5])) { optional = false; } } } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public String getExtension() - { + public String getExtension() { return extension; } - public String getVersion() - { + public String getVersion() { return version; } - public String getScope() - { + public String getScope() { return scope; } @Override - public String toString() - { + public String toString() { return definition; } - public String getId() - { + public String getId() { return id; } - public String getReference() - { + public String getReference() { return reference; } - public boolean isReference() - { + public boolean isReference() { return reference != null; } - public boolean hasId() - { + public boolean hasId() { return id != null; } - public Boolean getOptional() - { + public Boolean getOptional() { return optional; } } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/ArtifactDescription.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/ArtifactDescription.java index 5c1f530e4..1ecb795e3 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/ArtifactDescription.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/ArtifactDescription.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.util.List; @@ -27,8 +26,7 @@ /** */ -class ArtifactDescription -{ +class ArtifactDescription { private final List repositories; @@ -38,33 +36,30 @@ class ArtifactDescription private final Artifact relocation; - ArtifactDescription( Artifact relocation, List dependencies, List managedDependencies, - List repositories ) - { + ArtifactDescription( + Artifact relocation, + List dependencies, + List managedDependencies, + List repositories) { this.relocation = relocation; this.dependencies = dependencies; this.managedDependencies = managedDependencies; this.repositories = repositories; } - public Artifact getRelocation() - { + public Artifact getRelocation() { return relocation; } - public List getRepositories() - { + public List getRepositories() { return repositories; } - public List getManagedDependencies() - { + public List getManagedDependencies() { return managedDependencies; } - public List getDependencies() - { + public List getDependencies() { return dependencies; } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/DependencyGraphParser.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/DependencyGraphParser.java index 09b048912..237d75da4 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/DependencyGraphParser.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/DependencyGraphParser.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.io.BufferedReader; import java.io.IOException; @@ -46,7 +45,7 @@ /** * Creates a dependency graph from a text description.

    Definition

    Each (non-empty) line in the input defines * one node of the resulting graph: - * + * *
      * line      ::= (indent? ("(null)" | node | reference))? comment?
      * comment   ::= "#" rest-of-line
    @@ -56,7 +55,7 @@
      *                  ("relocations=" coords ("," coords)*)? ("(" id ")")?
      * coords    ::= groupId ":" artifactId (":" extension (":" classifier)?)? ":" version
      * 
    - * + * * The special token {@code (null)} may be used to indicate an "empty" root node with no dependency. *

    * If {@code indent} is empty, the line defines the root node. Only one root node may be defined. The level is @@ -65,7 +64,7 @@ * The {@code ^id} syntax allows to reuse a previously built node to share common sub graphs among different parent * nodes. *

    Example

    - * + * *
      * gid:aid:ver
      * +- gid:aid2:ver scope
    @@ -73,7 +72,7 @@
      * +- gid:aid4:ext:ver scope
      * \- ^id1                            # reuse previous node
      * 
    - * + * *

    Multiple definitions in one resource

    *

    * By using {@link #parseMultiResource(String)}, definitions divided by a line beginning with "---" can be read from the @@ -84,17 +83,16 @@ * {@link #DependencyGraphParser(String, Collection)}). Every '%s' in the definition will be substituted by the next * String in the defined substitutions. *

    Example

    - * + * *
      * parser.setSubstitutions( "foo", "bar" );
      * String def = "gid:%s:ext:ver\n" + "+- gid:%s:ext:ver";
      * 
    - * + * * The first node will have "foo" as its artifact id, the second node (child to the first) will have "bar" as its * artifact id. */ -public class DependencyGraphParser -{ +public class DependencyGraphParser { private final VersionScheme versionScheme; @@ -104,11 +102,10 @@ public class DependencyGraphParser /** * Create a parser with the given prefix and the given substitution strings. - * + * * @see DependencyGraphParser#parseResource(String) */ - public DependencyGraphParser( String prefix, Collection substitutions ) - { + public DependencyGraphParser(String prefix, Collection substitutions) { this.prefix = prefix; this.substitutions = substitutions; versionScheme = new TestVersionScheme(); @@ -116,30 +113,26 @@ public DependencyGraphParser( String prefix, Collection substitutions ) /** * Create a parser with the given prefix. - * + * * @see DependencyGraphParser#parseResource(String) */ - public DependencyGraphParser( String prefix ) - { - this( prefix, Collections.emptyList() ); + public DependencyGraphParser(String prefix) { + this(prefix, Collections.emptyList()); } /** * Create a parser with an empty prefix. */ - public DependencyGraphParser() - { - this( "" ); + public DependencyGraphParser() { + this(""); } /** * Parse the given graph definition. */ - public DependencyNode parseLiteral( String dependencyGraph ) - throws IOException - { - BufferedReader reader = new BufferedReader( new StringReader( dependencyGraph ) ); - DependencyNode node = parse( reader ); + public DependencyNode parseLiteral(String dependencyGraph) throws IOException { + BufferedReader reader = new BufferedReader(new StringReader(dependencyGraph)); + DependencyNode node = parse(reader); reader.close(); return node; } @@ -148,36 +141,29 @@ public DependencyNode parseLiteral( String dependencyGraph ) * Parse the graph definition read from the given classpath resource. If a prefix is set, this method will load the * resource from 'prefix + resource'. */ - public DependencyNode parseResource( String resource ) - throws IOException - { - URL res = this.getClass().getClassLoader().getResource( prefix + resource ); - if ( res == null ) - { - throw new IOException( "Could not find classpath resource " + prefix + resource ); + public DependencyNode parseResource(String resource) throws IOException { + URL res = this.getClass().getClassLoader().getResource(prefix + resource); + if (res == null) { + throw new IOException("Could not find classpath resource " + prefix + resource); } - return parse( res ); + return parse(res); } /** * Parse multiple graphs in one resource, divided by "---". */ - public List parseMultiResource( String resource ) - throws IOException - { - URL res = this.getClass().getClassLoader().getResource( prefix + resource ); - if ( res == null ) - { - throw new IOException( "Could not find classpath resource " + prefix + resource ); + public List parseMultiResource(String resource) throws IOException { + URL res = this.getClass().getClassLoader().getResource(prefix + resource); + if (res == null) { + throw new IOException("Could not find classpath resource " + prefix + resource); } - BufferedReader reader = new BufferedReader( new InputStreamReader( res.openStream(), StandardCharsets.UTF_8 ) ); + BufferedReader reader = new BufferedReader(new InputStreamReader(res.openStream(), StandardCharsets.UTF_8)); List ret = new ArrayList<>(); DependencyNode root = null; - while ( ( root = parse( reader ) ) != null ) - { - ret.add( root ); + while ((root = parse(reader)) != null) { + ret.add(root); } return ret; } @@ -185,36 +171,25 @@ public List parseMultiResource( String resource ) /** * Parse the graph definition read from the given URL. */ - public DependencyNode parse( URL resource ) - throws IOException - { + public DependencyNode parse(URL resource) throws IOException { BufferedReader reader = null; - try - { - reader = new BufferedReader( new InputStreamReader( resource.openStream(), StandardCharsets.UTF_8 ) ); - return parse( reader ); - } - finally - { - try - { - if ( reader != null ) - { + try { + reader = new BufferedReader(new InputStreamReader(resource.openStream(), StandardCharsets.UTF_8)); + return parse(reader); + } finally { + try { + if (reader != null) { reader.close(); reader = null; } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } } - private DependencyNode parse( BufferedReader in ) - throws IOException - { - Iterator substitutionIterator = ( substitutions != null ) ? substitutions.iterator() : null; + private DependencyNode parse(BufferedReader in) throws IOException { + Iterator substitutionIterator = (substitutions != null) ? substitutions.iterator() : null; String line = null; @@ -226,71 +201,58 @@ private DependencyNode parse( BufferedReader in ) LinkedList stack = new LinkedList<>(); boolean isRootNode = true; - while ( ( line = in.readLine() ) != null ) - { - line = cutComment( line ); + while ((line = in.readLine()) != null) { + line = cutComment(line); - if ( isEmpty( line ) ) - { + if (isEmpty(line)) { // skip empty line continue; } - if ( isEOFMarker( line ) ) - { + if (isEOFMarker(line)) { // stop parsing break; } - while ( line.contains( "%s" ) ) - { - if ( !substitutionIterator.hasNext() ) - { - throw new IllegalStateException( "not enough substitutions to fill placeholders" ); + while (line.contains("%s")) { + if (!substitutionIterator.hasNext()) { + throw new IllegalStateException("not enough substitutions to fill placeholders"); } - line = line.replaceFirst( "%s", substitutionIterator.next() ); + line = line.replaceFirst("%s", substitutionIterator.next()); } - LineContext ctx = createContext( line ); - if ( prevLevel < ctx.getLevel() ) - { + LineContext ctx = createContext(line); + if (prevLevel < ctx.getLevel()) { // previous node is new parent - stack.add( node ); + stack.add(node); } // get to real parent - while ( prevLevel > ctx.getLevel() ) - { + while (prevLevel > ctx.getLevel()) { stack.removeLast(); prevLevel -= 1; } prevLevel = ctx.getLevel(); - if ( ctx.getDefinition() != null && ctx.getDefinition().reference != null ) - { + if (ctx.getDefinition() != null && ctx.getDefinition().reference != null) { String reference = ctx.getDefinition().reference; - DependencyNode child = nodes.get( reference ); - if ( child == null ) - { - throw new IllegalStateException( "undefined reference " + reference ); + DependencyNode child = nodes.get(reference); + if (child == null) { + throw new IllegalStateException("undefined reference " + reference); } - node.getChildren().add( child ); - } - else - { + node.getChildren().add(child); + } else { - node = build( isRootNode ? null : stack.getLast(), ctx, isRootNode ); + node = build(isRootNode ? null : stack.getLast(), ctx, isRootNode); - if ( isRootNode ) - { + if (isRootNode) { root = node; isRootNode = false; } - if ( ctx.getDefinition() != null && ctx.getDefinition().id != null ) - { - nodes.put( ctx.getDefinition().id, node ); + if (ctx.getDefinition() != null && ctx.getDefinition().id != null) { + nodes.put(ctx.getDefinition().id, node); } } } @@ -298,268 +260,222 @@ private DependencyNode parse( BufferedReader in ) return root; } - private boolean isEOFMarker( String line ) - { - return line.startsWith( "---" ); + private boolean isEOFMarker(String line) { + return line.startsWith("---"); } - private static boolean isEmpty( String line ) - { + private static boolean isEmpty(String line) { return line == null || line.length() == 0; } - private static String cutComment( String line ) - { - int idx = line.indexOf( '#' ); + private static String cutComment(String line) { + int idx = line.indexOf('#'); - if ( idx != -1 ) - { - line = line.substring( 0, idx ); + if (idx != -1) { + line = line.substring(0, idx); } return line; } - private DependencyNode build( DependencyNode parent, LineContext ctx, boolean isRoot ) - { + private DependencyNode build(DependencyNode parent, LineContext ctx, boolean isRoot) { NodeDefinition def = ctx.getDefinition(); - if ( !isRoot && parent == null ) - { - throw new IllegalStateException( "dangling node: " + def ); - } - else if ( ctx.getLevel() == 0 && parent != null ) - { - throw new IllegalStateException( "inconsistent leveling (parent for level 0?): " + def ); + if (!isRoot && parent == null) { + throw new IllegalStateException("dangling node: " + def); + } else if (ctx.getLevel() == 0 && parent != null) { + throw new IllegalStateException("inconsistent leveling (parent for level 0?): " + def); } DefaultDependencyNode node; - if ( def != null ) - { - DefaultArtifact artifact = new DefaultArtifact( def.coords, def.properties ); - Dependency dependency = new Dependency( artifact, def.scope, def.optional ); - node = new DefaultDependencyNode( dependency ); + if (def != null) { + DefaultArtifact artifact = new DefaultArtifact(def.coords, def.properties); + Dependency dependency = new Dependency(artifact, def.scope, def.optional); + node = new DefaultDependencyNode(dependency); int managedBits = 0; - if ( def.premanagedScope != null ) - { + if (def.premanagedScope != null) { managedBits |= DependencyNode.MANAGED_SCOPE; - node.setData( "premanaged.scope", def.premanagedScope ); + node.setData("premanaged.scope", def.premanagedScope); } - if ( def.premanagedVersion != null ) - { + if (def.premanagedVersion != null) { managedBits |= DependencyNode.MANAGED_VERSION; - node.setData( "premanaged.version", def.premanagedVersion ); + node.setData("premanaged.version", def.premanagedVersion); } - node.setManagedBits( managedBits ); - if ( def.relocations != null ) - { + node.setManagedBits(managedBits); + if (def.relocations != null) { List relocations = new ArrayList<>(); - for ( String relocation : def.relocations ) - { - relocations.add( new DefaultArtifact( relocation ) ); + for (String relocation : def.relocations) { + relocations.add(new DefaultArtifact(relocation)); } - node.setRelocations( relocations ); - } - try - { - node.setVersion( versionScheme.parseVersion( artifact.getVersion() ) ); - node.setVersionConstraint( versionScheme.parseVersionConstraint( def.range != null ? def.range - : artifact.getVersion() ) ); + node.setRelocations(relocations); } - catch ( InvalidVersionSpecificationException e ) - { - throw new IllegalArgumentException( "bad version: " + e.getMessage(), e ); + try { + node.setVersion(versionScheme.parseVersion(artifact.getVersion())); + node.setVersionConstraint( + versionScheme.parseVersionConstraint(def.range != null ? def.range : artifact.getVersion())); + } catch (InvalidVersionSpecificationException e) { + throw new IllegalArgumentException("bad version: " + e.getMessage(), e); } - } - else - { - node = new DefaultDependencyNode( (Dependency) null ); + } else { + node = new DefaultDependencyNode((Dependency) null); } - if ( parent != null ) - { - parent.getChildren().add( node ); + if (parent != null) { + parent.getChildren().add(node); } return node; } - public String dump( DependencyNode root ) - { + public String dump(DependencyNode root) { StringBuilder ret = new StringBuilder(); List entries = new ArrayList<>(); - addNode( root, 0, entries ); + addNode(root, 0, entries); - for ( NodeEntry nodeEntry : entries ) - { - char[] level = new char[( nodeEntry.getLevel() * 3 )]; - Arrays.fill( level, ' ' ); + for (NodeEntry nodeEntry : entries) { + char[] level = new char[(nodeEntry.getLevel() * 3)]; + Arrays.fill(level, ' '); - if ( level.length != 0 ) - { + if (level.length != 0) { level[level.length - 3] = '+'; level[level.length - 2] = '-'; } String definition = nodeEntry.getDefinition(); - ret.append( level ).append( definition ).append( "\n" ); + ret.append(level).append(definition).append("\n"); } return ret.toString(); - } - private void addNode( DependencyNode root, int level, List entries ) - { + private void addNode(DependencyNode root, int level, List entries) { NodeEntry entry = new NodeEntry(); Dependency dependency = root.getDependency(); StringBuilder defBuilder = new StringBuilder(); - if ( dependency == null ) - { - defBuilder.append( "(null)" ); - } - else - { + if (dependency == null) { + defBuilder.append("(null)"); + } else { Artifact artifact = dependency.getArtifact(); - defBuilder.append( artifact.getGroupId() ).append( ":" ).append( artifact.getArtifactId() ).append( ":" ) - .append( artifact.getExtension() ).append( ":" ).append( artifact.getVersion() ); - if ( dependency.getScope() != null && ( !"".equals( dependency.getScope() ) ) ) - { - defBuilder.append( ":" ).append( dependency.getScope() ); + defBuilder + .append(artifact.getGroupId()) + .append(":") + .append(artifact.getArtifactId()) + .append(":") + .append(artifact.getExtension()) + .append(":") + .append(artifact.getVersion()); + if (dependency.getScope() != null && (!"".equals(dependency.getScope()))) { + defBuilder.append(":").append(dependency.getScope()); } Map properties = artifact.getProperties(); - if ( !( properties == null || properties.isEmpty() ) ) - { - for ( Map.Entry prop : properties.entrySet() ) - { - defBuilder.append( ";" ).append( prop.getKey() ).append( "=" ).append( prop.getValue() ); + if (!(properties == null || properties.isEmpty())) { + for (Map.Entry prop : properties.entrySet()) { + defBuilder.append(";").append(prop.getKey()).append("=").append(prop.getValue()); } } } - entry.setDefinition( defBuilder.toString() ); - entry.setLevel( level++ ); + entry.setDefinition(defBuilder.toString()); + entry.setLevel(level++); - entries.add( entry ); + entries.add(entry); - for ( DependencyNode node : root.getChildren() ) - { - addNode( node, level, entries ); + for (DependencyNode node : root.getChildren()) { + addNode(node, level, entries); } - } - class NodeEntry - { + class NodeEntry { int level; String definition; Map properties; - public int getLevel() - { + public int getLevel() { return level; } - public void setLevel( int level ) - { + public void setLevel(int level) { this.level = level; } - public String getDefinition() - { + public String getDefinition() { return definition; } - public void setDefinition( String definition ) - { + public void setDefinition(String definition) { this.definition = definition; } - public Map getProperties() - { + public Map getProperties() { return properties; } - public void setProperties( Map properties ) - { + public void setProperties(Map properties) { this.properties = properties; } } - private static LineContext createContext( String line ) - { + private static LineContext createContext(String line) { LineContext ctx = new LineContext(); String definition; - String[] split = line.split( "- " ); - if ( split.length == 1 ) // root + String[] split = line.split("- "); + if (split.length == 1) // root { - ctx.setLevel( 0 ); + ctx.setLevel(0); definition = split[0]; - } - else - { - ctx.setLevel( (int) Math.ceil( (double) split[0].length() / (double) 3 ) ); + } else { + ctx.setLevel((int) Math.ceil((double) split[0].length() / (double) 3)); definition = split[1]; } - if ( "(null)".equalsIgnoreCase( definition ) ) - { + if ("(null)".equalsIgnoreCase(definition)) { return ctx; } - ctx.setDefinition( new NodeDefinition( definition ) ); + ctx.setDefinition(new NodeDefinition(definition)); return ctx; } - static class LineContext - { + static class LineContext { NodeDefinition definition; int level; - public NodeDefinition getDefinition() - { + public NodeDefinition getDefinition() { return definition; } - public void setDefinition( NodeDefinition definition ) - { + public void setDefinition(NodeDefinition definition) { this.definition = definition; } - public int getLevel() - { + public int getLevel() { return level; } - public void setLevel( int level ) - { + public void setLevel(int level) { this.level = level; } } - public Collection getSubstitutions() - { + public Collection getSubstitutions() { return substitutions; } - public void setSubstitutions( Collection substitutions ) - { + public void setSubstitutions(Collection substitutions) { this.substitutions = substitutions; } - public void setSubstitutions( String... substitutions ) - { - setSubstitutions( Arrays.asList( substitutions ) ); + public void setSubstitutions(String... substitutions) { + setSubstitutions(Arrays.asList(substitutions)); } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/IniArtifactDataReader.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/IniArtifactDataReader.java index 08a693b81..3d0718dd2 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/IniArtifactDataReader.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/IniArtifactDataReader.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.io.BufferedReader; import java.io.IOException; @@ -42,72 +41,62 @@ /** * @see IniArtifactDescriptorReader */ -class IniArtifactDataReader -{ +class IniArtifactDataReader { private String prefix = ""; /** * Constructs a data reader with the prefix {@code ""}. */ - IniArtifactDataReader() - { - this( "" ); + IniArtifactDataReader() { + this(""); } /** * Constructs a data reader with the given prefix. - * + * * @param prefix the prefix to use for loading resources from the classpath. */ - IniArtifactDataReader( String prefix ) - { + IniArtifactDataReader(String prefix) { this.prefix = prefix; - } /** * Load an artifact description from the classpath and parse it. */ - public ArtifactDescription parse( String resource ) - throws IOException - { - URL res = this.getClass().getClassLoader().getResource( prefix + resource ); - - if ( res == null ) - { - throw new IOException( "cannot find resource: " + resource ); + public ArtifactDescription parse(String resource) throws IOException { + URL res = this.getClass().getClassLoader().getResource(prefix + resource); + + if (res == null) { + throw new IOException("cannot find resource: " + resource); } - return parse( res ); + return parse(res); } /** * Open the given URL and parse ist. */ - public ArtifactDescription parse( URL res ) - throws IOException - { - return parse( new InputStreamReader( res.openStream(), StandardCharsets.UTF_8 ) ); + public ArtifactDescription parse(URL res) throws IOException { + return parse(new InputStreamReader(res.openStream(), StandardCharsets.UTF_8)); } /** * Parse the given String. */ - public ArtifactDescription parseLiteral( String description ) - throws IOException - { - StringReader reader = new StringReader( description ); - return parse( reader ); + public ArtifactDescription parseLiteral(String description) throws IOException { + StringReader reader = new StringReader(description); + return parse(reader); } - private enum State - { - NONE, RELOCATION, DEPENDENCIES, MANAGEDDEPENDENCIES, REPOSITORIES + private enum State { + NONE, + RELOCATION, + DEPENDENCIES, + MANAGEDDEPENDENCIES, + REPOSITORIES } - private ArtifactDescription parse( Reader reader ) - throws IOException - { + private ArtifactDescription parse(Reader reader) throws IOException { String line = null; State state = State.NONE; @@ -115,93 +104,72 @@ private ArtifactDescription parse( Reader reader ) Map> sections = new HashMap<>(); BufferedReader in = null; - try - { - in = new BufferedReader( reader ); - while ( ( line = in.readLine() ) != null ) - { - - line = cutComment( line ); - if ( isEmpty( line ) ) - { + try { + in = new BufferedReader(reader); + while ((line = in.readLine()) != null) { + + line = cutComment(line); + if (isEmpty(line)) { continue; } - if ( line.startsWith( "[" ) ) - { - try - { - String name = line.substring( 1, line.length() - 1 ); - name = name.replace( "-", "" ).toUpperCase( Locale.ENGLISH ); - state = State.valueOf( name ); - sections.put( state, new ArrayList() ); + if (line.startsWith("[")) { + try { + String name = line.substring(1, line.length() - 1); + name = name.replace("-", "").toUpperCase(Locale.ENGLISH); + state = State.valueOf(name); + sections.put(state, new ArrayList()); + } catch (IllegalArgumentException e) { + throw new IOException("unknown section: " + line); } - catch ( IllegalArgumentException e ) - { - throw new IOException( "unknown section: " + line ); + } else { + List lines = sections.get(state); + if (lines == null) { + throw new IOException("missing section: " + line); } - } - else - { - List lines = sections.get( state ); - if ( lines == null ) - { - throw new IOException( "missing section: " + line ); - } - lines.add( line.trim() ); + lines.add(line.trim()); } } in.close(); in = null; - } - finally - { - try - { - if ( in != null ) - { + } finally { + try { + if (in != null) { in.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } - Artifact relocation = relocation( sections.get( State.RELOCATION ) ); - List dependencies = dependencies( sections.get( State.DEPENDENCIES ), false ); - List managedDependencies = dependencies( sections.get( State.MANAGEDDEPENDENCIES ), true ); - List repositories = repositories( sections.get( State.REPOSITORIES ) ); + Artifact relocation = relocation(sections.get(State.RELOCATION)); + List dependencies = dependencies(sections.get(State.DEPENDENCIES), false); + List managedDependencies = dependencies(sections.get(State.MANAGEDDEPENDENCIES), true); + List repositories = repositories(sections.get(State.REPOSITORIES)); - return new ArtifactDescription( relocation, dependencies, managedDependencies, repositories ); + return new ArtifactDescription(relocation, dependencies, managedDependencies, repositories); } - private List repositories( List list ) - { + private List repositories(List list) { ArrayList ret = new ArrayList<>(); - if ( list == null ) - { + if (list == null) { return ret; } - for ( String coords : list ) - { - String[] split = coords.split( ":", 3 ); + for (String coords : list) { + String[] split = coords.split(":", 3); String id = split[0]; String type = split[1]; String url = split[2]; - ret.add( new RemoteRepository.Builder( id, type, url ).build() ); + ret.add(new RemoteRepository.Builder(id, type, url).build()); } return ret; } - private List dependencies( List list, boolean managed ) - { + private List dependencies(List list, boolean managed) { List ret = new ArrayList<>(); - if ( list == null ) - { + if (list == null) { return ret; } @@ -211,76 +179,63 @@ private List dependencies( List list, boolean managed ) Artifact artifact = null; String scope = null; - for ( String coords : list ) - { - if ( coords.startsWith( "-" ) ) - { - coords = coords.substring( 1 ); - String[] split = coords.split( ":" ); - exclusions.add( new Exclusion( split[0], split[1], "*", "*" ) ); - } - else - { - if ( artifact != null ) - { + for (String coords : list) { + if (coords.startsWith("-")) { + coords = coords.substring(1); + String[] split = coords.split(":"); + exclusions.add(new Exclusion(split[0], split[1], "*", "*")); + } else { + if (artifact != null) { // commit dependency - Dependency dep = new Dependency( artifact, scope, optional, exclusions ); - ret.add( dep ); + Dependency dep = new Dependency(artifact, scope, optional, exclusions); + ret.add(dep); exclusions = new ArrayList<>(); } - ArtifactDefinition def = new ArtifactDefinition( coords ); + ArtifactDefinition def = new ArtifactDefinition(coords); - optional = managed ? def.getOptional() : Boolean.valueOf( Boolean.TRUE.equals( def.getOptional() ) ); + optional = managed ? def.getOptional() : Boolean.valueOf(Boolean.TRUE.equals(def.getOptional())); - scope = "".equals( def.getScope() ) && !managed ? "compile" : def.getScope(); + scope = "".equals(def.getScope()) && !managed ? "compile" : def.getScope(); - artifact = - new DefaultArtifact( def.getGroupId(), def.getArtifactId(), "", def.getExtension(), - def.getVersion() ); + artifact = new DefaultArtifact( + def.getGroupId(), def.getArtifactId(), "", def.getExtension(), def.getVersion()); } } - if ( artifact != null ) - { + if (artifact != null) { // commit dependency - Dependency dep = new Dependency( artifact, scope, optional, exclusions ); - ret.add( dep ); + Dependency dep = new Dependency(artifact, scope, optional, exclusions); + ret.add(dep); } return ret; } - private Artifact relocation( List list ) - { - if ( list == null || list.isEmpty() ) - { + private Artifact relocation(List list) { + if (list == null || list.isEmpty()) { return null; } - String coords = list.get( 0 ); - ArtifactDefinition def = new ArtifactDefinition( coords ); - return new DefaultArtifact( def.getGroupId(), def.getArtifactId(), "", def.getExtension(), def.getVersion() ); + String coords = list.get(0); + ArtifactDefinition def = new ArtifactDefinition(coords); + return new DefaultArtifact(def.getGroupId(), def.getArtifactId(), "", def.getExtension(), def.getVersion()); } - private static boolean isEmpty( String line ) - { + private static boolean isEmpty(String line) { return line == null || line.length() == 0; } - private static String cutComment( String line ) - { - int idx = line.indexOf( '#' ); + private static String cutComment(String line) { + int idx = line.indexOf('#'); - if ( idx != -1 ) - { - line = line.substring( 0, idx ); + if (idx != -1) { + line = line.substring(0, idx); } return line; } - static class Definition - { + static class Definition { private String groupId; private String artifactId; @@ -299,97 +254,78 @@ static class Definition private boolean optional = false; - Definition( String def ) - { + Definition(String def) { this.definition = def.trim(); - if ( definition.startsWith( "(" ) ) - { - int idx = definition.indexOf( ')' ); - this.id = definition.substring( 1, idx ); - this.definition = definition.substring( idx + 1 ); - } - else if ( definition.startsWith( "^" ) ) - { - this.reference = definition.substring( 1 ); + if (definition.startsWith("(")) { + int idx = definition.indexOf(')'); + this.id = definition.substring(1, idx); + this.definition = definition.substring(idx + 1); + } else if (definition.startsWith("^")) { + this.reference = definition.substring(1); return; } - String[] split = definition.split( ":" ); - if ( split.length < 4 ) - { - throw new IllegalArgumentException( "Need definition like 'gid:aid:ext:ver[:scope]', but was: " - + definition ); + String[] split = definition.split(":"); + if (split.length < 4) { + throw new IllegalArgumentException( + "Need definition like 'gid:aid:ext:ver[:scope]', but was: " + definition); } groupId = split[0]; artifactId = split[1]; extension = split[2]; version = split[3]; - if ( split.length > 4 ) - { + if (split.length > 4) { scope = split[4]; } - if ( split.length > 5 && "true".equalsIgnoreCase( split[5] ) ) - { + if (split.length > 5 && "true".equalsIgnoreCase(split[5])) { optional = true; } } - public String getGroupId() - { + public String getGroupId() { return groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public String getType() - { + public String getType() { return extension; } - public String getVersion() - { + public String getVersion() { return version; } - public String getScope() - { + public String getScope() { return scope; } @Override - public String toString() - { + public String toString() { return definition; } - public String getId() - { + public String getId() { return id; } - public String getReference() - { + public String getReference() { return reference; } - public boolean isReference() - { + public boolean isReference() { return reference != null; } - public boolean hasId() - { + public boolean hasId() { return id != null; } - public boolean isOptional() - { + public boolean isOptional() { return optional; } } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/IniArtifactDescriptorReader.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/IniArtifactDescriptorReader.java index 17f98b3b2..16d7dde9b 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/IniArtifactDescriptorReader.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/IniArtifactDescriptorReader.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -38,92 +37,80 @@ *
  • repositories
  • * * The relocation and dependency sections contain artifact coordinates of the form: - * + * *
      * gid:aid:ext:ver[:scope][:optional]
      * 
    - * + * * The dependency sections may also specify exclusions: - * + * *
      * -gid:aid
      * 
    - * + * * A repository definition is of the form: - * + * *
      * id:type:url
      * 
    - * + * *

    Example

    - * + * *
      * [relocation]
      * gid:aid:ext:ver
    - * 
    + *
      * [dependencies]
      * gid:aid:ext:ver:scope
      * -exclusion:aid
      * gid:aid2:ext:ver:scope:optional
    - * 
    + *
      * [managed-dependencies]
      * gid:aid2:ext:ver2:scope
      * -gid:aid
      * -gid:aid
    - * 
    + *
      * [repositories]
      * id:type:file:///test-repo
      * 
    */ -public class IniArtifactDescriptorReader -{ +public class IniArtifactDescriptorReader { private final IniArtifactDataReader reader; /** * Use the given prefix to load the artifact descriptions from the classpath. */ - public IniArtifactDescriptorReader( String prefix ) - { - reader = new IniArtifactDataReader( prefix ); + public IniArtifactDescriptorReader(String prefix) { + reader = new IniArtifactDataReader(prefix); } /** * Parses the resource {@code $prefix/gid_aid_ver.ini} from the request artifact as an artifact description and * wraps it into an ArtifactDescriptorResult. */ - public ArtifactDescriptorResult readArtifactDescriptor( RepositorySystemSession session, - ArtifactDescriptorRequest request ) - throws ArtifactDescriptorException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); - ArtifactDescriptorResult result = new ArtifactDescriptorResult( request ); - for ( Artifact artifact = request.getArtifact();; ) - { - String resourceName = - String.format( "%s_%s_%s.ini", artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion() ); - try - { - ArtifactDescription data = reader.parse( resourceName ); - if ( data.getRelocation() != null ) - { - result.addRelocation( artifact ); + public ArtifactDescriptorResult readArtifactDescriptor( + RepositorySystemSession session, ArtifactDescriptorRequest request) throws ArtifactDescriptorException { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); + ArtifactDescriptorResult result = new ArtifactDescriptorResult(request); + for (Artifact artifact = request.getArtifact(); ; ) { + String resourceName = String.format( + "%s_%s_%s.ini", artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); + try { + ArtifactDescription data = reader.parse(resourceName); + if (data.getRelocation() != null) { + result.addRelocation(artifact); artifact = data.getRelocation(); - } - else - { - result.setArtifact( artifact ); - result.setDependencies( data.getDependencies() ); - result.setManagedDependencies( data.getManagedDependencies() ); - result.setRepositories( data.getRepositories() ); + } else { + result.setArtifact(artifact); + result.setDependencies(data.getDependencies()); + result.setManagedDependencies(data.getManagedDependencies()); + result.setRepositories(data.getRepositories()); return result; } - } - catch ( Exception e ) - { - throw new ArtifactDescriptorException( result, e.getMessage(), e ); + } catch (Exception e) { + throw new ArtifactDescriptorException(result, e.getMessage(), e); } } } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/NodeBuilder.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/NodeBuilder.java index 446c0c2e1..1632712d7 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/NodeBuilder.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/NodeBuilder.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.io.File; import java.util.ArrayList; @@ -37,8 +36,7 @@ /** * A builder to create dependency nodes for unit testing. */ -public class NodeBuilder -{ +public class NodeBuilder { private String groupId = "test"; @@ -62,103 +60,84 @@ public class NodeBuilder private final VersionScheme versionScheme = new TestVersionScheme(); - private Map properties = new HashMap<>( 0 ); + private Map properties = new HashMap<>(0); - public NodeBuilder artifactId( String artifactId ) - { + public NodeBuilder artifactId(String artifactId) { this.artifactId = artifactId; return this; } - public NodeBuilder groupId( String groupId ) - { + public NodeBuilder groupId(String groupId) { this.groupId = groupId; return this; - } - public NodeBuilder ext( String ext ) - { + public NodeBuilder ext(String ext) { this.ext = ext; return this; } - public NodeBuilder version( String version ) - { + public NodeBuilder version(String version) { this.version = version; this.range = null; return this; } - public NodeBuilder range( String range ) - { + public NodeBuilder range(String range) { this.range = range; return this; } - public NodeBuilder scope( String scope ) - { + public NodeBuilder scope(String scope) { this.scope = scope; return this; } - public NodeBuilder optional( boolean optional ) - { + public NodeBuilder optional(boolean optional) { this.optional = optional; return this; } - public NodeBuilder context( String context ) - { + public NodeBuilder context(String context) { this.context = context; return this; } - public NodeBuilder reloc( String artifactId ) - { - Artifact relocation = new DefaultArtifact( groupId, artifactId, classifier, ext, version ); - relocations.add( relocation ); + public NodeBuilder reloc(String artifactId) { + Artifact relocation = new DefaultArtifact(groupId, artifactId, classifier, ext, version); + relocations.add(relocation); return this; } - public NodeBuilder reloc( String groupId, String artifactId, String version ) - { - Artifact relocation = new DefaultArtifact( groupId, artifactId, classifier, ext, version ); - relocations.add( relocation ); + public NodeBuilder reloc(String groupId, String artifactId, String version) { + Artifact relocation = new DefaultArtifact(groupId, artifactId, classifier, ext, version); + relocations.add(relocation); return this; } - public NodeBuilder properties( Map properties ) - { + public NodeBuilder properties(Map properties) { this.properties = properties != null ? properties : Collections.emptyMap(); return this; } - public DependencyNode build() - { + public DependencyNode build() { Dependency dependency = null; - if ( artifactId != null && artifactId.length() > 0 ) - { + if (artifactId != null && artifactId.length() > 0) { Artifact artifact = - new DefaultArtifact( groupId, artifactId, classifier, ext, version, properties, (File) null ); - dependency = new Dependency( artifact, scope, optional ); + new DefaultArtifact(groupId, artifactId, classifier, ext, version, properties, (File) null); + dependency = new Dependency(artifact, scope, optional); } - DefaultDependencyNode node = new DefaultDependencyNode( dependency ); - if ( artifactId != null && artifactId.length() > 0 ) - { - try - { - node.setVersion( versionScheme.parseVersion( version ) ); - node.setVersionConstraint( versionScheme.parseVersionConstraint( range != null ? range : version ) ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new IllegalArgumentException( "bad version: " + e.getMessage(), e ); + DefaultDependencyNode node = new DefaultDependencyNode(dependency); + if (artifactId != null && artifactId.length() > 0) { + try { + node.setVersion(versionScheme.parseVersion(version)); + node.setVersionConstraint(versionScheme.parseVersionConstraint(range != null ? range : version)); + } catch (InvalidVersionSpecificationException e) { + throw new IllegalArgumentException("bad version: " + e.getMessage(), e); } } - node.setRequestContext( context ); - node.setRelocations( relocations ); + node.setRequestContext(context); + node.setRelocations(relocations); return node; } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/NodeDefinition.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/NodeDefinition.java index 5d2145533..5ce953baf 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/NodeDefinition.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/NodeDefinition.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.util.ArrayList; import java.util.Collections; @@ -29,11 +28,10 @@ /** * A definition of a dependency node via a single line of text. - * + * * @see DependencyGraphParser */ -class NodeDefinition -{ +class NodeDefinition { static final String ID = "\\(([-_a-zA-Z0-9]+)\\)"; @@ -41,7 +39,7 @@ class NodeDefinition static final String COORDS = "([^: \\(]+):([^: ]+)(?::([^: ]*)(?::([^: ]+))?)?:([^: \\[\\(<]+)"; - private static final String COORDS_NC = NodeDefinition.COORDS.replaceAll( "\\((?=\\[)", "(?:" ); + private static final String COORDS_NC = NodeDefinition.COORDS.replaceAll("\\((?=\\[)", "(?:"); private static final String RANGE_NC = "[\\(\\[][^\\(\\)\\[\\]]+[\\)\\]]"; @@ -60,11 +58,11 @@ class NodeDefinition static final String COORDSX = "(" + COORDS_NC + ")" + RANGE + "?(?:<((?:" + RANGE_NC + ")|\\S+))?"; static final String NODE = COORDSX + "(?:\\s+" + PROPS + ")?" + "(?:\\s+" + SCOPE + ")?" + "(?:\\s+" + OPTIONAL - + ")?" + "(?:\\s+" + RELOCATIONS + ")?" + "(?:\\s+" + ID + ")?"; + + ")?" + "(?:\\s+" + RELOCATIONS + ")?" + "(?:\\s+" + ID + ")?"; static final String LINE = "(?:" + IDREF + ")|(?:" + NODE + ")"; - private static final Pattern PATTERN = Pattern.compile( LINE ); + private static final Pattern PATTERN = Pattern.compile(LINE); private final String def; @@ -88,57 +86,49 @@ class NodeDefinition String reference; - NodeDefinition( String definition ) - { + NodeDefinition(String definition) { def = definition.trim(); - Matcher m = PATTERN.matcher( def ); - if ( !m.matches() ) - { - throw new IllegalArgumentException( "bad syntax: " + def ); + Matcher m = PATTERN.matcher(def); + if (!m.matches()) { + throw new IllegalArgumentException("bad syntax: " + def); } - reference = m.group( 1 ); - if ( reference != null ) - { + reference = m.group(1); + if (reference != null) { return; } - coords = m.group( 2 ); - range = m.group( 3 ); - premanagedVersion = m.group( 4 ); + coords = m.group(2); + range = m.group(3); + premanagedVersion = m.group(4); - String props = m.group( 5 ); - if ( props != null ) - { + String props = m.group(5); + if (props != null) { properties = new LinkedHashMap<>(); - for ( String prop : props.split( "\\s*,\\s*" ) ) - { - int sep = prop.indexOf( ':' ); - String key = prop.substring( 0, sep ); - String val = prop.substring( sep + 1 ); - properties.put( key, val ); + for (String prop : props.split("\\s*,\\s*")) { + int sep = prop.indexOf(':'); + String key = prop.substring(0, sep); + String val = prop.substring(sep + 1); + properties.put(key, val); } } - scope = m.group( 6 ); - premanagedScope = m.group( 7 ); - optional = ( m.group( 8 ) != null ) ? !m.group( 8 ).startsWith( "!" ) : Boolean.FALSE; + scope = m.group(6); + premanagedScope = m.group(7); + optional = (m.group(8) != null) ? !m.group(8).startsWith("!") : Boolean.FALSE; - String relocs = m.group( 9 ); - if ( relocs != null ) - { + String relocs = m.group(9); + if (relocs != null) { relocations = new ArrayList<>(); - Collections.addAll( relocations, relocs.split( "\\s*,\\s*" ) ); + Collections.addAll(relocations, relocs.split("\\s*,\\s*")); } - id = m.group( 10 ); + id = m.group(10); } @Override - public String toString() - { + public String toString() { return def; } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestDependencyCollectionContext.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestDependencyCollectionContext.java index c99326ee7..c6986ac7e 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestDependencyCollectionContext.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestDependencyCollectionContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.util.List; @@ -28,9 +27,7 @@ /** */ -final class TestDependencyCollectionContext - implements DependencyCollectionContext -{ +final class TestDependencyCollectionContext implements DependencyCollectionContext { private final RepositorySystemSession session; @@ -40,39 +37,35 @@ final class TestDependencyCollectionContext private final List managedDependencies; - TestDependencyCollectionContext( RepositorySystemSession session, Artifact artifact, Dependency dependency, - List managedDependencies ) - { + TestDependencyCollectionContext( + RepositorySystemSession session, + Artifact artifact, + Dependency dependency, + List managedDependencies) { this.session = session; - this.artifact = ( dependency != null ) ? dependency.getArtifact() : artifact; + this.artifact = (dependency != null) ? dependency.getArtifact() : artifact; this.dependency = dependency; this.managedDependencies = managedDependencies; } - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } - public Artifact getArtifact() - { + public Artifact getArtifact() { return artifact; } - public Dependency getDependency() - { + public Dependency getDependency() { return dependency; } - public List getManagedDependencies() - { + public List getManagedDependencies() { return managedDependencies; } @Override - public String toString() - { - return String.valueOf( getDependency() ); + public String toString() { + return String.valueOf(getDependency()); } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestDependencyGraphTransformationContext.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestDependencyGraphTransformationContext.java index ee6fe606a..80cb555a8 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestDependencyGraphTransformationContext.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestDependencyGraphTransformationContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,57 +16,48 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.util.HashMap; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.collection.DependencyGraphTransformationContext; +import static java.util.Objects.requireNonNull; + /** */ -class TestDependencyGraphTransformationContext - implements DependencyGraphTransformationContext -{ +class TestDependencyGraphTransformationContext implements DependencyGraphTransformationContext { private final RepositorySystemSession session; private final Map map; - TestDependencyGraphTransformationContext( RepositorySystemSession session ) - { + TestDependencyGraphTransformationContext(RepositorySystemSession session) { this.session = session; this.map = new HashMap<>(); } - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } - public Object get( Object key ) - { - return map.get( requireNonNull( key, "key cannot be null" ) ); + public Object get(Object key) { + return map.get(requireNonNull(key, "key cannot be null")); } - public Object put( Object key, Object value ) - { - requireNonNull( key, "key cannot be null" ); - if ( value != null ) - { - return map.put( key, value ); - } - else - { - return map.remove( key ); + public Object put(Object key, Object value) { + requireNonNull(key, "key cannot be null"); + if (value != null) { + return map.put(key, value); + } else { + return map.remove(key); } } @Override - public String toString() - { - return String.valueOf( map ); + public String toString() { + return String.valueOf(map); } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestFileProcessor.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestFileProcessor.java index ae5d9f812..93ab4da4b 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestFileProcessor.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestFileProcessor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.io.BufferedOutputStream; import java.io.File; @@ -36,158 +35,113 @@ /** * A simple file processor implementation to help satisfy component requirements during tests. */ -public class TestFileProcessor - implements FileProcessor -{ - - public boolean mkdirs( File directory ) - { - if ( directory == null ) - { +public class TestFileProcessor implements FileProcessor { + + public boolean mkdirs(File directory) { + if (directory == null) { return false; } - if ( directory.exists() ) - { + if (directory.exists()) { return false; } - if ( directory.mkdir() ) - { + if (directory.mkdir()) { return true; } File canonDir = null; - try - { + try { canonDir = directory.getCanonicalFile(); - } - catch ( IOException e ) - { + } catch (IOException e) { return false; } File parentDir = canonDir.getParentFile(); - return ( parentDir != null && ( mkdirs( parentDir ) || parentDir.exists() ) && canonDir.mkdir() ); + return (parentDir != null && (mkdirs(parentDir) || parentDir.exists()) && canonDir.mkdir()); } - public void write( File file, String data ) - throws IOException - { - mkdirs( file.getParentFile() ); + public void write(File file, String data) throws IOException { + mkdirs(file.getParentFile()); FileOutputStream fos = null; - try - { - fos = new FileOutputStream( file ); + try { + fos = new FileOutputStream(file); - if ( data != null ) - { - fos.write( data.getBytes( StandardCharsets.UTF_8 ) ); + if (data != null) { + fos.write(data.getBytes(StandardCharsets.UTF_8)); } fos.close(); fos = null; - } - finally - { - try - { - if ( fos != null ) - { + } finally { + try { + if (fos != null) { fos.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } } - public void write( File target, InputStream source ) - throws IOException - { - mkdirs( target.getAbsoluteFile().getParentFile() ); + public void write(File target, InputStream source) throws IOException { + mkdirs(target.getAbsoluteFile().getParentFile()); OutputStream fos = null; - try - { - fos = new BufferedOutputStream( new FileOutputStream( target ) ); + try { + fos = new BufferedOutputStream(new FileOutputStream(target)); - copy( fos, source, null ); + copy(fos, source, null); fos.close(); fos = null; - } - finally - { - try - { - if ( fos != null ) - { + } finally { + try { + if (fos != null) { fos.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } } - public void copy( File source, File target ) - throws IOException - { - copy( source, target, null ); + public void copy(File source, File target) throws IOException { + copy(source, target, null); } - public long copy( File source, File target, ProgressListener listener ) - throws IOException - { + public long copy(File source, File target, ProgressListener listener) throws IOException { long total = 0; InputStream fis = null; OutputStream fos = null; - try - { - fis = new FileInputStream( source ); + try { + fis = new FileInputStream(source); - mkdirs( target.getAbsoluteFile().getParentFile() ); + mkdirs(target.getAbsoluteFile().getParentFile()); - fos = new BufferedOutputStream( new FileOutputStream( target ) ); + fos = new BufferedOutputStream(new FileOutputStream(target)); - total = copy( fos, fis, listener ); + total = copy(fos, fis, listener); fos.close(); fos = null; fis.close(); fis = null; - } - finally - { - try - { - if ( fos != null ) - { + } finally { + try { + if (fos != null) { fos.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. - } - finally - { - try - { - if ( fis != null ) - { + } finally { + try { + if (fis != null) { fis.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } @@ -196,36 +150,28 @@ public long copy( File source, File target, ProgressListener listener ) return total; } - private long copy( OutputStream os, InputStream is, ProgressListener listener ) - throws IOException - { + private long copy(OutputStream os, InputStream is, ProgressListener listener) throws IOException { long total = 0L; - ByteBuffer buffer = ByteBuffer.allocate( 1024 * 32 ); + ByteBuffer buffer = ByteBuffer.allocate(1024 * 32); byte[] array = buffer.array(); - while ( true ) - { - int bytes = is.read( array ); - if ( bytes < 0 ) - { + while (true) { + int bytes = is.read(array); + if (bytes < 0) { break; } - os.write( array, 0, bytes ); + os.write(array, 0, bytes); total += bytes; - if ( listener != null && bytes > 0 ) - { - try - { - ( (Buffer) buffer ).rewind(); - ( (Buffer) buffer ).limit( bytes ); - listener.progressed( buffer ); - } - catch ( Exception e ) - { + if (listener != null && bytes > 0) { + try { + ((Buffer) buffer).rewind(); + ((Buffer) buffer).limit(bytes); + listener.progressed(buffer); + } catch (Exception e) { // too bad } } @@ -234,30 +180,25 @@ private long copy( OutputStream os, InputStream is, ProgressListener listener ) return total; } - public void move( File source, File target ) - throws IOException - { + public void move(File source, File target) throws IOException { target.delete(); - if ( !source.renameTo( target ) ) - { - copy( source, target ); + if (!source.renameTo(target)) { + copy(source, target); - target.setLastModified( source.lastModified() ); + target.setLastModified(source.lastModified()); source.delete(); } } @Override - public String readChecksum( final File checksumFile ) throws IOException - { - return new String( Files.readAllBytes( checksumFile.toPath() ), StandardCharsets.UTF_8 ); + public String readChecksum(final File checksumFile) throws IOException { + return new String(Files.readAllBytes(checksumFile.toPath()), StandardCharsets.UTF_8); } @Override - public void writeChecksum( final File checksumFile, final String checksum ) throws IOException - { - write( checksumFile, checksum ); + public void writeChecksum(final File checksumFile, final String checksum) throws IOException { + write(checksumFile, checksum); } } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestFileUtils.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestFileUtils.java index a2f3560c3..acf175565 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestFileUtils.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestFileUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.io.BufferedOutputStream; import java.io.File; @@ -35,170 +34,131 @@ /** * Provides utility methods to read and write (temporary) files. */ -public class TestFileUtils -{ - - private static final File TMP = new File( System.getProperty( "java.io.tmpdir" ), "aether-" - + UUID.randomUUID().toString().substring( 0, 8 ) ); - - static - { - Runtime.getRuntime().addShutdownHook( new Thread( () -> - { - try - { - deleteFile( TMP ); - } - catch ( IOException e ) - { +public class TestFileUtils { + + private static final File TMP = new File( + System.getProperty("java.io.tmpdir"), + "aether-" + UUID.randomUUID().toString().substring(0, 8)); + + static { + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { + deleteFile(TMP); + } catch (IOException e) { e.printStackTrace(); } - } ) ); + })); } - private TestFileUtils() - { + private TestFileUtils() { // hide constructor } - public static void deleteTempFiles() - throws IOException - { - deleteFile( TMP ); + public static void deleteTempFiles() throws IOException { + deleteFile(TMP); } - public static void deleteFile( File file ) - throws IOException - { - if ( file == null ) - { + public static void deleteFile(File file) throws IOException { + if (file == null) { return; } Collection undeletables = new ArrayList<>(); - delete( file, undeletables ); + delete(file, undeletables); - if ( !undeletables.isEmpty() ) - { - throw new IOException( "Failed to delete " + undeletables ); + if (!undeletables.isEmpty()) { + throw new IOException("Failed to delete " + undeletables); } } - private static void delete( File file, Collection undeletables ) - { + private static void delete(File file, Collection undeletables) { String[] children = file.list(); - if ( children != null ) - { - for ( String child : children ) - { - delete( new File( file, child ), undeletables ); + if (children != null) { + for (String child : children) { + delete(new File(file, child), undeletables); } } - if ( !del( file ) ) - { - undeletables.add( file.getAbsoluteFile() ); + if (!del(file)) { + undeletables.add(file.getAbsoluteFile()); } } - private static boolean del( File file ) - { - for ( int i = 0; i < 10; i++ ) - { - if ( file.delete() || !file.exists() ) - { + private static boolean del(File file) { + for (int i = 0; i < 10; i++) { + if (file.delete() || !file.exists()) { return true; } } return false; } - public static boolean mkdirs( File directory ) - { - if ( directory == null ) - { + public static boolean mkdirs(File directory) { + if (directory == null) { return false; } - if ( directory.exists() ) - { + if (directory.exists()) { return false; } - if ( directory.mkdir() ) - { + if (directory.mkdir()) { return true; } File canonDir = null; - try - { + try { canonDir = directory.getCanonicalFile(); - } - catch ( IOException e ) - { + } catch (IOException e) { return false; } File parentDir = canonDir.getParentFile(); - return ( parentDir != null && ( mkdirs( parentDir ) || parentDir.exists() ) && canonDir.mkdir() ); + return (parentDir != null && (mkdirs(parentDir) || parentDir.exists()) && canonDir.mkdir()); } - public static File createTempFile( String contents ) - throws IOException - { - return createTempFile( contents.getBytes( StandardCharsets.UTF_8 ), 1 ); + public static File createTempFile(String contents) throws IOException { + return createTempFile(contents.getBytes(StandardCharsets.UTF_8), 1); } - public static File createTempFile( byte[] pattern, int repeat ) - throws IOException - { - mkdirs( TMP ); - File tmpFile = File.createTempFile( "tmpfile-", ".data", TMP ); - writeBytes( tmpFile, pattern, repeat ); + public static File createTempFile(byte[] pattern, int repeat) throws IOException { + mkdirs(TMP); + File tmpFile = File.createTempFile("tmpfile-", ".data", TMP); + writeBytes(tmpFile, pattern, repeat); return tmpFile; } - public static File createTempDir() - throws IOException - { - return createTempDir( "" ); + public static File createTempDir() throws IOException { + return createTempDir(""); } - public static File createTempDir( String suffix ) - throws IOException - { - mkdirs( TMP ); - File tmpFile = File.createTempFile( "tmpdir-", suffix, TMP ); - deleteFile( tmpFile ); - mkdirs( tmpFile ); + public static File createTempDir(String suffix) throws IOException { + mkdirs(TMP); + File tmpFile = File.createTempFile("tmpdir-", suffix, TMP); + deleteFile(tmpFile); + mkdirs(tmpFile); return tmpFile; } - public static long copyFile( File source, File target ) - throws IOException - { + public static long copyFile(File source, File target) throws IOException { long total = 0; FileInputStream fis = null; OutputStream fos = null; - try - { - fis = new FileInputStream( source ); + try { + fis = new FileInputStream(source); - mkdirs( target.getParentFile() ); + mkdirs(target.getParentFile()); - fos = new BufferedOutputStream( new FileOutputStream( target ) ); + fos = new BufferedOutputStream(new FileOutputStream(target)); - for ( byte[] buffer = new byte[ 1024 * 32 ];; ) - { - int bytes = fis.read( buffer ); - if ( bytes < 0 ) - { + for (byte[] buffer = new byte[1024 * 32]; ; ) { + int bytes = fis.read(buffer); + if (bytes < 0) { break; } - fos.write( buffer, 0, bytes ); + fos.write(buffer, 0, bytes); total += bytes; } @@ -208,31 +168,19 @@ public static long copyFile( File source, File target ) fis.close(); fis = null; - } - finally - { - try - { - if ( fos != null ) - { + } finally { + try { + if (fos != null) { fos.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. - } - finally - { - try - { - if ( fis != null ) - { + } finally { + try { + if (fis != null) { fis.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } @@ -241,134 +189,92 @@ public static long copyFile( File source, File target ) return total; } - public static byte[] readBytes( File file ) - throws IOException - { + public static byte[] readBytes(File file) throws IOException { RandomAccessFile in = null; - try - { - in = new RandomAccessFile( file, "r" ); - byte[] actual = new byte[ (int) in.length() ]; - in.readFully( actual ); + try { + in = new RandomAccessFile(file, "r"); + byte[] actual = new byte[(int) in.length()]; + in.readFully(actual); in.close(); in = null; return actual; - } - finally - { - try - { - if ( in != null ) - { + } finally { + try { + if (in != null) { in.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } } - public static void writeBytes( File file, byte[] pattern, int repeat ) - throws IOException - { + public static void writeBytes(File file, byte[] pattern, int repeat) throws IOException { file.deleteOnExit(); file.getParentFile().mkdirs(); OutputStream out = null; - try - { - out = new BufferedOutputStream( new FileOutputStream( file ) ); - for ( int i = 0; i < repeat; i++ ) - { - out.write( pattern ); + try { + out = new BufferedOutputStream(new FileOutputStream(file)); + for (int i = 0; i < repeat; i++) { + out.write(pattern); } out.close(); out = null; - } - finally - { - try - { - if ( out != null ) - { + } finally { + try { + if (out != null) { out.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } } - public static String readString( File file ) - throws IOException - { - byte[] content = readBytes( file ); - return new String( content, StandardCharsets.UTF_8 ); + public static String readString(File file) throws IOException { + byte[] content = readBytes(file); + return new String(content, StandardCharsets.UTF_8); } - public static void writeString( File file, String content ) - throws IOException - { - writeBytes( file, content.getBytes( StandardCharsets.UTF_8 ), 1 ); + public static void writeString(File file, String content) throws IOException { + writeBytes(file, content.getBytes(StandardCharsets.UTF_8), 1); } - public static void readProps( File file, Properties props ) - throws IOException - { + public static void readProps(File file, Properties props) throws IOException { FileInputStream fis = null; - try - { - fis = new FileInputStream( file ); - props.load( fis ); + try { + fis = new FileInputStream(file); + props.load(fis); fis.close(); fis = null; - } - finally - { - try - { - if ( fis != null ) - { + } finally { + try { + if (fis != null) { fis.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } } - public static void writeProps( File file, Properties props ) - throws IOException - { + public static void writeProps(File file, Properties props) throws IOException { file.getParentFile().mkdirs(); FileOutputStream fos = null; - try - { - fos = new FileOutputStream( file ); - props.store( fos, "aether-test" ); + try { + fos = new FileOutputStream(file); + props.store(fos, "aether-test"); fos.close(); fos = null; - } - finally - { - try - { - if ( fos != null ) - { + } finally { + try { + if (fos != null) { fos.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestLocalRepositoryManager.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestLocalRepositoryManager.java index c927d4491..4d1b442c2 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestLocalRepositoryManager.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestLocalRepositoryManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.io.File; import java.io.IOException; @@ -42,9 +41,7 @@ /** * A simplistic local repository manager that uses a temporary base directory. */ -public class TestLocalRepositoryManager - implements LocalRepositoryManager -{ +public class TestLocalRepositoryManager implements LocalRepositoryManager { private LocalRepository localRepository; @@ -54,26 +51,20 @@ public class TestLocalRepositoryManager private final Set metadataRegistrations = new HashSet<>(); - public TestLocalRepositoryManager() - { - try - { - localRepository = new LocalRepository( TestFileUtils.createTempDir( "test-local-repo" ) ); - } - catch ( IOException e ) - { - throw new IllegalStateException( e ); + public TestLocalRepositoryManager() { + try { + localRepository = new LocalRepository(TestFileUtils.createTempDir("test-local-repo")); + } catch (IOException e) { + throw new IllegalStateException(e); } } - public LocalRepository getRepository() - { + public LocalRepository getRepository() { return localRepository; } - public String getPathForLocalArtifact( Artifact artifact ) - { - requireNonNull( artifact, "artifact cannot be null" ); + public String getPathForLocalArtifact(Artifact artifact) { + requireNonNull(artifact, "artifact cannot be null"); String artifactId = artifact.getArtifactId(); String groupId = artifact.getGroupId(); @@ -81,101 +72,88 @@ public String getPathForLocalArtifact( Artifact artifact ) String version = artifact.getVersion(); String classifier = artifact.getClassifier(); - return String.format( "%s/%s/%s/%s-%s-%s%s.%s", groupId, artifactId, version, groupId, artifactId, version, - classifier, extension ); + return String.format( + "%s/%s/%s/%s-%s-%s%s.%s", + groupId, artifactId, version, groupId, artifactId, version, classifier, extension); } - public String getPathForRemoteArtifact( Artifact artifact, RemoteRepository repository, String context ) - { - requireNonNull( artifact, "artifact cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); + public String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context) { + requireNonNull(artifact, "artifact cannot be null"); + requireNonNull(repository, "repository cannot be null"); - return getPathForLocalArtifact( artifact ); + return getPathForLocalArtifact(artifact); } - public String getPathForLocalMetadata( Metadata metadata ) - { - requireNonNull( metadata, "metadata cannot be null" ); + public String getPathForLocalMetadata(Metadata metadata) { + requireNonNull(metadata, "metadata cannot be null"); String artifactId = metadata.getArtifactId(); String groupId = metadata.getGroupId(); String version = metadata.getVersion(); - return String.format( "%s/%s/%s/%s-%s-%s.xml", groupId, artifactId, version, groupId, artifactId, version ); + return String.format("%s/%s/%s/%s-%s-%s.xml", groupId, artifactId, version, groupId, artifactId, version); } - public String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repository, String context ) - { - requireNonNull( metadata, "metadata cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); + public String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context) { + requireNonNull(metadata, "metadata cannot be null"); + requireNonNull(repository, "repository cannot be null"); - return getPathForLocalMetadata( metadata ); + return getPathForLocalMetadata(metadata); } - public LocalArtifactResult find( RepositorySystemSession session, LocalArtifactRequest request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); + public LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); Artifact artifact = request.getArtifact(); - LocalArtifactResult result = new LocalArtifactResult( request ); - File file = new File( localRepository.getBasedir(), getPathForLocalArtifact( artifact ) ); - result.setFile( file.isFile() ? file : null ); - result.setAvailable( file.isFile() && !unavailableArtifacts.contains( artifact ) ); + LocalArtifactResult result = new LocalArtifactResult(request); + File file = new File(localRepository.getBasedir(), getPathForLocalArtifact(artifact)); + result.setFile(file.isFile() ? file : null); + result.setAvailable(file.isFile() && !unavailableArtifacts.contains(artifact)); return result; } - public void add( RepositorySystemSession session, LocalArtifactRegistration request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); + public void add(RepositorySystemSession session, LocalArtifactRegistration request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); - artifactRegistrations.add( request.getArtifact() ); + artifactRegistrations.add(request.getArtifact()); } - public LocalMetadataResult find( RepositorySystemSession session, LocalMetadataRequest request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); + public LocalMetadataResult find(RepositorySystemSession session, LocalMetadataRequest request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); Metadata metadata = request.getMetadata(); - LocalMetadataResult result = new LocalMetadataResult( request ); - File file = new File( localRepository.getBasedir(), getPathForLocalMetadata( metadata ) ); - result.setFile( file.isFile() ? file : null ); + LocalMetadataResult result = new LocalMetadataResult(request); + File file = new File(localRepository.getBasedir(), getPathForLocalMetadata(metadata)); + result.setFile(file.isFile() ? file : null); return result; } - public void add( RepositorySystemSession session, LocalMetadataRegistration request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); + public void add(RepositorySystemSession session, LocalMetadataRegistration request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); - metadataRegistrations.add( request.getMetadata() ); + metadataRegistrations.add(request.getMetadata()); } - public Set getArtifactRegistration() - { + public Set getArtifactRegistration() { return artifactRegistrations; } - public Set getMetadataRegistration() - { + public Set getMetadataRegistration() { return metadataRegistrations; } - public void setArtifactAvailability( Artifact artifact, boolean available ) - { - if ( available ) - { - unavailableArtifacts.remove( artifact ); - } - else - { - unavailableArtifacts.add( artifact ); + public void setArtifactAvailability(Artifact artifact, boolean available) { + if (available) { + unavailableArtifacts.remove(artifact); + } else { + unavailableArtifacts.add(artifact); } } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestLoggerFactory.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestLoggerFactory.java index ae58a16c6..d72e7baa7 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestLoggerFactory.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestLoggerFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.io.PrintStream; @@ -30,82 +29,64 @@ * @deprecated Use SLF4J instead */ @Deprecated -public final class TestLoggerFactory - implements LoggerFactory -{ +public final class TestLoggerFactory implements LoggerFactory { private final Logger logger; /** * Creates a new logger factory that writes to {@link System#out}. */ - public TestLoggerFactory() - { - this( null ); + public TestLoggerFactory() { + this(null); } /** * Creates a new logger factory that writes to the specified print stream. */ - public TestLoggerFactory( PrintStream out ) - { - logger = new TestLogger( out ); + public TestLoggerFactory(PrintStream out) { + logger = new TestLogger(out); } - public Logger getLogger( String name ) - { + public Logger getLogger(String name) { return logger; } - private static final class TestLogger - implements Logger - { + private static final class TestLogger implements Logger { private final PrintStream out; - TestLogger( PrintStream out ) - { - this.out = ( out != null ) ? out : System.out; + TestLogger(PrintStream out) { + this.out = (out != null) ? out : System.out; } - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return true; } - public void warn( String msg, Throwable error ) - { - out.println( "[WARN] " + msg ); - if ( error != null ) - { - error.printStackTrace( out ); + public void warn(String msg, Throwable error) { + out.println("[WARN] " + msg); + if (error != null) { + error.printStackTrace(out); } } - public void warn( String msg ) - { - warn( msg, null ); + public void warn(String msg) { + warn(msg, null); } - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return true; } - public void debug( String msg, Throwable error ) - { - out.println( "[DEBUG] " + msg ); - if ( error != null ) - { - error.printStackTrace( out ); + public void debug(String msg, Throwable error) { + out.println("[DEBUG] " + msg); + if (error != null) { + error.printStackTrace(out); } } - public void debug( String msg ) - { - debug( msg, null ); + public void debug(String msg) { + debug(msg, null); } - } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestUtils.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestUtils.java index cc0c4cb0f..41c9b3739 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestUtils.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.util.List; @@ -33,11 +32,9 @@ /** * Utility methods to help unit testing. */ -public class TestUtils -{ +public class TestUtils { - private TestUtils() - { + private TestUtils() { // hide constructor } @@ -45,48 +42,43 @@ private TestUtils() * Creates a new repository session whose local repository manager is initialized with an instance of * {@link TestLocalRepositoryManager}. */ - public static DefaultRepositorySystemSession newSession() - { + public static DefaultRepositorySystemSession newSession() { DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(); - session.setLocalRepositoryManager( new TestLocalRepositoryManager() ); + session.setLocalRepositoryManager(new TestLocalRepositoryManager()); return session; } /** * Creates a new dependency collection context. */ - public static DependencyCollectionContext newCollectionContext( RepositorySystemSession session, - Dependency dependency, - List managedDependencies ) - { - return new TestDependencyCollectionContext( session, null, dependency, managedDependencies ); + public static DependencyCollectionContext newCollectionContext( + RepositorySystemSession session, Dependency dependency, List managedDependencies) { + return new TestDependencyCollectionContext(session, null, dependency, managedDependencies); } /** * Creates a new dependency collection context. */ - public static DependencyCollectionContext newCollectionContext( RepositorySystemSession session, Artifact artifact, - Dependency dependency, - List managedDependencies ) - { - return new TestDependencyCollectionContext( session, artifact, dependency, managedDependencies ); + public static DependencyCollectionContext newCollectionContext( + RepositorySystemSession session, + Artifact artifact, + Dependency dependency, + List managedDependencies) { + return new TestDependencyCollectionContext(session, artifact, dependency, managedDependencies); } /** * Creates a new dependency graph transformation context. */ - public static DependencyGraphTransformationContext newTransformationContext( RepositorySystemSession session ) - { - return new TestDependencyGraphTransformationContext( session ); + public static DependencyGraphTransformationContext newTransformationContext(RepositorySystemSession session) { + return new TestDependencyGraphTransformationContext(session); } /** * Creates a new version filter context from the specified session and version range result. */ - public static VersionFilter.VersionFilterContext newVersionFilterContext( RepositorySystemSession session, - VersionRangeResult rangeResult ) - { - return new TestVersionFilterContext( session, rangeResult ); + public static VersionFilter.VersionFilterContext newVersionFilterContext( + RepositorySystemSession session, VersionRangeResult rangeResult) { + return new TestVersionFilterContext(session, rangeResult); } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersion.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersion.java index d9d29e2b1..a8769306f 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersion.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersion.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,71 +16,57 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import org.eclipse.aether.version.Version; /** * Version ordering by {@link String#compareToIgnoreCase(String)}. */ -public final class TestVersion - implements Version -{ +public final class TestVersion implements Version { private final String version; - public TestVersion( String version ) - { + public TestVersion(String version) { this.version = version == null ? "" : version; } - public int compareTo( Version o ) - { - return version.compareTo( o.toString() ); + public int compareTo(Version o) { + return version.compareTo(o.toString()); } @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ( ( version == null ) ? 0 : version.hashCode() ); + result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null ) - { + if (obj == null) { return false; } - if ( getClass() != obj.getClass() ) - { + if (getClass() != obj.getClass()) { return false; } TestVersion other = (TestVersion) obj; - if ( version == null ) - { - if ( other.version != null ) - { + if (version == null) { + if (other.version != null) { return false; } - } - else if ( !version.equals( other.version ) ) - { + } else if (!version.equals(other.version)) { return false; } return true; } @Override - public String toString() - { + public String toString() { return version; } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionConstraint.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionConstraint.java index 9edd1c9a5..c941df6e0 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionConstraint.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionConstraint.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,21 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; -import static java.util.Objects.requireNonNull; +import java.util.Objects; import org.eclipse.aether.version.Version; import org.eclipse.aether.version.VersionConstraint; import org.eclipse.aether.version.VersionRange; -import java.util.Objects; +import static java.util.Objects.requireNonNull; /** * A constraint on versions for a dependency. */ -public final class TestVersionConstraint - implements VersionConstraint -{ +public final class TestVersionConstraint implements VersionConstraint { private final VersionRange range; @@ -43,9 +40,8 @@ public final class TestVersionConstraint * * @param range The version range, must not be {@code null}. */ - public TestVersionConstraint( VersionRange range ) - { - this.range = requireNonNull( range, "version range cannot be null" ); + public TestVersionConstraint(VersionRange range) { + this.range = requireNonNull(range, "version range cannot be null"); this.version = null; } @@ -54,70 +50,55 @@ public TestVersionConstraint( VersionRange range ) * * @param version The version, must not be {@code null}. */ - public TestVersionConstraint( Version version ) - { - this.version = requireNonNull( version, "version cannot be null" ); + public TestVersionConstraint(Version version) { + this.version = requireNonNull(version, "version cannot be null"); this.range = null; } - public VersionRange getRange() - { + public VersionRange getRange() { return range; } - public Version getVersion() - { + public Version getVersion() { return version; } - public boolean containsVersion( Version version ) - { - if ( range == null ) - { - return version.equals( this.version ); - } - else - { - return range.containsVersion( version ); + public boolean containsVersion(Version version) { + if (range == null) { + return version.equals(this.version); + } else { + return range.containsVersion(version); } } @Override - public String toString() - { - return String.valueOf( ( range == null ) ? version : range ); + public String toString() { + return String.valueOf((range == null) ? version : range); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } TestVersionConstraint that = (TestVersionConstraint) obj; - return Objects.equals( range, that.range ) - && Objects.equals( version, that.getVersion() ); + return Objects.equals(range, that.range) && Objects.equals(version, that.getVersion()); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + hash( getRange() ); - hash = hash * 31 + hash( getVersion() ); + hash = hash * 31 + hash(getRange()); + hash = hash * 31 + hash(getVersion()); return hash; } - private static int hash( Object obj ) - { + private static int hash(Object obj) { return obj != null ? obj.hashCode() : 0; } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionFilterContext.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionFilterContext.java index 44f4f5613..62e9a1bd8 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionFilterContext.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionFilterContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.util.ArrayList; import java.util.Collections; @@ -35,9 +34,7 @@ /** */ -class TestVersionFilterContext - implements VersionFilter.VersionFilterContext -{ +class TestVersionFilterContext implements VersionFilter.VersionFilterContext { private final RepositorySystemSession session; @@ -47,47 +44,38 @@ class TestVersionFilterContext private final List versions; - TestVersionFilterContext( RepositorySystemSession session, VersionRangeResult result ) - { + TestVersionFilterContext(RepositorySystemSession session, VersionRangeResult result) { this.session = session; this.result = result; - dependency = new Dependency( result.getRequest().getArtifact(), "" ); - versions = new ArrayList<>( result.getVersions() ); + dependency = new Dependency(result.getRequest().getArtifact(), ""); + versions = new ArrayList<>(result.getVersions()); } - public RepositorySystemSession getSession() - { + public RepositorySystemSession getSession() { return session; } - public Dependency getDependency() - { + public Dependency getDependency() { return dependency; } - public int getCount() - { + public int getCount() { return versions.size(); } - public Iterator iterator() - { + public Iterator iterator() { return versions.iterator(); } - public VersionConstraint getVersionConstraint() - { + public VersionConstraint getVersionConstraint() { return result.getVersionConstraint(); } - public ArtifactRepository getRepository( Version version ) - { - return result.getRepository( version ); + public ArtifactRepository getRepository(Version version) { + return result.getRepository(version); } - public List getRepositories() - { - return Collections.unmodifiableList( result.getRequest().getRepositories() ); + public List getRepositories() { + return Collections.unmodifiableList(result.getRequest().getRepositories()); } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionRange.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionRange.java index 750a63f0d..e326c601e 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionRange.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionRange.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,19 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; + +import java.util.Objects; import org.eclipse.aether.version.InvalidVersionSpecificationException; import org.eclipse.aether.version.Version; import org.eclipse.aether.version.VersionRange; -import java.util.Objects; - /** * A version range inspired by mathematical range syntax. For example, "[1.0,2.0)", "[1.0,)" or "[1.0]". */ -final class TestVersionRange - implements VersionRange -{ +final class TestVersionRange implements VersionRange { private final Version lowerBound; @@ -42,205 +39,164 @@ final class TestVersionRange /** * Creates a version range from the specified range specification. - * + * * @param range The range specification to parse, must not be {@code null}. * @throws InvalidVersionSpecificationException If the range could not be parsed. */ - TestVersionRange( String range ) - throws InvalidVersionSpecificationException - { + TestVersionRange(String range) throws InvalidVersionSpecificationException { String process = range; - if ( range.startsWith( "[" ) ) - { + if (range.startsWith("[")) { lowerBoundInclusive = true; - } - else if ( range.startsWith( "(" ) ) - { + } else if (range.startsWith("(")) { lowerBoundInclusive = false; - } - else - { - throw new InvalidVersionSpecificationException( range, "Invalid version range " + range - + ", a range must start with either [ or (" ); + } else { + throw new InvalidVersionSpecificationException( + range, "Invalid version range " + range + ", a range must start with either [ or ("); } - if ( range.endsWith( "]" ) ) - { + if (range.endsWith("]")) { upperBoundInclusive = true; - } - else if ( range.endsWith( ")" ) ) - { + } else if (range.endsWith(")")) { upperBoundInclusive = false; - } - else - { - throw new InvalidVersionSpecificationException( range, "Invalid version range " + range - + ", a range must end with either [ or (" ); + } else { + throw new InvalidVersionSpecificationException( + range, "Invalid version range " + range + ", a range must end with either [ or ("); } - process = process.substring( 1, process.length() - 1 ); + process = process.substring(1, process.length() - 1); - int index = process.indexOf( "," ); + int index = process.indexOf(","); - if ( index < 0 ) - { - if ( !lowerBoundInclusive || !upperBoundInclusive ) - { - throw new InvalidVersionSpecificationException( range, "Invalid version range " + range - + ", single version must be surrounded by []" ); + if (index < 0) { + if (!lowerBoundInclusive || !upperBoundInclusive) { + throw new InvalidVersionSpecificationException( + range, "Invalid version range " + range + ", single version must be surrounded by []"); } - lowerBound = new TestVersion( process.trim() ); - upperBound = new TestVersion( process.trim() ); - } - else - { - String parsedLowerBound = process.substring( 0, index ).trim(); - String parsedUpperBound = process.substring( index + 1 ).trim(); + lowerBound = new TestVersion(process.trim()); + upperBound = new TestVersion(process.trim()); + } else { + String parsedLowerBound = process.substring(0, index).trim(); + String parsedUpperBound = process.substring(index + 1).trim(); // more than two bounds, e.g. (1,2,3) - if ( parsedUpperBound.contains( "," ) ) - { - throw new InvalidVersionSpecificationException( range, "Invalid version range " + range - + ", bounds may not contain additional ','" ); + if (parsedUpperBound.contains(",")) { + throw new InvalidVersionSpecificationException( + range, "Invalid version range " + range + ", bounds may not contain additional ','"); } - lowerBound = parsedLowerBound.length() > 0 ? new TestVersion( parsedLowerBound ) : null; - upperBound = parsedUpperBound.length() > 0 ? new TestVersion( parsedUpperBound ) : null; + lowerBound = parsedLowerBound.length() > 0 ? new TestVersion(parsedLowerBound) : null; + upperBound = parsedUpperBound.length() > 0 ? new TestVersion(parsedUpperBound) : null; - if ( upperBound != null && lowerBound != null ) - { - if ( upperBound.compareTo( lowerBound ) < 0 ) - { - throw new InvalidVersionSpecificationException( range, "Invalid version range " + range - + ", lower bound must not be greater than upper bound" ); + if (upperBound != null && lowerBound != null) { + if (upperBound.compareTo(lowerBound) < 0) { + throw new InvalidVersionSpecificationException( + range, + "Invalid version range " + range + ", lower bound must not be greater than upper bound"); } } } } - public Bound getLowerBound() - { - return new Bound( lowerBound, lowerBoundInclusive ); + public Bound getLowerBound() { + return new Bound(lowerBound, lowerBoundInclusive); } - public Bound getUpperBound() - { - return new Bound( upperBound, upperBoundInclusive ); + public Bound getUpperBound() { + return new Bound(upperBound, upperBoundInclusive); } - public boolean acceptsSnapshots() - { - return isSnapshot( lowerBound ) || isSnapshot( upperBound ); + public boolean acceptsSnapshots() { + return isSnapshot(lowerBound) || isSnapshot(upperBound); } - public boolean containsVersion( Version version ) - { - boolean snapshot = isSnapshot( version ); + public boolean containsVersion(Version version) { + boolean snapshot = isSnapshot(version); - if ( lowerBound != null ) - { - int comparison = lowerBound.compareTo( version ); + if (lowerBound != null) { + int comparison = lowerBound.compareTo(version); - if ( snapshot && comparison == 0 ) - { + if (snapshot && comparison == 0) { return true; } - if ( comparison == 0 && !lowerBoundInclusive ) - { + if (comparison == 0 && !lowerBoundInclusive) { return false; } - if ( comparison > 0 ) - { + if (comparison > 0) { return false; } } - if ( upperBound != null ) - { - int comparison = upperBound.compareTo( version ); + if (upperBound != null) { + int comparison = upperBound.compareTo(version); - if ( snapshot && comparison == 0 ) - { + if (snapshot && comparison == 0) { return true; } - if ( comparison == 0 && !upperBoundInclusive ) - { + if (comparison == 0 && !upperBoundInclusive) { return false; } - if ( comparison < 0 ) - { + if (comparison < 0) { return false; } } - if ( lowerBound != null || upperBound != null ) - { + if (lowerBound != null || upperBound != null) { return !snapshot; } return true; } - private boolean isSnapshot( Version version ) - { - return version != null && version.toString().endsWith( "SNAPSHOT" ); + private boolean isSnapshot(Version version) { + return version != null && version.toString().endsWith("SNAPSHOT"); } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + } else if (obj == null || !getClass().equals(obj.getClass())) { return false; } TestVersionRange that = (TestVersionRange) obj; - return upperBoundInclusive == that.upperBoundInclusive && lowerBoundInclusive == that.lowerBoundInclusive - && Objects.equals( upperBound, that.upperBound ) - && Objects.equals( lowerBound, that.lowerBound ); + return upperBoundInclusive == that.upperBoundInclusive + && lowerBoundInclusive == that.lowerBoundInclusive + && Objects.equals(upperBound, that.upperBound) + && Objects.equals(lowerBound, that.lowerBound); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + hash( upperBound ); - hash = hash * 31 + ( upperBoundInclusive ? 1 : 0 ); - hash = hash * 31 + hash( lowerBound ); - hash = hash * 31 + ( lowerBoundInclusive ? 1 : 0 ); + hash = hash * 31 + hash(upperBound); + hash = hash * 31 + (upperBoundInclusive ? 1 : 0); + hash = hash * 31 + hash(lowerBound); + hash = hash * 31 + (lowerBoundInclusive ? 1 : 0); return hash; } - private static int hash( Object obj ) - { + private static int hash(Object obj) { return obj != null ? obj.hashCode() : 0; } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 64 ); - buffer.append( lowerBoundInclusive ? '[' : '(' ); - if ( lowerBound != null ) - { - buffer.append( lowerBound ); + public String toString() { + StringBuilder buffer = new StringBuilder(64); + buffer.append(lowerBoundInclusive ? '[' : '('); + if (lowerBound != null) { + buffer.append(lowerBound); } - buffer.append( ',' ); - if ( upperBound != null ) - { - buffer.append( upperBound ); + buffer.append(','); + if (upperBound != null) { + buffer.append(upperBound); } - buffer.append( upperBoundInclusive ? ']' : ')' ); + buffer.append(upperBoundInclusive ? ']' : ')'); return buffer.toString(); } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionScheme.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionScheme.java index 5fd5c8a30..7fd597494 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionScheme.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/TestVersionScheme.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.test.util; import java.util.ArrayList; import java.util.Collection; @@ -33,92 +32,74 @@ /** * A version scheme using a generic version syntax. */ -final class TestVersionScheme - implements VersionScheme -{ - - public Version parseVersion( final String version ) - { - requireNonNull( version, "version cannot be null" ); - return new TestVersion( version ); +final class TestVersionScheme implements VersionScheme { + + public Version parseVersion(final String version) { + requireNonNull(version, "version cannot be null"); + return new TestVersion(version); } - public VersionRange parseVersionRange( final String range ) - throws InvalidVersionSpecificationException - { - requireNonNull( range, "range cannot be null" ); - return new TestVersionRange( range ); + public VersionRange parseVersionRange(final String range) throws InvalidVersionSpecificationException { + requireNonNull(range, "range cannot be null"); + return new TestVersionRange(range); } - public VersionConstraint parseVersionConstraint( final String constraint ) - throws InvalidVersionSpecificationException - { - requireNonNull( constraint, "constraint cannot be null" ); + public VersionConstraint parseVersionConstraint(final String constraint) + throws InvalidVersionSpecificationException { + requireNonNull(constraint, "constraint cannot be null"); Collection ranges = new ArrayList<>(); String process = constraint; - while ( process.startsWith( "[" ) || process.startsWith( "(" ) ) - { - int index1 = process.indexOf( ')' ); - int index2 = process.indexOf( ']' ); + while (process.startsWith("[") || process.startsWith("(")) { + int index1 = process.indexOf(')'); + int index2 = process.indexOf(']'); int index = index2; - if ( index2 < 0 || ( index1 >= 0 && index1 < index2 ) ) - { + if (index2 < 0 || (index1 >= 0 && index1 < index2)) { index = index1; } - if ( index < 0 ) - { - throw new InvalidVersionSpecificationException( constraint, "Unbounded version range " + constraint ); + if (index < 0) { + throw new InvalidVersionSpecificationException(constraint, "Unbounded version range " + constraint); } - VersionRange range = parseVersionRange( process.substring( 0, index + 1 ) ); - ranges.add( range ); + VersionRange range = parseVersionRange(process.substring(0, index + 1)); + ranges.add(range); - process = process.substring( index + 1 ).trim(); + process = process.substring(index + 1).trim(); - if ( process.length() > 0 && process.startsWith( "," ) ) - { - process = process.substring( 1 ).trim(); + if (process.length() > 0 && process.startsWith(",")) { + process = process.substring(1).trim(); } } - if ( process.length() > 0 && !ranges.isEmpty() ) - { - throw new InvalidVersionSpecificationException( constraint, "Invalid version range " + constraint - + ", expected [ or ( but got " + process ); + if (process.length() > 0 && !ranges.isEmpty()) { + throw new InvalidVersionSpecificationException( + constraint, "Invalid version range " + constraint + ", expected [ or ( but got " + process); } VersionConstraint result; - if ( ranges.isEmpty() ) - { - result = new TestVersionConstraint( parseVersion( constraint ) ); - } - else - { - result = new TestVersionConstraint( ranges.iterator().next() ); + if (ranges.isEmpty()) { + result = new TestVersionConstraint(parseVersion(constraint)); + } else { + result = new TestVersionConstraint(ranges.iterator().next()); } return result; } @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { + public boolean equals(final Object obj) { + if (this == obj) { return true; } - return obj != null && getClass().equals( obj.getClass() ); + return obj != null && getClass().equals(obj.getClass()); } @Override - public int hashCode() - { + public int hashCode() { return getClass().hashCode(); } - } diff --git a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/package-info.java b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/package-info.java index 4d874dac0..f6b3bc041 100644 --- a/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/package-info.java +++ b/maven-resolver-test-util/src/main/java/org/eclipse/aether/internal/test/util/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -23,4 +23,3 @@ * a stable API and are subject to change without prior notice. */ package org.eclipse.aether.internal.test.util; - diff --git a/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/DependencyGraphParserTest.java b/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/DependencyGraphParserTest.java index 10f257b45..197ea4956 100644 --- a/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/DependencyGraphParserTest.java +++ b/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/DependencyGraphParserTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.test.util; import java.io.IOException; import java.util.Arrays; @@ -29,271 +26,237 @@ import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.DependencyNode; -import org.eclipse.aether.internal.test.util.DependencyGraphParser; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DependencyGraphParserTest -{ +public class DependencyGraphParserTest { private DependencyGraphParser parser; @Before - public void setup() - { + public void setup() { this.parser = new DependencyGraphParser(); } @Test - public void testOnlyRoot() - throws IOException - { + public void testOnlyRoot() throws IOException { String def = "gid:aid:jar:1 scope"; - DependencyNode node = parser.parseLiteral( def ); + DependencyNode node = parser.parseLiteral(def); - assertNotNull( node ); - assertEquals( 0, node.getChildren().size() ); + assertNotNull(node); + assertEquals(0, node.getChildren().size()); Dependency dependency = node.getDependency(); - assertNotNull( dependency ); - assertEquals( "scope", dependency.getScope() ); + assertNotNull(dependency); + assertEquals("scope", dependency.getScope()); Artifact artifact = dependency.getArtifact(); - assertNotNull( artifact ); + assertNotNull(artifact); - assertEquals( "gid", artifact.getGroupId() ); - assertEquals( "aid", artifact.getArtifactId() ); - assertEquals( "jar", artifact.getExtension() ); - assertEquals( "1", artifact.getVersion() ); + assertEquals("gid", artifact.getGroupId()); + assertEquals("aid", artifact.getArtifactId()); + assertEquals("jar", artifact.getExtension()); + assertEquals("1", artifact.getVersion()); } @Test - public void testOptionalScope() - throws IOException - { + public void testOptionalScope() throws IOException { String def = "gid:aid:jar:1"; - DependencyNode node = parser.parseLiteral( def ); + DependencyNode node = parser.parseLiteral(def); - assertNotNull( node ); - assertEquals( 0, node.getChildren().size() ); + assertNotNull(node); + assertEquals(0, node.getChildren().size()); Dependency dependency = node.getDependency(); - assertNotNull( dependency ); - assertEquals( "", dependency.getScope() ); + assertNotNull(dependency); + assertEquals("", dependency.getScope()); } @Test - public void testWithChildren() - throws IOException - { + public void testWithChildren() throws IOException { String def = - "gid1:aid1:ext1:ver1 scope1\n" + "+- gid2:aid2:ext2:ver2 scope2\n" + "\\- gid3:aid3:ext3:ver3 scope3\n"; + "gid1:aid1:ext1:ver1 scope1\n" + "+- gid2:aid2:ext2:ver2 scope2\n" + "\\- gid3:aid3:ext3:ver3 scope3\n"; - DependencyNode node = parser.parseLiteral( def ); - assertNotNull( node ); + DependencyNode node = parser.parseLiteral(def); + assertNotNull(node); int idx = 1; - assertNodeProperties( node, idx++ ); + assertNodeProperties(node, idx++); List children = node.getChildren(); - assertEquals( 2, children.size() ); + assertEquals(2, children.size()); - for ( DependencyNode child : children ) - { - assertNodeProperties( child, idx++ ); + for (DependencyNode child : children) { + assertNodeProperties(child, idx++); } - } @Test - public void testDeepChildren() - throws IOException - { - String def = - "gid1:aid1:ext1:ver1\n" + "+- gid2:aid2:ext2:ver2 scope2\n" + "| \\- gid3:aid3:ext3:ver3\n" + public void testDeepChildren() throws IOException { + String def = "gid1:aid1:ext1:ver1\n" + "+- gid2:aid2:ext2:ver2 scope2\n" + "| \\- gid3:aid3:ext3:ver3\n" + "\\- gid4:aid4:ext4:ver4 scope4"; - DependencyNode node = parser.parseLiteral( def ); - assertNodeProperties( node, 1 ); + DependencyNode node = parser.parseLiteral(def); + assertNodeProperties(node, 1); - assertEquals( 2, node.getChildren().size() ); - assertNodeProperties( node.getChildren().get( 1 ), 4 ); - DependencyNode lvl1Node = node.getChildren().get( 0 ); - assertNodeProperties( lvl1Node, 2 ); + assertEquals(2, node.getChildren().size()); + assertNodeProperties(node.getChildren().get(1), 4); + DependencyNode lvl1Node = node.getChildren().get(0); + assertNodeProperties(lvl1Node, 2); - assertEquals( 1, lvl1Node.getChildren().size() ); - assertNodeProperties( lvl1Node.getChildren().get( 0 ), 3 ); + assertEquals(1, lvl1Node.getChildren().size()); + assertNodeProperties(lvl1Node.getChildren().get(0), 3); } - private void assertNodeProperties( DependencyNode node, int idx ) - { - assertNodeProperties( node, String.valueOf( idx ) ); + private void assertNodeProperties(DependencyNode node, int idx) { + assertNodeProperties(node, String.valueOf(idx)); } - private void assertNodeProperties( DependencyNode node, String suffix ) - { - assertNotNull( node ); + private void assertNodeProperties(DependencyNode node, String suffix) { + assertNotNull(node); Dependency dependency = node.getDependency(); - assertNotNull( dependency ); - if ( !"".equals( dependency.getScope() ) ) - { - assertEquals( "scope" + suffix, dependency.getScope() ); + assertNotNull(dependency); + if (!"".equals(dependency.getScope())) { + assertEquals("scope" + suffix, dependency.getScope()); } Artifact artifact = dependency.getArtifact(); - assertNotNull( artifact ); + assertNotNull(artifact); - assertEquals( "gid" + suffix, artifact.getGroupId() ); - assertEquals( "aid" + suffix, artifact.getArtifactId() ); - assertEquals( "ext" + suffix, artifact.getExtension() ); - assertEquals( "ver" + suffix, artifact.getVersion() ); + assertEquals("gid" + suffix, artifact.getGroupId()); + assertEquals("aid" + suffix, artifact.getArtifactId()); + assertEquals("ext" + suffix, artifact.getExtension()); + assertEquals("ver" + suffix, artifact.getVersion()); } @Test - public void testComments() - throws IOException - { + public void testComments() throws IOException { String def = "# first line\n#second line\ngid:aid:ext:ver # root artifact asdf:qwer:zcxv:uip"; - DependencyNode node = parser.parseLiteral( def ); + DependencyNode node = parser.parseLiteral(def); - assertNodeProperties( node, "" ); + assertNodeProperties(node, ""); } @Test - public void testId() - throws IOException - { + public void testId() throws IOException { String def = "gid:aid:ext:ver (id)\n\\- ^id"; - DependencyNode node = parser.parseLiteral( def ); - assertNodeProperties( node, "" ); + DependencyNode node = parser.parseLiteral(def); + assertNodeProperties(node, ""); - assertNotNull( node.getChildren() ); - assertEquals( 1, node.getChildren().size() ); + assertNotNull(node.getChildren()); + assertEquals(1, node.getChildren().size()); - assertSame( node, node.getChildren().get( 0 ) ); + assertSame(node, node.getChildren().get(0)); } @Test - public void testResourceLoading() - throws IOException - { + public void testResourceLoading() throws IOException { String prefix = "org/eclipse/aether/internal/test/util/"; String name = "testResourceLoading.txt"; - DependencyNode node = parser.parseResource( prefix + name ); - assertEquals( 0, node.getChildren().size() ); - assertNodeProperties( node, "" ); + DependencyNode node = parser.parseResource(prefix + name); + assertEquals(0, node.getChildren().size()); + assertNodeProperties(node, ""); } @Test - public void testResourceLoadingWithPrefix() - throws IOException - { + public void testResourceLoadingWithPrefix() throws IOException { String prefix = "org/eclipse/aether/internal/test/util/"; - parser = new DependencyGraphParser( prefix ); + parser = new DependencyGraphParser(prefix); String name = "testResourceLoading.txt"; - DependencyNode node = parser.parseResource( name ); - assertEquals( 0, node.getChildren().size() ); - assertNodeProperties( node, "" ); + DependencyNode node = parser.parseResource(name); + assertEquals(0, node.getChildren().size()); + assertNodeProperties(node, ""); } @Test - public void testProperties() - throws IOException - { + public void testProperties() throws IOException { String def = "gid:aid:ext:ver props=test:foo,test2:fizzle"; - DependencyNode node = parser.parseLiteral( def ); + DependencyNode node = parser.parseLiteral(def); - assertNodeProperties( node, "" ); + assertNodeProperties(node, ""); Map properties = node.getDependency().getArtifact().getProperties(); - assertNotNull( properties ); - assertEquals( 2, properties.size() ); + assertNotNull(properties); + assertEquals(2, properties.size()); - assertTrue( properties.containsKey( "test" ) ); - assertEquals( "foo", properties.get( "test" ) ); - assertTrue( properties.containsKey( "test2" ) ); - assertEquals( "fizzle", properties.get( "test2" ) ); + assertTrue(properties.containsKey("test")); + assertEquals("foo", properties.get("test")); + assertTrue(properties.containsKey("test2")); + assertEquals("fizzle", properties.get("test2")); } @Test - public void testSubstitutions() - throws IOException - { - parser.setSubstitutions( Arrays.asList( "subst1", "subst2" ) ); + public void testSubstitutions() throws IOException { + parser.setSubstitutions(Arrays.asList("subst1", "subst2")); String def = "%s:%s:ext:ver"; - DependencyNode root = parser.parseLiteral( def ); + DependencyNode root = parser.parseLiteral(def); Artifact artifact = root.getDependency().getArtifact(); - assertEquals( "subst2", artifact.getArtifactId() ); - assertEquals( "subst1", artifact.getGroupId() ); + assertEquals("subst2", artifact.getArtifactId()); + assertEquals("subst1", artifact.getGroupId()); def = "%s:aid:ext:ver\n\\- %s:aid:ext:ver"; - root = parser.parseLiteral( def ); + root = parser.parseLiteral(def); - assertEquals( "subst1", root.getDependency().getArtifact().getGroupId() ); - assertEquals( "subst2", root.getChildren().get( 0 ).getDependency().getArtifact().getGroupId() ); + assertEquals("subst1", root.getDependency().getArtifact().getGroupId()); + assertEquals( + "subst2", + root.getChildren().get(0).getDependency().getArtifact().getGroupId()); } @Test - public void testMultiple() - throws IOException - { + public void testMultiple() throws IOException { String prefix = "org/eclipse/aether/internal/test/util/"; String name = "testResourceLoading.txt"; - List nodes = parser.parseMultiResource( prefix + name ); + List nodes = parser.parseMultiResource(prefix + name); - assertEquals( 2, nodes.size() ); - assertEquals( "aid", nodes.get( 0 ).getDependency().getArtifact().getArtifactId() ); - assertEquals( "aid2", nodes.get( 1 ).getDependency().getArtifact().getArtifactId() ); + assertEquals(2, nodes.size()); + assertEquals("aid", nodes.get(0).getDependency().getArtifact().getArtifactId()); + assertEquals("aid2", nodes.get(1).getDependency().getArtifact().getArtifactId()); } @Test - public void testRootNullDependency() - throws IOException - { + public void testRootNullDependency() throws IOException { String literal = "(null)\n+- gid:aid:ext:ver"; - DependencyNode root = parser.parseLiteral( literal ); + DependencyNode root = parser.parseLiteral(literal); - assertNull( root.getDependency() ); - assertEquals( 1, root.getChildren().size() ); + assertNull(root.getDependency()); + assertEquals(1, root.getChildren().size()); } @Test - public void testChildNullDependency() - throws IOException - { + public void testChildNullDependency() throws IOException { String literal = "gid:aid:ext:ver\n+- (null)"; - DependencyNode root = parser.parseLiteral( literal ); + DependencyNode root = parser.parseLiteral(literal); - assertNotNull( root.getDependency() ); - assertEquals( 1, root.getChildren().size() ); - assertNull( root.getChildren().get( 0 ).getDependency() ); + assertNotNull(root.getDependency()); + assertEquals(1, root.getChildren().size()); + assertNull(root.getChildren().get(0).getDependency()); } @Test - public void testOptional() - throws IOException - { + public void testOptional() throws IOException { String def = "gid:aid:jar:1 compile optional"; - DependencyNode node = parser.parseLiteral( def ); + DependencyNode node = parser.parseLiteral(def); - assertNotNull( node ); - assertEquals( 0, node.getChildren().size() ); + assertNotNull(node); + assertEquals(0, node.getChildren().size()); Dependency dependency = node.getDependency(); - assertNotNull( dependency ); - assertEquals( "compile", dependency.getScope() ); - assertTrue( dependency.isOptional() ); + assertNotNull(dependency); + assertEquals("compile", dependency.getScope()); + assertTrue(dependency.isOptional()); } - } diff --git a/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/IniArtifactDataReaderTest.java b/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/IniArtifactDataReaderTest.java index 4a509538b..b59d60636 100644 --- a/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/IniArtifactDataReaderTest.java +++ b/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/IniArtifactDataReaderTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.test.util; import java.io.IOException; import java.util.Collection; @@ -29,203 +26,190 @@ import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.Exclusion; -import org.eclipse.aether.internal.test.util.ArtifactDescription; -import org.eclipse.aether.internal.test.util.IniArtifactDataReader; import org.eclipse.aether.repository.RemoteRepository; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class IniArtifactDataReaderTest -{ +public class IniArtifactDataReaderTest { private IniArtifactDataReader parser; @Before - public void setup() - { - this.parser = new IniArtifactDataReader( "org/eclipse/aether/internal/test/util/" ); + public void setup() { + this.parser = new IniArtifactDataReader("org/eclipse/aether/internal/test/util/"); } @Test - public void testRelocation() - throws IOException - { + public void testRelocation() throws IOException { String def = "[relocation]\ngid:aid:ext:ver"; - ArtifactDescription description = parser.parseLiteral( def ); + ArtifactDescription description = parser.parseLiteral(def); Artifact artifact = description.getRelocation(); - assertNotNull( artifact ); - assertEquals( "aid", artifact.getArtifactId() ); - assertEquals( "gid", artifact.getGroupId() ); - assertEquals( "ver", artifact.getVersion() ); - assertEquals( "ext", artifact.getExtension() ); + assertNotNull(artifact); + assertEquals("aid", artifact.getArtifactId()); + assertEquals("gid", artifact.getGroupId()); + assertEquals("ver", artifact.getVersion()); + assertEquals("ext", artifact.getExtension()); } @Test - public void testDependencies() - throws IOException - { + public void testDependencies() throws IOException { String def = "[dependencies]\ngid:aid:ext:ver\n-exclusion:aid\ngid2:aid2:ext2:ver2"; - ArtifactDescription description = parser.parseLiteral( def ); + ArtifactDescription description = parser.parseLiteral(def); List dependencies = description.getDependencies(); - assertNotNull( dependencies ); - assertEquals( 2, dependencies.size() ); + assertNotNull(dependencies); + assertEquals(2, dependencies.size()); - Dependency dependency = dependencies.get( 0 ); - assertEquals( "compile", dependency.getScope() ); + Dependency dependency = dependencies.get(0); + assertEquals("compile", dependency.getScope()); Artifact artifact = dependency.getArtifact(); - assertNotNull( artifact ); - assertEquals( "aid", artifact.getArtifactId() ); - assertEquals( "gid", artifact.getGroupId() ); - assertEquals( "ver", artifact.getVersion() ); - assertEquals( "ext", artifact.getExtension() ); + assertNotNull(artifact); + assertEquals("aid", artifact.getArtifactId()); + assertEquals("gid", artifact.getGroupId()); + assertEquals("ver", artifact.getVersion()); + assertEquals("ext", artifact.getExtension()); Collection exclusions = dependency.getExclusions(); - assertNotNull( exclusions ); - assertEquals( 1, exclusions.size() ); + assertNotNull(exclusions); + assertEquals(1, exclusions.size()); Exclusion exclusion = exclusions.iterator().next(); - assertEquals( "exclusion", exclusion.getGroupId() ); - assertEquals( "aid", exclusion.getArtifactId() ); - assertEquals( "*", exclusion.getClassifier() ); - assertEquals( "*", exclusion.getExtension() ); + assertEquals("exclusion", exclusion.getGroupId()); + assertEquals("aid", exclusion.getArtifactId()); + assertEquals("*", exclusion.getClassifier()); + assertEquals("*", exclusion.getExtension()); - dependency = dependencies.get( 1 ); + dependency = dependencies.get(1); artifact = dependency.getArtifact(); - assertNotNull( artifact ); - assertEquals( "aid2", artifact.getArtifactId() ); - assertEquals( "gid2", artifact.getGroupId() ); - assertEquals( "ver2", artifact.getVersion() ); - assertEquals( "ext2", artifact.getExtension() ); + assertNotNull(artifact); + assertEquals("aid2", artifact.getArtifactId()); + assertEquals("gid2", artifact.getGroupId()); + assertEquals("ver2", artifact.getVersion()); + assertEquals("ext2", artifact.getExtension()); } @Test - public void testManagedDependencies() - throws IOException - { + public void testManagedDependencies() throws IOException { String def = "[managed-dependencies]\ngid:aid:ext:ver\n-exclusion:aid\ngid2:aid2:ext2:ver2:runtime"; - ArtifactDescription description = parser.parseLiteral( def ); + ArtifactDescription description = parser.parseLiteral(def); List dependencies = description.getManagedDependencies(); - assertNotNull( dependencies ); - assertEquals( 2, dependencies.size() ); + assertNotNull(dependencies); + assertEquals(2, dependencies.size()); - Dependency dependency = dependencies.get( 0 ); - assertEquals( "", dependency.getScope() ); + Dependency dependency = dependencies.get(0); + assertEquals("", dependency.getScope()); Artifact artifact = dependency.getArtifact(); - assertNotNull( artifact ); - assertEquals( "aid", artifact.getArtifactId() ); - assertEquals( "gid", artifact.getGroupId() ); - assertEquals( "ver", artifact.getVersion() ); - assertEquals( "ext", artifact.getExtension() ); + assertNotNull(artifact); + assertEquals("aid", artifact.getArtifactId()); + assertEquals("gid", artifact.getGroupId()); + assertEquals("ver", artifact.getVersion()); + assertEquals("ext", artifact.getExtension()); Collection exclusions = dependency.getExclusions(); - assertNotNull( exclusions ); - assertEquals( 1, exclusions.size() ); + assertNotNull(exclusions); + assertEquals(1, exclusions.size()); Exclusion exclusion = exclusions.iterator().next(); - assertEquals( "exclusion", exclusion.getGroupId() ); - assertEquals( "aid", exclusion.getArtifactId() ); - assertEquals( "*", exclusion.getClassifier() ); - assertEquals( "*", exclusion.getExtension() ); + assertEquals("exclusion", exclusion.getGroupId()); + assertEquals("aid", exclusion.getArtifactId()); + assertEquals("*", exclusion.getClassifier()); + assertEquals("*", exclusion.getExtension()); - dependency = dependencies.get( 1 ); - assertEquals( "runtime", dependency.getScope() ); + dependency = dependencies.get(1); + assertEquals("runtime", dependency.getScope()); artifact = dependency.getArtifact(); - assertNotNull( artifact ); - assertEquals( "aid2", artifact.getArtifactId() ); - assertEquals( "gid2", artifact.getGroupId() ); - assertEquals( "ver2", artifact.getVersion() ); - assertEquals( "ext2", artifact.getExtension() ); + assertNotNull(artifact); + assertEquals("aid2", artifact.getArtifactId()); + assertEquals("gid2", artifact.getGroupId()); + assertEquals("ver2", artifact.getVersion()); + assertEquals("ext2", artifact.getExtension()); - assertEquals( 0, dependency.getExclusions().size() ); + assertEquals(0, dependency.getExclusions().size()); } @Test - public void testResource() - throws IOException - { - ArtifactDescription description = parser.parse( "ArtifactDataReaderTest.ini" ); + public void testResource() throws IOException { + ArtifactDescription description = parser.parse("ArtifactDataReaderTest.ini"); Artifact artifact = description.getRelocation(); - assertEquals( "gid", artifact.getGroupId() ); - assertEquals( "aid", artifact.getArtifactId() ); - assertEquals( "ver", artifact.getVersion() ); - assertEquals( "ext", artifact.getExtension() ); - - assertEquals( 1, description.getRepositories().size() ); - RemoteRepository repo = description.getRepositories().get( 0 ); - assertEquals( "id", repo.getId() ); - assertEquals( "type", repo.getContentType() ); - assertEquals( "protocol://some/url?for=testing", repo.getUrl() ); - - assertDependencies( description.getDependencies() ); - assertDependencies( description.getManagedDependencies() ); - + assertEquals("gid", artifact.getGroupId()); + assertEquals("aid", artifact.getArtifactId()); + assertEquals("ver", artifact.getVersion()); + assertEquals("ext", artifact.getExtension()); + + assertEquals(1, description.getRepositories().size()); + RemoteRepository repo = description.getRepositories().get(0); + assertEquals("id", repo.getId()); + assertEquals("type", repo.getContentType()); + assertEquals("protocol://some/url?for=testing", repo.getUrl()); + + assertDependencies(description.getDependencies()); + assertDependencies(description.getManagedDependencies()); } - private void assertDependencies( List deps ) - { - assertEquals( 4, deps.size() ); + private void assertDependencies(List deps) { + assertEquals(4, deps.size()); - Dependency dep = deps.get( 0 ); - assertEquals( "scope", dep.getScope() ); - assertFalse( dep.isOptional() ); - assertEquals( 2, dep.getExclusions().size() ); + Dependency dep = deps.get(0); + assertEquals("scope", dep.getScope()); + assertFalse(dep.isOptional()); + assertEquals(2, dep.getExclusions().size()); Iterator it = dep.getExclusions().iterator(); Exclusion excl = it.next(); - assertEquals( "gid3", excl.getGroupId() ); - assertEquals( "aid", excl.getArtifactId() ); + assertEquals("gid3", excl.getGroupId()); + assertEquals("aid", excl.getArtifactId()); excl = it.next(); - assertEquals( "gid2", excl.getGroupId() ); - assertEquals( "aid2", excl.getArtifactId() ); + assertEquals("gid2", excl.getGroupId()); + assertEquals("aid2", excl.getArtifactId()); Artifact art = dep.getArtifact(); - assertEquals( "gid", art.getGroupId() ); - assertEquals( "aid", art.getArtifactId() ); - assertEquals( "ver", art.getVersion() ); - assertEquals( "ext", art.getExtension() ); + assertEquals("gid", art.getGroupId()); + assertEquals("aid", art.getArtifactId()); + assertEquals("ver", art.getVersion()); + assertEquals("ext", art.getExtension()); - dep = deps.get( 1 ); - assertEquals( "scope", dep.getScope() ); - assertTrue( dep.isOptional() ); - assertEquals( 0, dep.getExclusions().size() ); + dep = deps.get(1); + assertEquals("scope", dep.getScope()); + assertTrue(dep.isOptional()); + assertEquals(0, dep.getExclusions().size()); art = dep.getArtifact(); - assertEquals( "gid", art.getGroupId() ); - assertEquals( "aid2", art.getArtifactId() ); - assertEquals( "ver", art.getVersion() ); - assertEquals( "ext", art.getExtension() ); + assertEquals("gid", art.getGroupId()); + assertEquals("aid2", art.getArtifactId()); + assertEquals("ver", art.getVersion()); + assertEquals("ext", art.getExtension()); - dep = deps.get( 2 ); - assertEquals( "scope", dep.getScope() ); - assertTrue( dep.isOptional() ); - assertEquals( 0, dep.getExclusions().size() ); + dep = deps.get(2); + assertEquals("scope", dep.getScope()); + assertTrue(dep.isOptional()); + assertEquals(0, dep.getExclusions().size()); art = dep.getArtifact(); - assertEquals( "gid", art.getGroupId() ); - assertEquals( "aid", art.getArtifactId() ); - assertEquals( "ver3", art.getVersion() ); - assertEquals( "ext", art.getExtension() ); + assertEquals("gid", art.getGroupId()); + assertEquals("aid", art.getArtifactId()); + assertEquals("ver3", art.getVersion()); + assertEquals("ext", art.getExtension()); - dep = deps.get( 3 ); - assertEquals( "scope5", dep.getScope() ); - assertTrue( dep.isOptional() ); - assertEquals( 0, dep.getExclusions().size() ); + dep = deps.get(3); + assertEquals("scope5", dep.getScope()); + assertTrue(dep.isOptional()); + assertEquals(0, dep.getExclusions().size()); art = dep.getArtifact(); - assertEquals( "gid1", art.getGroupId() ); - assertEquals( "aid", art.getArtifactId() ); - assertEquals( "ver", art.getVersion() ); - assertEquals( "ext", art.getExtension() ); + assertEquals("gid1", art.getGroupId()); + assertEquals("aid", art.getArtifactId()); + assertEquals("ver", art.getVersion()); + assertEquals("ext", art.getExtension()); } - } diff --git a/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/IniArtifactDescriptorReaderTest.java b/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/IniArtifactDescriptorReaderTest.java index b98d8d888..08d9cf1fb 100644 --- a/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/IniArtifactDescriptorReaderTest.java +++ b/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/IniArtifactDescriptorReaderTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.test.util; import java.util.Iterator; import java.util.List; @@ -36,114 +33,107 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class IniArtifactDescriptorReaderTest -{ +public class IniArtifactDescriptorReaderTest { private IniArtifactDescriptorReader reader; private RepositorySystemSession session; @Before - public void setup() - { - reader = new IniArtifactDescriptorReader( "org/eclipse/aether/internal/test/util/" ); + public void setup() { + reader = new IniArtifactDescriptorReader("org/eclipse/aether/internal/test/util/"); session = TestUtils.newSession(); } - @Test( expected = ArtifactDescriptorException.class ) - public void testMissingDescriptor() - throws ArtifactDescriptorException - { - Artifact art = new DefaultArtifact( "missing:aid:ver:ext" ); - ArtifactDescriptorRequest request = new ArtifactDescriptorRequest( art, null, "" ); - reader.readArtifactDescriptor( session, request ); + @Test(expected = ArtifactDescriptorException.class) + public void testMissingDescriptor() throws ArtifactDescriptorException { + Artifact art = new DefaultArtifact("missing:aid:ver:ext"); + ArtifactDescriptorRequest request = new ArtifactDescriptorRequest(art, null, ""); + reader.readArtifactDescriptor(session, request); } @Test - public void testLookup() - throws ArtifactDescriptorException - { - Artifact art = new DefaultArtifact( "gid:aid:ext:ver" ); - ArtifactDescriptorRequest request = new ArtifactDescriptorRequest( art, null, "" ); - ArtifactDescriptorResult description = reader.readArtifactDescriptor( session, request ); - - assertEquals( request, description.getRequest() ); - assertEquals( art.setVersion( "1" ), description.getArtifact() ); - - assertEquals( 1, description.getRelocations().size() ); - Artifact artifact = description.getRelocations().get( 0 ); - assertEquals( "gid", artifact.getGroupId() ); - assertEquals( "aid", artifact.getArtifactId() ); - assertEquals( "ver", artifact.getVersion() ); - assertEquals( "ext", artifact.getExtension() ); - - assertEquals( 1, description.getRepositories().size() ); - RemoteRepository repo = description.getRepositories().get( 0 ); - assertEquals( "id", repo.getId() ); - assertEquals( "type", repo.getContentType() ); - assertEquals( "protocol://some/url?for=testing", repo.getUrl() ); - - assertDependencies( description.getDependencies() ); - assertDependencies( description.getManagedDependencies() ); - + public void testLookup() throws ArtifactDescriptorException { + Artifact art = new DefaultArtifact("gid:aid:ext:ver"); + ArtifactDescriptorRequest request = new ArtifactDescriptorRequest(art, null, ""); + ArtifactDescriptorResult description = reader.readArtifactDescriptor(session, request); + + assertEquals(request, description.getRequest()); + assertEquals(art.setVersion("1"), description.getArtifact()); + + assertEquals(1, description.getRelocations().size()); + Artifact artifact = description.getRelocations().get(0); + assertEquals("gid", artifact.getGroupId()); + assertEquals("aid", artifact.getArtifactId()); + assertEquals("ver", artifact.getVersion()); + assertEquals("ext", artifact.getExtension()); + + assertEquals(1, description.getRepositories().size()); + RemoteRepository repo = description.getRepositories().get(0); + assertEquals("id", repo.getId()); + assertEquals("type", repo.getContentType()); + assertEquals("protocol://some/url?for=testing", repo.getUrl()); + + assertDependencies(description.getDependencies()); + assertDependencies(description.getManagedDependencies()); } - private void assertDependencies( List deps ) - { - assertEquals( 4, deps.size() ); + private void assertDependencies(List deps) { + assertEquals(4, deps.size()); - Dependency dep = deps.get( 0 ); - assertEquals( "scope", dep.getScope() ); - assertFalse( dep.isOptional() ); - assertEquals( 2, dep.getExclusions().size() ); + Dependency dep = deps.get(0); + assertEquals("scope", dep.getScope()); + assertFalse(dep.isOptional()); + assertEquals(2, dep.getExclusions().size()); Iterator it = dep.getExclusions().iterator(); Exclusion excl = it.next(); - assertEquals( "gid3", excl.getGroupId() ); - assertEquals( "aid", excl.getArtifactId() ); + assertEquals("gid3", excl.getGroupId()); + assertEquals("aid", excl.getArtifactId()); excl = it.next(); - assertEquals( "gid2", excl.getGroupId() ); - assertEquals( "aid2", excl.getArtifactId() ); + assertEquals("gid2", excl.getGroupId()); + assertEquals("aid2", excl.getArtifactId()); Artifact art = dep.getArtifact(); - assertEquals( "gid", art.getGroupId() ); - assertEquals( "aid", art.getArtifactId() ); - assertEquals( "ver", art.getVersion() ); - assertEquals( "ext", art.getExtension() ); + assertEquals("gid", art.getGroupId()); + assertEquals("aid", art.getArtifactId()); + assertEquals("ver", art.getVersion()); + assertEquals("ext", art.getExtension()); - dep = deps.get( 1 ); - assertEquals( "scope", dep.getScope() ); - assertTrue( dep.isOptional() ); - assertEquals( 0, dep.getExclusions().size() ); + dep = deps.get(1); + assertEquals("scope", dep.getScope()); + assertTrue(dep.isOptional()); + assertEquals(0, dep.getExclusions().size()); art = dep.getArtifact(); - assertEquals( "gid", art.getGroupId() ); - assertEquals( "aid2", art.getArtifactId() ); - assertEquals( "ver", art.getVersion() ); - assertEquals( "ext", art.getExtension() ); + assertEquals("gid", art.getGroupId()); + assertEquals("aid2", art.getArtifactId()); + assertEquals("ver", art.getVersion()); + assertEquals("ext", art.getExtension()); - dep = deps.get( 2 ); - assertEquals( "scope", dep.getScope() ); - assertTrue( dep.isOptional() ); - assertEquals( 0, dep.getExclusions().size() ); + dep = deps.get(2); + assertEquals("scope", dep.getScope()); + assertTrue(dep.isOptional()); + assertEquals(0, dep.getExclusions().size()); art = dep.getArtifact(); - assertEquals( "gid", art.getGroupId() ); - assertEquals( "aid", art.getArtifactId() ); - assertEquals( "ver3", art.getVersion() ); - assertEquals( "ext", art.getExtension() ); + assertEquals("gid", art.getGroupId()); + assertEquals("aid", art.getArtifactId()); + assertEquals("ver3", art.getVersion()); + assertEquals("ext", art.getExtension()); - dep = deps.get( 3 ); - assertEquals( "scope5", dep.getScope() ); - assertTrue( dep.isOptional() ); - assertEquals( 0, dep.getExclusions().size() ); + dep = deps.get(3); + assertEquals("scope5", dep.getScope()); + assertTrue(dep.isOptional()); + assertEquals(0, dep.getExclusions().size()); art = dep.getArtifact(); - assertEquals( "gid1", art.getGroupId() ); - assertEquals( "aid", art.getArtifactId() ); - assertEquals( "ver", art.getVersion() ); - assertEquals( "ext", art.getExtension() ); + assertEquals("gid1", art.getGroupId()); + assertEquals("aid", art.getArtifactId()); + assertEquals("ver", art.getVersion()); + assertEquals("ext", art.getExtension()); } - } diff --git a/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/NodeDefinitionTest.java b/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/NodeDefinitionTest.java index 769691a13..1d4c6d37a 100644 --- a/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/NodeDefinitionTest.java +++ b/maven-resolver-test-util/src/test/java/org/eclipse/aether/internal/test/util/NodeDefinitionTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.test.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.internal.test.util; import java.util.Arrays; import java.util.Collections; @@ -28,129 +25,143 @@ import org.junit.Test; -public class NodeDefinitionTest -{ - - private void assertMatch( String text, String regex, String... groups ) - { - Pattern pattern = Pattern.compile( regex ); - Matcher matcher = pattern.matcher( text ); - assertTrue( matcher.matches() ); - assertTrue( groups.length + " vs " + matcher.groupCount(), groups.length <= matcher.groupCount() ); - for ( int i = 1; i <= groups.length; i++ ) - { - assertEquals( "Mismatch for group " + i, groups[i - 1], matcher.group( i ) ); +import static org.junit.Assert.*; + +public class NodeDefinitionTest { + + private void assertMatch(String text, String regex, String... groups) { + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(text); + assertTrue(matcher.matches()); + assertTrue(groups.length + " vs " + matcher.groupCount(), groups.length <= matcher.groupCount()); + for (int i = 1; i <= groups.length; i++) { + assertEquals("Mismatch for group " + i, groups[i - 1], matcher.group(i)); } } - private void assertNoMatch( String text, String regex ) - { - Pattern pattern = Pattern.compile( regex ); - Matcher matcher = pattern.matcher( text ); - assertFalse( matcher.matches() ); + private void assertNoMatch(String text, String regex) { + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(text); + assertFalse(matcher.matches()); } @Test - public void testPatterns() - { - assertMatch( "(Example-ID_0123456789)", NodeDefinition.ID, "Example-ID_0123456789" ); - assertMatch( "^Example-ID_0123456789", NodeDefinition.IDREF, "Example-ID_0123456789" ); - - assertMatch( "gid:aid:1", NodeDefinition.COORDS, "gid", "aid", null, null, "1" ); - assertMatch( "gid:aid:jar:1", NodeDefinition.COORDS, "gid", "aid", "jar", null, "1" ); - assertMatch( "gid:aid:jar:cls:1", NodeDefinition.COORDS, "gid", "aid", "jar", "cls", "1" ); - - assertMatch( "[1]", NodeDefinition.RANGE, "[1]" ); - assertMatch( "[1,)", NodeDefinition.RANGE, "[1,)" ); - assertMatch( "(1,2)", NodeDefinition.RANGE, "(1,2)" ); - - assertMatch( "scope = compile", NodeDefinition.SCOPE, "compile", null ); - assertMatch( "scope=compile - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-transport-classpath Maven Artifact Resolver Transport Classpath - - A transport implementation for repositories using classpath:// URLs. - + A transport implementation for repositories using classpath:// URLs. org.apache.maven.resolver.transport.classpath diff --git a/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ClasspathTransporter.java b/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ClasspathTransporter.java index 968c231a4..ee8148e48 100644 --- a/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ClasspathTransporter.java +++ b/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ClasspathTransporter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.classpath; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.classpath; import java.net.URI; import java.net.URISyntaxException; @@ -37,112 +36,80 @@ /** * A transporter reading from the classpath. */ -final class ClasspathTransporter - extends AbstractTransporter -{ +final class ClasspathTransporter extends AbstractTransporter { private final String resourceBase; private final ClassLoader classLoader; - ClasspathTransporter( RepositorySystemSession session, RemoteRepository repository ) - throws NoTransporterException - { - if ( !"classpath".equalsIgnoreCase( repository.getProtocol() ) ) - { - throw new NoTransporterException( repository ); + ClasspathTransporter(RepositorySystemSession session, RemoteRepository repository) throws NoTransporterException { + if (!"classpath".equalsIgnoreCase(repository.getProtocol())) { + throw new NoTransporterException(repository); } String base; - try - { - URI uri = new URI( repository.getUrl() ); + try { + URI uri = new URI(repository.getUrl()); String ssp = uri.getSchemeSpecificPart(); - if ( ssp.startsWith( "/" ) ) - { + if (ssp.startsWith("/")) { base = uri.getPath(); - if ( base == null ) - { + if (base == null) { base = ""; + } else if (base.startsWith("/")) { + base = base.substring(1); } - else if ( base.startsWith( "/" ) ) - { - base = base.substring( 1 ); - } - } - else - { + } else { base = ssp; } - if ( base.length() > 0 && !base.endsWith( "/" ) ) - { + if (base.length() > 0 && !base.endsWith("/")) { base += '/'; } - } - catch ( URISyntaxException e ) - { - throw new NoTransporterException( repository, e ); + } catch (URISyntaxException e) { + throw new NoTransporterException(repository, e); } resourceBase = base; - Object cl = ConfigUtils.getObject( session, null, ClasspathTransporterFactory.CONFIG_PROP_CLASS_LOADER ); - if ( cl instanceof ClassLoader ) - { + Object cl = ConfigUtils.getObject(session, null, ClasspathTransporterFactory.CONFIG_PROP_CLASS_LOADER); + if (cl instanceof ClassLoader) { classLoader = (ClassLoader) cl; - } - else - { + } else { classLoader = Thread.currentThread().getContextClassLoader(); } } - private URL getResource( TransportTask task ) - throws Exception - { + private URL getResource(TransportTask task) throws Exception { String resource = resourceBase + task.getLocation().getPath(); - URL url = classLoader.getResource( resource ); - if ( url == null ) - { - throw new ResourceNotFoundException( "Could not locate " + resource ); + URL url = classLoader.getResource(resource); + if (url == null) { + throw new ResourceNotFoundException("Could not locate " + resource); } return url; } - public int classify( Throwable error ) - { - if ( error instanceof ResourceNotFoundException ) - { + public int classify(Throwable error) { + if (error instanceof ResourceNotFoundException) { return ERROR_NOT_FOUND; } return ERROR_OTHER; } @Override - protected void implPeek( PeekTask task ) - throws Exception - { - getResource( task ); + protected void implPeek(PeekTask task) throws Exception { + getResource(task); } @Override - protected void implGet( GetTask task ) - throws Exception - { - URL url = getResource( task ); + protected void implGet(GetTask task) throws Exception { + URL url = getResource(task); URLConnection conn = url.openConnection(); - utilGet( task, conn.getInputStream(), true, conn.getContentLength(), false ); + utilGet(task, conn.getInputStream(), true, conn.getContentLength(), false); } @Override - protected void implPut( PutTask task ) - throws Exception - { - throw new UnsupportedOperationException( "Uploading to a classpath: repository is not supported" ); + protected void implPut(PutTask task) throws Exception { + throw new UnsupportedOperationException("Uploading to a classpath: repository is not supported"); } @Override - protected void implClose() - { - } - + protected void implClose() {} } diff --git a/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ClasspathTransporterFactory.java b/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ClasspathTransporterFactory.java index 9ed2147e6..b9522f256 100644 --- a/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ClasspathTransporterFactory.java +++ b/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ClasspathTransporterFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.classpath; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.classpath; import javax.inject.Named; @@ -37,10 +36,8 @@ *

    * Note: Such repositories are read-only and uploads to them are generally not supported. */ -@Named( "classpath" ) -public final class ClasspathTransporterFactory - implements TransporterFactory -{ +@Named("classpath") +public final class ClasspathTransporterFactory implements TransporterFactory { /** * The key in the repository session's {@link RepositorySystemSession#getConfigProperties() configuration @@ -56,14 +53,11 @@ public final class ClasspathTransporterFactory * by clients, the new factory needs to be configured via its various mutators before first use or runtime errors * will occur. */ - public ClasspathTransporterFactory() - { + public ClasspathTransporterFactory() { // enables default constructor } - - public float getPriority() - { + public float getPriority() { return priority; } @@ -73,19 +67,16 @@ public float getPriority() * @param priority The priority. * @return This component for chaining, never {@code null}. */ - public ClasspathTransporterFactory setPriority( float priority ) - { + public ClasspathTransporterFactory setPriority(float priority) { this.priority = priority; return this; } - public Transporter newInstance( RepositorySystemSession session, RemoteRepository repository ) - throws NoTransporterException - { - Objects.requireNonNull( session, "session cannot be null" ); - Objects.requireNonNull( repository, "repository cannot be null" ); + public Transporter newInstance(RepositorySystemSession session, RemoteRepository repository) + throws NoTransporterException { + Objects.requireNonNull(session, "session cannot be null"); + Objects.requireNonNull(repository, "repository cannot be null"); - return new ClasspathTransporter( session, repository ); + return new ClasspathTransporter(session, repository); } - } diff --git a/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ResourceNotFoundException.java b/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ResourceNotFoundException.java index 737aade60..3618b9b75 100644 --- a/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ResourceNotFoundException.java +++ b/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/ResourceNotFoundException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.classpath; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.classpath; import java.io.IOException; @@ -25,13 +24,9 @@ * Special exception type used instead of {@code FileNotFoundException} to avoid misinterpretation of errors unrelated * to the remote resource. */ -class ResourceNotFoundException - extends IOException -{ +class ResourceNotFoundException extends IOException { - ResourceNotFoundException( String message ) - { - super( message ); + ResourceNotFoundException(String message) { + super(message); } - } diff --git a/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/package-info.java b/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/package-info.java index 8bcda932e..635f9a24d 100644 --- a/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/package-info.java +++ b/maven-resolver-transport-classpath/src/main/java/org/eclipse/aether/transport/classpath/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Support for downloads that utilize the classpath as "remote" storage. */ package org.eclipse.aether.transport.classpath; - diff --git a/maven-resolver-transport-classpath/src/test/java/org/eclipse/aether/transport/classpath/ClasspathTransporterTest.java b/maven-resolver-transport-classpath/src/test/java/org/eclipse/aether/transport/classpath/ClasspathTransporterTest.java index d61dec9c1..46fde0e3b 100644 --- a/maven-resolver-transport-classpath/src/test/java/org/eclipse/aether/transport/classpath/ClasspathTransporterTest.java +++ b/maven-resolver-transport-classpath/src/test/java/org/eclipse/aether/transport/classpath/ClasspathTransporterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.classpath; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.transport.classpath; import java.io.File; import java.io.FileNotFoundException; @@ -41,10 +38,11 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class ClasspathTransporterTest -{ +public class ClasspathTransporterTest { private DefaultRepositorySystemSession session; @@ -52,36 +50,28 @@ public class ClasspathTransporterTest private Transporter transporter; - private RemoteRepository newRepo( String url ) - { - return new RemoteRepository.Builder( "test", "default", url ).build(); + private RemoteRepository newRepo(String url) { + return new RemoteRepository.Builder("test", "default", url).build(); } - private void newTransporter( String url ) - throws Exception - { - if ( transporter != null ) - { + private void newTransporter(String url) throws Exception { + if (transporter != null) { transporter.close(); transporter = null; } - transporter = factory.newInstance( session, newRepo( url ) ); + transporter = factory.newInstance(session, newRepo(url)); } @Before - public void setUp() - throws Exception - { + public void setUp() throws Exception { session = TestUtils.newSession(); - factory = new ClasspathTransporterFactory( ); - newTransporter( "classpath:/repository" ); + factory = new ClasspathTransporterFactory(); + newTransporter("classpath:/repository"); } @After - public void tearDown() - { - if ( transporter != null ) - { + public void tearDown() { + if (transporter != null) { transporter.close(); transporter = null; } @@ -90,321 +80,240 @@ public void tearDown() } @Test - public void testClassify() - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( new FileNotFoundException() ) ); - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( new ResourceNotFoundException( "test" ) ) ); + public void testClassify() { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(new FileNotFoundException())); + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(new ResourceNotFoundException("test"))); } @Test - public void testPeek() - throws Exception - { - transporter.peek( new PeekTask( URI.create( "file.txt" ) ) ); + public void testPeek() throws Exception { + transporter.peek(new PeekTask(URI.create("file.txt"))); } @Test - public void testPeek_NotFound() - throws Exception - { - try - { - transporter.peek( new PeekTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( ResourceNotFoundException e ) - { - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( e ) ); + public void testPeek_NotFound() throws Exception { + try { + transporter.peek(new PeekTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (ResourceNotFoundException e) { + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e)); } } @Test - public void testPeek_Closed() - throws Exception - { + public void testPeek_Closed() throws Exception { transporter.close(); - try - { - transporter.peek( new PeekTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.peek(new PeekTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testGet_ToMemory() - throws Exception - { + public void testGet_ToMemory() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "file.txt" ) ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( task.getDataString(), new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("file.txt")).setListener(listener); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals(task.getDataString(), new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_ToFile() - throws Exception - { - File file = TestFileUtils.createTempFile( "failure" ); + public void testGet_ToFile() throws Exception { + File file = TestFileUtils.createTempFile("failure"); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "file.txt" ) ).setDataFile( file ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", TestFileUtils.readString( file ) ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "test", new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("file.txt")).setDataFile(file).setListener(listener); + transporter.get(task); + assertEquals("test", TestFileUtils.readString(file)); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("test", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_EmptyResource() - throws Exception - { - File file = TestFileUtils.createTempFile( "failure" ); + public void testGet_EmptyResource() throws Exception { + File file = TestFileUtils.createTempFile("failure"); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "empty.txt" ) ).setDataFile( file ).setListener( listener ); - transporter.get( task ); - assertEquals( "", TestFileUtils.readString( file ) ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 0L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); - assertEquals( "", new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("empty.txt")).setDataFile(file).setListener(listener); + transporter.get(task); + assertEquals("", TestFileUtils.readString(file)); + assertEquals(0L, listener.dataOffset); + assertEquals(0L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); + assertEquals("", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_EncodedResourcePath() - throws Exception - { - GetTask task = new GetTask( URI.create( "some%20space.txt" ) ); - transporter.get( task ); - assertEquals( "space", task.getDataString() ); + public void testGet_EncodedResourcePath() throws Exception { + GetTask task = new GetTask(URI.create("some%20space.txt")); + transporter.get(task); + assertEquals("space", task.getDataString()); } @Test - public void testGet_Fragment() - throws Exception - { - GetTask task = new GetTask( URI.create( "file.txt#ignored" ) ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); + public void testGet_Fragment() throws Exception { + GetTask task = new GetTask(URI.create("file.txt#ignored")); + transporter.get(task); + assertEquals("test", task.getDataString()); } @Test - public void testGet_Query() - throws Exception - { - GetTask task = new GetTask( URI.create( "file.txt?ignored" ) ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); + public void testGet_Query() throws Exception { + GetTask task = new GetTask(URI.create("file.txt?ignored")); + transporter.get(task); + assertEquals("test", task.getDataString()); } @Test - public void testGet_FileHandleLeak() - throws Exception - { - for ( int i = 0; i < 100; i++ ) - { - File file = TestFileUtils.createTempFile( "failure" ); - transporter.get( new GetTask( URI.create( "file.txt" ) ).setDataFile( file ) ); - assertTrue( i + ", " + file.getAbsolutePath(), file.delete() ); + public void testGet_FileHandleLeak() throws Exception { + for (int i = 0; i < 100; i++) { + File file = TestFileUtils.createTempFile("failure"); + transporter.get(new GetTask(URI.create("file.txt")).setDataFile(file)); + assertTrue(i + ", " + file.getAbsolutePath(), file.delete()); } } @Test - public void testGet_NotFound() - throws Exception - { - try - { - transporter.get( new GetTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( ResourceNotFoundException e ) - { - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( e ) ); + public void testGet_NotFound() throws Exception { + try { + transporter.get(new GetTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (ResourceNotFoundException e) { + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e)); } } @Test - public void testGet_Closed() - throws Exception - { + public void testGet_Closed() throws Exception { transporter.close(); - try - { - transporter.get( new GetTask( URI.create( "file.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.get(new GetTask(URI.create("file.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testGet_StartCancelled() - throws Exception - { + public void testGet_StartCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelStart = true; - GetTask task = new GetTask( URI.create( "file.txt" ) ).setListener( listener ); - try - { - transporter.get( task ); - fail( "Expected error" ); - } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + GetTask task = new GetTask(URI.create("file.txt")).setListener(listener); + try { + transporter.get(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); } @Test - public void testGet_ProgressCancelled() - throws Exception - { + public void testGet_ProgressCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelProgress = true; - GetTask task = new GetTask( URI.create( "file.txt" ) ).setListener( listener ); - try - { - transporter.get( task ); - fail( "Expected error" ); + GetTask task = new GetTask(URI.create("file.txt")).setListener(listener); + try { + transporter.get(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); - } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 1, listener.progressedCount ); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(1, listener.progressedCount); } @Test - public void testPut() - throws Exception - { - try - { - transporter.put( new PutTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( UnsupportedOperationException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + public void testPut() throws Exception { + try { + transporter.put(new PutTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (UnsupportedOperationException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testPut_Closed() - throws Exception - { + public void testPut_Closed() throws Exception { transporter.close(); - try - { - transporter.put( new PutTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.put(new PutTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } - @Test( expected = NoTransporterException.class ) - public void testInit_BadProtocol() - throws Exception - { - newTransporter( "bad:/void" ); + @Test(expected = NoTransporterException.class) + public void testInit_BadProtocol() throws Exception { + newTransporter("bad:/void"); } @Test - public void testInit_CaseInsensitiveProtocol() - throws Exception - { - newTransporter( "classpath:/void" ); - newTransporter( "CLASSPATH:/void" ); - newTransporter( "ClassPath:/void" ); + public void testInit_CaseInsensitiveProtocol() throws Exception { + newTransporter("classpath:/void"); + newTransporter("CLASSPATH:/void"); + newTransporter("ClassPath:/void"); } @Test - public void testInit_OpaqueUrl() - throws Exception - { - testInit( "classpath:repository" ); + public void testInit_OpaqueUrl() throws Exception { + testInit("classpath:repository"); } @Test - public void testInit_OpaqueUrlTrailingSlash() - throws Exception - { - testInit( "classpath:repository/" ); + public void testInit_OpaqueUrlTrailingSlash() throws Exception { + testInit("classpath:repository/"); } @Test - public void testInit_OpaqueUrlSpaces() - throws Exception - { - testInit( "classpath:repo%20space" ); + public void testInit_OpaqueUrlSpaces() throws Exception { + testInit("classpath:repo%20space"); } @Test - public void testInit_HierarchicalUrl() - throws Exception - { - testInit( "classpath:/repository" ); + public void testInit_HierarchicalUrl() throws Exception { + testInit("classpath:/repository"); } @Test - public void testInit_HierarchicalUrlTrailingSlash() - throws Exception - { - testInit( "classpath:/repository/" ); + public void testInit_HierarchicalUrlTrailingSlash() throws Exception { + testInit("classpath:/repository/"); } @Test - public void testInit_HierarchicalUrlSpaces() - throws Exception - { - testInit( "classpath:/repo%20space" ); + public void testInit_HierarchicalUrlSpaces() throws Exception { + testInit("classpath:/repo%20space"); } @Test - public void testInit_HierarchicalUrlRoot() - throws Exception - { - testInit( "classpath:/" ); + public void testInit_HierarchicalUrlRoot() throws Exception { + testInit("classpath:/"); } @Test - public void testInit_HierarchicalUrlNoPath() - throws Exception - { - testInit( "classpath://reserved" ); + public void testInit_HierarchicalUrlNoPath() throws Exception { + testInit("classpath://reserved"); } - private void testInit( String base ) - throws Exception - { - newTransporter( base ); - GetTask task = new GetTask( URI.create( "file.txt" ) ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); + private void testInit(String base) throws Exception { + newTransporter(base); + GetTask task = new GetTask(URI.create("file.txt")); + transporter.get(task); + assertEquals("test", task.getDataString()); } - } diff --git a/maven-resolver-transport-classpath/src/test/java/org/eclipse/aether/transport/classpath/RecordingTransportListener.java b/maven-resolver-transport-classpath/src/test/java/org/eclipse/aether/transport/classpath/RecordingTransportListener.java index 8d453b131..400f24dcc 100644 --- a/maven-resolver-transport-classpath/src/test/java/org/eclipse/aether/transport/classpath/RecordingTransportListener.java +++ b/maven-resolver-transport-classpath/src/test/java/org/eclipse/aether/transport/classpath/RecordingTransportListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.classpath; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.classpath; import java.io.ByteArrayOutputStream; import java.nio.Buffer; @@ -26,11 +25,9 @@ import org.eclipse.aether.spi.connector.transport.TransportListener; import org.eclipse.aether.transfer.TransferCancelledException; -class RecordingTransportListener - extends TransportListener -{ +class RecordingTransportListener extends TransportListener { - public final ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 ); + public final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); public long dataOffset; @@ -45,30 +42,23 @@ class RecordingTransportListener public boolean cancelProgress; @Override - public void transportStarted( long dataOffset, long dataLength ) - throws TransferCancelledException - { + public void transportStarted(long dataOffset, long dataLength) throws TransferCancelledException { startedCount++; progressedCount = 0; this.dataLength = dataLength; this.dataOffset = dataOffset; baos.reset(); - if ( cancelStart ) - { + if (cancelStart) { throw new TransferCancelledException(); } } @Override - public void transportProgressed( ByteBuffer data ) - throws TransferCancelledException - { + public void transportProgressed(ByteBuffer data) throws TransferCancelledException { progressedCount++; - baos.write( data.array(), data.arrayOffset() + ( (Buffer) data ).position(), data.remaining() ); - if ( cancelProgress ) - { + baos.write(data.array(), data.arrayOffset() + ((Buffer) data).position(), data.remaining()); + if (cancelProgress) { throw new TransferCancelledException(); } } - } diff --git a/maven-resolver-transport-file/pom.xml b/maven-resolver-transport-file/pom.xml index 5da978a80..d37432fab 100644 --- a/maven-resolver-transport-file/pom.xml +++ b/maven-resolver-transport-file/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-transport-file Maven Artifact Resolver Transport File - - A transport implementation for repositories using file:// URLs. - + A transport implementation for repositories using file:// URLs. org.apache.maven.resolver.transport.file diff --git a/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/FileTransporter.java b/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/FileTransporter.java index d2c971cd3..e2cde760d 100644 --- a/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/FileTransporter.java +++ b/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/FileTransporter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.file; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.file; import java.io.File; import java.nio.file.Files; @@ -35,92 +34,67 @@ /** * A transporter using {@link java.io.File}. */ -final class FileTransporter - extends AbstractTransporter -{ +final class FileTransporter extends AbstractTransporter { - private static final Logger LOGGER = LoggerFactory.getLogger( FileTransporter.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(FileTransporter.class); private final File basedir; - FileTransporter( RemoteRepository repository ) - throws NoTransporterException - { - if ( !"file".equalsIgnoreCase( repository.getProtocol() ) ) - { - throw new NoTransporterException( repository ); + FileTransporter(RemoteRepository repository) throws NoTransporterException { + if (!"file".equalsIgnoreCase(repository.getProtocol())) { + throw new NoTransporterException(repository); } - basedir = new File( PathUtils.basedir( repository.getUrl() ) ).getAbsoluteFile(); + basedir = new File(PathUtils.basedir(repository.getUrl())).getAbsoluteFile(); } - File getBasedir() - { + File getBasedir() { return basedir; } - public int classify( Throwable error ) - { - if ( error instanceof ResourceNotFoundException ) - { + public int classify(Throwable error) { + if (error instanceof ResourceNotFoundException) { return ERROR_NOT_FOUND; } return ERROR_OTHER; } @Override - protected void implPeek( PeekTask task ) - throws Exception - { - getFile( task, true ); + protected void implPeek(PeekTask task) throws Exception { + getFile(task, true); } @Override - protected void implGet( GetTask task ) - throws Exception - { - File file = getFile( task, true ); - utilGet( task, Files.newInputStream( file.toPath() ), true, file.length(), false ); + protected void implGet(GetTask task) throws Exception { + File file = getFile(task, true); + utilGet(task, Files.newInputStream(file.toPath()), true, file.length(), false); } @Override - protected void implPut( PutTask task ) - throws Exception - { - File file = getFile( task, false ); + protected void implPut(PutTask task) throws Exception { + File file = getFile(task, false); file.getParentFile().mkdirs(); - try - { - utilPut( task, Files.newOutputStream( file.toPath() ), true ); - } - catch ( Exception e ) - { - if ( !file.delete() && file.exists() ) - { - LOGGER.debug( "Could not delete partial file {}", file ); + try { + utilPut(task, Files.newOutputStream(file.toPath()), true); + } catch (Exception e) { + if (!file.delete() && file.exists()) { + LOGGER.debug("Could not delete partial file {}", file); } throw e; } } - private File getFile( TransportTask task, boolean required ) - throws Exception - { + private File getFile(TransportTask task, boolean required) throws Exception { String path = task.getLocation().getPath(); - if ( path.contains( "../" ) ) - { - throw new IllegalArgumentException( "illegal resource path: " + path ); + if (path.contains("../")) { + throw new IllegalArgumentException("illegal resource path: " + path); } - File file = new File( basedir, path ); - if ( required && !file.exists() ) - { - throw new ResourceNotFoundException( "Could not locate " + file ); + File file = new File(basedir, path); + if (required && !file.exists()) { + throw new ResourceNotFoundException("Could not locate " + file); } return file; } @Override - protected void implClose() - { - } - + protected void implClose() {} } diff --git a/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/FileTransporterFactory.java b/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/FileTransporterFactory.java index 349b4369d..d4d02d6eb 100644 --- a/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/FileTransporterFactory.java +++ b/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/FileTransporterFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.file; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.file; import javax.inject.Named; @@ -32,10 +31,8 @@ /** * A transporter factory for repositories using the {@code file:} protocol. */ -@Named( "file" ) -public final class FileTransporterFactory - implements TransporterFactory -{ +@Named("file") +public final class FileTransporterFactory implements TransporterFactory { private float priority; @@ -44,13 +41,11 @@ public final class FileTransporterFactory * by clients, the new factory needs to be configured via its various mutators before first use or runtime errors * will occur. */ - public FileTransporterFactory() - { + public FileTransporterFactory() { // enables default constructor } - public float getPriority() - { + public float getPriority() { return priority; } @@ -60,19 +55,16 @@ public float getPriority() * @param priority The priority. * @return This component for chaining, never {@code null}. */ - public FileTransporterFactory setPriority( float priority ) - { + public FileTransporterFactory setPriority(float priority) { this.priority = priority; return this; } - public Transporter newInstance( RepositorySystemSession session, RemoteRepository repository ) - throws NoTransporterException - { - Objects.requireNonNull( session, "session cannot be null" ); - Objects.requireNonNull( repository, "repository cannot be null" ); + public Transporter newInstance(RepositorySystemSession session, RemoteRepository repository) + throws NoTransporterException { + Objects.requireNonNull(session, "session cannot be null"); + Objects.requireNonNull(repository, "repository cannot be null"); - return new FileTransporter( repository ); + return new FileTransporter(repository); } - } diff --git a/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/PathUtils.java b/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/PathUtils.java index ac3f8fd3e..7795421ea 100644 --- a/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/PathUtils.java +++ b/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/PathUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.file; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,82 +16,66 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.file; /** * URL handling for file URLs. Based on org.apache.maven.wagon.PathUtils. */ -final class PathUtils -{ +final class PathUtils { - private PathUtils() - { - } + private PathUtils() {} /** * Return the protocol name.
    * E.g: for input http://www.codehause.org this method will return http - * + * * @param url the url * @return the host name */ - public static String protocol( final String url ) - { - final int pos = url.indexOf( ":" ); + public static String protocol(final String url) { + final int pos = url.indexOf(":"); - if ( pos == -1 ) - { + if (pos == -1) { return ""; } - return url.substring( 0, pos ).trim(); + return url.substring(0, pos).trim(); } /** * Derive the path portion of the given URL. - * + * * @param url the file-repository URL * @return the basedir of the repository */ - public static String basedir( String url ) - { - String protocol = PathUtils.protocol( url ); + public static String basedir(String url) { + String protocol = PathUtils.protocol(url); String retValue = null; - if ( protocol.length() > 0 ) - { - retValue = url.substring( protocol.length() + 1 ); - } - else - { + if (protocol.length() > 0) { + retValue = url.substring(protocol.length() + 1); + } else { retValue = url; } - retValue = decode( retValue ); + retValue = decode(retValue); // special case: if omitted // on protocol, keep path as is - if ( retValue.startsWith( "//" ) ) - { - retValue = retValue.substring( 2 ); + if (retValue.startsWith("//")) { + retValue = retValue.substring(2); - if ( retValue.length() >= 2 && ( retValue.charAt( 1 ) == '|' || retValue.charAt( 1 ) == ':' ) ) - { + if (retValue.length() >= 2 && (retValue.charAt(1) == '|' || retValue.charAt(1) == ':')) { // special case: if there is a windows drive letter, then keep the original return value - retValue = retValue.charAt( 0 ) + ":" + retValue.substring( 2 ); - } - else - { + retValue = retValue.charAt(0) + ":" + retValue.substring(2); + } else { // Now we expect the host - int index = retValue.indexOf( "/" ); - if ( index >= 0 ) - { - retValue = retValue.substring( index + 1 ); + int index = retValue.indexOf("/"); + if (index >= 0) { + retValue = retValue.substring(index + 1); } // special case: if there is a windows drive letter, then keep the original return value - if ( retValue.length() >= 2 && ( retValue.charAt( 1 ) == '|' || retValue.charAt( 1 ) == ':' ) ) - { - retValue = retValue.charAt( 0 ) + ":" + retValue.substring( 2 ); - } - else if ( index >= 0 ) - { + if (retValue.length() >= 2 && (retValue.charAt(1) == '|' || retValue.charAt(1) == ':')) { + retValue = retValue.charAt(0) + ":" + retValue.substring(2); + } else if (index >= 0) { // leading / was previously stripped retValue = "/" + retValue; } @@ -101,9 +83,8 @@ else if ( index >= 0 ) } // special case: if there is a windows drive letter using |, switch to : - if ( retValue.length() >= 2 && retValue.charAt( 1 ) == '|' ) - { - retValue = retValue.charAt( 0 ) + ":" + retValue.substring( 2 ); + if (retValue.length() >= 2 && retValue.charAt(1) == '|') { + retValue = retValue.charAt(0) + ":" + retValue.substring(2); } return retValue.trim(); @@ -112,27 +93,22 @@ else if ( index >= 0 ) /** * Decodes the specified (portion of a) URL. Note: This decoder assumes that ISO-8859-1 is used to * convert URL-encoded octets to characters. - * + * * @param url The URL to decode, may be null. * @return The decoded URL or null if the input was null. */ - static String decode( String url ) - { + static String decode(String url) { String decoded = url; - if ( url != null ) - { + if (url != null) { int pos = -1; - while ( ( pos = decoded.indexOf( '%', pos + 1 ) ) >= 0 ) - { - if ( pos + 2 < decoded.length() ) - { - String hexStr = decoded.substring( pos + 1, pos + 3 ); - char ch = (char) Integer.parseInt( hexStr, 16 ); - decoded = decoded.substring( 0, pos ) + ch + decoded.substring( pos + 3 ); + while ((pos = decoded.indexOf('%', pos + 1)) >= 0) { + if (pos + 2 < decoded.length()) { + String hexStr = decoded.substring(pos + 1, pos + 3); + char ch = (char) Integer.parseInt(hexStr, 16); + decoded = decoded.substring(0, pos) + ch + decoded.substring(pos + 3); } } } return decoded; } - } diff --git a/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/ResourceNotFoundException.java b/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/ResourceNotFoundException.java index 4f2736676..288e5b246 100644 --- a/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/ResourceNotFoundException.java +++ b/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/ResourceNotFoundException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.file; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.file; import java.io.IOException; @@ -25,13 +24,9 @@ * Special exception type used instead of {@code FileNotFoundException} to avoid misinterpretation of errors unrelated * to the remote resource. */ -class ResourceNotFoundException - extends IOException -{ +class ResourceNotFoundException extends IOException { - ResourceNotFoundException( String message ) - { - super( message ); + ResourceNotFoundException(String message) { + super(message); } - } diff --git a/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/package-info.java b/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/package-info.java index 8220bf413..4a9c9030c 100644 --- a/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/package-info.java +++ b/maven-resolver-transport-file/src/main/java/org/eclipse/aether/transport/file/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Support for downloads/uploads using the local filesystem as "remote" storage. */ package org.eclipse.aether.transport.file; - diff --git a/maven-resolver-transport-file/src/test/java/org/eclipse/aether/transport/file/FileTransporterTest.java b/maven-resolver-transport-file/src/test/java/org/eclipse/aether/transport/file/FileTransporterTest.java index e075dfd88..23cc631f6 100644 --- a/maven-resolver-transport-file/src/test/java/org/eclipse/aether/transport/file/FileTransporterTest.java +++ b/maven-resolver-transport-file/src/test/java/org/eclipse/aether/transport/file/FileTransporterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.file; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.transport.file; import java.io.File; import java.io.FileNotFoundException; @@ -41,10 +38,11 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class FileTransporterTest -{ +public class FileTransporterTest { private DefaultRepositorySystemSession session; @@ -54,40 +52,32 @@ public class FileTransporterTest private File repoDir; - private RemoteRepository newRepo( String url ) - { - return new RemoteRepository.Builder( "test", "default", url ).build(); + private RemoteRepository newRepo(String url) { + return new RemoteRepository.Builder("test", "default", url).build(); } - private void newTransporter( String url ) - throws Exception - { - if ( transporter != null ) - { + private void newTransporter(String url) throws Exception { + if (transporter != null) { transporter.close(); transporter = null; } - transporter = factory.newInstance( session, newRepo( url ) ); + transporter = factory.newInstance(session, newRepo(url)); } @Before - public void setUp() - throws Exception - { + public void setUp() throws Exception { session = TestUtils.newSession(); - factory = new FileTransporterFactory( ); + factory = new FileTransporterFactory(); repoDir = TestFileUtils.createTempDir(); - TestFileUtils.writeString( new File( repoDir, "file.txt" ), "test" ); - TestFileUtils.writeString( new File( repoDir, "empty.txt" ), "" ); - TestFileUtils.writeString( new File( repoDir, "some space.txt" ), "space" ); - newTransporter( repoDir.toURI().toString() ); + TestFileUtils.writeString(new File(repoDir, "file.txt"), "test"); + TestFileUtils.writeString(new File(repoDir, "empty.txt"), ""); + TestFileUtils.writeString(new File(repoDir, "some space.txt"), "space"); + newTransporter(repoDir.toURI().toString()); } @After - public void tearDown() - { - if ( transporter != null ) - { + public void tearDown() { + if (transporter != null) { transporter.close(); transporter = null; } @@ -96,458 +86,356 @@ public void tearDown() } @Test - public void testClassify() - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( new FileNotFoundException() ) ); - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( new ResourceNotFoundException( "test" ) ) ); + public void testClassify() { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(new FileNotFoundException())); + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(new ResourceNotFoundException("test"))); } @Test - public void testPeek() - throws Exception - { - transporter.peek( new PeekTask( URI.create( "file.txt" ) ) ); + public void testPeek() throws Exception { + transporter.peek(new PeekTask(URI.create("file.txt"))); } @Test - public void testPeek_NotFound() - throws Exception - { - try - { - transporter.peek( new PeekTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( ResourceNotFoundException e ) - { - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( e ) ); + public void testPeek_NotFound() throws Exception { + try { + transporter.peek(new PeekTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (ResourceNotFoundException e) { + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e)); } } @Test - public void testPeek_Closed() - throws Exception - { + public void testPeek_Closed() throws Exception { transporter.close(); - try - { - transporter.peek( new PeekTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.peek(new PeekTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testGet_ToMemory() - throws Exception - { + public void testGet_ToMemory() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "file.txt" ) ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( task.getDataString(), new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("file.txt")).setListener(listener); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals(task.getDataString(), new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_ToFile() - throws Exception - { - File file = TestFileUtils.createTempFile( "failure" ); + public void testGet_ToFile() throws Exception { + File file = TestFileUtils.createTempFile("failure"); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "file.txt" ) ).setDataFile( file ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", TestFileUtils.readString( file ) ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "test", new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("file.txt")).setDataFile(file).setListener(listener); + transporter.get(task); + assertEquals("test", TestFileUtils.readString(file)); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("test", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_EmptyResource() - throws Exception - { - File file = TestFileUtils.createTempFile( "failure" ); + public void testGet_EmptyResource() throws Exception { + File file = TestFileUtils.createTempFile("failure"); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "empty.txt" ) ).setDataFile( file ).setListener( listener ); - transporter.get( task ); - assertEquals( "", TestFileUtils.readString( file ) ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 0L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); - assertEquals( "", new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("empty.txt")).setDataFile(file).setListener(listener); + transporter.get(task); + assertEquals("", TestFileUtils.readString(file)); + assertEquals(0L, listener.dataOffset); + assertEquals(0L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); + assertEquals("", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_EncodedResourcePath() - throws Exception - { - GetTask task = new GetTask( URI.create( "some%20space.txt" ) ); - transporter.get( task ); - assertEquals( "space", task.getDataString() ); + public void testGet_EncodedResourcePath() throws Exception { + GetTask task = new GetTask(URI.create("some%20space.txt")); + transporter.get(task); + assertEquals("space", task.getDataString()); } @Test - public void testGet_Fragment() - throws Exception - { - GetTask task = new GetTask( URI.create( "file.txt#ignored" ) ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); + public void testGet_Fragment() throws Exception { + GetTask task = new GetTask(URI.create("file.txt#ignored")); + transporter.get(task); + assertEquals("test", task.getDataString()); } @Test - public void testGet_Query() - throws Exception - { - GetTask task = new GetTask( URI.create( "file.txt?ignored" ) ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); + public void testGet_Query() throws Exception { + GetTask task = new GetTask(URI.create("file.txt?ignored")); + transporter.get(task); + assertEquals("test", task.getDataString()); } @Test - public void testGet_FileHandleLeak() - throws Exception - { - for ( int i = 0; i < 100; i++ ) - { - File file = TestFileUtils.createTempFile( "failure" ); - transporter.get( new GetTask( URI.create( "file.txt" ) ).setDataFile( file ) ); - assertTrue( i + ", " + file.getAbsolutePath(), file.delete() ); + public void testGet_FileHandleLeak() throws Exception { + for (int i = 0; i < 100; i++) { + File file = TestFileUtils.createTempFile("failure"); + transporter.get(new GetTask(URI.create("file.txt")).setDataFile(file)); + assertTrue(i + ", " + file.getAbsolutePath(), file.delete()); } } @Test - public void testGet_NotFound() - throws Exception - { - try - { - transporter.get( new GetTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( ResourceNotFoundException e ) - { - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( e ) ); + public void testGet_NotFound() throws Exception { + try { + transporter.get(new GetTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (ResourceNotFoundException e) { + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e)); } } @Test - public void testGet_Closed() - throws Exception - { + public void testGet_Closed() throws Exception { transporter.close(); - try - { - transporter.get( new GetTask( URI.create( "file.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.get(new GetTask(URI.create("file.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testGet_StartCancelled() - throws Exception - { + public void testGet_StartCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelStart = true; - GetTask task = new GetTask( URI.create( "file.txt" ) ).setListener( listener ); - try - { - transporter.get( task ); - fail( "Expected error" ); + GetTask task = new GetTask(URI.create("file.txt")).setListener(listener); + try { + transporter.get(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); - } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); } @Test - public void testGet_ProgressCancelled() - throws Exception - { + public void testGet_ProgressCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelProgress = true; - GetTask task = new GetTask( URI.create( "file.txt" ) ).setListener( listener ); - try - { - transporter.get( task ); - fail( "Expected error" ); - } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + GetTask task = new GetTask(URI.create("file.txt")).setListener(listener); + try { + transporter.get(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 1, listener.progressedCount ); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(1, listener.progressedCount); } @Test - public void testPut_FromMemory() - throws Exception - { + public void testPut_FromMemory() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = new PutTask(URI.create("file.txt")).setListener(listener).setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_FromFile() - throws Exception - { - File file = TestFileUtils.createTempFile( "upload" ); + public void testPut_FromFile() throws Exception { + File file = TestFileUtils.createTempFile("upload"); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "file.txt" ) ).setListener( listener ).setDataFile( file ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = new PutTask(URI.create("file.txt")).setListener(listener).setDataFile(file); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_EmptyResource() - throws Exception - { + public void testPut_EmptyResource() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "file.txt" ) ).setListener( listener ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 0L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); - assertEquals( "", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = new PutTask(URI.create("file.txt")).setListener(listener); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(0L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); + assertEquals("", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_NonExistentParentDir() - throws Exception - { + public void testPut_NonExistentParentDir() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = - new PutTask( URI.create( "dir/sub/dir/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "dir/sub/dir/file.txt" ) ) ); + PutTask task = new PutTask(URI.create("dir/sub/dir/file.txt")) + .setListener(listener) + .setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "dir/sub/dir/file.txt"))); } @Test - public void testPut_EncodedResourcePath() - throws Exception - { + public void testPut_EncodedResourcePath() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "some%20space.txt" ) ).setListener( listener ).setDataString( "OK" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 2L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "OK", TestFileUtils.readString( new File( repoDir, "some space.txt" ) ) ); - } - - @Test - public void testPut_FileHandleLeak() - throws Exception - { - for ( int i = 0; i < 100; i++ ) - { - File src = TestFileUtils.createTempFile( "upload" ); - File dst = new File( repoDir, "file.txt" ); - transporter.put( new PutTask( URI.create( "file.txt" ) ).setDataFile( src ) ); - assertTrue( i + ", " + src.getAbsolutePath(), src.delete() ); - assertTrue( i + ", " + dst.getAbsolutePath(), dst.delete() ); + PutTask task = new PutTask(URI.create("some%20space.txt")) + .setListener(listener) + .setDataString("OK"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(2L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("OK", TestFileUtils.readString(new File(repoDir, "some space.txt"))); + } + + @Test + public void testPut_FileHandleLeak() throws Exception { + for (int i = 0; i < 100; i++) { + File src = TestFileUtils.createTempFile("upload"); + File dst = new File(repoDir, "file.txt"); + transporter.put(new PutTask(URI.create("file.txt")).setDataFile(src)); + assertTrue(i + ", " + src.getAbsolutePath(), src.delete()); + assertTrue(i + ", " + dst.getAbsolutePath(), dst.delete()); } } @Test - public void testPut_Closed() - throws Exception - { + public void testPut_Closed() throws Exception { transporter.close(); - try - { - transporter.put( new PutTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.put(new PutTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testPut_StartCancelled() - throws Exception - { + public void testPut_StartCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelStart = true; - PutTask task = new PutTask( URI.create( "file.txt" ) ).setListener( listener ).setDataString( "upload" ); - try - { - transporter.put( task ); - fail( "Expected error" ); - } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + PutTask task = new PutTask(URI.create("file.txt")).setListener(listener).setDataString("upload"); + try { + transporter.put(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); - assertFalse( new File( repoDir, "file.txt" ).exists() ); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); + assertFalse(new File(repoDir, "file.txt").exists()); } @Test - public void testPut_ProgressCancelled() - throws Exception - { + public void testPut_ProgressCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelProgress = true; - PutTask task = new PutTask( URI.create( "file.txt" ) ).setListener( listener ).setDataString( "upload" ); - try - { - transporter.put( task ); - fail( "Expected error" ); + PutTask task = new PutTask(URI.create("file.txt")).setListener(listener).setDataString("upload"); + try { + transporter.put(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); - } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 1, listener.progressedCount ); - assertFalse( new File( repoDir, "file.txt" ).exists() ); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(1, listener.progressedCount); + assertFalse(new File(repoDir, "file.txt").exists()); } - @Test( expected = NoTransporterException.class ) - public void testInit_BadProtocol() - throws Exception - { - newTransporter( "bad:/void" ); + @Test(expected = NoTransporterException.class) + public void testInit_BadProtocol() throws Exception { + newTransporter("bad:/void"); } @Test - public void testInit_CaseInsensitiveProtocol() - throws Exception - { - newTransporter( "file:/void" ); - newTransporter( "FILE:/void" ); - newTransporter( "File:/void" ); + public void testInit_CaseInsensitiveProtocol() throws Exception { + newTransporter("file:/void"); + newTransporter("FILE:/void"); + newTransporter("File:/void"); } @Test - public void testInit_OpaqueUrl() - throws Exception - { - testInit( "file:repository", "repository" ); + public void testInit_OpaqueUrl() throws Exception { + testInit("file:repository", "repository"); } @Test - public void testInit_OpaqueUrlTrailingSlash() - throws Exception - { - testInit( "file:repository/", "repository" ); + public void testInit_OpaqueUrlTrailingSlash() throws Exception { + testInit("file:repository/", "repository"); } @Test - public void testInit_OpaqueUrlSpaces() - throws Exception - { - testInit( "file:repo%20space", "repo space" ); + public void testInit_OpaqueUrlSpaces() throws Exception { + testInit("file:repo%20space", "repo space"); } @Test - public void testInit_OpaqueUrlSpacesDecoded() - throws Exception - { - testInit( "file:repo space", "repo space" ); + public void testInit_OpaqueUrlSpacesDecoded() throws Exception { + testInit("file:repo space", "repo space"); } @Test - public void testInit_HierarchicalUrl() - throws Exception - { - testInit( "file:/repository", "/repository" ); + public void testInit_HierarchicalUrl() throws Exception { + testInit("file:/repository", "/repository"); } @Test - public void testInit_HierarchicalUrlTrailingSlash() - throws Exception - { - testInit( "file:/repository/", "/repository" ); + public void testInit_HierarchicalUrlTrailingSlash() throws Exception { + testInit("file:/repository/", "/repository"); } @Test - public void testInit_HierarchicalUrlSpaces() - throws Exception - { - testInit( "file:/repo%20space", "/repo space" ); + public void testInit_HierarchicalUrlSpaces() throws Exception { + testInit("file:/repo%20space", "/repo space"); } @Test - public void testInit_HierarchicalUrlSpacesDecoded() - throws Exception - { - testInit( "file:/repo space", "/repo space" ); + public void testInit_HierarchicalUrlSpacesDecoded() throws Exception { + testInit("file:/repo space", "/repo space"); } @Test - public void testInit_HierarchicalUrlRoot() - throws Exception - { - testInit( "file:/", "/" ); + public void testInit_HierarchicalUrlRoot() throws Exception { + testInit("file:/", "/"); } @Test - public void testInit_HierarchicalUrlHostNoPath() - throws Exception - { - testInit( "file://host/", "/" ); + public void testInit_HierarchicalUrlHostNoPath() throws Exception { + testInit("file://host/", "/"); } @Test - public void testInit_HierarchicalUrlHostPath() - throws Exception - { - testInit( "file://host/dir", "/dir" ); + public void testInit_HierarchicalUrlHostPath() throws Exception { + testInit("file://host/dir", "/dir"); } - private void testInit( String base, String expected ) - throws Exception - { - newTransporter( base ); - File exp = new File( expected ).getAbsoluteFile(); - assertEquals( exp, ( (FileTransporter) transporter ).getBasedir() ); + private void testInit(String base, String expected) throws Exception { + newTransporter(base); + File exp = new File(expected).getAbsoluteFile(); + assertEquals(exp, ((FileTransporter) transporter).getBasedir()); } - } diff --git a/maven-resolver-transport-file/src/test/java/org/eclipse/aether/transport/file/RecordingTransportListener.java b/maven-resolver-transport-file/src/test/java/org/eclipse/aether/transport/file/RecordingTransportListener.java index 76e35859f..03d1060c2 100644 --- a/maven-resolver-transport-file/src/test/java/org/eclipse/aether/transport/file/RecordingTransportListener.java +++ b/maven-resolver-transport-file/src/test/java/org/eclipse/aether/transport/file/RecordingTransportListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.file; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.file; import java.io.ByteArrayOutputStream; import java.nio.Buffer; @@ -26,11 +25,9 @@ import org.eclipse.aether.spi.connector.transport.TransportListener; import org.eclipse.aether.transfer.TransferCancelledException; -class RecordingTransportListener - extends TransportListener -{ +class RecordingTransportListener extends TransportListener { - public final ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 ); + public final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); public long dataOffset; @@ -45,30 +42,23 @@ class RecordingTransportListener public boolean cancelProgress; @Override - public void transportStarted( long dataOffset, long dataLength ) - throws TransferCancelledException - { + public void transportStarted(long dataOffset, long dataLength) throws TransferCancelledException { startedCount++; progressedCount = 0; this.dataLength = dataLength; this.dataOffset = dataOffset; baos.reset(); - if ( cancelStart ) - { + if (cancelStart) { throw new TransferCancelledException(); } } @Override - public void transportProgressed( ByteBuffer data ) - throws TransferCancelledException - { + public void transportProgressed(ByteBuffer data) throws TransferCancelledException { progressedCount++; - baos.write( data.array(), data.arrayOffset() + ( (Buffer) data ).position(), data.remaining() ); - if ( cancelProgress ) - { + baos.write(data.array(), data.arrayOffset() + ((Buffer) data).position(), data.remaining()); + if (cancelProgress) { throw new TransferCancelledException(); } } - } diff --git a/maven-resolver-transport-http/pom.xml b/maven-resolver-transport-http/pom.xml index 7dd670247..9770632a0 100644 --- a/maven-resolver-transport-http/pom.xml +++ b/maven-resolver-transport-http/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-transport-http Maven Artifact Resolver Transport HTTP - - A transport implementation for repositories using http:// and https:// URLs. - + A transport implementation for repositories using http:// and https:// URLs. org.apache.maven.resolver.transport.http diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/AuthSchemePool.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/AuthSchemePool.java index 384227fa4..2603eae56 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/AuthSchemePool.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/AuthSchemePool.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; import java.util.LinkedList; @@ -28,44 +27,34 @@ /** * Pool of (equivalent) auth schemes for a single host. */ -final class AuthSchemePool -{ +final class AuthSchemePool { private final LinkedList authSchemes; private String schemeName; - AuthSchemePool() - { + AuthSchemePool() { authSchemes = new LinkedList<>(); } - public synchronized AuthScheme get() - { + public synchronized AuthScheme get() { AuthScheme authScheme = null; - if ( !authSchemes.isEmpty() ) - { + if (!authSchemes.isEmpty()) { authScheme = authSchemes.removeLast(); - } - else if ( AuthSchemes.BASIC.equalsIgnoreCase( schemeName ) ) - { + } else if (AuthSchemes.BASIC.equalsIgnoreCase(schemeName)) { authScheme = new BasicScheme(); } return authScheme; } - public synchronized void put( AuthScheme authScheme ) - { - if ( authScheme == null ) - { + public synchronized void put(AuthScheme authScheme) { + if (authScheme == null) { return; } - if ( !authScheme.getSchemeName().equals( schemeName ) ) - { + if (!authScheme.getSchemeName().equals(schemeName)) { schemeName = authScheme.getSchemeName(); authSchemes.clear(); } - authSchemes.add( authScheme ); + authSchemes.add(authScheme); } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/ChecksumExtractor.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/ChecksumExtractor.java index 8fde9b817..879b1f53e 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/ChecksumExtractor.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/ChecksumExtractor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,38 +16,36 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; + +import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.HttpResponseException; import org.apache.http.client.methods.HttpUriRequest; -import java.util.Map; - /** * A component extracting included checksums from response of artifact request. * * @since 1.8.0 */ -public abstract class ChecksumExtractor -{ +public abstract class ChecksumExtractor { /** * Prepares request, if needed. */ - public void prepareRequest( HttpUriRequest request ) - { + public void prepareRequest(HttpUriRequest request) { // nothing } /** * May control is request to be retried with checksum extractors disabled. */ - public boolean retryWithoutExtractor( HttpResponseException exception ) - { + public boolean retryWithoutExtractor(HttpResponseException exception) { return false; // nothing, usually tied to prepareRequest } /** * Tries to extract checksums from response headers, if present, otherwise returns {@code null}. */ - public abstract Map extractChecksums( HttpResponse response ); + public abstract Map extractChecksums(HttpResponse response); } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/DeferredCredentialsProvider.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/DeferredCredentialsProvider.java index 233eb426a..664e8fb06 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/DeferredCredentialsProvider.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/DeferredCredentialsProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; import java.net.InetAddress; import java.net.UnknownHostException; @@ -36,164 +35,127 @@ /** * Credentials provider that defers calls into the auth context until authentication is actually requested. */ -final class DeferredCredentialsProvider - implements CredentialsProvider -{ +final class DeferredCredentialsProvider implements CredentialsProvider { private final CredentialsProvider delegate; private final Map factories; - DeferredCredentialsProvider() - { + DeferredCredentialsProvider() { delegate = new BasicCredentialsProvider(); factories = new HashMap<>(); } - public void setCredentials( AuthScope authScope, Factory factory ) - { - factories.put( authScope, factory ); + public void setCredentials(AuthScope authScope, Factory factory) { + factories.put(authScope, factory); } @Override - public void setCredentials( AuthScope authScope, Credentials credentials ) - { - delegate.setCredentials( authScope, credentials ); + public void setCredentials(AuthScope authScope, Credentials credentials) { + delegate.setCredentials(authScope, credentials); } @Override - public Credentials getCredentials( AuthScope authScope ) - { - synchronized ( factories ) - { - for ( Iterator> it = factories.entrySet().iterator(); it.hasNext(); ) - { + public Credentials getCredentials(AuthScope authScope) { + synchronized (factories) { + for (Iterator> it = + factories.entrySet().iterator(); + it.hasNext(); ) { Map.Entry entry = it.next(); - if ( authScope.match( entry.getKey() ) >= 0 ) - { + if (authScope.match(entry.getKey()) >= 0) { it.remove(); - delegate.setCredentials( entry.getKey(), entry.getValue().newCredentials() ); + delegate.setCredentials(entry.getKey(), entry.getValue().newCredentials()); } } } - return delegate.getCredentials( authScope ); + return delegate.getCredentials(authScope); } @Override - public void clear() - { + public void clear() { delegate.clear(); } - interface Factory - { + interface Factory { Credentials newCredentials(); - } - static class BasicFactory - implements Factory - { + static class BasicFactory implements Factory { private final AuthenticationContext authContext; - BasicFactory( AuthenticationContext authContext ) - { + BasicFactory(AuthenticationContext authContext) { this.authContext = authContext; } @Override - public Credentials newCredentials() - { - String username = authContext.get( AuthenticationContext.USERNAME ); - if ( username == null ) - { + public Credentials newCredentials() { + String username = authContext.get(AuthenticationContext.USERNAME); + if (username == null) { return null; } - String password = authContext.get( AuthenticationContext.PASSWORD ); - return new UsernamePasswordCredentials( username, password ); + String password = authContext.get(AuthenticationContext.PASSWORD); + return new UsernamePasswordCredentials(username, password); } - } - static class NtlmFactory - implements Factory - { + static class NtlmFactory implements Factory { private final AuthenticationContext authContext; - NtlmFactory( AuthenticationContext authContext ) - { + NtlmFactory(AuthenticationContext authContext) { this.authContext = authContext; } @Override - public Credentials newCredentials() - { - String username = authContext.get( AuthenticationContext.USERNAME ); - if ( username == null ) - { + public Credentials newCredentials() { + String username = authContext.get(AuthenticationContext.USERNAME); + if (username == null) { return null; } - String password = authContext.get( AuthenticationContext.PASSWORD ); - String domain = authContext.get( AuthenticationContext.NTLM_DOMAIN ); - String workstation = authContext.get( AuthenticationContext.NTLM_WORKSTATION ); - - if ( domain == null ) - { - int backslash = username.indexOf( '\\' ); - if ( backslash < 0 ) - { + String password = authContext.get(AuthenticationContext.PASSWORD); + String domain = authContext.get(AuthenticationContext.NTLM_DOMAIN); + String workstation = authContext.get(AuthenticationContext.NTLM_WORKSTATION); + + if (domain == null) { + int backslash = username.indexOf('\\'); + if (backslash < 0) { domain = guessDomain(); - } - else - { - domain = username.substring( 0, backslash ); - username = username.substring( backslash + 1 ); + } else { + domain = username.substring(0, backslash); + username = username.substring(backslash + 1); } } - if ( workstation == null ) - { + if (workstation == null) { workstation = guessWorkstation(); } - return new NTCredentials( username, password, workstation, domain ); + return new NTCredentials(username, password, workstation, domain); } - private static String guessDomain() - { - return safeNtlmString( System.getProperty( "http.auth.ntlm.domain" ), System.getenv( "USERDOMAIN" ) ); + private static String guessDomain() { + return safeNtlmString(System.getProperty("http.auth.ntlm.domain"), System.getenv("USERDOMAIN")); } - private static String guessWorkstation() - { + private static String guessWorkstation() { String localHost = null; - try - { + try { localHost = InetAddress.getLocalHost().getHostName(); - } - catch ( UnknownHostException e ) - { + } catch (UnknownHostException e) { // well, we have other options to try } - return safeNtlmString( System.getProperty( "http.auth.ntlm.host" ), System.getenv( "COMPUTERNAME" ), - localHost ); + return safeNtlmString(System.getProperty("http.auth.ntlm.host"), System.getenv("COMPUTERNAME"), localHost); } - private static String safeNtlmString( String... strings ) - { - for ( String string : strings ) - { - if ( string != null ) - { + private static String safeNtlmString(String... strings) { + for (String string : strings) { + if (string != null) { return string; } } // avoid NPE from httpclient and trigger proper auth failure instead return ""; } - } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/DemuxCredentialsProvider.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/DemuxCredentialsProvider.java index a0d565368..042621f42 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/DemuxCredentialsProvider.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/DemuxCredentialsProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; @@ -30,9 +29,7 @@ * to redirects, we use an auth scope for server credentials that's not specific enough to not be mistaken for proxy * auth. This provider helps to maintain the proper isolation. */ -final class DemuxCredentialsProvider - implements CredentialsProvider -{ +final class DemuxCredentialsProvider implements CredentialsProvider { private final CredentialsProvider serverCredentialsProvider; @@ -40,40 +37,35 @@ final class DemuxCredentialsProvider private final HttpHost proxy; - DemuxCredentialsProvider( CredentialsProvider serverCredentialsProvider, - CredentialsProvider proxyCredentialsProvider, HttpHost proxy ) - { + DemuxCredentialsProvider( + CredentialsProvider serverCredentialsProvider, + CredentialsProvider proxyCredentialsProvider, + HttpHost proxy) { this.serverCredentialsProvider = serverCredentialsProvider; this.proxyCredentialsProvider = proxyCredentialsProvider; this.proxy = proxy; } - private CredentialsProvider getDelegate( AuthScope authScope ) - { - if ( proxy.getPort() == authScope.getPort() && proxy.getHostName().equalsIgnoreCase( authScope.getHost() ) ) - { + private CredentialsProvider getDelegate(AuthScope authScope) { + if (proxy.getPort() == authScope.getPort() && proxy.getHostName().equalsIgnoreCase(authScope.getHost())) { return proxyCredentialsProvider; } return serverCredentialsProvider; } @Override - public Credentials getCredentials( AuthScope authScope ) - { - return getDelegate( authScope ).getCredentials( authScope ); + public Credentials getCredentials(AuthScope authScope) { + return getDelegate(authScope).getCredentials(authScope); } @Override - public void setCredentials( AuthScope authScope, Credentials credentials ) - { - getDelegate( authScope ).setCredentials( authScope, credentials ); + public void setCredentials(AuthScope authScope, Credentials credentials) { + getDelegate(authScope).setCredentials(authScope, credentials); } @Override - public void clear() - { + public void clear() { serverCredentialsProvider.clear(); proxyCredentialsProvider.clear(); } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/GlobalState.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/GlobalState.java index b8d8c8003..4d925aa60 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/GlobalState.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/GlobalState.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSocketFactory; import java.io.Closeable; import java.util.Arrays; @@ -37,54 +39,42 @@ import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.util.ConfigUtils; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLSocketFactory; - /** * Container for HTTP-related state that can be shared across incarnations of the transporter to optimize the * communication with servers. */ -final class GlobalState - implements Closeable -{ +final class GlobalState implements Closeable { - static class CompoundKey - { + static class CompoundKey { private final Object[] keys; - CompoundKey( Object... keys ) - { + CompoundKey(Object... keys) { this.keys = keys; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } CompoundKey that = (CompoundKey) obj; - return Arrays.equals( keys, that.keys ); + return Arrays.equals(keys, that.keys); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + Arrays.hashCode( keys ); + hash = hash * 31 + Arrays.hashCode(keys); return hash; } @Override - public String toString() - { - return Arrays.toString( keys ); + public String toString() { + return Arrays.toString(keys); } } @@ -100,34 +90,23 @@ public String toString() private final ConcurrentMap expectContinues; - public static GlobalState get( RepositorySystemSession session ) - { + public static GlobalState get(RepositorySystemSession session) { GlobalState cache; RepositoryCache repoCache = session.getCache(); - if ( repoCache == null || !ConfigUtils.getBoolean( session, true, CONFIG_PROP_CACHE_STATE ) ) - { + if (repoCache == null || !ConfigUtils.getBoolean(session, true, CONFIG_PROP_CACHE_STATE)) { cache = null; - } - else - { - Object tmp = repoCache.get( session, KEY ); - if ( tmp instanceof GlobalState ) - { + } else { + Object tmp = repoCache.get(session, KEY); + if (tmp instanceof GlobalState) { cache = (GlobalState) tmp; - } - else - { - synchronized ( GlobalState.class ) - { - tmp = repoCache.get( session, KEY ); - if ( tmp instanceof GlobalState ) - { + } else { + synchronized (GlobalState.class) { + tmp = repoCache.get(session, KEY); + if (tmp instanceof GlobalState) { cache = (GlobalState) tmp; - } - else - { + } else { cache = new GlobalState(); - repoCache.put( session, KEY, cache ); + repoCache.put(session, KEY, cache); } } } @@ -135,8 +114,7 @@ public static GlobalState get( RepositorySystemSession session ) return cache; } - private GlobalState() - { + private GlobalState() { connectionManagers = new ConcurrentHashMap<>(); userTokens = new ConcurrentHashMap<>(); authSchemePools = new ConcurrentHashMap<>(); @@ -144,93 +122,78 @@ private GlobalState() } @Override - public void close() - { - for ( Iterator> it = connectionManagers.entrySet().iterator(); - it.hasNext(); ) - { + public void close() { + for (Iterator> it = + connectionManagers.entrySet().iterator(); + it.hasNext(); ) { HttpClientConnectionManager connMgr = it.next().getValue(); it.remove(); connMgr.shutdown(); } } - public HttpClientConnectionManager getConnectionManager( SslConfig config ) - { - HttpClientConnectionManager manager = connectionManagers.get( config ); - if ( manager == null ) - { - HttpClientConnectionManager connMgr = newConnectionManager( config ); - manager = connectionManagers.putIfAbsent( config, connMgr ); - if ( manager != null ) - { + public HttpClientConnectionManager getConnectionManager(SslConfig config) { + HttpClientConnectionManager manager = connectionManagers.get(config); + if (manager == null) { + HttpClientConnectionManager connMgr = newConnectionManager(config); + manager = connectionManagers.putIfAbsent(config, connMgr); + if (manager != null) { connMgr.shutdown(); - } - else - { + } else { manager = connMgr; } } return manager; } - @SuppressWarnings( "checkstyle:magicnumber" ) - public static HttpClientConnectionManager newConnectionManager( SslConfig sslConfig ) - { + @SuppressWarnings("checkstyle:magicnumber") + public static HttpClientConnectionManager newConnectionManager(SslConfig sslConfig) { RegistryBuilder registryBuilder = RegistryBuilder.create() - .register( "http", PlainConnectionSocketFactory.getSocketFactory() ); - - if ( sslConfig == null ) - { - registryBuilder.register( "https", SSLConnectionSocketFactory.getSystemSocketFactory() ); + .register("http", PlainConnectionSocketFactory.getSocketFactory()); + + if (sslConfig == null) { + registryBuilder.register("https", SSLConnectionSocketFactory.getSystemSocketFactory()); + } else { + SSLSocketFactory sslSocketFactory = (sslConfig.context != null) + ? sslConfig.context.getSocketFactory() + : (SSLSocketFactory) SSLSocketFactory.getDefault(); + + HostnameVerifier hostnameVerifier = (sslConfig.verifier != null) + ? sslConfig.verifier + : SSLConnectionSocketFactory.getDefaultHostnameVerifier(); + + registryBuilder.register( + "https", + new SSLConnectionSocketFactory( + sslSocketFactory, sslConfig.protocols, sslConfig.cipherSuites, hostnameVerifier)); } - else - { - SSLSocketFactory sslSocketFactory = ( sslConfig.context != null ) - ? sslConfig.context.getSocketFactory() : (SSLSocketFactory) SSLSocketFactory.getDefault(); - - HostnameVerifier hostnameVerifier = ( sslConfig.verifier != null ) - ? sslConfig.verifier : SSLConnectionSocketFactory.getDefaultHostnameVerifier(); - - registryBuilder.register( "https", new SSLConnectionSocketFactory( - sslSocketFactory, sslConfig.protocols, sslConfig.cipherSuites, hostnameVerifier ) ); - } - PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( registryBuilder.build() ); - connMgr.setMaxTotal( 100 ); - connMgr.setDefaultMaxPerRoute( 50 ); + PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(registryBuilder.build()); + connMgr.setMaxTotal(100); + connMgr.setDefaultMaxPerRoute(50); return connMgr; } - public Object getUserToken( CompoundKey key ) - { - return userTokens.get( key ); + public Object getUserToken(CompoundKey key) { + return userTokens.get(key); } - public void setUserToken( CompoundKey key, Object userToken ) - { - if ( userToken != null ) - { - userTokens.put( key, userToken ); - } - else - { - userTokens.remove( key ); + public void setUserToken(CompoundKey key, Object userToken) { + if (userToken != null) { + userTokens.put(key, userToken); + } else { + userTokens.remove(key); } } - public ConcurrentMap getAuthSchemePools() - { + public ConcurrentMap getAuthSchemePools() { return authSchemePools; } - public Boolean getExpectContinue( CompoundKey key ) - { - return expectContinues.get( key ); + public Boolean getExpectContinue(CompoundKey key) { + return expectContinues.get(key); } - public void setExpectContinue( CompoundKey key, boolean enabled ) - { - expectContinues.put( key, enabled ); + public void setExpectContinue(CompoundKey key, boolean enabled) { + expectContinues.put(key, enabled); } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpMkCol.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpMkCol.java index b3b479e15..a8937efa8 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpMkCol.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpMkCol.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; import java.net.URI; @@ -26,19 +25,14 @@ /** * WebDAV MKCOL request to create parent directories. */ -final class HttpMkCol - extends HttpRequestBase -{ +final class HttpMkCol extends HttpRequestBase { - HttpMkCol( URI uri ) - { - setURI( uri ); + HttpMkCol(URI uri) { + setURI(uri); } @Override - public String getMethod() - { + public String getMethod() { return "MKCOL"; } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpTransporter.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpTransporter.java index 09d7c169d..64a700c9b 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpTransporter.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpTransporter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,25 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InterruptedIOException; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.http.Header; import org.apache.http.HttpEntity; @@ -69,37 +86,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InterruptedIOException; -import java.io.OutputStream; -import java.io.UncheckedIOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import static java.util.Objects.requireNonNull; /** * A transporter for HTTP/HTTPS. */ -final class HttpTransporter - extends AbstractTransporter -{ +final class HttpTransporter extends AbstractTransporter { private static final Pattern CONTENT_RANGE_PATTERN = - Pattern.compile( "\\s*bytes\\s+([0-9]+)\\s*-\\s*([0-9]+)\\s*/.*" ); + Pattern.compile("\\s*bytes\\s+([0-9]+)\\s*-\\s*([0-9]+)\\s*/.*"); - private static final Logger LOGGER = LoggerFactory.getLogger( HttpTransporter.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(HttpTransporter.class); private final Map checksumExtractors; @@ -119,208 +116,179 @@ final class HttpTransporter private final LocalState state; - HttpTransporter( Map checksumExtractors, - RemoteRepository repository, - RepositorySystemSession session ) - throws NoTransporterException - { - if ( !"http".equalsIgnoreCase( repository.getProtocol() ) - && !"https".equalsIgnoreCase( repository.getProtocol() ) ) - { - throw new NoTransporterException( repository ); - } - this.checksumExtractors = requireNonNull( checksumExtractors, "checksum extractors must not be null" ); - try - { - this.baseUri = new URI( repository.getUrl() ).parseServerAuthority(); - if ( baseUri.isOpaque() ) - { - throw new URISyntaxException( repository.getUrl(), "URL must not be opaque" ); + HttpTransporter( + Map checksumExtractors, + RemoteRepository repository, + RepositorySystemSession session) + throws NoTransporterException { + if (!"http".equalsIgnoreCase(repository.getProtocol()) && !"https".equalsIgnoreCase(repository.getProtocol())) { + throw new NoTransporterException(repository); + } + this.checksumExtractors = requireNonNull(checksumExtractors, "checksum extractors must not be null"); + try { + this.baseUri = new URI(repository.getUrl()).parseServerAuthority(); + if (baseUri.isOpaque()) { + throw new URISyntaxException(repository.getUrl(), "URL must not be opaque"); } - this.server = URIUtils.extractHost( baseUri ); - if ( server == null ) - { - throw new URISyntaxException( repository.getUrl(), "URL lacks host name" ); + this.server = URIUtils.extractHost(baseUri); + if (server == null) { + throw new URISyntaxException(repository.getUrl(), "URL lacks host name"); } + } catch (URISyntaxException e) { + throw new NoTransporterException(repository, e.getMessage(), e); } - catch ( URISyntaxException e ) - { - throw new NoTransporterException( repository, e.getMessage(), e ); - } - this.proxy = toHost( repository.getProxy() ); + this.proxy = toHost(repository.getProxy()); - this.repoAuthContext = AuthenticationContext.forRepository( session, repository ); - this.proxyAuthContext = AuthenticationContext.forProxy( session, repository ); + this.repoAuthContext = AuthenticationContext.forRepository(session, repository); + this.proxyAuthContext = AuthenticationContext.forProxy(session, repository); - this.state = new LocalState( session, repository, new SslConfig( session, repoAuthContext ) ); + this.state = new LocalState(session, repository, new SslConfig(session, repoAuthContext)); - this.headers = ConfigUtils.getMap( session, Collections.emptyMap(), + this.headers = ConfigUtils.getMap( + session, + Collections.emptyMap(), ConfigurationProperties.HTTP_HEADERS + "." + repository.getId(), - ConfigurationProperties.HTTP_HEADERS ); + ConfigurationProperties.HTTP_HEADERS); - String credentialEncoding = ConfigUtils.getString( session, + String credentialEncoding = ConfigUtils.getString( + session, ConfigurationProperties.DEFAULT_HTTP_CREDENTIAL_ENCODING, ConfigurationProperties.HTTP_CREDENTIAL_ENCODING + "." + repository.getId(), - ConfigurationProperties.HTTP_CREDENTIAL_ENCODING ); - int connectTimeout = ConfigUtils.getInteger( session, + ConfigurationProperties.HTTP_CREDENTIAL_ENCODING); + int connectTimeout = ConfigUtils.getInteger( + session, ConfigurationProperties.DEFAULT_CONNECT_TIMEOUT, ConfigurationProperties.CONNECT_TIMEOUT + "." + repository.getId(), - ConfigurationProperties.CONNECT_TIMEOUT ); - int requestTimeout = ConfigUtils.getInteger( session, + ConfigurationProperties.CONNECT_TIMEOUT); + int requestTimeout = ConfigUtils.getInteger( + session, ConfigurationProperties.DEFAULT_REQUEST_TIMEOUT, ConfigurationProperties.REQUEST_TIMEOUT + "." + repository.getId(), - ConfigurationProperties.REQUEST_TIMEOUT ); - String userAgent = ConfigUtils.getString( session, - ConfigurationProperties.DEFAULT_USER_AGENT, - ConfigurationProperties.USER_AGENT ); + ConfigurationProperties.REQUEST_TIMEOUT); + String userAgent = ConfigUtils.getString( + session, ConfigurationProperties.DEFAULT_USER_AGENT, ConfigurationProperties.USER_AGENT); - Charset credentialsCharset = Charset.forName( credentialEncoding ); + Charset credentialsCharset = Charset.forName(credentialEncoding); Registry authSchemeRegistry = RegistryBuilder.create() - .register( AuthSchemes.BASIC, new BasicSchemeFactory( credentialsCharset ) ) - .register( AuthSchemes.DIGEST, new DigestSchemeFactory( credentialsCharset ) ) - .register( AuthSchemes.NTLM, new NTLMSchemeFactory() ) - .register( AuthSchemes.SPNEGO, new SPNegoSchemeFactory() ) - .register( AuthSchemes.KERBEROS, new KerberosSchemeFactory() ) + .register(AuthSchemes.BASIC, new BasicSchemeFactory(credentialsCharset)) + .register(AuthSchemes.DIGEST, new DigestSchemeFactory(credentialsCharset)) + .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) + .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) + .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()) .build(); - SocketConfig socketConfig = SocketConfig.custom() - .setSoTimeout( requestTimeout ).build(); + SocketConfig socketConfig = + SocketConfig.custom().setSoTimeout(requestTimeout).build(); RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout( connectTimeout ) - .setConnectionRequestTimeout( connectTimeout ) - .setSocketTimeout( requestTimeout ).build(); + .setConnectTimeout(connectTimeout) + .setConnectionRequestTimeout(connectTimeout) + .setSocketTimeout(requestTimeout) + .build(); this.client = HttpClientBuilder.create() - .setUserAgent( userAgent ) - .setDefaultSocketConfig( socketConfig ) - .setDefaultRequestConfig( requestConfig ) - .setDefaultAuthSchemeRegistry( authSchemeRegistry ) - .setConnectionManager( state.getConnectionManager() ) - .setConnectionManagerShared( true ) - .setDefaultCredentialsProvider( - toCredentialsProvider( server, repoAuthContext, proxy, proxyAuthContext ) - ) - .setProxy( proxy ) + .setUserAgent(userAgent) + .setDefaultSocketConfig(socketConfig) + .setDefaultRequestConfig(requestConfig) + .setDefaultAuthSchemeRegistry(authSchemeRegistry) + .setConnectionManager(state.getConnectionManager()) + .setConnectionManagerShared(true) + .setDefaultCredentialsProvider(toCredentialsProvider(server, repoAuthContext, proxy, proxyAuthContext)) + .setProxy(proxy) .build(); } - private static HttpHost toHost( Proxy proxy ) - { + private static HttpHost toHost(Proxy proxy) { HttpHost host = null; - if ( proxy != null ) - { - host = new HttpHost( proxy.getHost(), proxy.getPort() ); + if (proxy != null) { + host = new HttpHost(proxy.getHost(), proxy.getPort()); } return host; } - private static CredentialsProvider toCredentialsProvider( HttpHost server, AuthenticationContext serverAuthCtx, - HttpHost proxy, AuthenticationContext proxyAuthCtx ) - { - CredentialsProvider provider = toCredentialsProvider( server.getHostName(), AuthScope.ANY_PORT, serverAuthCtx ); - if ( proxy != null ) - { - CredentialsProvider p = toCredentialsProvider( proxy.getHostName(), proxy.getPort(), proxyAuthCtx ); - provider = new DemuxCredentialsProvider( provider, p, proxy ); + private static CredentialsProvider toCredentialsProvider( + HttpHost server, AuthenticationContext serverAuthCtx, HttpHost proxy, AuthenticationContext proxyAuthCtx) { + CredentialsProvider provider = toCredentialsProvider(server.getHostName(), AuthScope.ANY_PORT, serverAuthCtx); + if (proxy != null) { + CredentialsProvider p = toCredentialsProvider(proxy.getHostName(), proxy.getPort(), proxyAuthCtx); + provider = new DemuxCredentialsProvider(provider, p, proxy); } return provider; } - private static CredentialsProvider toCredentialsProvider( String host, int port, AuthenticationContext ctx ) - { + private static CredentialsProvider toCredentialsProvider(String host, int port, AuthenticationContext ctx) { DeferredCredentialsProvider provider = new DeferredCredentialsProvider(); - if ( ctx != null ) - { - AuthScope basicScope = new AuthScope( host, port ); - provider.setCredentials( basicScope, new DeferredCredentialsProvider.BasicFactory( ctx ) ); + if (ctx != null) { + AuthScope basicScope = new AuthScope(host, port); + provider.setCredentials(basicScope, new DeferredCredentialsProvider.BasicFactory(ctx)); - AuthScope ntlmScope = new AuthScope( host, port, AuthScope.ANY_REALM, "ntlm" ); - provider.setCredentials( ntlmScope, new DeferredCredentialsProvider.NtlmFactory( ctx ) ); + AuthScope ntlmScope = new AuthScope(host, port, AuthScope.ANY_REALM, "ntlm"); + provider.setCredentials(ntlmScope, new DeferredCredentialsProvider.NtlmFactory(ctx)); } return provider; } - LocalState getState() - { + LocalState getState() { return state; } - private URI resolve( TransportTask task ) - { - return UriUtils.resolve( baseUri, task.getLocation() ); + private URI resolve(TransportTask task) { + return UriUtils.resolve(baseUri, task.getLocation()); } @Override - public int classify( Throwable error ) - { - if ( error instanceof HttpResponseException - && ( (HttpResponseException) error ).getStatusCode() == HttpStatus.SC_NOT_FOUND ) - { + public int classify(Throwable error) { + if (error instanceof HttpResponseException + && ((HttpResponseException) error).getStatusCode() == HttpStatus.SC_NOT_FOUND) { return ERROR_NOT_FOUND; } return ERROR_OTHER; } @Override - protected void implPeek( PeekTask task ) - throws Exception - { - HttpHead request = commonHeaders( new HttpHead( resolve( task ) ) ); - execute( request, null ); + protected void implPeek(PeekTask task) throws Exception { + HttpHead request = commonHeaders(new HttpHead(resolve(task))); + execute(request, null); } @Override - protected void implGet( GetTask task ) - throws Exception - { + protected void implGet(GetTask task) throws Exception { boolean resume = true; boolean applyChecksumExtractors = true; - EntityGetter getter = new EntityGetter( task ); - HttpGet request = commonHeaders( new HttpGet( resolve( task ) ) ); - while ( true ) - { - try - { - if ( resume ) - { - resume( request, task ); + EntityGetter getter = new EntityGetter(task); + HttpGet request = commonHeaders(new HttpGet(resolve(task))); + while (true) { + try { + if (resume) { + resume(request, task); } - if ( applyChecksumExtractors ) - { - for ( ChecksumExtractor checksumExtractor : checksumExtractors.values() ) - { - checksumExtractor.prepareRequest( request ); + if (applyChecksumExtractors) { + for (ChecksumExtractor checksumExtractor : checksumExtractors.values()) { + checksumExtractor.prepareRequest(request); } } - execute( request, getter ); + execute(request, getter); break; - } - catch ( HttpResponseException e ) - { - if ( resume && e.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED - && request.containsHeader( HttpHeaders.RANGE ) ) - { - request = commonHeaders( new HttpGet( resolve( task ) ) ); + } catch (HttpResponseException e) { + if (resume + && e.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED + && request.containsHeader(HttpHeaders.RANGE)) { + request = commonHeaders(new HttpGet(resolve(task))); resume = false; continue; } - if ( applyChecksumExtractors ) - { + if (applyChecksumExtractors) { boolean retryWithoutExtractors = false; - for ( ChecksumExtractor checksumExtractor : checksumExtractors.values() ) - { - if ( checksumExtractor.retryWithoutExtractor( e ) ) - { + for (ChecksumExtractor checksumExtractor : checksumExtractors.values()) { + if (checksumExtractor.retryWithoutExtractor(e)) { retryWithoutExtractors = true; break; } } - if ( retryWithoutExtractors ) - { - request = commonHeaders( new HttpGet( resolve( task ) ) ); + if (retryWithoutExtractors) { + request = commonHeaders(new HttpGet(resolve(task))); applyChecksumExtractors = false; continue; } @@ -331,374 +299,277 @@ protected void implGet( GetTask task ) } @Override - protected void implPut( PutTask task ) - throws Exception - { - PutTaskEntity entity = new PutTaskEntity( task ); - HttpPut request = commonHeaders( entity( new HttpPut( resolve( task ) ), entity ) ); - try - { - execute( request, null ); - } - catch ( HttpResponseException e ) - { - if ( e.getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED && request.containsHeader( HttpHeaders.EXPECT ) ) - { - state.setExpectContinue( false ); - request = commonHeaders( entity( new HttpPut( request.getURI() ), entity ) ); - execute( request, null ); + protected void implPut(PutTask task) throws Exception { + PutTaskEntity entity = new PutTaskEntity(task); + HttpPut request = commonHeaders(entity(new HttpPut(resolve(task)), entity)); + try { + execute(request, null); + } catch (HttpResponseException e) { + if (e.getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED && request.containsHeader(HttpHeaders.EXPECT)) { + state.setExpectContinue(false); + request = commonHeaders(entity(new HttpPut(request.getURI()), entity)); + execute(request, null); return; } throw e; } } - private void execute( HttpUriRequest request, EntityGetter getter ) - throws Exception - { - try - { - SharingHttpContext context = new SharingHttpContext( state ); - prepare( request, context ); - try ( CloseableHttpResponse response = client.execute( server, request, context ) ) - { - try - { + private void execute(HttpUriRequest request, EntityGetter getter) throws Exception { + try { + SharingHttpContext context = new SharingHttpContext(state); + prepare(request, context); + try (CloseableHttpResponse response = client.execute(server, request, context)) { + try { context.close(); - handleStatus( response ); - if ( getter != null ) - { - getter.handle( response ); + handleStatus(response); + if (getter != null) { + getter.handle(response); } - } - finally - { - EntityUtils.consumeQuietly( response.getEntity() ); + } finally { + EntityUtils.consumeQuietly(response.getEntity()); } } - } - catch ( IOException e ) - { - if ( e.getCause() instanceof TransferCancelledException ) - { + } catch (IOException e) { + if (e.getCause() instanceof TransferCancelledException) { throw (Exception) e.getCause(); } throw e; } } - private void prepare( HttpUriRequest request, SharingHttpContext context ) - { - boolean put = HttpPut.METHOD_NAME.equalsIgnoreCase( request.getMethod() ); - if ( state.getWebDav() == null && ( put || isPayloadPresent( request ) ) ) - { - HttpOptions req = commonHeaders( new HttpOptions( request.getURI() ) ); - try ( CloseableHttpResponse response = client.execute( server, req, context ) ) - { - state.setWebDav( isWebDav( response ) ); - EntityUtils.consumeQuietly( response.getEntity() ); - } - catch ( IOException e ) - { - LOGGER.debug( "Failed to prepare HTTP context", e ); + private void prepare(HttpUriRequest request, SharingHttpContext context) { + boolean put = HttpPut.METHOD_NAME.equalsIgnoreCase(request.getMethod()); + if (state.getWebDav() == null && (put || isPayloadPresent(request))) { + HttpOptions req = commonHeaders(new HttpOptions(request.getURI())); + try (CloseableHttpResponse response = client.execute(server, req, context)) { + state.setWebDav(isWebDav(response)); + EntityUtils.consumeQuietly(response.getEntity()); + } catch (IOException e) { + LOGGER.debug("Failed to prepare HTTP context", e); } } - if ( put && Boolean.TRUE.equals( state.getWebDav() ) ) - { - mkdirs( request.getURI(), context ); + if (put && Boolean.TRUE.equals(state.getWebDav())) { + mkdirs(request.getURI(), context); } } - private boolean isWebDav( CloseableHttpResponse response ) - { - return response.containsHeader( HttpHeaders.DAV ); + private boolean isWebDav(CloseableHttpResponse response) { + return response.containsHeader(HttpHeaders.DAV); } - @SuppressWarnings( "checkstyle:magicnumber" ) - private void mkdirs( URI uri, SharingHttpContext context ) - { - List dirs = UriUtils.getDirectories( baseUri, uri ); + @SuppressWarnings("checkstyle:magicnumber") + private void mkdirs(URI uri, SharingHttpContext context) { + List dirs = UriUtils.getDirectories(baseUri, uri); int index = 0; - for ( ; index < dirs.size(); index++ ) - { - try ( CloseableHttpResponse response = - client.execute( server, commonHeaders( new HttpMkCol( dirs.get( index ) ) ), context ) ) - { - try - { + for (; index < dirs.size(); index++) { + try (CloseableHttpResponse response = + client.execute(server, commonHeaders(new HttpMkCol(dirs.get(index))), context)) { + try { int status = response.getStatusLine().getStatusCode(); - if ( status < 300 || status == HttpStatus.SC_METHOD_NOT_ALLOWED ) - { + if (status < 300 || status == HttpStatus.SC_METHOD_NOT_ALLOWED) { break; - } - else if ( status == HttpStatus.SC_CONFLICT ) - { + } else if (status == HttpStatus.SC_CONFLICT) { continue; } - handleStatus( response ); - } - finally - { - EntityUtils.consumeQuietly( response.getEntity() ); + handleStatus(response); + } finally { + EntityUtils.consumeQuietly(response.getEntity()); } - } - catch ( IOException e ) - { - LOGGER.debug( "Failed to create parent directory {}", dirs.get( index ), e ); + } catch (IOException e) { + LOGGER.debug("Failed to create parent directory {}", dirs.get(index), e); return; } } - for ( index--; index >= 0; index-- ) - { - try ( CloseableHttpResponse response = - client.execute( server, commonHeaders( new HttpMkCol( dirs.get( index ) ) ), context ) ) - { - try - { - handleStatus( response ); - } - finally - { - EntityUtils.consumeQuietly( response.getEntity() ); + for (index--; index >= 0; index--) { + try (CloseableHttpResponse response = + client.execute(server, commonHeaders(new HttpMkCol(dirs.get(index))), context)) { + try { + handleStatus(response); + } finally { + EntityUtils.consumeQuietly(response.getEntity()); } - } - catch ( IOException e ) - { - LOGGER.debug( "Failed to create parent directory {}", dirs.get( index ), e ); + } catch (IOException e) { + LOGGER.debug("Failed to create parent directory {}", dirs.get(index), e); return; } } } - private T entity( T request, HttpEntity entity ) - { - request.setEntity( entity ); + private T entity(T request, HttpEntity entity) { + request.setEntity(entity); return request; } - private boolean isPayloadPresent( HttpUriRequest request ) - { - if ( request instanceof HttpEntityEnclosingRequest ) - { - HttpEntity entity = ( (HttpEntityEnclosingRequest) request ).getEntity(); + private boolean isPayloadPresent(HttpUriRequest request) { + if (request instanceof HttpEntityEnclosingRequest) { + HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); return entity != null && entity.getContentLength() != 0; } return false; } - private T commonHeaders( T request ) - { - request.setHeader( HttpHeaders.CACHE_CONTROL, "no-cache, no-store" ); - request.setHeader( HttpHeaders.PRAGMA, "no-cache" ); + private T commonHeaders(T request) { + request.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store"); + request.setHeader(HttpHeaders.PRAGMA, "no-cache"); - if ( state.isExpectContinue() && isPayloadPresent( request ) ) - { - request.setHeader( HttpHeaders.EXPECT, "100-continue" ); + if (state.isExpectContinue() && isPayloadPresent(request)) { + request.setHeader(HttpHeaders.EXPECT, "100-continue"); } - for ( Map.Entry entry : headers.entrySet() ) - { - if ( !( entry.getKey() instanceof String ) ) - { + for (Map.Entry entry : headers.entrySet()) { + if (!(entry.getKey() instanceof String)) { continue; } - if ( entry.getValue() instanceof String ) - { - request.setHeader( entry.getKey().toString(), entry.getValue().toString() ); - } - else - { - request.removeHeaders( entry.getKey().toString() ); + if (entry.getValue() instanceof String) { + request.setHeader(entry.getKey().toString(), entry.getValue().toString()); + } else { + request.removeHeaders(entry.getKey().toString()); } } - if ( !state.isExpectContinue() ) - { - request.removeHeaders( HttpHeaders.EXPECT ); + if (!state.isExpectContinue()) { + request.removeHeaders(HttpHeaders.EXPECT); } return request; } - @SuppressWarnings( "checkstyle:magicnumber" ) - private T resume( T request, GetTask task ) - { + @SuppressWarnings("checkstyle:magicnumber") + private T resume(T request, GetTask task) { long resumeOffset = task.getResumeOffset(); - if ( resumeOffset > 0L && task.getDataFile() != null ) - { - request.setHeader( HttpHeaders.RANGE, "bytes=" + resumeOffset + '-' ); - request.setHeader( HttpHeaders.IF_UNMODIFIED_SINCE, - DateUtils.formatDate( new Date( task.getDataFile().lastModified() - 60L * 1000L ) ) ); - request.setHeader( HttpHeaders.ACCEPT_ENCODING, "identity" ); + if (resumeOffset > 0L && task.getDataFile() != null) { + request.setHeader(HttpHeaders.RANGE, "bytes=" + resumeOffset + '-'); + request.setHeader( + HttpHeaders.IF_UNMODIFIED_SINCE, + DateUtils.formatDate(new Date(task.getDataFile().lastModified() - 60L * 1000L))); + request.setHeader(HttpHeaders.ACCEPT_ENCODING, "identity"); } return request; } - @SuppressWarnings( "checkstyle:magicnumber" ) - private void handleStatus( CloseableHttpResponse response ) - throws HttpResponseException - { + @SuppressWarnings("checkstyle:magicnumber") + private void handleStatus(CloseableHttpResponse response) throws HttpResponseException { int status = response.getStatusLine().getStatusCode(); - if ( status >= 300 ) - { - throw new HttpResponseException( status, response.getStatusLine().getReasonPhrase() + " (" + status + ")" ); + if (status >= 300) { + throw new HttpResponseException(status, response.getStatusLine().getReasonPhrase() + " (" + status + ")"); } } @Override - protected void implClose() - { - try - { + protected void implClose() { + try { client.close(); + } catch (IOException e) { + throw new UncheckedIOException(e); } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); - } - AuthenticationContext.close( repoAuthContext ); - AuthenticationContext.close( proxyAuthContext ); + AuthenticationContext.close(repoAuthContext); + AuthenticationContext.close(proxyAuthContext); state.close(); } - private class EntityGetter - { + private class EntityGetter { private final GetTask task; - EntityGetter( GetTask task ) - { + EntityGetter(GetTask task) { this.task = task; } - public void handle( CloseableHttpResponse response ) - throws IOException, TransferCancelledException - { + public void handle(CloseableHttpResponse response) throws IOException, TransferCancelledException { HttpEntity entity = response.getEntity(); - if ( entity == null ) - { - entity = new ByteArrayEntity( new byte[0] ); + if (entity == null) { + entity = new ByteArrayEntity(new byte[0]); } long offset = 0L, length = entity.getContentLength(); - Header rangeHeader = response.getFirstHeader( HttpHeaders.CONTENT_RANGE ); + Header rangeHeader = response.getFirstHeader(HttpHeaders.CONTENT_RANGE); String range = rangeHeader != null ? rangeHeader.getValue() : null; - if ( range != null ) - { - Matcher m = CONTENT_RANGE_PATTERN.matcher( range ); - if ( !m.matches() ) - { - throw new IOException( "Invalid Content-Range header for partial download: " + range ); + if (range != null) { + Matcher m = CONTENT_RANGE_PATTERN.matcher(range); + if (!m.matches()) { + throw new IOException("Invalid Content-Range header for partial download: " + range); } - offset = Long.parseLong( m.group( 1 ) ); - length = Long.parseLong( m.group( 2 ) ) + 1L; - if ( offset < 0L || offset >= length || ( offset > 0L && offset != task.getResumeOffset() ) ) - { - throw new IOException( "Invalid Content-Range header for partial download from offset " - + task.getResumeOffset() + ": " + range ); + offset = Long.parseLong(m.group(1)); + length = Long.parseLong(m.group(2)) + 1L; + if (offset < 0L || offset >= length || (offset > 0L && offset != task.getResumeOffset())) { + throw new IOException("Invalid Content-Range header for partial download from offset " + + task.getResumeOffset() + ": " + range); } } final boolean resume = offset > 0L; final File dataFile = task.getDataFile(); - if ( dataFile == null ) - { - try ( InputStream is = entity.getContent() ) - { - utilGet( task, is, true, length, resume ); - extractChecksums( response ); + if (dataFile == null) { + try (InputStream is = entity.getContent()) { + utilGet(task, is, true, length, resume); + extractChecksums(response); } - } - else - { - try ( FileUtils.CollocatedTempFile tempFile = FileUtils.newTempFile( dataFile.toPath() ) ) - { - task.setDataFile( tempFile.getPath().toFile(), resume ); - if ( resume && Files.isRegularFile( dataFile.toPath() ) ) - { - try ( InputStream inputStream = Files.newInputStream( dataFile.toPath() ) ) - { - Files.copy( inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING ); + } else { + try (FileUtils.CollocatedTempFile tempFile = FileUtils.newTempFile(dataFile.toPath())) { + task.setDataFile(tempFile.getPath().toFile(), resume); + if (resume && Files.isRegularFile(dataFile.toPath())) { + try (InputStream inputStream = Files.newInputStream(dataFile.toPath())) { + Files.copy(inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING); } } - try ( InputStream is = entity.getContent() ) - { - utilGet( task, is, true, length, resume ); + try (InputStream is = entity.getContent()) { + utilGet(task, is, true, length, resume); } tempFile.move(); - } - finally - { - task.setDataFile( dataFile ); + } finally { + task.setDataFile(dataFile); } } - extractChecksums( response ); + extractChecksums(response); } - private void extractChecksums( CloseableHttpResponse response ) - { - for ( Map.Entry extractorEntry : checksumExtractors.entrySet() ) - { - Map checksums = extractorEntry.getValue().extractChecksums( response ); - if ( checksums != null ) - { - checksums.forEach( task::setChecksum ); + private void extractChecksums(CloseableHttpResponse response) { + for (Map.Entry extractorEntry : checksumExtractors.entrySet()) { + Map checksums = extractorEntry.getValue().extractChecksums(response); + if (checksums != null) { + checksums.forEach(task::setChecksum); return; } } } } - private class PutTaskEntity - extends AbstractHttpEntity - { + private class PutTaskEntity extends AbstractHttpEntity { private final PutTask task; - PutTaskEntity( PutTask task ) - { + PutTaskEntity(PutTask task) { this.task = task; } @Override - public boolean isRepeatable() - { + public boolean isRepeatable() { return true; } @Override - public boolean isStreaming() - { + public boolean isStreaming() { return false; } @Override - public long getContentLength() - { + public long getContentLength() { return task.getDataLength(); } @Override - public InputStream getContent() - throws IOException - { + public InputStream getContent() throws IOException { return task.newInputStream(); } @Override - public void writeTo( OutputStream os ) - throws IOException - { - try - { - utilPut( task, os, false ); - } - catch ( TransferCancelledException e ) - { - throw (IOException) new InterruptedIOException().initCause( e ); + public void writeTo(OutputStream os) throws IOException { + try { + utilPut(task, os, false); + } catch (TransferCancelledException e) { + throw (IOException) new InterruptedIOException().initCause(e); } } - } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpTransporterFactory.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpTransporterFactory.java index a38ed6864..f11670485 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpTransporterFactory.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/HttpTransporterFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; import javax.inject.Inject; import javax.inject.Named; @@ -38,16 +37,13 @@ * A transporter factory for repositories using the {@code http:} or {@code https:} protocol. The provided transporters * support uploads to WebDAV servers and resumable downloads. */ -@Named( "http" ) -public final class HttpTransporterFactory - implements TransporterFactory -{ - private static Map getManuallyCreatedExtractors() - { +@Named("http") +public final class HttpTransporterFactory implements TransporterFactory { + private static Map getManuallyCreatedExtractors() { HashMap map = new HashMap<>(); - map.put( Nexus2ChecksumExtractor.NAME, new Nexus2ChecksumExtractor() ); - map.put( XChecksumChecksumExtractor.NAME, new XChecksumChecksumExtractor() ); - return Collections.unmodifiableMap( map ); + map.put(Nexus2ChecksumExtractor.NAME, new Nexus2ChecksumExtractor()); + map.put(XChecksumChecksumExtractor.NAME, new XChecksumChecksumExtractor()); + return Collections.unmodifiableMap(map); } private float priority = 5.0f; @@ -58,9 +54,8 @@ private static Map getManuallyCreatedExtractors() * Ctor for ServiceLocator. */ @Deprecated - public HttpTransporterFactory() - { - this( getManuallyCreatedExtractors() ); + public HttpTransporterFactory() { + this(getManuallyCreatedExtractors()); } /** @@ -69,14 +64,12 @@ public HttpTransporterFactory() * will occur. */ @Inject - public HttpTransporterFactory( Map extractors ) - { - this.extractors = requireNonNull( extractors ); + public HttpTransporterFactory(Map extractors) { + this.extractors = requireNonNull(extractors); } @Override - public float getPriority() - { + public float getPriority() { return priority; } @@ -86,20 +79,17 @@ public float getPriority() * @param priority The priority. * @return This component for chaining, never {@code null}. */ - public HttpTransporterFactory setPriority( float priority ) - { + public HttpTransporterFactory setPriority(float priority) { this.priority = priority; return this; } @Override - public Transporter newInstance( RepositorySystemSession session, RemoteRepository repository ) - throws NoTransporterException - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( repository, "repository cannot be null" ); + public Transporter newInstance(RepositorySystemSession session, RemoteRepository repository) + throws NoTransporterException { + requireNonNull(session, "session cannot be null"); + requireNonNull(repository, "repository cannot be null"); - return new HttpTransporter( extractors, repository, session ); + return new HttpTransporter(extractors, repository, session); } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/LocalState.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/LocalState.java index c0f83523f..a4812361e 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/LocalState.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/LocalState.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; import java.io.Closeable; import java.util.concurrent.ConcurrentHashMap; @@ -34,9 +33,7 @@ * Container for HTTP-related state that can be shared across invocations of the transporter to optimize the * communication with server. */ -final class LocalState - implements Closeable -{ +final class LocalState implements Closeable { private final GlobalState global; private final HttpClientConnectionManager connMgr; @@ -53,110 +50,87 @@ final class LocalState private final ConcurrentMap authSchemePools; - LocalState( RepositorySystemSession session, RemoteRepository repo, SslConfig sslConfig ) - { - global = GlobalState.get( session ); + LocalState(RepositorySystemSession session, RemoteRepository repo, SslConfig sslConfig) { + global = GlobalState.get(session); userToken = this; - if ( global == null ) - { - connMgr = GlobalState.newConnectionManager( sslConfig ); + if (global == null) { + connMgr = GlobalState.newConnectionManager(sslConfig); userTokenKey = null; expectContinueKey = null; authSchemePools = new ConcurrentHashMap<>(); - } - else - { - connMgr = global.getConnectionManager( sslConfig ); - userTokenKey = new CompoundKey( repo.getId(), repo.getUrl(), repo.getAuthentication(), repo.getProxy() ); - expectContinueKey = new CompoundKey( repo.getUrl(), repo.getProxy() ); + } else { + connMgr = global.getConnectionManager(sslConfig); + userTokenKey = new CompoundKey(repo.getId(), repo.getUrl(), repo.getAuthentication(), repo.getProxy()); + expectContinueKey = new CompoundKey(repo.getUrl(), repo.getProxy()); authSchemePools = global.getAuthSchemePools(); } } - public HttpClientConnectionManager getConnectionManager() - { + public HttpClientConnectionManager getConnectionManager() { return connMgr; } - public Object getUserToken() - { - if ( userToken == this ) - { - userToken = ( global != null ) ? global.getUserToken( userTokenKey ) : null; + public Object getUserToken() { + if (userToken == this) { + userToken = (global != null) ? global.getUserToken(userTokenKey) : null; } return userToken; } - public void setUserToken( Object userToken ) - { + public void setUserToken(Object userToken) { this.userToken = userToken; - if ( global != null ) - { - global.setUserToken( userTokenKey, userToken ); + if (global != null) { + global.setUserToken(userTokenKey, userToken); } } - public boolean isExpectContinue() - { - if ( expectContinue == null ) - { + public boolean isExpectContinue() { + if (expectContinue == null) { expectContinue = - !Boolean.FALSE.equals( ( global != null ) ? global.getExpectContinue( expectContinueKey ) : null ); + !Boolean.FALSE.equals((global != null) ? global.getExpectContinue(expectContinueKey) : null); } return expectContinue; } - public void setExpectContinue( boolean enabled ) - { + public void setExpectContinue(boolean enabled) { expectContinue = enabled; - if ( global != null ) - { - global.setExpectContinue( expectContinueKey, enabled ); + if (global != null) { + global.setExpectContinue(expectContinueKey, enabled); } } - public Boolean getWebDav() - { + public Boolean getWebDav() { return webDav; } - public void setWebDav( boolean webDav ) - { + public void setWebDav(boolean webDav) { this.webDav = webDav; } - public AuthScheme getAuthScheme( HttpHost host ) - { - AuthSchemePool pool = authSchemePools.get( host ); - if ( pool != null ) - { + public AuthScheme getAuthScheme(HttpHost host) { + AuthSchemePool pool = authSchemePools.get(host); + if (pool != null) { return pool.get(); } return null; } - public void setAuthScheme( HttpHost host, AuthScheme authScheme ) - { - AuthSchemePool pool = authSchemePools.get( host ); - if ( pool == null ) - { + public void setAuthScheme(HttpHost host, AuthScheme authScheme) { + AuthSchemePool pool = authSchemePools.get(host); + if (pool == null) { AuthSchemePool p = new AuthSchemePool(); - pool = authSchemePools.putIfAbsent( host, p ); - if ( pool == null ) - { + pool = authSchemePools.putIfAbsent(host, p); + if (pool == null) { pool = p; } } - pool.put( authScheme ); + pool.put(authScheme); } @Override - public void close() - { - if ( global == null ) - { + public void close() { + if (global == null) { connMgr.shutdown(); } } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/Nexus2ChecksumExtractor.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/Nexus2ChecksumExtractor.java index 78332bcca..fd36f0c97 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/Nexus2ChecksumExtractor.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/Nexus2ChecksumExtractor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,40 +16,37 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.http.Header; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; +package org.eclipse.aether.transport.http; import javax.inject.Named; import javax.inject.Singleton; + import java.util.Collections; import java.util.Map; +import org.apache.http.Header; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; + /** * A component extracting Nexus2 ETag "shielded" style-checksums from response headers. * * @since 1.8.0 */ @Singleton -@Named( Nexus2ChecksumExtractor.NAME ) -public class Nexus2ChecksumExtractor - extends ChecksumExtractor -{ +@Named(Nexus2ChecksumExtractor.NAME) +public class Nexus2ChecksumExtractor extends ChecksumExtractor { public static final String NAME = "nexus2"; @Override - public Map extractChecksums( HttpResponse response ) - { + public Map extractChecksums(HttpResponse response) { // Nexus-style, ETag: "{SHA1{d40d68ba1f88d8e9b0040f175a6ff41928abd5e7}}" - Header header = response.getFirstHeader( HttpHeaders.ETAG ); + Header header = response.getFirstHeader(HttpHeaders.ETAG); String etag = header != null ? header.getValue() : null; - if ( etag != null ) - { - int start = etag.indexOf( "SHA1{" ), end = etag.indexOf( "}", start + 5 ); - if ( start >= 0 && end > start ) - { - return Collections.singletonMap( "SHA-1", etag.substring( start + 5, end ) ); + if (etag != null) { + int start = etag.indexOf("SHA1{"), end = etag.indexOf("}", start + 5); + if (start >= 0 && end > start) { + return Collections.singletonMap("SHA-1", etag.substring(start + 5, end)); } } return null; diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SharingAuthCache.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SharingAuthCache.java index 70dca44e4..57bd9b4bf 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SharingAuthCache.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SharingAuthCache.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; import java.util.HashMap; import java.util.Map; @@ -30,82 +29,65 @@ * Auth scheme cache that upon clearing releases all cached schemes into a pool for future reuse by other requests, * thereby reducing challenge-response roundtrips. */ -final class SharingAuthCache - implements AuthCache -{ +final class SharingAuthCache implements AuthCache { private final LocalState state; private final Map authSchemes; - SharingAuthCache( LocalState state ) - { + SharingAuthCache(LocalState state) { this.state = state; authSchemes = new HashMap<>(); } - @SuppressWarnings( "checkstyle:magicnumber" ) - private static HttpHost toKey( HttpHost host ) - { - if ( host.getPort() <= 0 ) - { - int port = host.getSchemeName().equalsIgnoreCase( "https" ) ? 443 : 80; - return new HttpHost( host.getHostName(), port, host.getSchemeName() ); + @SuppressWarnings("checkstyle:magicnumber") + private static HttpHost toKey(HttpHost host) { + if (host.getPort() <= 0) { + int port = host.getSchemeName().equalsIgnoreCase("https") ? 443 : 80; + return new HttpHost(host.getHostName(), port, host.getSchemeName()); } return host; } @Override - public AuthScheme get( HttpHost host ) - { - host = toKey( host ); - AuthScheme authScheme = authSchemes.get( host ); - if ( authScheme == null ) - { - authScheme = state.getAuthScheme( host ); - authSchemes.put( host, authScheme ); + public AuthScheme get(HttpHost host) { + host = toKey(host); + AuthScheme authScheme = authSchemes.get(host); + if (authScheme == null) { + authScheme = state.getAuthScheme(host); + authSchemes.put(host, authScheme); } return authScheme; } @Override - public void put( HttpHost host, AuthScheme authScheme ) - { - if ( authScheme != null ) - { - authSchemes.put( toKey( host ), authScheme ); - } - else - { - remove( host ); + public void put(HttpHost host, AuthScheme authScheme) { + if (authScheme != null) { + authSchemes.put(toKey(host), authScheme); + } else { + remove(host); } } @Override - public void remove( HttpHost host ) - { - authSchemes.remove( toKey( host ) ); + public void remove(HttpHost host) { + authSchemes.remove(toKey(host)); } @Override - public void clear() - { + public void clear() { share(); authSchemes.clear(); } - private void share() - { - for ( Map.Entry entry : authSchemes.entrySet() ) - { - state.setAuthScheme( entry.getKey(), entry.getValue() ); + private void share() { + for (Map.Entry entry : authSchemes.entrySet()) { + state.setAuthScheme(entry.getKey(), entry.getValue()); } } @Override - public String toString() - { + public String toString() { return authSchemes.toString(); } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SharingHttpContext.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SharingHttpContext.java index 3ccd907bb..3e67cbbbf 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SharingHttpContext.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SharingHttpContext.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; import java.io.Closeable; @@ -26,64 +25,50 @@ /** * HTTP context that shares certain attributes among requests to optimize the communication with the server. - * + * * @see Stateful HTTP * connections */ -final class SharingHttpContext - extends BasicHttpContext - implements Closeable -{ +final class SharingHttpContext extends BasicHttpContext implements Closeable { private final LocalState state; private final SharingAuthCache authCache; - SharingHttpContext( LocalState state ) - { + SharingHttpContext(LocalState state) { this.state = state; - authCache = new SharingAuthCache( state ); - super.setAttribute( HttpClientContext.AUTH_CACHE, authCache ); + authCache = new SharingAuthCache(state); + super.setAttribute(HttpClientContext.AUTH_CACHE, authCache); } @Override - public Object getAttribute( String id ) - { - if ( HttpClientContext.USER_TOKEN.equals( id ) ) - { + public Object getAttribute(String id) { + if (HttpClientContext.USER_TOKEN.equals(id)) { return state.getUserToken(); } - return super.getAttribute( id ); + return super.getAttribute(id); } @Override - public void setAttribute( String id, Object obj ) - { - if ( HttpClientContext.USER_TOKEN.equals( id ) ) - { - state.setUserToken( obj ); - } - else - { - super.setAttribute( id, obj ); + public void setAttribute(String id, Object obj) { + if (HttpClientContext.USER_TOKEN.equals(id)) { + state.setUserToken(obj); + } else { + super.setAttribute(id, obj); } } @Override - public Object removeAttribute( String id ) - { - if ( HttpClientContext.USER_TOKEN.equals( id ) ) - { - state.setUserToken( null ); + public Object removeAttribute(String id) { + if (HttpClientContext.USER_TOKEN.equals(id)) { + state.setUserToken(null); return null; } - return super.removeAttribute( id ); + return super.removeAttribute(id); } @Override - public void close() - { + public void close() { authCache.clear(); } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SslConfig.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SslConfig.java index d90e1777a..b08e393c6 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SslConfig.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/SslConfig.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ - -import java.util.Arrays; -import java.util.Objects; +package org.eclipse.aether.transport.http; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; +import java.util.Arrays; +import java.util.Objects; + import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.AuthenticationContext; import org.eclipse.aether.util.ConfigUtils; @@ -32,8 +31,7 @@ /** * SSL-related configuration and cache key for connection pools (whose scheme registries are derived from this config). */ -final class SslConfig -{ +final class SslConfig { private static final String CIPHER_SUITES = "https.cipherSuites"; @@ -47,69 +45,57 @@ final class SslConfig final String[] protocols; - SslConfig( RepositorySystemSession session, AuthenticationContext authContext ) - { - context = - ( authContext != null ) ? authContext.get( AuthenticationContext.SSL_CONTEXT, SSLContext.class ) : null; - verifier = - ( authContext != null ) ? authContext.get( AuthenticationContext.SSL_HOSTNAME_VERIFIER, - HostnameVerifier.class ) : null; + SslConfig(RepositorySystemSession session, AuthenticationContext authContext) { + context = (authContext != null) ? authContext.get(AuthenticationContext.SSL_CONTEXT, SSLContext.class) : null; + verifier = (authContext != null) + ? authContext.get(AuthenticationContext.SSL_HOSTNAME_VERIFIER, HostnameVerifier.class) + : null; - cipherSuites = split( get( session, CIPHER_SUITES ) ); - protocols = split( get( session, PROTOCOLS ) ); + cipherSuites = split(get(session, CIPHER_SUITES)); + protocols = split(get(session, PROTOCOLS)); } - private static String get( RepositorySystemSession session, String key ) - { - String value = ConfigUtils.getString( session, null, "aether.connector." + key, key ); - if ( value == null ) - { - value = System.getProperty( key ); + private static String get(RepositorySystemSession session, String key) { + String value = ConfigUtils.getString(session, null, "aether.connector." + key, key); + if (value == null) { + value = System.getProperty(key); } return value; } - private static String[] split( String value ) - { - if ( value == null || value.isEmpty() ) - { + private static String[] split(String value) { + if (value == null || value.isEmpty()) { return null; } - return value.split( ",+" ); + return value.split(",+"); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } SslConfig that = (SslConfig) obj; - return Objects.equals( context, that.context ) - && Objects.equals( verifier, that.verifier ) - && Arrays.equals( cipherSuites, that.cipherSuites ) - && Arrays.equals( protocols, that.protocols ); + return Objects.equals(context, that.context) + && Objects.equals(verifier, that.verifier) + && Arrays.equals(cipherSuites, that.cipherSuites) + && Arrays.equals(protocols, that.protocols); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + hash( context ); - hash = hash * 31 + hash( verifier ); - hash = hash * 31 + Arrays.hashCode( cipherSuites ); - hash = hash * 31 + Arrays.hashCode( protocols ); + hash = hash * 31 + hash(context); + hash = hash * 31 + hash(verifier); + hash = hash * 31 + Arrays.hashCode(cipherSuites); + hash = hash * 31 + Arrays.hashCode(protocols); return hash; } - private static int hash( Object obj ) - { + private static int hash(Object obj) { return obj != null ? obj.hashCode() : 0; } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/UriUtils.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/UriUtils.java index 23502293c..80c9542e4 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/UriUtils.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/UriUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; import java.net.URI; import java.net.URISyntaxException; @@ -29,56 +28,42 @@ /** * Helps to deal with URIs. */ -final class UriUtils -{ +final class UriUtils { - public static URI resolve( URI base, URI ref ) - { + public static URI resolve(URI base, URI ref) { String path = ref.getRawPath(); - if ( path != null && path.length() > 0 ) - { + if (path != null && path.length() > 0) { path = base.getRawPath(); - if ( path == null || !path.endsWith( "/" ) ) - { - try - { - base = new URI( base.getScheme(), base.getAuthority(), base.getPath() + '/', null, null ); - } - catch ( URISyntaxException e ) - { - throw new IllegalStateException( e ); + if (path == null || !path.endsWith("/")) { + try { + base = new URI(base.getScheme(), base.getAuthority(), base.getPath() + '/', null, null); + } catch (URISyntaxException e) { + throw new IllegalStateException(e); } } } - return URIUtils.resolve( base, ref ); + return URIUtils.resolve(base, ref); } - public static List getDirectories( URI base, URI uri ) - { + public static List getDirectories(URI base, URI uri) { List dirs = new ArrayList<>(); - for ( URI dir = uri.resolve( "." ); !isBase( base, dir ); dir = dir.resolve( ".." ) ) - { - dirs.add( dir ); + for (URI dir = uri.resolve("."); !isBase(base, dir); dir = dir.resolve("..")) { + dirs.add(dir); } return dirs; } - private static boolean isBase( URI base, URI uri ) - { + private static boolean isBase(URI base, URI uri) { String path = uri.getRawPath(); - if ( path == null || "/".equals( path ) ) - { + if (path == null || "/".equals(path)) { return true; } - if ( base != null ) - { - URI rel = base.relativize( uri ); - if ( rel.getRawPath() == null || rel.getRawPath().isEmpty() || rel.equals( uri ) ) - { + if (base != null) { + URI rel = base.relativize(uri); + if (rel.getRawPath() == null || rel.getRawPath().isEmpty() || rel.equals(uri)) { return true; } } return false; } - } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/XChecksumChecksumExtractor.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/XChecksumChecksumExtractor.java index 26edf3279..e9c7a1322 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/XChecksumChecksumExtractor.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/XChecksumChecksumExtractor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,15 +16,17 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.http.Header; -import org.apache.http.HttpResponse; +package org.eclipse.aether.transport.http; import javax.inject.Named; import javax.inject.Singleton; + import java.util.HashMap; import java.util.Map; +import org.apache.http.Header; +import org.apache.http.HttpResponse; + /** * A component extracting {@code x-} non-standard style checksums from response headers. * Tried headers (in order): @@ -40,52 +40,43 @@ * @since 1.8.0 */ @Singleton -@Named( XChecksumChecksumExtractor.NAME ) -public class XChecksumChecksumExtractor - extends ChecksumExtractor -{ +@Named(XChecksumChecksumExtractor.NAME) +public class XChecksumChecksumExtractor extends ChecksumExtractor { public static final String NAME = "x-checksum"; @Override - public Map extractChecksums( HttpResponse response ) - { + public Map extractChecksums(HttpResponse response) { String value; HashMap result = new HashMap<>(); // Central style: x-checksum-sha1: c74edb60ca2a0b57ef88d9a7da28f591e3d4ce7b - value = extractChecksum( response, "x-checksum-sha1" ); - if ( value != null ) - { - result.put( "SHA-1", value ); + value = extractChecksum(response, "x-checksum-sha1"); + if (value != null) { + result.put("SHA-1", value); } // Central style: x-checksum-md5: 9ad0d8e3482767c122e85f83567b8ce6 - value = extractChecksum( response, "x-checksum-md5" ); - if ( value != null ) - { - result.put( "MD5", value ); + value = extractChecksum(response, "x-checksum-md5"); + if (value != null) { + result.put("MD5", value); } - if ( !result.isEmpty() ) - { + if (!result.isEmpty()) { return result; } // Google style: x-goog-meta-checksum-sha1: c74edb60ca2a0b57ef88d9a7da28f591e3d4ce7b - value = extractChecksum( response, "x-goog-meta-checksum-sha1" ); - if ( value != null ) - { - result.put( "SHA-1", value ); + value = extractChecksum(response, "x-goog-meta-checksum-sha1"); + if (value != null) { + result.put("SHA-1", value); } // Central style: x-goog-meta-checksum-sha1: 9ad0d8e3482767c122e85f83567b8ce6 - value = extractChecksum( response, "x-goog-meta-checksum-md5" ); - if ( value != null ) - { - result.put( "MD5", value ); + value = extractChecksum(response, "x-goog-meta-checksum-md5"); + if (value != null) { + result.put("MD5", value); } return result.isEmpty() ? null : result; } - private String extractChecksum( HttpResponse response, String name ) - { - Header header = response.getFirstHeader( name ); + private String extractChecksum(HttpResponse response, String name) { + Header header = response.getFirstHeader(name); return header != null ? header.getValue() : null; } } diff --git a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/package-info.java b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/package-info.java index 828299eeb..2bc34186b 100644 --- a/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/package-info.java +++ b/maven-resolver-transport-http/src/main/java/org/eclipse/aether/transport/http/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -22,4 +22,3 @@ * Apache HttpClient. */ package org.eclipse.aether.transport.http; - diff --git a/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/HttpServer.java b/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/HttpServer.java index 67cb450f6..64a578c2d 100644 --- a/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/HttpServer.java +++ b/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/HttpServer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; @@ -32,9 +34,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.eclipse.aether.util.ChecksumUtils; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpMethod; @@ -51,11 +50,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class HttpServer -{ +public class HttpServer { - public static class LogEntry - { + public static class LogEntry { public final String method; @@ -63,32 +60,30 @@ public static class LogEntry public final Map headers; - public LogEntry( String method, String path, Map headers ) - { + public LogEntry(String method, String path, Map headers) { this.method = method; this.path = path; this.headers = headers; } @Override - public String toString() - { + public String toString() { return method + " " + path; } - } - public enum ExpectContinue - { - FAIL, PROPER, BROKEN + public enum ExpectContinue { + FAIL, + PROPER, + BROKEN } - public enum ChecksumHeader - { - NEXUS, XCHECKSUM + public enum ChecksumHeader { + NEXUS, + XCHECKSUM } - private static final Logger LOGGER = LoggerFactory.getLogger( HttpServer.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(HttpServer.class); private File repoDir; @@ -114,135 +109,111 @@ public enum ChecksumHeader private String proxyPassword; - private List logEntries = Collections.synchronizedList( new ArrayList() ); + private List logEntries = Collections.synchronizedList(new ArrayList()); - public String getHost() - { + public String getHost() { return "localhost"; } - public int getHttpPort() - { + public int getHttpPort() { return httpConnector != null ? httpConnector.getLocalPort() : -1; } - public int getHttpsPort() - { + public int getHttpsPort() { return httpsConnector != null ? httpsConnector.getLocalPort() : -1; } - public String getHttpUrl() - { + public String getHttpUrl() { return "http://" + getHost() + ":" + getHttpPort(); } - public String getHttpsUrl() - { + public String getHttpsUrl() { return "https://" + getHost() + ":" + getHttpsPort(); } - public HttpServer addSslConnector() - { - if ( httpsConnector == null ) - { + public HttpServer addSslConnector() { + if (httpsConnector == null) { SslContextFactory.Server ssl = new SslContextFactory.Server(); - ssl.setNeedClientAuth( true ); - ssl.setKeyStorePath( new File( "src/test/resources/ssl/server-store" ).getAbsolutePath() ); - ssl.setKeyStorePassword( "server-pwd" ); - ssl.setTrustStorePath( new File( "src/test/resources/ssl/client-store" ).getAbsolutePath() ); - ssl.setTrustStorePassword( "client-pwd" ); - httpsConnector = new ServerConnector( server, ssl ); - server.addConnector( httpsConnector ); - try - { + ssl.setNeedClientAuth(true); + ssl.setKeyStorePath(new File("src/test/resources/ssl/server-store").getAbsolutePath()); + ssl.setKeyStorePassword("server-pwd"); + ssl.setTrustStorePath(new File("src/test/resources/ssl/client-store").getAbsolutePath()); + ssl.setTrustStorePassword("client-pwd"); + httpsConnector = new ServerConnector(server, ssl); + server.addConnector(httpsConnector); + try { httpsConnector.start(); - } - catch ( Exception e ) - { - throw new IllegalStateException( e ); + } catch (Exception e) { + throw new IllegalStateException(e); } } return this; } - public List getLogEntries() - { + public List getLogEntries() { return logEntries; } - public HttpServer setRepoDir( File repoDir ) - { + public HttpServer setRepoDir(File repoDir) { this.repoDir = repoDir; return this; } - public HttpServer setRangeSupport( boolean rangeSupport ) - { + public HttpServer setRangeSupport(boolean rangeSupport) { this.rangeSupport = rangeSupport; return this; } - public HttpServer setWebDav( boolean webDav ) - { + public HttpServer setWebDav(boolean webDav) { this.webDav = webDav; return this; } - public HttpServer setExpectSupport( ExpectContinue expectContinue ) - { + public HttpServer setExpectSupport(ExpectContinue expectContinue) { this.expectContinue = expectContinue; return this; } - public HttpServer setChecksumHeader( ChecksumHeader checksumHeader ) - { + public HttpServer setChecksumHeader(ChecksumHeader checksumHeader) { this.checksumHeader = checksumHeader; return this; } - public HttpServer setAuthentication( String username, String password ) - { + public HttpServer setAuthentication(String username, String password) { this.username = username; this.password = password; return this; } - public HttpServer setProxyAuthentication( String username, String password ) - { + public HttpServer setProxyAuthentication(String username, String password) { proxyUsername = username; proxyPassword = password; return this; } - public HttpServer start() - throws Exception - { - if ( server != null ) - { + public HttpServer start() throws Exception { + if (server != null) { return this; } HandlerList handlers = new HandlerList(); - handlers.addHandler( new LogHandler() ); - handlers.addHandler( new ProxyAuthHandler() ); - handlers.addHandler( new AuthHandler() ); - handlers.addHandler( new RedirectHandler() ); - handlers.addHandler( new RepoHandler() ); + handlers.addHandler(new LogHandler()); + handlers.addHandler(new ProxyAuthHandler()); + handlers.addHandler(new AuthHandler()); + handlers.addHandler(new RedirectHandler()); + handlers.addHandler(new RepoHandler()); server = new Server(); - httpConnector = new ServerConnector( server ); - server.addConnector( httpConnector ); - server.setHandler( handlers ); + httpConnector = new ServerConnector(server); + server.addConnector(httpConnector); + server.setHandler(handlers); server.start(); return this; } - public void stop() - throws Exception - { - if ( server != null ) - { + public void stop() throws Exception { + if (server != null) { server.stop(); server = null; httpConnector = null; @@ -250,328 +221,242 @@ public void stop() } } - private class LogHandler - extends AbstractHandler - { + private class LogHandler extends AbstractHandler { - public void handle( String target, Request req, HttpServletRequest request, HttpServletResponse response ) - { - LOGGER.info( "{} {}{}", req.getMethod(), req.getRequestURL(), + public void handle(String target, Request req, HttpServletRequest request, HttpServletResponse response) { + LOGGER.info( + "{} {}{}", + req.getMethod(), + req.getRequestURL(), req.getQueryString() != null ? "?" + req.getQueryString() : ""); - Map headers = new TreeMap<>( String.CASE_INSENSITIVE_ORDER ); - for ( Enumeration en = req.getHeaderNames(); en.hasMoreElements(); ) - { + Map headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + for (Enumeration en = req.getHeaderNames(); en.hasMoreElements(); ) { String name = en.nextElement(); - StringBuilder buffer = new StringBuilder( 128 ); - for ( Enumeration ien = req.getHeaders( name ); ien.hasMoreElements(); ) - { - if ( buffer.length() > 0 ) - { - buffer.append( ", " ); + StringBuilder buffer = new StringBuilder(128); + for (Enumeration ien = req.getHeaders(name); ien.hasMoreElements(); ) { + if (buffer.length() > 0) { + buffer.append(", "); } - buffer.append( ien.nextElement() ); + buffer.append(ien.nextElement()); } - headers.put( name, buffer.toString() ); + headers.put(name, buffer.toString()); } - logEntries.add( new LogEntry( req.getMethod(), req.getPathInfo(), Collections.unmodifiableMap( headers ) ) ); + logEntries.add(new LogEntry(req.getMethod(), req.getPathInfo(), Collections.unmodifiableMap(headers))); } - } - private class RepoHandler - extends AbstractHandler - { + private class RepoHandler extends AbstractHandler { - private final Pattern SIMPLE_RANGE = Pattern.compile( "bytes=([0-9])+-" ); + private final Pattern SIMPLE_RANGE = Pattern.compile("bytes=([0-9])+-"); - public void handle( String target, Request req, HttpServletRequest request, HttpServletResponse response ) - throws IOException - { - String path = req.getPathInfo().substring( 1 ); + public void handle(String target, Request req, HttpServletRequest request, HttpServletResponse response) + throws IOException { + String path = req.getPathInfo().substring(1); - if ( !path.startsWith( "repo/" ) ) - { + if (!path.startsWith("repo/")) { return; } - req.setHandled( true ); + req.setHandled(true); - if ( ExpectContinue.FAIL.equals( expectContinue ) && request.getHeader( HttpHeader.EXPECT.asString() ) != null ) - { - response.setStatus( HttpServletResponse.SC_EXPECTATION_FAILED ); + if (ExpectContinue.FAIL.equals(expectContinue) && request.getHeader(HttpHeader.EXPECT.asString()) != null) { + response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED); return; } - File file = new File( repoDir, path.substring( 5 ) ); - if ( HttpMethod.GET.is( req.getMethod() ) || HttpMethod.HEAD.is( req.getMethod() ) ) - { - if ( !file.isFile() || path.endsWith( URIUtil.SLASH ) ) - { - response.setStatus( HttpServletResponse.SC_NOT_FOUND ); + File file = new File(repoDir, path.substring(5)); + if (HttpMethod.GET.is(req.getMethod()) || HttpMethod.HEAD.is(req.getMethod())) { + if (!file.isFile() || path.endsWith(URIUtil.SLASH)) { + response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } - long ifUnmodifiedSince = request.getDateHeader( HttpHeader.IF_UNMODIFIED_SINCE.asString() ); - if ( ifUnmodifiedSince != -1L && file.lastModified() > ifUnmodifiedSince ) - { - response.setStatus( HttpServletResponse.SC_PRECONDITION_FAILED ); + long ifUnmodifiedSince = request.getDateHeader(HttpHeader.IF_UNMODIFIED_SINCE.asString()); + if (ifUnmodifiedSince != -1L && file.lastModified() > ifUnmodifiedSince) { + response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return; } long offset = 0L; - String range = request.getHeader( HttpHeader.RANGE.asString() ); - if ( range != null && rangeSupport ) - { - Matcher m = SIMPLE_RANGE.matcher( range ); - if ( m.matches() ) - { - offset = Long.parseLong( m.group( 1 ) ); - if ( offset >= file.length() ) - { - response.setStatus( HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE ); + String range = request.getHeader(HttpHeader.RANGE.asString()); + if (range != null && rangeSupport) { + Matcher m = SIMPLE_RANGE.matcher(range); + if (m.matches()) { + offset = Long.parseLong(m.group(1)); + if (offset >= file.length()) { + response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } } - String encoding = request.getHeader( HttpHeader.ACCEPT_ENCODING.asString() ); - if ( ( encoding != null && !"identity".equals( encoding ) ) || ifUnmodifiedSince == -1L ) - { - response.setStatus( HttpServletResponse.SC_BAD_REQUEST ); + String encoding = request.getHeader(HttpHeader.ACCEPT_ENCODING.asString()); + if ((encoding != null && !"identity".equals(encoding)) || ifUnmodifiedSince == -1L) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } } - response.setStatus( ( offset > 0L ) ? HttpServletResponse.SC_PARTIAL_CONTENT : HttpServletResponse.SC_OK ); - response.setDateHeader( HttpHeader.LAST_MODIFIED.asString(), file.lastModified() ); - response.setHeader( HttpHeader.CONTENT_LENGTH.asString(), Long.toString( file.length() - offset ) ); - if ( offset > 0L ) - { - response.setHeader( HttpHeader.CONTENT_RANGE.asString(), "bytes " + offset + "-" + ( file.length() - 1L ) - + "/" + file.length() ); + response.setStatus((offset > 0L) ? HttpServletResponse.SC_PARTIAL_CONTENT : HttpServletResponse.SC_OK); + response.setDateHeader(HttpHeader.LAST_MODIFIED.asString(), file.lastModified()); + response.setHeader(HttpHeader.CONTENT_LENGTH.asString(), Long.toString(file.length() - offset)); + if (offset > 0L) { + response.setHeader( + HttpHeader.CONTENT_RANGE.asString(), + "bytes " + offset + "-" + (file.length() - 1L) + "/" + file.length()); } - if ( checksumHeader != null ) - { - Map checksums = ChecksumUtils.calc( file, Collections.singleton( "SHA-1" ) ); - if ( checksumHeader == ChecksumHeader.NEXUS ) - { - response.setHeader( HttpHeader.ETAG.asString(), "{SHA1{" + checksums.get( "SHA-1" ) + "}}" ); - } - else if ( checksumHeader == ChecksumHeader.XCHECKSUM ) - { - response.setHeader( "x-checksum-sha1", checksums.get( "SHA-1" ).toString() ); + if (checksumHeader != null) { + Map checksums = ChecksumUtils.calc(file, Collections.singleton("SHA-1")); + if (checksumHeader == ChecksumHeader.NEXUS) { + response.setHeader(HttpHeader.ETAG.asString(), "{SHA1{" + checksums.get("SHA-1") + "}}"); + } else if (checksumHeader == ChecksumHeader.XCHECKSUM) { + response.setHeader( + "x-checksum-sha1", checksums.get("SHA-1").toString()); } } - if ( HttpMethod.HEAD.is( req.getMethod() ) ) - { + if (HttpMethod.HEAD.is(req.getMethod())) { return; } FileInputStream is = null; - try - { - is = new FileInputStream( file ); - if ( offset > 0L ) - { - long skipped = is.skip( offset ); - while ( skipped < offset && is.read() >= 0 ) - { + try { + is = new FileInputStream(file); + if (offset > 0L) { + long skipped = is.skip(offset); + while (skipped < offset && is.read() >= 0) { skipped++; } } - IO.copy( is, response.getOutputStream() ); + IO.copy(is, response.getOutputStream()); is.close(); is = null; - } - finally - { - try - { - if ( is != null ) - { + } finally { + try { + if (is != null) { is.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } - } - else if ( HttpMethod.PUT.is( req.getMethod() ) ) - { - if ( !webDav ) - { + } else if (HttpMethod.PUT.is(req.getMethod())) { + if (!webDav) { file.getParentFile().mkdirs(); } - if ( file.getParentFile().exists() ) - { - try - { + if (file.getParentFile().exists()) { + try { FileOutputStream os = null; - try - { - os = new FileOutputStream( file ); - IO.copy( request.getInputStream(), os ); + try { + os = new FileOutputStream(file); + IO.copy(request.getInputStream(), os); os.close(); os = null; - } - finally - { - try - { - if ( os != null ) - { + } finally { + try { + if (os != null) { os.close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { // Suppressed due to an exception already thrown in the try block. } } - } - catch ( IOException e ) - { + } catch (IOException e) { file.delete(); throw e; } - response.setStatus( HttpServletResponse.SC_NO_CONTENT ); - } - else - { - response.setStatus( HttpServletResponse.SC_FORBIDDEN ); - } - } - else if ( HttpMethod.OPTIONS.is( req.getMethod() ) ) - { - if ( webDav ) - { - response.setHeader( "DAV", "1,2" ); - } - response.setHeader( HttpHeader.ALLOW.asString(), "GET, PUT, HEAD, OPTIONS" ); - response.setStatus( HttpServletResponse.SC_OK ); - } - else if ( webDav && "MKCOL".equals( req.getMethod() ) ) - { - if ( file.exists() ) - { - response.setStatus( HttpServletResponse.SC_METHOD_NOT_ALLOWED ); + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + } else { + response.setStatus(HttpServletResponse.SC_FORBIDDEN); } - else if ( file.mkdir() ) - { - response.setStatus( HttpServletResponse.SC_CREATED ); + } else if (HttpMethod.OPTIONS.is(req.getMethod())) { + if (webDav) { + response.setHeader("DAV", "1,2"); } - else - { - response.setStatus( HttpServletResponse.SC_CONFLICT ); + response.setHeader(HttpHeader.ALLOW.asString(), "GET, PUT, HEAD, OPTIONS"); + response.setStatus(HttpServletResponse.SC_OK); + } else if (webDav && "MKCOL".equals(req.getMethod())) { + if (file.exists()) { + response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + } else if (file.mkdir()) { + response.setStatus(HttpServletResponse.SC_CREATED); + } else { + response.setStatus(HttpServletResponse.SC_CONFLICT); } - } - else - { - response.setStatus( HttpServletResponse.SC_METHOD_NOT_ALLOWED ); + } else { + response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } - } - private class RedirectHandler - extends AbstractHandler - { + private class RedirectHandler extends AbstractHandler { - public void handle( String target, Request req, HttpServletRequest request, HttpServletResponse response ) - { + public void handle(String target, Request req, HttpServletRequest request, HttpServletResponse response) { String path = req.getPathInfo(); - if ( !path.startsWith( "/redirect/" ) ) - { + if (!path.startsWith("/redirect/")) { return; } - req.setHandled( true ); - StringBuilder location = new StringBuilder( 128 ); - String scheme = req.getParameter( "scheme" ); - location.append( scheme != null ? scheme : req.getScheme() ); - location.append( "://" ); - location.append( req.getServerName() ); - location.append( ":" ); - if ( "http".equalsIgnoreCase( scheme ) ) - { - location.append( getHttpPort() ); - } - else if ( "https".equalsIgnoreCase( scheme ) ) - { - location.append( getHttpsPort() ); - } - else - { - location.append( req.getServerPort() ); + req.setHandled(true); + StringBuilder location = new StringBuilder(128); + String scheme = req.getParameter("scheme"); + location.append(scheme != null ? scheme : req.getScheme()); + location.append("://"); + location.append(req.getServerName()); + location.append(":"); + if ("http".equalsIgnoreCase(scheme)) { + location.append(getHttpPort()); + } else if ("https".equalsIgnoreCase(scheme)) { + location.append(getHttpsPort()); + } else { + location.append(req.getServerPort()); } - location.append( "/repo" ).append( path.substring( 9 ) ); - response.setStatus( HttpServletResponse.SC_MOVED_PERMANENTLY ); - response.setHeader( HttpHeader.LOCATION.asString(), location.toString() ); + location.append("/repo").append(path.substring(9)); + response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); + response.setHeader(HttpHeader.LOCATION.asString(), location.toString()); } - } - private class AuthHandler - extends AbstractHandler - { + private class AuthHandler extends AbstractHandler { - public void handle( String target, Request req, HttpServletRequest request, HttpServletResponse response ) - throws IOException - { - if ( ExpectContinue.BROKEN.equals( expectContinue ) - && "100-continue".equalsIgnoreCase( request.getHeader( HttpHeader.EXPECT.asString() ) ) ) - { + public void handle(String target, Request req, HttpServletRequest request, HttpServletResponse response) + throws IOException { + if (ExpectContinue.BROKEN.equals(expectContinue) + && "100-continue".equalsIgnoreCase(request.getHeader(HttpHeader.EXPECT.asString()))) { request.getInputStream(); } - if ( username != null && password != null ) - { - if ( checkBasicAuth( request.getHeader( HttpHeader.AUTHORIZATION.asString() ), username, password ) ) - { + if (username != null && password != null) { + if (checkBasicAuth(request.getHeader(HttpHeader.AUTHORIZATION.asString()), username, password)) { return; } - req.setHandled( true ); - response.setHeader( HttpHeader.WWW_AUTHENTICATE.asString(), "basic realm=\"Test-Realm\"" ); - response.setStatus( HttpServletResponse.SC_UNAUTHORIZED ); + req.setHandled(true); + response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "basic realm=\"Test-Realm\""); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } } - } - private class ProxyAuthHandler - extends AbstractHandler - { + private class ProxyAuthHandler extends AbstractHandler { - public void handle( String target, Request req, HttpServletRequest request, HttpServletResponse response ) - { - if ( proxyUsername != null && proxyPassword != null ) - { - if ( checkBasicAuth( request.getHeader( HttpHeader.PROXY_AUTHORIZATION.asString() ), proxyUsername, proxyPassword ) ) - { + public void handle(String target, Request req, HttpServletRequest request, HttpServletResponse response) { + if (proxyUsername != null && proxyPassword != null) { + if (checkBasicAuth( + request.getHeader(HttpHeader.PROXY_AUTHORIZATION.asString()), proxyUsername, proxyPassword)) { return; } - req.setHandled( true ); - response.setHeader( HttpHeader.PROXY_AUTHENTICATE.asString(), "basic realm=\"Test-Realm\"" ); - response.setStatus( HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED ); + req.setHandled(true); + response.setHeader(HttpHeader.PROXY_AUTHENTICATE.asString(), "basic realm=\"Test-Realm\""); + response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED); } } - } - static boolean checkBasicAuth( String credentials, String username, String password ) - { - if ( credentials != null ) - { - int space = credentials.indexOf( ' ' ); - if ( space > 0 ) - { - String method = credentials.substring( 0, space ); - if ( "basic".equalsIgnoreCase( method ) ) - { - credentials = credentials.substring( space + 1 ); - credentials = B64Code.decode( credentials, StringUtil.__ISO_8859_1 ); - int i = credentials.indexOf( ':' ); - if ( i > 0 ) - { - String user = credentials.substring( 0, i ); - String pass = credentials.substring( i + 1 ); - if ( username.equals( user ) && password.equals( pass ) ) - { + static boolean checkBasicAuth(String credentials, String username, String password) { + if (credentials != null) { + int space = credentials.indexOf(' '); + if (space > 0) { + String method = credentials.substring(0, space); + if ("basic".equalsIgnoreCase(method)) { + credentials = credentials.substring(space + 1); + credentials = B64Code.decode(credentials, StringUtil.__ISO_8859_1); + int i = credentials.indexOf(':'); + if (i > 0) { + String user = credentials.substring(0, i); + String pass = credentials.substring(i + 1); + if (username.equals(user) && password.equals(pass)) { return true; } } @@ -580,5 +465,4 @@ static boolean checkBasicAuth( String credentials, String username, String passw } return false; } - } diff --git a/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/HttpTransporterTest.java b/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/HttpTransporterTest.java index 745514f9f..46a508f31 100644 --- a/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/HttpTransporterTest.java +++ b/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/HttpTransporterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.transport.http; import java.io.File; import java.io.FileNotFoundException; @@ -58,19 +55,18 @@ import org.junit.Test; import org.junit.rules.TestName; +import static org.junit.Assert.*; + /** */ -public class HttpTransporterTest -{ +public class HttpTransporterTest { - static - { - System.setProperty( "javax.net.ssl.trustStore", - new File( "src/test/resources/ssl/server-store" ).getAbsolutePath() ); - System.setProperty( "javax.net.ssl.trustStorePassword", "server-pwd" ); - System.setProperty( "javax.net.ssl.keyStore", - new File( "src/test/resources/ssl/client-store" ).getAbsolutePath() ); - System.setProperty( "javax.net.ssl.keyStorePassword", "client-pwd" ); + static { + System.setProperty( + "javax.net.ssl.trustStore", new File("src/test/resources/ssl/server-store").getAbsolutePath()); + System.setProperty("javax.net.ssl.trustStorePassword", "server-pwd"); + System.setProperty("javax.net.ssl.keyStore", new File("src/test/resources/ssl/client-store").getAbsolutePath()); + System.setProperty("javax.net.ssl.keyStorePassword", "client-pwd"); } @Rule @@ -90,52 +86,45 @@ public class HttpTransporterTest private Proxy proxy; - private RemoteRepository newRepo( String url ) - { - return new RemoteRepository.Builder( "test", "default", url ).setAuthentication( auth ).setProxy( proxy ).build(); + private RemoteRepository newRepo(String url) { + return new RemoteRepository.Builder("test", "default", url) + .setAuthentication(auth) + .setProxy(proxy) + .build(); } - private void newTransporter( String url ) - throws Exception - { - if ( transporter != null ) - { + private void newTransporter(String url) throws Exception { + if (transporter != null) { transporter.close(); transporter = null; } - transporter = factory.newInstance( session, newRepo( url ) ); + transporter = factory.newInstance(session, newRepo(url)); } @Before - public void setUp() - throws Exception - { - System.out.println( "=== " + testName.getMethodName() + " ===" ); + public void setUp() throws Exception { + System.out.println("=== " + testName.getMethodName() + " ==="); session = TestUtils.newSession(); - factory = new HttpTransporterFactory( ); + factory = new HttpTransporterFactory(); repoDir = TestFileUtils.createTempDir(); - TestFileUtils.writeString( new File( repoDir, "file.txt" ), "test" ); - TestFileUtils.writeString( new File( repoDir, "dir/file.txt" ), "test" ); - TestFileUtils.writeString( new File( repoDir, "empty.txt" ), "" ); - TestFileUtils.writeString( new File( repoDir, "some space.txt" ), "space" ); - File resumable = new File( repoDir, "resume.txt" ); - TestFileUtils.writeString( resumable, "resumable" ); - resumable.setLastModified( System.currentTimeMillis() - 90 * 1000 ); - httpServer = new HttpServer().setRepoDir( repoDir ).start(); - newTransporter( httpServer.getHttpUrl() ); + TestFileUtils.writeString(new File(repoDir, "file.txt"), "test"); + TestFileUtils.writeString(new File(repoDir, "dir/file.txt"), "test"); + TestFileUtils.writeString(new File(repoDir, "empty.txt"), ""); + TestFileUtils.writeString(new File(repoDir, "some space.txt"), "space"); + File resumable = new File(repoDir, "resume.txt"); + TestFileUtils.writeString(resumable, "resumable"); + resumable.setLastModified(System.currentTimeMillis() - 90 * 1000); + httpServer = new HttpServer().setRepoDir(repoDir).start(); + newTransporter(httpServer.getHttpUrl()); } @After - public void tearDown() - throws Exception - { - if ( transporter != null ) - { + public void tearDown() throws Exception { + if (transporter != null) { transporter.close(); transporter = null; } - if ( httpServer != null ) - { + if (httpServer != null) { httpServer.stop(); httpServer = null; } @@ -144,1026 +133,906 @@ public void tearDown() } @Test - public void testClassify() - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( new FileNotFoundException() ) ); - assertEquals( Transporter.ERROR_OTHER, transporter.classify( new HttpResponseException( 403, "Forbidden" ) ) ); - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( new HttpResponseException( 404, "Not Found" ) ) ); + public void testClassify() { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(new FileNotFoundException())); + assertEquals(Transporter.ERROR_OTHER, transporter.classify(new HttpResponseException(403, "Forbidden"))); + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(new HttpResponseException(404, "Not Found"))); } @Test - public void testPeek() - throws Exception - { - transporter.peek( new PeekTask( URI.create( "repo/file.txt" ) ) ); + public void testPeek() throws Exception { + transporter.peek(new PeekTask(URI.create("repo/file.txt"))); } @Test - public void testPeek_NotFound() - throws Exception - { - try - { - transporter.peek( new PeekTask( URI.create( "repo/missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( HttpResponseException e ) - { - assertEquals( 404, e.getStatusCode() ); - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( e ) ); + public void testPeek_NotFound() throws Exception { + try { + transporter.peek(new PeekTask(URI.create("repo/missing.txt"))); + fail("Expected error"); + } catch (HttpResponseException e) { + assertEquals(404, e.getStatusCode()); + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e)); } } @Test - public void testPeek_Closed() - throws Exception - { + public void testPeek_Closed() throws Exception { transporter.close(); - try - { - transporter.peek( new PeekTask( URI.create( "repo/missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.peek(new PeekTask(URI.create("repo/missing.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testPeek_Authenticated() - throws Exception - { - httpServer.setAuthentication( "testuser", "testpass" ); - auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - newTransporter( httpServer.getHttpUrl() ); - transporter.peek( new PeekTask( URI.create( "repo/file.txt" ) ) ); + public void testPeek_Authenticated() throws Exception { + httpServer.setAuthentication("testuser", "testpass"); + auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + newTransporter(httpServer.getHttpUrl()); + transporter.peek(new PeekTask(URI.create("repo/file.txt"))); } @Test - public void testPeek_Unauthenticated() - throws Exception - { - httpServer.setAuthentication( "testuser", "testpass" ); - try - { - transporter.peek( new PeekTask( URI.create( "repo/file.txt" ) ) ); - fail( "Expected error" ); - } - catch ( HttpResponseException e ) - { - assertEquals( 401, e.getStatusCode() ); - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + public void testPeek_Unauthenticated() throws Exception { + httpServer.setAuthentication("testuser", "testpass"); + try { + transporter.peek(new PeekTask(URI.create("repo/file.txt"))); + fail("Expected error"); + } catch (HttpResponseException e) { + assertEquals(401, e.getStatusCode()); + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testPeek_ProxyAuthenticated() - throws Exception - { - httpServer.setProxyAuthentication( "testuser", "testpass" ); - auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - proxy = new Proxy( Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth ); - newTransporter( "http://bad.localhost:1/" ); - transporter.peek( new PeekTask( URI.create( "repo/file.txt" ) ) ); + public void testPeek_ProxyAuthenticated() throws Exception { + httpServer.setProxyAuthentication("testuser", "testpass"); + auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth); + newTransporter("http://bad.localhost:1/"); + transporter.peek(new PeekTask(URI.create("repo/file.txt"))); } @Test - public void testPeek_ProxyUnauthenticated() - throws Exception - { - httpServer.setProxyAuthentication( "testuser", "testpass" ); - proxy = new Proxy( Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort() ); - newTransporter( "http://bad.localhost:1/" ); - try - { - transporter.peek( new PeekTask( URI.create( "repo/file.txt" ) ) ); - fail( "Expected error" ); - } - catch ( HttpResponseException e ) - { - assertEquals( 407, e.getStatusCode() ); - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + public void testPeek_ProxyUnauthenticated() throws Exception { + httpServer.setProxyAuthentication("testuser", "testpass"); + proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort()); + newTransporter("http://bad.localhost:1/"); + try { + transporter.peek(new PeekTask(URI.create("repo/file.txt"))); + fail("Expected error"); + } catch (HttpResponseException e) { + assertEquals(407, e.getStatusCode()); + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testPeek_SSL() - throws Exception - { + public void testPeek_SSL() throws Exception { httpServer.addSslConnector(); - newTransporter( httpServer.getHttpsUrl() ); - transporter.peek( new PeekTask( URI.create( "repo/file.txt" ) ) ); + newTransporter(httpServer.getHttpsUrl()); + transporter.peek(new PeekTask(URI.create("repo/file.txt"))); } @Test - public void testPeek_Redirect() - throws Exception - { + public void testPeek_Redirect() throws Exception { httpServer.addSslConnector(); - transporter.peek( new PeekTask( URI.create( "redirect/file.txt" ) ) ); - transporter.peek( new PeekTask( URI.create( "redirect/file.txt?scheme=https" ) ) ); + transporter.peek(new PeekTask(URI.create("redirect/file.txt"))); + transporter.peek(new PeekTask(URI.create("redirect/file.txt?scheme=https"))); } @Test - public void testGet_ToMemory() - throws Exception - { + public void testGet_ToMemory() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "repo/file.txt" ) ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( task.getDataString(), new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals(task.getDataString(), new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_ToFile() - throws Exception - { - File file = TestFileUtils.createTempFile( "failure" ); + public void testGet_ToFile() throws Exception { + File file = TestFileUtils.createTempFile("failure"); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "repo/file.txt" ) ).setDataFile( file ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", TestFileUtils.readString( file ) ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "test", new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = + new GetTask(URI.create("repo/file.txt")).setDataFile(file).setListener(listener); + transporter.get(task); + assertEquals("test", TestFileUtils.readString(file)); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("test", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_EmptyResource() - throws Exception - { - File file = TestFileUtils.createTempFile( "failure" ); + public void testGet_EmptyResource() throws Exception { + File file = TestFileUtils.createTempFile("failure"); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "repo/empty.txt" ) ).setDataFile( file ).setListener( listener ); - transporter.get( task ); - assertEquals( "", TestFileUtils.readString( file ) ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 0L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); - assertEquals( "", new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = + new GetTask(URI.create("repo/empty.txt")).setDataFile(file).setListener(listener); + transporter.get(task); + assertEquals("", TestFileUtils.readString(file)); + assertEquals(0L, listener.dataOffset); + assertEquals(0L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); + assertEquals("", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_EncodedResourcePath() - throws Exception - { - GetTask task = new GetTask( URI.create( "repo/some%20space.txt" ) ); - transporter.get( task ); - assertEquals( "space", task.getDataString() ); + public void testGet_EncodedResourcePath() throws Exception { + GetTask task = new GetTask(URI.create("repo/some%20space.txt")); + transporter.get(task); + assertEquals("space", task.getDataString()); } @Test - public void testGet_Authenticated() - throws Exception - { - httpServer.setAuthentication( "testuser", "testpass" ); - auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - newTransporter( httpServer.getHttpUrl() ); + public void testGet_Authenticated() throws Exception { + httpServer.setAuthentication("testuser", "testpass"); + auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + newTransporter(httpServer.getHttpUrl()); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "repo/file.txt" ) ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( task.getDataString(), new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals(task.getDataString(), new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_Unauthenticated() - throws Exception - { - httpServer.setAuthentication( "testuser", "testpass" ); - try - { - transporter.get( new GetTask( URI.create( "repo/file.txt" ) ) ); - fail( "Expected error" ); - } - catch ( HttpResponseException e ) - { - assertEquals( 401, e.getStatusCode() ); - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + public void testGet_Unauthenticated() throws Exception { + httpServer.setAuthentication("testuser", "testpass"); + try { + transporter.get(new GetTask(URI.create("repo/file.txt"))); + fail("Expected error"); + } catch (HttpResponseException e) { + assertEquals(401, e.getStatusCode()); + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testGet_ProxyAuthenticated() - throws Exception - { - httpServer.setProxyAuthentication( "testuser", "testpass" ); - Authentication auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - proxy = new Proxy( Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth ); - newTransporter( "http://bad.localhost:1/" ); + public void testGet_ProxyAuthenticated() throws Exception { + httpServer.setProxyAuthentication("testuser", "testpass"); + Authentication auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth); + newTransporter("http://bad.localhost:1/"); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "repo/file.txt" ) ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( task.getDataString(), new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals(task.getDataString(), new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_ProxyUnauthenticated() - throws Exception - { - httpServer.setProxyAuthentication( "testuser", "testpass" ); - proxy = new Proxy( Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort() ); - newTransporter( "http://bad.localhost:1/" ); - try - { - transporter.get( new GetTask( URI.create( "repo/file.txt" ) ) ); - fail( "Expected error" ); - } - catch ( HttpResponseException e ) - { - assertEquals( 407, e.getStatusCode() ); - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + public void testGet_ProxyUnauthenticated() throws Exception { + httpServer.setProxyAuthentication("testuser", "testpass"); + proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort()); + newTransporter("http://bad.localhost:1/"); + try { + transporter.get(new GetTask(URI.create("repo/file.txt"))); + fail("Expected error"); + } catch (HttpResponseException e) { + assertEquals(407, e.getStatusCode()); + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testGet_SSL() - throws Exception - { + public void testGet_SSL() throws Exception { httpServer.addSslConnector(); - newTransporter( httpServer.getHttpsUrl() ); + newTransporter(httpServer.getHttpsUrl()); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "repo/file.txt" ) ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( task.getDataString(), new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals(task.getDataString(), new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_WebDav() - throws Exception - { - httpServer.setWebDav( true ); + public void testGet_WebDav() throws Exception { + httpServer.setWebDav(true); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "repo/dir/file.txt" ) ).setListener( listener ); - ( (HttpTransporter) transporter ).getState().setWebDav( true ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( task.getDataString(), new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); - assertEquals( httpServer.getLogEntries().toString(), 1, httpServer.getLogEntries().size() ); + GetTask task = new GetTask(URI.create("repo/dir/file.txt")).setListener(listener); + ((HttpTransporter) transporter).getState().setWebDav(true); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals(task.getDataString(), new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); + assertEquals( + httpServer.getLogEntries().toString(), + 1, + httpServer.getLogEntries().size()); } @Test - public void testGet_Redirect() - throws Exception - { + public void testGet_Redirect() throws Exception { httpServer.addSslConnector(); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "redirect/file.txt?scheme=https" ) ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( task.getDataString(), new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("redirect/file.txt?scheme=https")).setListener(listener); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals(task.getDataString(), new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_Resume() - throws Exception - { - File file = TestFileUtils.createTempFile( "re" ); + public void testGet_Resume() throws Exception { + File file = TestFileUtils.createTempFile("re"); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "repo/resume.txt" ) ).setDataFile( file, true ).setListener( listener ); - transporter.get( task ); - assertEquals( "resumable", TestFileUtils.readString( file ) ); - assertEquals( 1L, listener.startedCount ); - assertEquals( 2L, listener.dataOffset ); - assertEquals( 9, listener.dataLength ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "sumable", new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("repo/resume.txt")) + .setDataFile(file, true) + .setListener(listener); + transporter.get(task); + assertEquals("resumable", TestFileUtils.readString(file)); + assertEquals(1L, listener.startedCount); + assertEquals(2L, listener.dataOffset); + assertEquals(9, listener.dataLength); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("sumable", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_ResumeLocalContentsOutdated() - throws Exception - { - File file = TestFileUtils.createTempFile( "re" ); - file.setLastModified( System.currentTimeMillis() - 5 * 60 * 1000 ); + public void testGet_ResumeLocalContentsOutdated() throws Exception { + File file = TestFileUtils.createTempFile("re"); + file.setLastModified(System.currentTimeMillis() - 5 * 60 * 1000); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "repo/resume.txt" ) ).setDataFile( file, true ).setListener( listener ); - transporter.get( task ); - assertEquals( "resumable", TestFileUtils.readString( file ) ); - assertEquals( 1L, listener.startedCount ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 9, listener.dataLength ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "resumable", new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("repo/resume.txt")) + .setDataFile(file, true) + .setListener(listener); + transporter.get(task); + assertEquals("resumable", TestFileUtils.readString(file)); + assertEquals(1L, listener.startedCount); + assertEquals(0L, listener.dataOffset); + assertEquals(9, listener.dataLength); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("resumable", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_ResumeRangesNotSupportedByServer() - throws Exception - { - httpServer.setRangeSupport( false ); - File file = TestFileUtils.createTempFile( "re" ); + public void testGet_ResumeRangesNotSupportedByServer() throws Exception { + httpServer.setRangeSupport(false); + File file = TestFileUtils.createTempFile("re"); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "repo/resume.txt" ) ).setDataFile( file, true ).setListener( listener ); - transporter.get( task ); - assertEquals( "resumable", TestFileUtils.readString( file ) ); - assertEquals( 1L, listener.startedCount ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 9, listener.dataLength ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "resumable", new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("repo/resume.txt")) + .setDataFile(file, true) + .setListener(listener); + transporter.get(task); + assertEquals("resumable", TestFileUtils.readString(file)); + assertEquals(1L, listener.startedCount); + assertEquals(0L, listener.dataOffset); + assertEquals(9, listener.dataLength); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("resumable", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_Checksums_Nexus() - throws Exception - { - httpServer.setChecksumHeader( HttpServer.ChecksumHeader.NEXUS ); - GetTask task = new GetTask( URI.create( "repo/file.txt" ) ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", task.getChecksums().get( "SHA-1" ) ); + public void testGet_Checksums_Nexus() throws Exception { + httpServer.setChecksumHeader(HttpServer.ChecksumHeader.NEXUS); + GetTask task = new GetTask(URI.create("repo/file.txt")); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals( + "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", task.getChecksums().get("SHA-1")); } @Test - public void testGet_Checksums_XChecksum() - throws Exception - { - httpServer.setChecksumHeader( HttpServer.ChecksumHeader.XCHECKSUM ); - GetTask task = new GetTask( URI.create( "repo/file.txt" ) ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", task.getChecksums().get( "SHA-1" ) ); + public void testGet_Checksums_XChecksum() throws Exception { + httpServer.setChecksumHeader(HttpServer.ChecksumHeader.XCHECKSUM); + GetTask task = new GetTask(URI.create("repo/file.txt")); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals( + "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", task.getChecksums().get("SHA-1")); } @Test - public void testGet_FileHandleLeak() - throws Exception - { - for ( int i = 0; i < 100; i++ ) - { - File file = TestFileUtils.createTempFile( "failure" ); - transporter.get( new GetTask( URI.create( "repo/file.txt" ) ).setDataFile( file ) ); - assertTrue( i + ", " + file.getAbsolutePath(), file.delete() ); + public void testGet_FileHandleLeak() throws Exception { + for (int i = 0; i < 100; i++) { + File file = TestFileUtils.createTempFile("failure"); + transporter.get(new GetTask(URI.create("repo/file.txt")).setDataFile(file)); + assertTrue(i + ", " + file.getAbsolutePath(), file.delete()); } } @Test - public void testGet_NotFound() - throws Exception - { - try - { - transporter.get( new GetTask( URI.create( "repo/missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( HttpResponseException e ) - { - assertEquals( 404, e.getStatusCode() ); - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( e ) ); + public void testGet_NotFound() throws Exception { + try { + transporter.get(new GetTask(URI.create("repo/missing.txt"))); + fail("Expected error"); + } catch (HttpResponseException e) { + assertEquals(404, e.getStatusCode()); + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e)); } } @Test - public void testGet_Closed() - throws Exception - { + public void testGet_Closed() throws Exception { transporter.close(); - try - { - transporter.get( new GetTask( URI.create( "repo/file.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.get(new GetTask(URI.create("repo/file.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testGet_StartCancelled() - throws Exception - { + public void testGet_StartCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelStart = true; - GetTask task = new GetTask( URI.create( "repo/file.txt" ) ).setListener( listener ); - try - { - transporter.get( task ); - fail( "Expected error" ); - } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); + try { + transporter.get(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); } @Test - public void testGet_ProgressCancelled() - throws Exception - { + public void testGet_ProgressCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelProgress = true; - GetTask task = new GetTask( URI.create( "repo/file.txt" ) ).setListener( listener ); - try - { - transporter.get( task ); - fail( "Expected error" ); - } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + GetTask task = new GetTask(URI.create("repo/file.txt")).setListener(listener); + try { + transporter.get(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 1, listener.progressedCount ); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(1, listener.progressedCount); } @Test - public void testPut_FromMemory() - throws Exception - { + public void testPut_FromMemory() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_FromFile() - throws Exception - { - File file = TestFileUtils.createTempFile( "upload" ); + public void testPut_FromFile() throws Exception { + File file = TestFileUtils.createTempFile("upload"); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataFile( file ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataFile(file); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_EmptyResource() - throws Exception - { + public void testPut_EmptyResource() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 0L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); - assertEquals( "", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = new PutTask(URI.create("repo/file.txt")).setListener(listener); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(0L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); + assertEquals("", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_EncodedResourcePath() - throws Exception - { + public void testPut_EncodedResourcePath() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = - new PutTask( URI.create( "repo/some%20space.txt" ) ).setListener( listener ).setDataString( "OK" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 2L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "OK", TestFileUtils.readString( new File( repoDir, "some space.txt" ) ) ); + PutTask task = new PutTask(URI.create("repo/some%20space.txt")) + .setListener(listener) + .setDataString("OK"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(2L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("OK", TestFileUtils.readString(new File(repoDir, "some space.txt"))); } @Test - public void testPut_Authenticated_ExpectContinue() - throws Exception - { - httpServer.setAuthentication( "testuser", "testpass" ); - auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - newTransporter( httpServer.getHttpUrl() ); + public void testPut_Authenticated_ExpectContinue() throws Exception { + httpServer.setAuthentication("testuser", "testpass"); + auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + newTransporter(httpServer.getHttpUrl()); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_Authenticated_ExpectContinueBroken() - throws Exception - { - httpServer.setAuthentication( "testuser", "testpass" ); - httpServer.setExpectSupport( HttpServer.ExpectContinue.BROKEN ); - auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - newTransporter( httpServer.getHttpUrl() ); + public void testPut_Authenticated_ExpectContinueBroken() throws Exception { + httpServer.setAuthentication("testuser", "testpass"); + httpServer.setExpectSupport(HttpServer.ExpectContinue.BROKEN); + auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + newTransporter(httpServer.getHttpUrl()); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_Authenticated_ExpectContinueRejected() - throws Exception - { - httpServer.setAuthentication( "testuser", "testpass" ); - httpServer.setExpectSupport( HttpServer.ExpectContinue.FAIL ); - auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - newTransporter( httpServer.getHttpUrl() ); + public void testPut_Authenticated_ExpectContinueRejected() throws Exception { + httpServer.setAuthentication("testuser", "testpass"); + httpServer.setExpectSupport(HttpServer.ExpectContinue.FAIL); + auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + newTransporter(httpServer.getHttpUrl()); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_Authenticated_ExpectContinueRejected_ExplicitlyConfiguredHeader() - throws Exception - { + public void testPut_Authenticated_ExpectContinueRejected_ExplicitlyConfiguredHeader() throws Exception { Map headers = new HashMap<>(); - headers.put( "Expect", "100-continue" ); - session.setConfigProperty( ConfigurationProperties.HTTP_HEADERS + ".test", headers ); - httpServer.setAuthentication( "testuser", "testpass" ); - httpServer.setExpectSupport( HttpServer.ExpectContinue.FAIL ); - auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - newTransporter( httpServer.getHttpUrl() ); + headers.put("Expect", "100-continue"); + session.setConfigProperty(ConfigurationProperties.HTTP_HEADERS + ".test", headers); + httpServer.setAuthentication("testuser", "testpass"); + httpServer.setExpectSupport(HttpServer.ExpectContinue.FAIL); + auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + newTransporter(httpServer.getHttpUrl()); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_Unauthenticated() - throws Exception - { - httpServer.setAuthentication( "testuser", "testpass" ); + public void testPut_Unauthenticated() throws Exception { + httpServer.setAuthentication("testuser", "testpass"); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - try - { - transporter.put( task ); - fail( "Expected error" ); - } - catch ( HttpResponseException e ) - { - assertEquals( 401, e.getStatusCode() ); - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + try { + transporter.put(task); + fail("Expected error"); + } catch (HttpResponseException e) { + assertEquals(401, e.getStatusCode()); + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - assertEquals( 0, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); + assertEquals(0, listener.startedCount); + assertEquals(0, listener.progressedCount); } @Test - public void testPut_ProxyAuthenticated() - throws Exception - { - httpServer.setProxyAuthentication( "testuser", "testpass" ); - Authentication auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - proxy = new Proxy( Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth ); - newTransporter( "http://bad.localhost:1/" ); + public void testPut_ProxyAuthenticated() throws Exception { + httpServer.setProxyAuthentication("testuser", "testpass"); + Authentication auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth); + newTransporter("http://bad.localhost:1/"); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_ProxyUnauthenticated() - throws Exception - { - httpServer.setProxyAuthentication( "testuser", "testpass" ); - proxy = new Proxy( Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort() ); - newTransporter( "http://bad.localhost:1/" ); + public void testPut_ProxyUnauthenticated() throws Exception { + httpServer.setProxyAuthentication("testuser", "testpass"); + proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort()); + newTransporter("http://bad.localhost:1/"); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - try - { - transporter.put( task ); - fail( "Expected error" ); - } - catch ( HttpResponseException e ) - { - assertEquals( 407, e.getStatusCode() ); - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + try { + transporter.put(task); + fail("Expected error"); + } catch (HttpResponseException e) { + assertEquals(407, e.getStatusCode()); + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - assertEquals( 0, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); + assertEquals(0, listener.startedCount); + assertEquals(0, listener.progressedCount); } @Test - public void testPut_SSL() - throws Exception - { + public void testPut_SSL() throws Exception { httpServer.addSslConnector(); - httpServer.setAuthentication( "testuser", "testpass" ); - auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - newTransporter( httpServer.getHttpsUrl() ); + httpServer.setAuthentication("testuser", "testpass"); + auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + newTransporter(httpServer.getHttpsUrl()); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "file.txt" ) ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "file.txt"))); } @Test - public void testPut_WebDav() - throws Exception - { - httpServer.setWebDav( true ); + public void testPut_WebDav() throws Exception { + httpServer.setWebDav(true); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = - new PutTask( URI.create( "repo/dir1/dir2/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", TestFileUtils.readString( new File( repoDir, "dir1/dir2/file.txt" ) ) ); - - assertEquals( 5, httpServer.getLogEntries().size() ); - assertEquals( "OPTIONS", httpServer.getLogEntries().get( 0 ).method ); - assertEquals( "MKCOL", httpServer.getLogEntries().get( 1 ).method ); - assertEquals( "/repo/dir1/dir2/", httpServer.getLogEntries().get( 1 ).path ); - assertEquals( "MKCOL", httpServer.getLogEntries().get( 2 ).method ); - assertEquals( "/repo/dir1/", httpServer.getLogEntries().get( 2 ).path ); - assertEquals( "MKCOL", httpServer.getLogEntries().get( 3 ).method ); - assertEquals( "/repo/dir1/dir2/", httpServer.getLogEntries().get( 3 ).path ); - assertEquals( "PUT", httpServer.getLogEntries().get( 4 ).method ); + PutTask task = new PutTask(URI.create("repo/dir1/dir2/file.txt")) + .setListener(listener) + .setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", TestFileUtils.readString(new File(repoDir, "dir1/dir2/file.txt"))); + + assertEquals(5, httpServer.getLogEntries().size()); + assertEquals("OPTIONS", httpServer.getLogEntries().get(0).method); + assertEquals("MKCOL", httpServer.getLogEntries().get(1).method); + assertEquals("/repo/dir1/dir2/", httpServer.getLogEntries().get(1).path); + assertEquals("MKCOL", httpServer.getLogEntries().get(2).method); + assertEquals("/repo/dir1/", httpServer.getLogEntries().get(2).path); + assertEquals("MKCOL", httpServer.getLogEntries().get(3).method); + assertEquals("/repo/dir1/dir2/", httpServer.getLogEntries().get(3).path); + assertEquals("PUT", httpServer.getLogEntries().get(4).method); } @Test - public void testPut_FileHandleLeak() - throws Exception - { - for ( int i = 0; i < 100; i++ ) - { - File src = TestFileUtils.createTempFile( "upload" ); - File dst = new File( repoDir, "file.txt" ); - transporter.put( new PutTask( URI.create( "repo/file.txt" ) ).setDataFile( src ) ); - assertTrue( i + ", " + src.getAbsolutePath(), src.delete() ); - assertTrue( i + ", " + dst.getAbsolutePath(), dst.delete() ); + public void testPut_FileHandleLeak() throws Exception { + for (int i = 0; i < 100; i++) { + File src = TestFileUtils.createTempFile("upload"); + File dst = new File(repoDir, "file.txt"); + transporter.put(new PutTask(URI.create("repo/file.txt")).setDataFile(src)); + assertTrue(i + ", " + src.getAbsolutePath(), src.delete()); + assertTrue(i + ", " + dst.getAbsolutePath(), dst.delete()); } } @Test - public void testPut_Closed() - throws Exception - { + public void testPut_Closed() throws Exception { transporter.close(); - try - { - transporter.put( new PutTask( URI.create( "repo/missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.put(new PutTask(URI.create("repo/missing.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testPut_StartCancelled() - throws Exception - { + public void testPut_StartCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelStart = true; - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - try - { - transporter.put( task ); - fail( "Expected error" ); - } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + try { + transporter.put(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); } @Test - public void testPut_ProgressCancelled() - throws Exception - { + public void testPut_ProgressCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelProgress = true; - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - try - { - transporter.put( task ); - fail( "Expected error" ); - } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + try { + transporter.put(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 1, listener.progressedCount ); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(1, listener.progressedCount); } @Test - public void testGetPut_AuthCache() - throws Exception - { - httpServer.setAuthentication( "testuser", "testpass" ); - auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - newTransporter( httpServer.getHttpUrl() ); - GetTask get = new GetTask( URI.create( "repo/file.txt" ) ); - transporter.get( get ); + public void testGetPut_AuthCache() throws Exception { + httpServer.setAuthentication("testuser", "testpass"); + auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + newTransporter(httpServer.getHttpUrl()); + GetTask get = new GetTask(URI.create("repo/file.txt")); + transporter.get(get); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "repo/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 1, listener.startedCount ); - } - - @Test( timeout = 20000L ) - public void testConcurrency() - throws Exception - { - httpServer.setAuthentication( "testuser", "testpass" ); - auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - newTransporter( httpServer.getHttpUrl() ); + PutTask task = + new PutTask(URI.create("repo/file.txt")).setListener(listener).setDataString("upload"); + transporter.put(task); + assertEquals(1, listener.startedCount); + } + + @Test(timeout = 20000L) + public void testConcurrency() throws Exception { + httpServer.setAuthentication("testuser", "testpass"); + auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + newTransporter(httpServer.getHttpUrl()); final AtomicReference error = new AtomicReference<>(); Thread[] threads = new Thread[20]; - for ( int i = 0; i < threads.length; i++ ) - { + for (int i = 0; i < threads.length; i++) { final String path = "repo/file.txt?i=" + i; - threads[i] = new Thread() - { + threads[i] = new Thread() { @Override - public void run() - { - try - { - for ( int j = 0; j < 100; j++ ) - { - GetTask task = new GetTask( URI.create( path ) ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); + public void run() { + try { + for (int j = 0; j < 100; j++) { + GetTask task = new GetTask(URI.create(path)); + transporter.get(task); + assertEquals("test", task.getDataString()); } - } - catch ( Throwable t ) - { - error.compareAndSet( null, t ); - System.err.println( path ); + } catch (Throwable t) { + error.compareAndSet(null, t); + System.err.println(path); t.printStackTrace(); } } }; - threads[i].setName( "Task-" + i ); + threads[i].setName("Task-" + i); } - for ( Thread thread : threads ) - { + for (Thread thread : threads) { thread.start(); } - for ( Thread thread : threads ) - { + for (Thread thread : threads) { thread.join(); } - assertNull( String.valueOf( error.get() ), error.get() ); + assertNull(String.valueOf(error.get()), error.get()); } - @Test( timeout = 1000L ) - public void testConnectTimeout() - throws Exception - { - session.setConfigProperty( ConfigurationProperties.CONNECT_TIMEOUT, 100 ); + @Test(timeout = 1000L) + public void testConnectTimeout() throws Exception { + session.setConfigProperty(ConfigurationProperties.CONNECT_TIMEOUT, 100); int port = 1; - newTransporter( "http://localhost:" + port ); - try - { - transporter.get( new GetTask( URI.create( "repo/file.txt" ) ) ); - fail( "Expected error" ); - } - catch ( ConnectTimeoutException | ConnectException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + newTransporter("http://localhost:" + port); + try { + transporter.get(new GetTask(URI.create("repo/file.txt"))); + fail("Expected error"); + } catch (ConnectTimeoutException | ConnectException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } - @Test( timeout = 1000L ) - public void testRequestTimeout() - throws Exception - { - session.setConfigProperty( ConfigurationProperties.REQUEST_TIMEOUT, 100 ); - ServerSocket server = new ServerSocket( 0 ); - newTransporter( "http://localhost:" + server.getLocalPort() ); - try - { - try - { - transporter.get( new GetTask( URI.create( "repo/file.txt" ) ) ); - fail( "Expected error" ); + @Test(timeout = 1000L) + public void testRequestTimeout() throws Exception { + session.setConfigProperty(ConfigurationProperties.REQUEST_TIMEOUT, 100); + ServerSocket server = new ServerSocket(0); + newTransporter("http://localhost:" + server.getLocalPort()); + try { + try { + transporter.get(new GetTask(URI.create("repo/file.txt"))); + fail("Expected error"); + } catch (SocketTimeoutException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - catch ( SocketTimeoutException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); - } - } - finally - { + } finally { server.close(); } } @Test - public void testUserAgent() - throws Exception - { - session.setConfigProperty( ConfigurationProperties.USER_AGENT, "SomeTest/1.0" ); - newTransporter( httpServer.getHttpUrl() ); - transporter.get( new GetTask( URI.create( "repo/file.txt" ) ) ); - assertEquals( 1, httpServer.getLogEntries().size() ); - for ( HttpServer.LogEntry log : httpServer.getLogEntries() ) - { - assertEquals( "SomeTest/1.0", log.headers.get( "User-Agent" ) ); + public void testUserAgent() throws Exception { + session.setConfigProperty(ConfigurationProperties.USER_AGENT, "SomeTest/1.0"); + newTransporter(httpServer.getHttpUrl()); + transporter.get(new GetTask(URI.create("repo/file.txt"))); + assertEquals(1, httpServer.getLogEntries().size()); + for (HttpServer.LogEntry log : httpServer.getLogEntries()) { + assertEquals("SomeTest/1.0", log.headers.get("User-Agent")); } } @Test - public void testCustomHeaders() - throws Exception - { + public void testCustomHeaders() throws Exception { Map headers = new HashMap<>(); - headers.put( "User-Agent", "Custom/1.0" ); - headers.put( "X-CustomHeader", "Custom-Value" ); - session.setConfigProperty( ConfigurationProperties.USER_AGENT, "SomeTest/1.0" ); - session.setConfigProperty( ConfigurationProperties.HTTP_HEADERS + ".test", headers ); - newTransporter( httpServer.getHttpUrl() ); - transporter.get( new GetTask( URI.create( "repo/file.txt" ) ) ); - assertEquals( 1, httpServer.getLogEntries().size() ); - for ( HttpServer.LogEntry log : httpServer.getLogEntries() ) - { - for ( Map.Entry entry : headers.entrySet() ) - { - assertEquals( entry.getKey(), entry.getValue(), log.headers.get( entry.getKey() ) ); + headers.put("User-Agent", "Custom/1.0"); + headers.put("X-CustomHeader", "Custom-Value"); + session.setConfigProperty(ConfigurationProperties.USER_AGENT, "SomeTest/1.0"); + session.setConfigProperty(ConfigurationProperties.HTTP_HEADERS + ".test", headers); + newTransporter(httpServer.getHttpUrl()); + transporter.get(new GetTask(URI.create("repo/file.txt"))); + assertEquals(1, httpServer.getLogEntries().size()); + for (HttpServer.LogEntry log : httpServer.getLogEntries()) { + for (Map.Entry entry : headers.entrySet()) { + assertEquals(entry.getKey(), entry.getValue(), log.headers.get(entry.getKey())); } } } @Test - public void testServerAuthScope_NotUsedForProxy() - throws Exception - { + public void testServerAuthScope_NotUsedForProxy() throws Exception { String username = "testuser", password = "testpass"; - httpServer.setProxyAuthentication( username, password ); - auth = new AuthenticationBuilder().addUsername( username ).addPassword( password ).build(); - proxy = new Proxy( Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort() ); - newTransporter( "http://" + httpServer.getHost() + ":12/" ); - try - { - transporter.get( new GetTask( URI.create( "repo/file.txt" ) ) ); - fail( "Server auth must not be used as proxy auth" ); - } - catch ( HttpResponseException e ) - { - assertEquals( 407, e.getStatusCode() ); + httpServer.setProxyAuthentication(username, password); + auth = new AuthenticationBuilder() + .addUsername(username) + .addPassword(password) + .build(); + proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort()); + newTransporter("http://" + httpServer.getHost() + ":12/"); + try { + transporter.get(new GetTask(URI.create("repo/file.txt"))); + fail("Server auth must not be used as proxy auth"); + } catch (HttpResponseException e) { + assertEquals(407, e.getStatusCode()); } } @Test - public void testProxyAuthScope_NotUsedForServer() - throws Exception - { + public void testProxyAuthScope_NotUsedForServer() throws Exception { String username = "testuser", password = "testpass"; - httpServer.setAuthentication( username, password ); - Authentication auth = new AuthenticationBuilder().addUsername( username ).addPassword( password ).build(); - proxy = new Proxy( Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth ); - newTransporter( "http://" + httpServer.getHost() + ":12/" ); - try - { - transporter.get( new GetTask( URI.create( "repo/file.txt" ) ) ); - fail( "Proxy auth must not be used as server auth" ); - } - catch ( HttpResponseException e ) - { - assertEquals( 401, e.getStatusCode() ); + httpServer.setAuthentication(username, password); + Authentication auth = new AuthenticationBuilder() + .addUsername(username) + .addPassword(password) + .build(); + proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth); + newTransporter("http://" + httpServer.getHost() + ":12/"); + try { + transporter.get(new GetTask(URI.create("repo/file.txt"))); + fail("Proxy auth must not be used as server auth"); + } catch (HttpResponseException e) { + assertEquals(401, e.getStatusCode()); } } @Test - public void testAuthSchemeReuse() - throws Exception - { - httpServer.setAuthentication( "testuser", "testpass" ); - httpServer.setProxyAuthentication( "proxyuser", "proxypass" ); - session.setCache( new DefaultRepositoryCache() ); - auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - Authentication auth = new AuthenticationBuilder().addUsername( "proxyuser" ).addPassword( "proxypass" ).build(); - proxy = new Proxy( Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth ); - newTransporter( "http://bad.localhost:1/" ); - GetTask task = new GetTask( URI.create( "repo/file.txt" ) ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( 3, httpServer.getLogEntries().size() ); + public void testAuthSchemeReuse() throws Exception { + httpServer.setAuthentication("testuser", "testpass"); + httpServer.setProxyAuthentication("proxyuser", "proxypass"); + session.setCache(new DefaultRepositoryCache()); + auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + Authentication auth = new AuthenticationBuilder() + .addUsername("proxyuser") + .addPassword("proxypass") + .build(); + proxy = new Proxy(Proxy.TYPE_HTTP, httpServer.getHost(), httpServer.getHttpPort(), auth); + newTransporter("http://bad.localhost:1/"); + GetTask task = new GetTask(URI.create("repo/file.txt")); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals(3, httpServer.getLogEntries().size()); httpServer.getLogEntries().clear(); - newTransporter( "http://bad.localhost:1/" ); - task = new GetTask( URI.create( "repo/file.txt" ) ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( 1, httpServer.getLogEntries().size() ); - assertNotNull( httpServer.getLogEntries().get( 0 ).headers.get( "Authorization" ) ); - assertNotNull( httpServer.getLogEntries().get( 0 ).headers.get( "Proxy-Authorization" ) ); + newTransporter("http://bad.localhost:1/"); + task = new GetTask(URI.create("repo/file.txt")); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals(1, httpServer.getLogEntries().size()); + assertNotNull(httpServer.getLogEntries().get(0).headers.get("Authorization")); + assertNotNull(httpServer.getLogEntries().get(0).headers.get("Proxy-Authorization")); } @Test - public void testConnectionReuse() - throws Exception - { + public void testConnectionReuse() throws Exception { httpServer.addSslConnector(); - session.setCache( new DefaultRepositoryCache() ); - for ( int i = 0; i < 3; i++ ) - { - newTransporter( httpServer.getHttpsUrl() ); - GetTask task = new GetTask( URI.create( "repo/file.txt" ) ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); + session.setCache(new DefaultRepositoryCache()); + for (int i = 0; i < 3; i++) { + newTransporter(httpServer.getHttpsUrl()); + GetTask task = new GetTask(URI.create("repo/file.txt")); + transporter.get(task); + assertEquals("test", task.getDataString()); } - PoolStats stats = - ( (ConnPoolControl) ( (HttpTransporter) transporter ).getState().getConnectionManager() ).getTotalStats(); - assertEquals( stats.toString(), 1, stats.getAvailable() ); + PoolStats stats = ((ConnPoolControl) + ((HttpTransporter) transporter).getState().getConnectionManager()) + .getTotalStats(); + assertEquals(stats.toString(), 1, stats.getAvailable()); } - @Test( expected = NoTransporterException.class ) - public void testInit_BadProtocol() - throws Exception - { - newTransporter( "bad:/void" ); + @Test(expected = NoTransporterException.class) + public void testInit_BadProtocol() throws Exception { + newTransporter("bad:/void"); } - @Test( expected = NoTransporterException.class ) - public void testInit_BadUrl() - throws Exception - { - newTransporter( "http://localhost:NaN" ); + @Test(expected = NoTransporterException.class) + public void testInit_BadUrl() throws Exception { + newTransporter("http://localhost:NaN"); } @Test - public void testInit_CaseInsensitiveProtocol() - throws Exception - { - newTransporter( "http://localhost" ); - newTransporter( "HTTP://localhost" ); - newTransporter( "Http://localhost" ); - newTransporter( "https://localhost" ); - newTransporter( "HTTPS://localhost" ); - newTransporter( "HttpS://localhost" ); + public void testInit_CaseInsensitiveProtocol() throws Exception { + newTransporter("http://localhost"); + newTransporter("HTTP://localhost"); + newTransporter("Http://localhost"); + newTransporter("https://localhost"); + newTransporter("HTTPS://localhost"); + newTransporter("HttpS://localhost"); } - } diff --git a/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/RecordingTransportListener.java b/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/RecordingTransportListener.java index e7ca7c969..2c2eb124c 100644 --- a/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/RecordingTransportListener.java +++ b/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/RecordingTransportListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.http; import java.io.ByteArrayOutputStream; import java.nio.Buffer; @@ -26,11 +25,9 @@ import org.eclipse.aether.spi.connector.transport.TransportListener; import org.eclipse.aether.transfer.TransferCancelledException; -class RecordingTransportListener - extends TransportListener -{ +class RecordingTransportListener extends TransportListener { - public final ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 ); + public final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); public long dataOffset; @@ -45,30 +42,23 @@ class RecordingTransportListener public boolean cancelProgress; @Override - public void transportStarted( long dataOffset, long dataLength ) - throws TransferCancelledException - { + public void transportStarted(long dataOffset, long dataLength) throws TransferCancelledException { startedCount++; progressedCount = 0; this.dataLength = dataLength; this.dataOffset = dataOffset; baos.reset(); - if ( cancelStart ) - { + if (cancelStart) { throw new TransferCancelledException(); } } @Override - public void transportProgressed( ByteBuffer data ) - throws TransferCancelledException - { + public void transportProgressed(ByteBuffer data) throws TransferCancelledException { progressedCount++; - baos.write( data.array(), data.arrayOffset() + ( (Buffer) data ).position(), data.remaining() ); - if ( cancelProgress ) - { + baos.write(data.array(), data.arrayOffset() + ((Buffer) data).position(), data.remaining()); + if (cancelProgress) { throw new TransferCancelledException(); } } - } diff --git a/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/UriUtilsTest.java b/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/UriUtilsTest.java index 70fd34d0c..efeb80489 100644 --- a/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/UriUtilsTest.java +++ b/maven-resolver-transport-http/src/test/java/org/eclipse/aether/transport/http/UriUtilsTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.http; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.transport.http; import java.net.URI; import java.util.ArrayList; @@ -28,110 +25,99 @@ import org.junit.Test; -public class UriUtilsTest -{ +import static org.junit.Assert.*; + +public class UriUtilsTest { - private String resolve( URI base, String ref ) - { - return UriUtils.resolve( base, URI.create( ref ) ).toString(); + private String resolve(URI base, String ref) { + return UriUtils.resolve(base, URI.create(ref)).toString(); } @Test - public void testResolve_BaseEmptyPath() - { - URI base = URI.create( "http://host" ); - assertEquals( "http://host/file.jar", resolve( base, "file.jar" ) ); - assertEquals( "http://host/dir/file.jar", resolve( base, "dir/file.jar" ) ); - assertEquals( "http://host?arg=val", resolve( base, "?arg=val" ) ); - assertEquals( "http://host/file?arg=val", resolve( base, "file?arg=val" ) ); - assertEquals( "http://host/dir/file?arg=val", resolve( base, "dir/file?arg=val" ) ); + public void testResolve_BaseEmptyPath() { + URI base = URI.create("http://host"); + assertEquals("http://host/file.jar", resolve(base, "file.jar")); + assertEquals("http://host/dir/file.jar", resolve(base, "dir/file.jar")); + assertEquals("http://host?arg=val", resolve(base, "?arg=val")); + assertEquals("http://host/file?arg=val", resolve(base, "file?arg=val")); + assertEquals("http://host/dir/file?arg=val", resolve(base, "dir/file?arg=val")); } @Test - public void testResolve_BaseRootPath() - { - URI base = URI.create( "http://host/" ); - assertEquals( "http://host/file.jar", resolve( base, "file.jar" ) ); - assertEquals( "http://host/dir/file.jar", resolve( base, "dir/file.jar" ) ); - assertEquals( "http://host/?arg=val", resolve( base, "?arg=val" ) ); - assertEquals( "http://host/file?arg=val", resolve( base, "file?arg=val" ) ); - assertEquals( "http://host/dir/file?arg=val", resolve( base, "dir/file?arg=val" ) ); + public void testResolve_BaseRootPath() { + URI base = URI.create("http://host/"); + assertEquals("http://host/file.jar", resolve(base, "file.jar")); + assertEquals("http://host/dir/file.jar", resolve(base, "dir/file.jar")); + assertEquals("http://host/?arg=val", resolve(base, "?arg=val")); + assertEquals("http://host/file?arg=val", resolve(base, "file?arg=val")); + assertEquals("http://host/dir/file?arg=val", resolve(base, "dir/file?arg=val")); } @Test - public void testResolve_BasePathTrailingSlash() - { - URI base = URI.create( "http://host/sub/dir/" ); - assertEquals( "http://host/sub/dir/file.jar", resolve( base, "file.jar" ) ); - assertEquals( "http://host/sub/dir/dir/file.jar", resolve( base, "dir/file.jar" ) ); - assertEquals( "http://host/sub/dir/?arg=val", resolve( base, "?arg=val" ) ); - assertEquals( "http://host/sub/dir/file?arg=val", resolve( base, "file?arg=val" ) ); - assertEquals( "http://host/sub/dir/dir/file?arg=val", resolve( base, "dir/file?arg=val" ) ); + public void testResolve_BasePathTrailingSlash() { + URI base = URI.create("http://host/sub/dir/"); + assertEquals("http://host/sub/dir/file.jar", resolve(base, "file.jar")); + assertEquals("http://host/sub/dir/dir/file.jar", resolve(base, "dir/file.jar")); + assertEquals("http://host/sub/dir/?arg=val", resolve(base, "?arg=val")); + assertEquals("http://host/sub/dir/file?arg=val", resolve(base, "file?arg=val")); + assertEquals("http://host/sub/dir/dir/file?arg=val", resolve(base, "dir/file?arg=val")); } @Test - public void testResolve_BasePathNoTrailingSlash() - { - URI base = URI.create( "http://host/sub/d%20r" ); - assertEquals( "http://host/sub/d%20r/file.jar", resolve( base, "file.jar" ) ); - assertEquals( "http://host/sub/d%20r/dir/file.jar", resolve( base, "dir/file.jar" ) ); - assertEquals( "http://host/sub/d%20r?arg=val", resolve( base, "?arg=val" ) ); - assertEquals( "http://host/sub/d%20r/file?arg=val", resolve( base, "file?arg=val" ) ); - assertEquals( "http://host/sub/d%20r/dir/file?arg=val", resolve( base, "dir/file?arg=val" ) ); + public void testResolve_BasePathNoTrailingSlash() { + URI base = URI.create("http://host/sub/d%20r"); + assertEquals("http://host/sub/d%20r/file.jar", resolve(base, "file.jar")); + assertEquals("http://host/sub/d%20r/dir/file.jar", resolve(base, "dir/file.jar")); + assertEquals("http://host/sub/d%20r?arg=val", resolve(base, "?arg=val")); + assertEquals("http://host/sub/d%20r/file?arg=val", resolve(base, "file?arg=val")); + assertEquals("http://host/sub/d%20r/dir/file?arg=val", resolve(base, "dir/file?arg=val")); } - private List getDirs( String base, String uri ) - { - return UriUtils.getDirectories( ( base != null ) ? URI.create( base ) : null, URI.create( uri ) ); + private List getDirs(String base, String uri) { + return UriUtils.getDirectories((base != null) ? URI.create(base) : null, URI.create(uri)); } - private void assertUris( List actual, String... expected ) - { - List uris = new ArrayList<>( actual.size() ); - for ( URI uri : actual ) - { - uris.add( uri.toString() ); + private void assertUris(List actual, String... expected) { + List uris = new ArrayList<>(actual.size()); + for (URI uri : actual) { + uris.add(uri.toString()); } - assertEquals( Arrays.asList( expected ), uris ); + assertEquals(Arrays.asList(expected), uris); } @Test - public void testGetDirectories_NoBase() - { - List parents = getDirs( null, "http://host/repo/sub/dir/file.jar" ); - assertUris( parents, "http://host/repo/sub/dir/", "http://host/repo/sub/", "http://host/repo/" ); + public void testGetDirectories_NoBase() { + List parents = getDirs(null, "http://host/repo/sub/dir/file.jar"); + assertUris(parents, "http://host/repo/sub/dir/", "http://host/repo/sub/", "http://host/repo/"); - parents = getDirs( null, "http://host/repo/sub/dir/?file.jar" ); - assertUris( parents, "http://host/repo/sub/dir/", "http://host/repo/sub/", "http://host/repo/" ); + parents = getDirs(null, "http://host/repo/sub/dir/?file.jar"); + assertUris(parents, "http://host/repo/sub/dir/", "http://host/repo/sub/", "http://host/repo/"); - parents = getDirs( null, "http://host/" ); - assertUris( parents ); + parents = getDirs(null, "http://host/"); + assertUris(parents); } @Test - public void testGetDirectories_ExplicitBaseTrailingSlash() - { - List parents = getDirs( "http://host/repo/", "http://host/repo/sub/dir/file.jar" ); - assertUris( parents, "http://host/repo/sub/dir/", "http://host/repo/sub/" ); + public void testGetDirectories_ExplicitBaseTrailingSlash() { + List parents = getDirs("http://host/repo/", "http://host/repo/sub/dir/file.jar"); + assertUris(parents, "http://host/repo/sub/dir/", "http://host/repo/sub/"); - parents = getDirs( "http://host/repo/", "http://host/repo/sub/dir/?file.jar" ); - assertUris( parents, "http://host/repo/sub/dir/", "http://host/repo/sub/" ); + parents = getDirs("http://host/repo/", "http://host/repo/sub/dir/?file.jar"); + assertUris(parents, "http://host/repo/sub/dir/", "http://host/repo/sub/"); - parents = getDirs( "http://host/repo/", "http://host/" ); - assertUris( parents ); + parents = getDirs("http://host/repo/", "http://host/"); + assertUris(parents); } @Test - public void testGetDirectories_ExplicitBaseNoTrailingSlash() - { - List parents = getDirs( "http://host/repo", "http://host/repo/sub/dir/file.jar" ); - assertUris( parents, "http://host/repo/sub/dir/", "http://host/repo/sub/" ); + public void testGetDirectories_ExplicitBaseNoTrailingSlash() { + List parents = getDirs("http://host/repo", "http://host/repo/sub/dir/file.jar"); + assertUris(parents, "http://host/repo/sub/dir/", "http://host/repo/sub/"); - parents = getDirs( "http://host/repo", "http://host/repo/sub/dir/?file.jar" ); - assertUris( parents, "http://host/repo/sub/dir/", "http://host/repo/sub/" ); + parents = getDirs("http://host/repo", "http://host/repo/sub/dir/?file.jar"); + assertUris(parents, "http://host/repo/sub/dir/", "http://host/repo/sub/"); - parents = getDirs( "http://host/repo", "http://host/" ); - assertUris( parents ); + parents = getDirs("http://host/repo", "http://host/"); + assertUris(parents); } - } diff --git a/maven-resolver-transport-wagon/pom.xml b/maven-resolver-transport-wagon/pom.xml index 12440a40f..38e457a38 100644 --- a/maven-resolver-transport-wagon/pom.xml +++ b/maven-resolver-transport-wagon/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-transport-wagon Maven Artifact Resolver Transport Wagon - - A transport implementation based on Maven Wagon. - + A transport implementation based on Maven Wagon. org.apache.maven.resolver.transport.wagon diff --git a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/PlexusWagonConfigurator.java b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/PlexusWagonConfigurator.java index e41b1ee52..b12bf5add 100644 --- a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/PlexusWagonConfigurator.java +++ b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/PlexusWagonConfigurator.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,8 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.transport.wagon; -import static java.util.Objects.requireNonNull; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.wagon.Wagon; import org.codehaus.plexus.PlexusContainer; @@ -34,18 +35,14 @@ import org.codehaus.plexus.util.xml.Xpp3Dom; import org.eclipse.aether.transport.wagon.WagonConfigurator; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; +import static java.util.Objects.requireNonNull; /** * A wagon configurator based on the Plexus component configuration framework. */ -@Named ( "plexus" ) +@Named("plexus") @Singleton -public class PlexusWagonConfigurator - implements WagonConfigurator -{ +public class PlexusWagonConfigurator implements WagonConfigurator { private final PlexusContainer container; /** @@ -54,53 +51,43 @@ public class PlexusWagonConfigurator * @param container The Plexus container instance to use, must not be {@code null}. */ @Inject - public PlexusWagonConfigurator( final PlexusContainer container ) - { - this.container = requireNonNull( container, "plexus container cannot be null" ); + public PlexusWagonConfigurator(final PlexusContainer container) { + this.container = requireNonNull(container, "plexus container cannot be null"); } - public void configure( Wagon wagon, Object configuration ) - throws Exception - { - requireNonNull( wagon, "wagon cannot be null" ); - requireNonNull( configuration, "configuration cannot be null" ); + public void configure(Wagon wagon, Object configuration) throws Exception { + requireNonNull(wagon, "wagon cannot be null"); + requireNonNull(configuration, "configuration cannot be null"); PlexusConfiguration config; - if ( configuration instanceof PlexusConfiguration ) - { + if (configuration instanceof PlexusConfiguration) { config = (PlexusConfiguration) configuration; - } - else if ( configuration instanceof Xpp3Dom ) - { - config = new XmlPlexusConfiguration( (Xpp3Dom) configuration ); - } - else - { - throw new IllegalArgumentException( "unexpected configuration type: " - + configuration.getClass().getName() ); + } else if (configuration instanceof Xpp3Dom) { + config = new XmlPlexusConfiguration((Xpp3Dom) configuration); + } else { + throw new IllegalArgumentException( + "unexpected configuration type: " + configuration.getClass().getName()); } WagonComponentConfigurator configurator = new WagonComponentConfigurator(); - configurator.configureComponent( wagon, config, container.getContainerRealm() ); + configurator.configureComponent(wagon, config, container.getContainerRealm()); } - static class WagonComponentConfigurator - extends AbstractComponentConfigurator - { + static class WagonComponentConfigurator extends AbstractComponentConfigurator { @Override - public void configureComponent( Object component, PlexusConfiguration configuration, - ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm, - ConfigurationListener listener ) - throws ComponentConfigurationException - { + public void configureComponent( + Object component, + PlexusConfiguration configuration, + ExpressionEvaluator expressionEvaluator, + ClassRealm containerRealm, + ConfigurationListener listener) + throws ComponentConfigurationException { ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter(); - converter.processConfiguration( converterLookup, component, containerRealm, configuration, - expressionEvaluator, listener ); + converter.processConfiguration( + converterLookup, component, containerRealm, configuration, expressionEvaluator, listener); } - } - } diff --git a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/PlexusWagonProvider.java b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/PlexusWagonProvider.java index e46130c6b..16bb4db6a 100644 --- a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/PlexusWagonProvider.java +++ b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/PlexusWagonProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.internal.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,25 +16,24 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.internal.transport.wagon; -import static java.util.Objects.requireNonNull; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; import org.apache.maven.wagon.Wagon; import org.codehaus.plexus.PlexusContainer; import org.eclipse.aether.transport.wagon.WagonProvider; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; +import static java.util.Objects.requireNonNull; /** * A wagon provider backed by a Plexus container and the wagons registered with this container. */ -@Named( "plexus" ) +@Named("plexus") @Singleton -public class PlexusWagonProvider - implements WagonProvider -{ +public class PlexusWagonProvider implements WagonProvider { private final PlexusContainer container; /** @@ -45,30 +42,21 @@ public class PlexusWagonProvider * @param container The Plexus container instance to use, must not be {@code null}. */ @Inject - public PlexusWagonProvider( final PlexusContainer container ) - { - this.container = requireNonNull( container, "plexus container cannot be null" ); + public PlexusWagonProvider(final PlexusContainer container) { + this.container = requireNonNull(container, "plexus container cannot be null"); } - public Wagon lookup( String roleHint ) - throws Exception - { - return container.lookup( Wagon.class, roleHint ); + public Wagon lookup(String roleHint) throws Exception { + return container.lookup(Wagon.class, roleHint); } - public void release( Wagon wagon ) - { - try - { - if ( wagon != null ) - { - container.release( wagon ); + public void release(Wagon wagon) { + try { + if (wagon != null) { + container.release(wagon); } - } - catch ( Exception e ) - { + } catch (Exception e) { // too bad } } - } diff --git a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/package-info.java b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/package-info.java index 1d87669ff..4f7d03ec3 100644 --- a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/package-info.java +++ b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/internal/transport/wagon/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -22,4 +22,3 @@ * implementations. */ package org.eclipse.aether.internal.transport.wagon; - diff --git a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonCancelledException.java b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonCancelledException.java index 821e596db..1e7568fbf 100644 --- a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonCancelledException.java +++ b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonCancelledException.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,28 +16,23 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import org.eclipse.aether.transfer.TransferCancelledException; /** * Unchecked exception to allow the checked {@link TransferCancelledException} to bubble up from a wagon. */ -class WagonCancelledException - extends RuntimeException -{ +class WagonCancelledException extends RuntimeException { - WagonCancelledException( TransferCancelledException cause ) - { - super( cause ); + WagonCancelledException(TransferCancelledException cause) { + super(cause); } - public static Exception unwrap( Exception e ) - { - if ( e instanceof WagonCancelledException ) - { + public static Exception unwrap(Exception e) { + if (e instanceof WagonCancelledException) { e = (Exception) e.getCause(); } return e; } - } diff --git a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonConfigurator.java b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonConfigurator.java index 42399cba9..6912b8de2 100644 --- a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonConfigurator.java +++ b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonConfigurator.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,23 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import org.apache.maven.wagon.Wagon; /** * A component to configure wagon instances with provider-specific parameters. */ -public interface WagonConfigurator -{ +public interface WagonConfigurator { /** * Configures the specified wagon instance with the given configuration. - * + * * @param wagon The wagon instance to configure, must not be {@code null}. * @param configuration The configuration to apply to the wagon instance, must not be {@code null}. * @throws Exception If the configuration could not be applied to the wagon. */ - void configure( Wagon wagon, Object configuration ) - throws Exception; - + void configure(Wagon wagon, Object configuration) throws Exception; } diff --git a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonProvider.java b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonProvider.java index 77bf9d6b0..463e4b13e 100644 --- a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonProvider.java +++ b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonProvider.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,32 +16,30 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import org.apache.maven.wagon.Wagon; /** * A component to acquire and release wagon instances for uploads/downloads. */ -public interface WagonProvider -{ +public interface WagonProvider { /** * Acquires a wagon instance that matches the specified role hint. The role hint is derived from the URI scheme, * e.g. "http" or "file". - * + * * @param roleHint The role hint to get a wagon for, must not be {@code null}. * @return The requested wagon instance, never {@code null}. * @throws Exception If no wagon could be retrieved for the specified role hint. */ - Wagon lookup( String roleHint ) - throws Exception; + Wagon lookup(String roleHint) throws Exception; /** * Releases the specified wagon. A wagon provider may either free any resources allocated for the wagon instance or * return the instance back to a pool for future use. - * + * * @param wagon The wagon to release, may be {@code null}. */ - void release( Wagon wagon ); - + void release(Wagon wagon); } diff --git a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransferListener.java b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransferListener.java index 34363ae14..fd100770b 100644 --- a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransferListener.java +++ b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransferListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import java.nio.ByteBuffer; @@ -29,26 +28,19 @@ /** * A wagon transfer listener that forwards events to a transport listener. */ -final class WagonTransferListener - extends AbstractTransferListener -{ +final class WagonTransferListener extends AbstractTransferListener { private final TransportListener listener; - WagonTransferListener( TransportListener listener ) - { + WagonTransferListener(TransportListener listener) { this.listener = listener; } @Override - public void transferStarted( TransferEvent event ) - { - try - { - listener.transportStarted( 0, event.getResource().getContentLength() ); - } - catch ( TransferCancelledException e ) - { + public void transferStarted(TransferEvent event) { + try { + listener.transportStarted(0, event.getResource().getContentLength()); + } catch (TransferCancelledException e) { /* * NOTE: Wagon transfers are not freely abortable. In particular, aborting from * AbstractWagon.fire(Get|Put)Started() would result in unclosed streams so we avoid this case. @@ -57,16 +49,11 @@ public void transferStarted( TransferEvent event ) } @Override - public void transferProgress( TransferEvent event, byte[] buffer, int length ) - { - try - { - listener.transportProgressed( ByteBuffer.wrap( buffer, 0, length ) ); - } - catch ( TransferCancelledException e ) - { - throw new WagonCancelledException( e ); + public void transferProgress(TransferEvent event, byte[] buffer, int length) { + try { + listener.transportProgressed(ByteBuffer.wrap(buffer, 0, length)); + } catch (TransferCancelledException e) { + throw new WagonCancelledException(e); } } - } diff --git a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransporter.java b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransporter.java index 92f0971fe..90aebef8a 100644 --- a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransporter.java +++ b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransporter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import java.io.File; import java.io.IOException; @@ -64,9 +63,7 @@ /** * A transporter using Maven Wagon. */ -final class WagonTransporter - implements Transporter -{ +final class WagonTransporter implements Transporter { private static final String CONFIG_PROP_CONFIG = "aether.connector.wagon.config"; @@ -76,7 +73,7 @@ final class WagonTransporter private static final String CONFIG_PROP_GROUP = "aether.connector.perms.group"; - private static final Logger LOGGER = LoggerFactory.getLogger( WagonTransporter.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(WagonTransporter.class); private final RemoteRepository repository; @@ -104,114 +101,104 @@ final class WagonTransporter private final AtomicBoolean closed = new AtomicBoolean(); - WagonTransporter( WagonProvider wagonProvider, WagonConfigurator wagonConfigurator, - RemoteRepository repository, RepositorySystemSession session ) - throws NoTransporterException - { + WagonTransporter( + WagonProvider wagonProvider, + WagonConfigurator wagonConfigurator, + RemoteRepository repository, + RepositorySystemSession session) + throws NoTransporterException { this.wagonProvider = wagonProvider; this.wagonConfigurator = wagonConfigurator; this.repository = repository; this.session = session; - wagonRepo = new Repository( repository.getId(), repository.getUrl() ); - wagonRepo.setPermissions( getPermissions( repository.getId(), session ) ); + wagonRepo = new Repository(repository.getId(), repository.getUrl()); + wagonRepo.setPermissions(getPermissions(repository.getId(), session)); - wagonHint = wagonRepo.getProtocol().toLowerCase( Locale.ENGLISH ); - if ( wagonHint.isEmpty() ) - { - throw new NoTransporterException( repository ); + wagonHint = wagonRepo.getProtocol().toLowerCase(Locale.ENGLISH); + if (wagonHint.isEmpty()) { + throw new NoTransporterException(repository); } - try - { - wagons.add( lookupWagon() ); - } - catch ( Exception e ) - { - LOGGER.debug( "No transport", e ); - throw new NoTransporterException( repository, e ); + try { + wagons.add(lookupWagon()); + } catch (Exception e) { + LOGGER.debug("No transport", e); + throw new NoTransporterException(repository, e); } - repoAuthContext = AuthenticationContext.forRepository( session, repository ); - proxyAuthContext = AuthenticationContext.forProxy( session, repository ); + repoAuthContext = AuthenticationContext.forRepository(session, repository); + proxyAuthContext = AuthenticationContext.forProxy(session, repository); - wagonAuth = getAuthenticationInfo( repoAuthContext ); - wagonProxy = getProxy( repository, proxyAuthContext ); + wagonAuth = getAuthenticationInfo(repoAuthContext); + wagonProxy = getProxy(repository, proxyAuthContext); headers = new Properties(); - headers.put( "User-Agent", ConfigUtils.getString( session, ConfigurationProperties.DEFAULT_USER_AGENT, - ConfigurationProperties.USER_AGENT ) ); - Map headers = - ConfigUtils.getMap( session, null, ConfigurationProperties.HTTP_HEADERS + "." + repository.getId(), - ConfigurationProperties.HTTP_HEADERS ); - if ( headers != null ) - { - this.headers.putAll( headers ); + headers.put( + "User-Agent", + ConfigUtils.getString( + session, ConfigurationProperties.DEFAULT_USER_AGENT, ConfigurationProperties.USER_AGENT)); + Map headers = ConfigUtils.getMap( + session, + null, + ConfigurationProperties.HTTP_HEADERS + "." + repository.getId(), + ConfigurationProperties.HTTP_HEADERS); + if (headers != null) { + this.headers.putAll(headers); } } - private static RepositoryPermissions getPermissions( String repoId, RepositorySystemSession session ) - { + private static RepositoryPermissions getPermissions(String repoId, RepositorySystemSession session) { RepositoryPermissions result = null; RepositoryPermissions perms = new RepositoryPermissions(); String suffix = '.' + repoId; - String fileMode = ConfigUtils.getString( session, null, CONFIG_PROP_FILE_MODE + suffix ); - if ( fileMode != null ) - { - perms.setFileMode( fileMode ); + String fileMode = ConfigUtils.getString(session, null, CONFIG_PROP_FILE_MODE + suffix); + if (fileMode != null) { + perms.setFileMode(fileMode); result = perms; } - String dirMode = ConfigUtils.getString( session, null, CONFIG_PROP_DIR_MODE + suffix ); - if ( dirMode != null ) - { - perms.setDirectoryMode( dirMode ); + String dirMode = ConfigUtils.getString(session, null, CONFIG_PROP_DIR_MODE + suffix); + if (dirMode != null) { + perms.setDirectoryMode(dirMode); result = perms; } - String group = ConfigUtils.getString( session, null, CONFIG_PROP_GROUP + suffix ); - if ( group != null ) - { - perms.setGroup( group ); + String group = ConfigUtils.getString(session, null, CONFIG_PROP_GROUP + suffix); + if (group != null) { + perms.setGroup(group); result = perms; } return result; } - private AuthenticationInfo getAuthenticationInfo( final AuthenticationContext authContext ) - { + private AuthenticationInfo getAuthenticationInfo(final AuthenticationContext authContext) { AuthenticationInfo auth = null; - if ( authContext != null ) - { - auth = new AuthenticationInfo() - { + if (authContext != null) { + auth = new AuthenticationInfo() { @Override - public String getUserName() - { - return authContext.get( AuthenticationContext.USERNAME ); + public String getUserName() { + return authContext.get(AuthenticationContext.USERNAME); } @Override - public String getPassword() - { - return authContext.get( AuthenticationContext.PASSWORD ); + public String getPassword() { + return authContext.get(AuthenticationContext.PASSWORD); } @Override - public String getPrivateKey() - { - return authContext.get( AuthenticationContext.PRIVATE_KEY_PATH ); + public String getPrivateKey() { + return authContext.get(AuthenticationContext.PRIVATE_KEY_PATH); } @Override - public String getPassphrase() - { - return authContext.get( AuthenticationContext.PRIVATE_KEY_PASSPHRASE ); + public String getPassphrase() { + return authContext.get(AuthenticationContext.PRIVATE_KEY_PASSPHRASE); } }; } @@ -219,50 +206,40 @@ public String getPassphrase() return auth; } - private ProxyInfoProvider getProxy( RemoteRepository repository, final AuthenticationContext authContext ) - { + private ProxyInfoProvider getProxy(RemoteRepository repository, final AuthenticationContext authContext) { ProxyInfoProvider proxy = null; Proxy p = repository.getProxy(); - if ( p != null ) - { + if (p != null) { final ProxyInfo prox; - if ( authContext != null ) - { - prox = new ProxyInfo() - { + if (authContext != null) { + prox = new ProxyInfo() { @Override - public String getUserName() - { - return authContext.get( AuthenticationContext.USERNAME ); + public String getUserName() { + return authContext.get(AuthenticationContext.USERNAME); } @Override - public String getPassword() - { - return authContext.get( AuthenticationContext.PASSWORD ); + public String getPassword() { + return authContext.get(AuthenticationContext.PASSWORD); } @Override - public String getNtlmDomain() - { - return authContext.get( AuthenticationContext.NTLM_DOMAIN ); + public String getNtlmDomain() { + return authContext.get(AuthenticationContext.NTLM_DOMAIN); } @Override - public String getNtlmHost() - { - return authContext.get( AuthenticationContext.NTLM_WORKSTATION ); + public String getNtlmHost() { + return authContext.get(AuthenticationContext.NTLM_WORKSTATION); } }; - } - else - { + } else { prox = new ProxyInfo(); } - prox.setType( p.getType() ); - prox.setHost( p.getHost() ); - prox.setPort( p.getPort() ); + prox.setType(p.getType()); + prox.setHost(p.getHost()); + prox.setPort(p.getPort()); proxy = protocol -> prox; } @@ -270,108 +247,81 @@ public String getNtlmHost() return proxy; } - private Wagon lookupWagon() - throws Exception - { - return wagonProvider.lookup( wagonHint ); + private Wagon lookupWagon() throws Exception { + return wagonProvider.lookup(wagonHint); } - private void releaseWagon( Wagon wagon ) - { - wagonProvider.release( wagon ); + private void releaseWagon(Wagon wagon) { + wagonProvider.release(wagon); } - private void connectWagon( Wagon wagon ) - throws WagonException - { - if ( !headers.isEmpty() ) - { - try - { - Method setHttpHeaders = wagon.getClass().getMethod( "setHttpHeaders", Properties.class ); - setHttpHeaders.invoke( wagon, headers ); - } - catch ( NoSuchMethodException e ) - { + private void connectWagon(Wagon wagon) throws WagonException { + if (!headers.isEmpty()) { + try { + Method setHttpHeaders = wagon.getClass().getMethod("setHttpHeaders", Properties.class); + setHttpHeaders.invoke(wagon, headers); + } catch (NoSuchMethodException e) { // normal for non-http wagons - } - catch ( InvocationTargetException | IllegalAccessException | RuntimeException e ) - { - LOGGER.debug( "Could not set user agent for Wagon {}", wagon.getClass().getName(), e ); + } catch (InvocationTargetException | IllegalAccessException | RuntimeException e) { + LOGGER.debug( + "Could not set user agent for Wagon {}", + wagon.getClass().getName(), + e); } } - int connectTimeout = - ConfigUtils.getInteger( session, ConfigurationProperties.DEFAULT_CONNECT_TIMEOUT, - ConfigurationProperties.CONNECT_TIMEOUT ); - int requestTimeout = - ConfigUtils.getInteger( session, ConfigurationProperties.DEFAULT_REQUEST_TIMEOUT, - ConfigurationProperties.REQUEST_TIMEOUT ); - - wagon.setTimeout( Math.max( Math.max( connectTimeout, requestTimeout ), 0 ) ); - - wagon.setInteractive( ConfigUtils.getBoolean( session, ConfigurationProperties.DEFAULT_INTERACTIVE, - ConfigurationProperties.INTERACTIVE ) ); - - Object configuration = ConfigUtils.getObject( session, null, CONFIG_PROP_CONFIG + "." + repository.getId() ); - if ( configuration != null && wagonConfigurator != null ) - { - try - { - wagonConfigurator.configure( wagon, configuration ); - } - catch ( Exception e ) - { - LOGGER.warn( "Could not apply configuration for {} to Wagon {}", - repository.getId(), wagon.getClass().getName(), e ); + int connectTimeout = ConfigUtils.getInteger( + session, ConfigurationProperties.DEFAULT_CONNECT_TIMEOUT, ConfigurationProperties.CONNECT_TIMEOUT); + int requestTimeout = ConfigUtils.getInteger( + session, ConfigurationProperties.DEFAULT_REQUEST_TIMEOUT, ConfigurationProperties.REQUEST_TIMEOUT); + + wagon.setTimeout(Math.max(Math.max(connectTimeout, requestTimeout), 0)); + + wagon.setInteractive(ConfigUtils.getBoolean( + session, ConfigurationProperties.DEFAULT_INTERACTIVE, ConfigurationProperties.INTERACTIVE)); + + Object configuration = ConfigUtils.getObject(session, null, CONFIG_PROP_CONFIG + "." + repository.getId()); + if (configuration != null && wagonConfigurator != null) { + try { + wagonConfigurator.configure(wagon, configuration); + } catch (Exception e) { + LOGGER.warn( + "Could not apply configuration for {} to Wagon {}", + repository.getId(), + wagon.getClass().getName(), + e); } } - wagon.connect( wagonRepo, wagonAuth, wagonProxy ); + wagon.connect(wagonRepo, wagonAuth, wagonProxy); } - private void disconnectWagon( Wagon wagon ) - { - try - { - if ( wagon != null ) - { + private void disconnectWagon(Wagon wagon) { + try { + if (wagon != null) { wagon.disconnect(); } - } - catch ( ConnectionException e ) - { - LOGGER.debug( "Could not disconnect Wagon {}", wagon, e ); + } catch (ConnectionException e) { + LOGGER.debug("Could not disconnect Wagon {}", wagon, e); } } - private Wagon pollWagon() - throws Exception - { + private Wagon pollWagon() throws Exception { Wagon wagon = wagons.poll(); - if ( wagon == null ) - { - try - { + if (wagon == null) { + try { wagon = lookupWagon(); - connectWagon( wagon ); - } - catch ( Exception e ) - { - releaseWagon( wagon ); + connectWagon(wagon); + } catch (Exception e) { + releaseWagon(wagon); throw e; } - } - else if ( wagon.getRepository() == null ) - { - try - { - connectWagon( wagon ); - } - catch ( Exception e ) - { - wagons.add( wagon ); + } else if (wagon.getRepository() == null) { + try { + connectWagon(wagon); + } catch (Exception e) { + wagons.add(wagon); throw e; } } @@ -380,166 +330,121 @@ else if ( wagon.getRepository() == null ) } @Override - public int classify( Throwable error ) - { - if ( error instanceof ResourceDoesNotExistException ) - { + public int classify(Throwable error) { + if (error instanceof ResourceDoesNotExistException) { return ERROR_NOT_FOUND; } return ERROR_OTHER; } @Override - public void peek( PeekTask task ) - throws Exception - { - execute( task, new PeekTaskRunner( task ) ); + public void peek(PeekTask task) throws Exception { + execute(task, new PeekTaskRunner(task)); } @Override - public void get( GetTask task ) - throws Exception - { - execute( task, new GetTaskRunner( task ) ); + public void get(GetTask task) throws Exception { + execute(task, new GetTaskRunner(task)); } @Override - public void put( PutTask task ) - throws Exception - { - execute( task, new PutTaskRunner( task ) ); + public void put(PutTask task) throws Exception { + execute(task, new PutTaskRunner(task)); } - private void execute( TransportTask task, TaskRunner runner ) - throws Exception - { - Objects.requireNonNull( task, "task cannot be null" ); + private void execute(TransportTask task, TaskRunner runner) throws Exception { + Objects.requireNonNull(task, "task cannot be null"); - if ( closed.get() ) - { - throw new IllegalStateException( "transporter closed, cannot execute task " + task ); + if (closed.get()) { + throw new IllegalStateException("transporter closed, cannot execute task " + task); } - try - { - WagonTransferListener listener = new WagonTransferListener( task.getListener() ); + try { + WagonTransferListener listener = new WagonTransferListener(task.getListener()); Wagon wagon = pollWagon(); - try - { - wagon.addTransferListener( listener ); - runner.run( wagon ); + try { + wagon.addTransferListener(listener); + runner.run(wagon); + } finally { + wagon.removeTransferListener(listener); + wagons.add(wagon); } - finally - { - wagon.removeTransferListener( listener ); - wagons.add( wagon ); - } - } - catch ( RuntimeException e ) - { - throw WagonCancelledException.unwrap( e ); + } catch (RuntimeException e) { + throw WagonCancelledException.unwrap(e); } } @Override - public void close() - { - if ( closed.compareAndSet( false, true ) ) - { - AuthenticationContext.close( repoAuthContext ); - AuthenticationContext.close( proxyAuthContext ); - - for ( Wagon wagon = wagons.poll(); wagon != null; wagon = wagons.poll() ) - { - disconnectWagon( wagon ); - releaseWagon( wagon ); + public void close() { + if (closed.compareAndSet(false, true)) { + AuthenticationContext.close(repoAuthContext); + AuthenticationContext.close(proxyAuthContext); + + for (Wagon wagon = wagons.poll(); wagon != null; wagon = wagons.poll()) { + disconnectWagon(wagon); + releaseWagon(wagon); } } } - private interface TaskRunner - { - - void run( Wagon wagon ) - throws IOException, WagonException; + private interface TaskRunner { + void run(Wagon wagon) throws IOException, WagonException; } - private static class PeekTaskRunner - implements TaskRunner - { + private static class PeekTaskRunner implements TaskRunner { private final PeekTask task; - PeekTaskRunner( PeekTask task ) - { + PeekTaskRunner(PeekTask task) { this.task = task; } @Override - public void run( Wagon wagon ) - throws WagonException - { + public void run(Wagon wagon) throws WagonException { String src = task.getLocation().toString(); - if ( !wagon.resourceExists( src ) ) - { - throw new ResourceDoesNotExistException( "Could not find " + src + " in " - + wagon.getRepository().getUrl() ); + if (!wagon.resourceExists(src)) { + throw new ResourceDoesNotExistException( + "Could not find " + src + " in " + wagon.getRepository().getUrl()); } } - } - private static class GetTaskRunner - implements TaskRunner - { + private static class GetTaskRunner implements TaskRunner { private final GetTask task; - GetTaskRunner( GetTask task ) - { + GetTaskRunner(GetTask task) { this.task = task; } @Override - public void run( Wagon wagon ) - throws IOException, WagonException - { + public void run(Wagon wagon) throws IOException, WagonException { final String src = task.getLocation().toString(); final File file = task.getDataFile(); - if ( file == null && wagon instanceof StreamingWagon ) - { - try ( OutputStream dst = task.newOutputStream() ) - { - ( (StreamingWagon) wagon ).getToStream( src, dst ); + if (file == null && wagon instanceof StreamingWagon) { + try (OutputStream dst = task.newOutputStream()) { + ((StreamingWagon) wagon).getToStream(src, dst); } - } - else - { + } else { // if file == null -> $TMP used, otherwise we place tmp file next to file - try ( FileUtils.TempFile tempFile = file == null ? FileUtils.newTempFile() - : FileUtils.newTempFile( file.toPath() ) ) - { + try (FileUtils.TempFile tempFile = + file == null ? FileUtils.newTempFile() : FileUtils.newTempFile(file.toPath())) { File dst = tempFile.getPath().toFile(); - wagon.get( src, dst ); + wagon.get(src, dst); /* * NOTE: Wagon (1.0-beta-6) doesn't create the destination file when transferring a 0-byte * resource. So if the resource we asked for didn't cause any exception but doesn't show up in * the dst file either, Wagon tells us in its weird way the file is empty. */ - if ( !dst.exists() && !dst.createNewFile() ) - { - throw new IOException( String.format( "Failure creating file '%s'.", dst.getAbsolutePath() ) ); + if (!dst.exists() && !dst.createNewFile()) { + throw new IOException(String.format("Failure creating file '%s'.", dst.getAbsolutePath())); } - if ( file != null ) - { - ( (FileUtils.CollocatedTempFile) tempFile ).move(); - } - else - { - try ( OutputStream outputStream = task.newOutputStream() ) - { - Files.copy( dst.toPath(), outputStream ); + if (file != null) { + ((FileUtils.CollocatedTempFile) tempFile).move(); + } else { + try (OutputStream outputStream = task.newOutputStream()) { + Files.copy(dst.toPath(), outputStream); } } } @@ -547,45 +452,32 @@ public void run( Wagon wagon ) } } - private static class PutTaskRunner - implements TaskRunner - { + private static class PutTaskRunner implements TaskRunner { private final PutTask task; - PutTaskRunner( PutTask task ) - { + PutTaskRunner(PutTask task) { this.task = task; } @Override - public void run( Wagon wagon ) - throws WagonException, IOException - { + public void run(Wagon wagon) throws WagonException, IOException { final String dst = task.getLocation().toString(); final File file = task.getDataFile(); - if ( file == null && wagon instanceof StreamingWagon ) - { - try ( InputStream src = task.newInputStream() ) - { + if (file == null && wagon instanceof StreamingWagon) { + try (InputStream src = task.newInputStream()) { // StreamingWagon uses an internal buffer on src input stream. - ( (StreamingWagon) wagon ).putFromStream( src, dst, task.getDataLength(), -1 ); + ((StreamingWagon) wagon).putFromStream(src, dst, task.getDataLength(), -1); } - } - else if ( file == null ) - { - try ( FileUtils.TempFile tempFile = FileUtils.newTempFile() ) - { - try ( InputStream inputStream = task.newInputStream() ) - { - Files.copy( inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING ); + } else if (file == null) { + try (FileUtils.TempFile tempFile = FileUtils.newTempFile()) { + try (InputStream inputStream = task.newInputStream()) { + Files.copy(inputStream, tempFile.getPath(), StandardCopyOption.REPLACE_EXISTING); } - wagon.put( tempFile.getPath().toFile(), dst ); + wagon.put(tempFile.getPath().toFile(), dst); } - } - else - { - wagon.put( file, dst ); + } else { + wagon.put(file, dst); } } } diff --git a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransporterFactory.java b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransporterFactory.java index c98fef3ff..2a6ffd59d 100644 --- a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransporterFactory.java +++ b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/WagonTransporterFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import javax.inject.Inject; import javax.inject.Named; @@ -37,10 +36,8 @@ * that this factory merely serves as an adapter to the Wagon API and by itself does not provide any transport services * unless one or more wagon implementations are registered with the {@link WagonProvider}. */ -@Named( "wagon" ) -public final class WagonTransporterFactory - implements TransporterFactory, Service -{ +@Named("wagon") +public final class WagonTransporterFactory implements TransporterFactory, Service { private WagonProvider wagonProvider; @@ -53,23 +50,20 @@ public final class WagonTransporterFactory * by clients, the new factory needs to be configured via its various mutators before first use or runtime errors * will occur. */ - public WagonTransporterFactory() - { + public WagonTransporterFactory() { // enables default constructor } @Inject - WagonTransporterFactory( WagonProvider wagonProvider, WagonConfigurator wagonConfigurator ) - { - setWagonProvider( wagonProvider ); - setWagonConfigurator( wagonConfigurator ); + WagonTransporterFactory(WagonProvider wagonProvider, WagonConfigurator wagonConfigurator) { + setWagonProvider(wagonProvider); + setWagonConfigurator(wagonConfigurator); } @Override - public void initService( ServiceLocator locator ) - { - setWagonProvider( locator.getService( WagonProvider.class ) ); - setWagonConfigurator( locator.getService( WagonConfigurator.class ) ); + public void initService(ServiceLocator locator) { + setWagonProvider(locator.getService(WagonProvider.class)); + setWagonConfigurator(locator.getService(WagonConfigurator.class)); } /** @@ -78,8 +72,7 @@ public void initService( ServiceLocator locator ) * @param wagonProvider The wagon provider to use, may be {@code null}. * @return This factory for chaining, never {@code null}. */ - public WagonTransporterFactory setWagonProvider( WagonProvider wagonProvider ) - { + public WagonTransporterFactory setWagonProvider(WagonProvider wagonProvider) { this.wagonProvider = wagonProvider; return this; } @@ -90,15 +83,13 @@ public WagonTransporterFactory setWagonProvider( WagonProvider wagonProvider ) * @param wagonConfigurator The wagon configurator to use, may be {@code null}. * @return This factory for chaining, never {@code null}. */ - public WagonTransporterFactory setWagonConfigurator( WagonConfigurator wagonConfigurator ) - { + public WagonTransporterFactory setWagonConfigurator(WagonConfigurator wagonConfigurator) { this.wagonConfigurator = wagonConfigurator; return this; } @Override - public float getPriority() - { + public float getPriority() { return priority; } @@ -108,20 +99,17 @@ public float getPriority() * @param priority The priority. * @return This component for chaining, never {@code null}. */ - public WagonTransporterFactory setPriority( float priority ) - { + public WagonTransporterFactory setPriority(float priority) { this.priority = priority; return this; } @Override - public Transporter newInstance( RepositorySystemSession session, RemoteRepository repository ) - throws NoTransporterException - { - Objects.requireNonNull( session, "session cannot be null" ); - Objects.requireNonNull( repository, "repository cannot be null" ); + public Transporter newInstance(RepositorySystemSession session, RemoteRepository repository) + throws NoTransporterException { + Objects.requireNonNull(session, "session cannot be null"); + Objects.requireNonNull(repository, "repository cannot be null"); - return new WagonTransporter( wagonProvider, wagonConfigurator, repository, session ); + return new WagonTransporter(wagonProvider, wagonConfigurator, repository, session); } - } diff --git a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/package-info.java b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/package-info.java index 82df9aced..dc52fe154 100644 --- a/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/package-info.java +++ b/maven-resolver-transport-wagon/src/main/java/org/eclipse/aether/transport/wagon/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Support for downloads/uploads using Apache Maven Wagon. */ package org.eclipse.aether.transport.wagon; - diff --git a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/AbstractWagonTransporterTest.java b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/AbstractWagonTransporterTest.java index cd6bd556b..9c440154f 100644 --- a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/AbstractWagonTransporterTest.java +++ b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/AbstractWagonTransporterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,10 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +package org.eclipse.aether.transport.wagon; import java.io.File; import java.net.URI; @@ -51,10 +46,13 @@ import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** */ -public abstract class AbstractWagonTransporterTest -{ +public abstract class AbstractWagonTransporterTest { private DefaultRepositorySystemSession session; @@ -68,67 +66,52 @@ public abstract class AbstractWagonTransporterTest protected abstract Wagon newWagon(); - private RemoteRepository newRepo( String url ) - { - return new RemoteRepository.Builder( "test", "default", url ).build(); + private RemoteRepository newRepo(String url) { + return new RemoteRepository.Builder("test", "default", url).build(); } - private void newTransporter( String url ) - throws Exception - { - newTransporter( newRepo( url ) ); + private void newTransporter(String url) throws Exception { + newTransporter(newRepo(url)); } - private void newTransporter( RemoteRepository repo ) - throws Exception - { - if ( transporter != null ) - { + private void newTransporter(RemoteRepository repo) throws Exception { + if (transporter != null) { transporter.close(); transporter = null; } - transporter = factory.newInstance( session, repo ); + transporter = factory.newInstance(session, repo); } @Before - public void setUp() - throws Exception - { + public void setUp() throws Exception { session = TestUtils.newSession(); - factory = new WagonTransporterFactory( new WagonProvider() - { - public Wagon lookup( String roleHint ) - { - if ( "mem".equalsIgnoreCase( roleHint ) ) - { - return newWagon(); - } - throw new IllegalArgumentException( "unknown wagon role: " + roleHint ); - } - - public void release( Wagon wagon ) - { - } - }, new WagonConfigurator() - { - public void configure( Wagon wagon, Object configuration ) - { - ( (Configurable) wagon ).setConfiguration( configuration ); - } - } ); - id = UUID.randomUUID().toString().replace( "-", "" ); - fs = MemWagonUtils.getFilesystem( id ); - fs.put( "file.txt", "test" ); - fs.put( "empty.txt", "" ); - fs.put( "some space.txt", "space" ); - newTransporter( "mem://" + id ); + factory = new WagonTransporterFactory( + new WagonProvider() { + public Wagon lookup(String roleHint) { + if ("mem".equalsIgnoreCase(roleHint)) { + return newWagon(); + } + throw new IllegalArgumentException("unknown wagon role: " + roleHint); + } + + public void release(Wagon wagon) {} + }, + new WagonConfigurator() { + public void configure(Wagon wagon, Object configuration) { + ((Configurable) wagon).setConfiguration(configuration); + } + }); + id = UUID.randomUUID().toString().replace("-", ""); + fs = MemWagonUtils.getFilesystem(id); + fs.put("file.txt", "test"); + fs.put("empty.txt", ""); + fs.put("some space.txt", "space"); + newTransporter("mem://" + id); } @After - public void tearDown() - { - if ( transporter != null ) - { + public void tearDown() { + if (transporter != null) { transporter.close(); transporter = null; } @@ -137,396 +120,323 @@ public void tearDown() } @Test - public void testClassify() - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( new TransferFailedException( "test" ) ) ); - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( new ResourceDoesNotExistException( "test" ) ) ); + public void testClassify() { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(new TransferFailedException("test"))); + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(new ResourceDoesNotExistException("test"))); } @Test - public void testPeek() - throws Exception - { - transporter.peek( new PeekTask( URI.create( "file.txt" ) ) ); + public void testPeek() throws Exception { + transporter.peek(new PeekTask(URI.create("file.txt"))); } @Test - public void testPeek_NotFound() - throws Exception - { - try - { - transporter.peek( new PeekTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( ResourceDoesNotExistException e ) - { - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( e ) ); + public void testPeek_NotFound() throws Exception { + try { + transporter.peek(new PeekTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (ResourceDoesNotExistException e) { + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e)); } } @Test - public void testPeek_Closed() - throws Exception - { + public void testPeek_Closed() throws Exception { transporter.close(); - try - { - transporter.peek( new PeekTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.peek(new PeekTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testGet_ToMemory() - throws Exception - { + public void testGet_ToMemory() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "file.txt" ) ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", task.getDataString() ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( task.getDataString(), new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("file.txt")).setListener(listener); + transporter.get(task); + assertEquals("test", task.getDataString()); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals(task.getDataString(), new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_ToFile() - throws Exception - { - File file = TestFileUtils.createTempFile( "failure" ); + public void testGet_ToFile() throws Exception { + File file = TestFileUtils.createTempFile("failure"); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "file.txt" ) ).setDataFile( file ).setListener( listener ); - transporter.get( task ); - assertEquals( "test", TestFileUtils.readString( file ) ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "test", new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("file.txt")).setDataFile(file).setListener(listener); + transporter.get(task); + assertEquals("test", TestFileUtils.readString(file)); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("test", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_EmptyResource() - throws Exception - { - File file = TestFileUtils.createTempFile( "failure" ); - assertTrue( file.delete() && !file.exists() ); + public void testGet_EmptyResource() throws Exception { + File file = TestFileUtils.createTempFile("failure"); + assertTrue(file.delete() && !file.exists()); RecordingTransportListener listener = new RecordingTransportListener(); - GetTask task = new GetTask( URI.create( "empty.txt" ) ).setDataFile( file ).setListener( listener ); - transporter.get( task ); - assertEquals( "", TestFileUtils.readString( file ) ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 0L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); - assertEquals( "", new String( listener.baos.toByteArray(), StandardCharsets.UTF_8 ) ); + GetTask task = new GetTask(URI.create("empty.txt")).setDataFile(file).setListener(listener); + transporter.get(task); + assertEquals("", TestFileUtils.readString(file)); + assertEquals(0L, listener.dataOffset); + assertEquals(0L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); + assertEquals("", new String(listener.baos.toByteArray(), StandardCharsets.UTF_8)); } @Test - public void testGet_EncodedResourcePath() - throws Exception - { - GetTask task = new GetTask( URI.create( "some%20space.txt" ) ); - transporter.get( task ); - assertEquals( "space", task.getDataString() ); + public void testGet_EncodedResourcePath() throws Exception { + GetTask task = new GetTask(URI.create("some%20space.txt")); + transporter.get(task); + assertEquals("space", task.getDataString()); } @Test - public void testGet_FileHandleLeak() - throws Exception - { - for ( int i = 0; i < 100; i++ ) - { - File file = TestFileUtils.createTempFile( "failure" ); - transporter.get( new GetTask( URI.create( "file.txt" ) ).setDataFile( file ) ); - assertTrue( i + ", " + file.getAbsolutePath(), file.delete() ); + public void testGet_FileHandleLeak() throws Exception { + for (int i = 0; i < 100; i++) { + File file = TestFileUtils.createTempFile("failure"); + transporter.get(new GetTask(URI.create("file.txt")).setDataFile(file)); + assertTrue(i + ", " + file.getAbsolutePath(), file.delete()); } } @Test - public void testGet_NotFound() - throws Exception - { - try - { - transporter.get( new GetTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( ResourceDoesNotExistException e ) - { - assertEquals( Transporter.ERROR_NOT_FOUND, transporter.classify( e ) ); + public void testGet_NotFound() throws Exception { + try { + transporter.get(new GetTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (ResourceDoesNotExistException e) { + assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e)); } } @Test - public void testGet_Closed() - throws Exception - { + public void testGet_Closed() throws Exception { transporter.close(); - try - { - transporter.get( new GetTask( URI.create( "file.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.get(new GetTask(URI.create("file.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testGet_StartCancelled() - throws Exception - { + public void testGet_StartCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelStart = true; - GetTask task = new GetTask( URI.create( "file.txt" ) ).setListener( listener ); - transporter.get( task ); - assertEquals( 1, listener.startedCount ); + GetTask task = new GetTask(URI.create("file.txt")).setListener(listener); + transporter.get(task); + assertEquals(1, listener.startedCount); } @Test - public void testGet_ProgressCancelled() - throws Exception - { + public void testGet_ProgressCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelProgress = true; - GetTask task = new GetTask( URI.create( "file.txt" ) ).setListener( listener ); - try - { - transporter.get( task ); - fail( "Expected error" ); + GetTask task = new GetTask(URI.create("file.txt")).setListener(listener); + try { + transporter.get(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); - } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 4L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 1, listener.progressedCount ); + assertEquals(0L, listener.dataOffset); + assertEquals(4L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(1, listener.progressedCount); } @Test - public void testPut_FromMemory() - throws Exception - { + public void testPut_FromMemory() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", fs.get( "file.txt" ) ); + PutTask task = new PutTask(URI.create("file.txt")).setListener(listener).setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", fs.get("file.txt")); } @Test - public void testPut_FromFile() - throws Exception - { - File file = TestFileUtils.createTempFile( "upload" ); + public void testPut_FromFile() throws Exception { + File file = TestFileUtils.createTempFile("upload"); RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "file.txt" ) ).setListener( listener ).setDataFile( file ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", fs.get( "file.txt" ) ); + PutTask task = new PutTask(URI.create("file.txt")).setListener(listener).setDataFile(file); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", fs.get("file.txt")); } @Test - public void testPut_EmptyResource() - throws Exception - { + public void testPut_EmptyResource() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "file.txt" ) ).setListener( listener ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 0L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 0, listener.progressedCount ); - assertEquals( "", fs.get( "file.txt" ) ); + PutTask task = new PutTask(URI.create("file.txt")).setListener(listener); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(0L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(0, listener.progressedCount); + assertEquals("", fs.get("file.txt")); } @Test - public void testPut_NonExistentParentDir() - throws Exception - { + public void testPut_NonExistentParentDir() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = - new PutTask( URI.create( "dir/sub/dir/file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "upload", fs.get( "dir/sub/dir/file.txt" ) ); + PutTask task = new PutTask(URI.create("dir/sub/dir/file.txt")) + .setListener(listener) + .setDataString("upload"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("upload", fs.get("dir/sub/dir/file.txt")); } @Test - public void testPut_EncodedResourcePath() - throws Exception - { + public void testPut_EncodedResourcePath() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); - PutTask task = new PutTask( URI.create( "some%20space.txt" ) ).setListener( listener ).setDataString( "OK" ); - transporter.put( task ); - assertEquals( 0L, listener.dataOffset ); - assertEquals( 2L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertTrue( "Count: " + listener.progressedCount, listener.progressedCount > 0 ); - assertEquals( "OK", fs.get( "some space.txt" ) ); + PutTask task = new PutTask(URI.create("some%20space.txt")) + .setListener(listener) + .setDataString("OK"); + transporter.put(task); + assertEquals(0L, listener.dataOffset); + assertEquals(2L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertTrue("Count: " + listener.progressedCount, listener.progressedCount > 0); + assertEquals("OK", fs.get("some space.txt")); } @Test - public void testPut_FileHandleLeak() - throws Exception - { - for ( int i = 0; i < 100; i++ ) - { - File src = TestFileUtils.createTempFile( "upload" ); - transporter.put( new PutTask( URI.create( "file.txt" ) ).setDataFile( src ) ); - assertTrue( i + ", " + src.getAbsolutePath(), src.delete() ); + public void testPut_FileHandleLeak() throws Exception { + for (int i = 0; i < 100; i++) { + File src = TestFileUtils.createTempFile("upload"); + transporter.put(new PutTask(URI.create("file.txt")).setDataFile(src)); + assertTrue(i + ", " + src.getAbsolutePath(), src.delete()); } } @Test - public void testPut_Closed() - throws Exception - { + public void testPut_Closed() throws Exception { transporter.close(); - try - { - transporter.put( new PutTask( URI.create( "missing.txt" ) ) ); - fail( "Expected error" ); - } - catch ( IllegalStateException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); + try { + transporter.put(new PutTask(URI.create("missing.txt"))); + fail("Expected error"); + } catch (IllegalStateException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } } @Test - public void testPut_StartCancelled() - throws Exception - { + public void testPut_StartCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelStart = true; - PutTask task = new PutTask( URI.create( "file.txt" ) ).setListener( listener ).setDataString( "upload" ); - transporter.put( task ); - assertEquals( 1, listener.startedCount ); + PutTask task = new PutTask(URI.create("file.txt")).setListener(listener).setDataString("upload"); + transporter.put(task); + assertEquals(1, listener.startedCount); } @Test - public void testPut_ProgressCancelled() - throws Exception - { + public void testPut_ProgressCancelled() throws Exception { RecordingTransportListener listener = new RecordingTransportListener(); listener.cancelProgress = true; - PutTask task = new PutTask( URI.create( "file.txt" ) ).setListener( listener ).setDataString( "upload" ); - try - { - transporter.put( task ); - fail( "Expected error" ); + PutTask task = new PutTask(URI.create("file.txt")).setListener(listener).setDataString("upload"); + try { + transporter.put(task); + fail("Expected error"); + } catch (TransferCancelledException e) { + assertEquals(Transporter.ERROR_OTHER, transporter.classify(e)); } - catch ( TransferCancelledException e ) - { - assertEquals( Transporter.ERROR_OTHER, transporter.classify( e ) ); - } - assertEquals( 0L, listener.dataOffset ); - assertEquals( 6L, listener.dataLength ); - assertEquals( 1, listener.startedCount ); - assertEquals( 1, listener.progressedCount ); + assertEquals(0L, listener.dataOffset); + assertEquals(6L, listener.dataLength); + assertEquals(1, listener.startedCount); + assertEquals(1, listener.progressedCount); } - @Test( expected = NoTransporterException.class ) - public void testInit_BadProtocol() - throws Exception - { - newTransporter( "bad:/void" ); + @Test(expected = NoTransporterException.class) + public void testInit_BadProtocol() throws Exception { + newTransporter("bad:/void"); } @Test - public void testInit_CaseInsensitiveProtocol() - throws Exception - { - newTransporter( "mem:/void" ); - newTransporter( "MEM:/void" ); - newTransporter( "mEm:/void" ); + public void testInit_CaseInsensitiveProtocol() throws Exception { + newTransporter("mem:/void"); + newTransporter("MEM:/void"); + newTransporter("mEm:/void"); } @Test - public void testInit_Configuration() - throws Exception - { - session.setConfigProperty( "aether.connector.wagon.config.test", "passed" ); - newTransporter( "mem://" + id + "?config=passed" ); - transporter.peek( new PeekTask( URI.create( "file.txt" ) ) ); + public void testInit_Configuration() throws Exception { + session.setConfigProperty("aether.connector.wagon.config.test", "passed"); + newTransporter("mem://" + id + "?config=passed"); + transporter.peek(new PeekTask(URI.create("file.txt"))); } @Test - public void testInit_UserAgent() - throws Exception - { - session.setConfigProperty( ConfigurationProperties.USER_AGENT, "Test/1.0" ); - newTransporter( "mem://" + id + "?userAgent=Test/1.0" ); - transporter.peek( new PeekTask( URI.create( "file.txt" ) ) ); + public void testInit_UserAgent() throws Exception { + session.setConfigProperty(ConfigurationProperties.USER_AGENT, "Test/1.0"); + newTransporter("mem://" + id + "?userAgent=Test/1.0"); + transporter.peek(new PeekTask(URI.create("file.txt"))); } @Test - public void testInit_Timeout() - throws Exception - { - session.setConfigProperty( ConfigurationProperties.REQUEST_TIMEOUT, "12345678" ); - newTransporter( "mem://" + id + "?requestTimeout=12345678" ); - transporter.peek( new PeekTask( URI.create( "file.txt" ) ) ); + public void testInit_Timeout() throws Exception { + session.setConfigProperty(ConfigurationProperties.REQUEST_TIMEOUT, "12345678"); + newTransporter("mem://" + id + "?requestTimeout=12345678"); + transporter.peek(new PeekTask(URI.create("file.txt"))); } @Test - public void testInit_ServerAuth() - throws Exception - { - String url = - "mem://" + id + "?serverUsername=testuser&serverPassword=testpass" + public void testInit_ServerAuth() throws Exception { + String url = "mem://" + id + "?serverUsername=testuser&serverPassword=testpass" + "&serverPrivateKey=testkey&serverPassphrase=testphrase"; - Authentication auth = - new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).addPrivateKey( "testkey", - "testphrase" ).build(); - RemoteRepository repo = - new RemoteRepository.Builder( "test", "default", url ).setAuthentication( auth ).build(); - newTransporter( repo ); - transporter.peek( new PeekTask( URI.create( "file.txt" ) ) ); + Authentication auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .addPrivateKey("testkey", "testphrase") + .build(); + RemoteRepository repo = new RemoteRepository.Builder("test", "default", url) + .setAuthentication(auth) + .build(); + newTransporter(repo); + transporter.peek(new PeekTask(URI.create("file.txt"))); } @Test - public void testInit_Proxy() - throws Exception - { + public void testInit_Proxy() throws Exception { String url = "mem://" + id + "?proxyHost=testhost&proxyPort=8888"; - RemoteRepository repo = - new RemoteRepository.Builder( "test", "default", url ).setProxy( new Proxy( "http", "testhost", 8888 ) ).build(); - newTransporter( repo ); - transporter.peek( new PeekTask( URI.create( "file.txt" ) ) ); + RemoteRepository repo = new RemoteRepository.Builder("test", "default", url) + .setProxy(new Proxy("http", "testhost", 8888)) + .build(); + newTransporter(repo); + transporter.peek(new PeekTask(URI.create("file.txt"))); } @Test - public void testInit_ProxyAuth() - throws Exception - { + public void testInit_ProxyAuth() throws Exception { String url = "mem://" + id + "?proxyUsername=testuser&proxyPassword=testpass"; - Authentication auth = new AuthenticationBuilder().addUsername( "testuser" ).addPassword( "testpass" ).build(); - RemoteRepository repo = - new RemoteRepository.Builder( "test", "default", url ).setProxy( new Proxy( "http", "testhost", 8888, auth ) ).build(); - newTransporter( repo ); - transporter.peek( new PeekTask( URI.create( "file.txt" ) ) ); + Authentication auth = new AuthenticationBuilder() + .addUsername("testuser") + .addPassword("testpass") + .build(); + RemoteRepository repo = new RemoteRepository.Builder("test", "default", url) + .setProxy(new Proxy("http", "testhost", 8888, auth)) + .build(); + newTransporter(repo); + transporter.peek(new PeekTask(URI.create("file.txt"))); } - } diff --git a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/Configurable.java b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/Configurable.java index 9a90f6ffc..845c6f0a4 100644 --- a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/Configurable.java +++ b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/Configurable.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,14 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; /** */ -public interface Configurable -{ +public interface Configurable { Object getConfiguration(); - void setConfiguration( Object config ); - + void setConfiguration(Object config); } diff --git a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemStreamWagon.java b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemStreamWagon.java index 6b4be8ffb..db86f12bb 100644 --- a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemStreamWagon.java +++ b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemStreamWagon.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -40,10 +39,7 @@ /** */ -public class MemStreamWagon - extends StreamWagon - implements Configurable -{ +public class MemStreamWagon extends StreamWagon implements Configurable { private Map fs; @@ -51,77 +47,64 @@ public class MemStreamWagon private Object config; - public void setConfiguration( Object config ) - { + public void setConfiguration(Object config) { this.config = config; } - public Object getConfiguration() - { + public Object getConfiguration() { return config; } - public void setHttpHeaders( Properties httpHeaders ) - { + public void setHttpHeaders(Properties httpHeaders) { headers = httpHeaders; } @Override - protected void openConnectionInternal() - throws ConnectionException, AuthenticationException - { - fs = - MemWagonUtils.openConnection( this, getAuthenticationInfo(), - getProxyInfo( "mem", getRepository().getHost() ), headers ); + protected void openConnectionInternal() throws ConnectionException, AuthenticationException { + fs = MemWagonUtils.openConnection( + this, + getAuthenticationInfo(), + getProxyInfo("mem", getRepository().getHost()), + headers); } @Override - public void closeConnection() - throws ConnectionException - { + public void closeConnection() throws ConnectionException { fs = null; } - private String getData( String resource ) - { - return fs.get( URI.create( resource ).getSchemeSpecificPart() ); + private String getData(String resource) { + return fs.get(URI.create(resource).getSchemeSpecificPart()); } @Override - public boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException - { - String data = getData( resourceName ); + public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException { + String data = getData(resourceName); return data != null; } @Override - public void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - String data = getData( inputData.getResource().getName() ); - if ( data == null ) - { - throw new ResourceDoesNotExistException( "Missing resource: " + inputData.getResource().getName() ); + public void fillInputData(InputData inputData) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + String data = getData(inputData.getResource().getName()); + if (data == null) { + throw new ResourceDoesNotExistException( + "Missing resource: " + inputData.getResource().getName()); } - byte[] bytes = data.getBytes( StandardCharsets.UTF_8 ); - inputData.getResource().setContentLength( bytes.length ); - inputData.setInputStream( new ByteArrayInputStream( bytes ) ); + byte[] bytes = data.getBytes(StandardCharsets.UTF_8); + inputData.getResource().setContentLength(bytes.length); + inputData.setInputStream(new ByteArrayInputStream(bytes)); } @Override - public void fillOutputData( OutputData outputData ) - throws TransferFailedException - { - outputData.setOutputStream( new ByteArrayOutputStream() ); + public void fillOutputData(OutputData outputData) throws TransferFailedException { + outputData.setOutputStream(new ByteArrayOutputStream()); } @Override - protected void finishPutTransfer( Resource resource, InputStream input, OutputStream output ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - String data = new String( ( (ByteArrayOutputStream) output ).toByteArray(), StandardCharsets.UTF_8 ); - fs.put( URI.create( resource.getName() ).getSchemeSpecificPart(), data ); + protected void finishPutTransfer(Resource resource, InputStream input, OutputStream output) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { + String data = new String(((ByteArrayOutputStream) output).toByteArray(), StandardCharsets.UTF_8); + fs.put(URI.create(resource.getName()).getSchemeSpecificPart(), data); } - } diff --git a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemWagon.java b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemWagon.java index e6e46ceac..dbce687b7 100644 --- a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemWagon.java +++ b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemWagon.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -42,10 +41,7 @@ /** */ -public class MemWagon - extends AbstractWagon - implements Configurable -{ +public class MemWagon extends AbstractWagon implements Configurable { private Map fs; @@ -53,155 +49,124 @@ public class MemWagon private Object config; - public void setConfiguration( Object config ) - { + public void setConfiguration(Object config) { this.config = config; } - public Object getConfiguration() - { + public Object getConfiguration() { return config; } - public void setHttpHeaders( Properties httpHeaders ) - { + public void setHttpHeaders(Properties httpHeaders) { headers = httpHeaders; } @Override - protected void openConnectionInternal() - throws ConnectionException, AuthenticationException - { - fs = - MemWagonUtils.openConnection( this, getAuthenticationInfo(), - getProxyInfo( "mem", getRepository().getHost() ), headers ); + protected void openConnectionInternal() throws ConnectionException, AuthenticationException { + fs = MemWagonUtils.openConnection( + this, + getAuthenticationInfo(), + getProxyInfo("mem", getRepository().getHost()), + headers); } @Override - protected void closeConnection() - throws ConnectionException - { + protected void closeConnection() throws ConnectionException { fs = null; } - private String getData( String resource ) - { - return fs.get( URI.create( resource ).getSchemeSpecificPart() ); + private String getData(String resource) { + return fs.get(URI.create(resource).getSchemeSpecificPart()); } @Override - public boolean resourceExists( String resourceName ) - throws TransferFailedException, AuthorizationException - { - String data = getData( resourceName ); + public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException { + String data = getData(resourceName); return data != null; } @Override - public void get( String resourceName, File destination ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - getIfNewer( resourceName, destination, 0 ); + public void get(String resourceName, File destination) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + getIfNewer(resourceName, destination, 0); } @Override - public boolean getIfNewer( String resourceName, File destination, long timestamp ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - Resource resource = new Resource( resourceName ); - fireGetInitiated( resource, destination ); - resource.setLastModified( timestamp ); - getTransfer( resource, destination, getInputStream( resource ) ); + public boolean getIfNewer(String resourceName, File destination, long timestamp) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + Resource resource = new Resource(resourceName); + fireGetInitiated(resource, destination); + resource.setLastModified(timestamp); + getTransfer(resource, destination, getInputStream(resource)); return true; } - protected InputStream getInputStream( Resource resource ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { + protected InputStream getInputStream(Resource resource) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { InputData inputData = new InputData(); - inputData.setResource( resource ); - try - { - fillInputData( inputData ); - } - catch ( TransferFailedException | AuthorizationException | ResourceDoesNotExistException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_GET ); - cleanupGetTransfer( resource ); + inputData.setResource(resource); + try { + fillInputData(inputData); + } catch (TransferFailedException | AuthorizationException | ResourceDoesNotExistException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_GET); + cleanupGetTransfer(resource); throw e; - } - finally - { - if ( inputData.getInputStream() == null ) - { - cleanupGetTransfer( resource ); + } finally { + if (inputData.getInputStream() == null) { + cleanupGetTransfer(resource); } } return inputData.getInputStream(); } - protected void fillInputData( InputData inputData ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - String data = getData( inputData.getResource().getName() ); - if ( data == null ) - { - throw new ResourceDoesNotExistException( "Missing resource: " + inputData.getResource().getName() ); + protected void fillInputData(InputData inputData) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + String data = getData(inputData.getResource().getName()); + if (data == null) { + throw new ResourceDoesNotExistException( + "Missing resource: " + inputData.getResource().getName()); } - byte[] bytes = data.getBytes( StandardCharsets.UTF_8 ); - inputData.getResource().setContentLength( bytes.length ); - inputData.setInputStream( new ByteArrayInputStream( bytes ) ); + byte[] bytes = data.getBytes(StandardCharsets.UTF_8); + inputData.getResource().setContentLength(bytes.length); + inputData.setInputStream(new ByteArrayInputStream(bytes)); } @Override - public void put( File source, String resourceName ) - throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException - { - Resource resource = new Resource( resourceName ); - firePutInitiated( resource, source ); - resource.setContentLength( source.length() ); - resource.setLastModified( source.lastModified() ); - OutputStream os = getOutputStream( resource ); - putTransfer( resource, source, os, true ); + public void put(File source, String resourceName) + throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { + Resource resource = new Resource(resourceName); + firePutInitiated(resource, source); + resource.setContentLength(source.length()); + resource.setLastModified(source.lastModified()); + OutputStream os = getOutputStream(resource); + putTransfer(resource, source, os, true); } - protected OutputStream getOutputStream( Resource resource ) - throws TransferFailedException - { + protected OutputStream getOutputStream(Resource resource) throws TransferFailedException { OutputData outputData = new OutputData(); - outputData.setResource( resource ); - try - { - fillOutputData( outputData ); - } - catch ( TransferFailedException e ) - { - fireTransferError( resource, e, TransferEvent.REQUEST_PUT ); + outputData.setResource(resource); + try { + fillOutputData(outputData); + } catch (TransferFailedException e) { + fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw e; - } - finally - { - if ( outputData.getOutputStream() == null ) - { - cleanupPutTransfer( resource ); + } finally { + if (outputData.getOutputStream() == null) { + cleanupPutTransfer(resource); } } return outputData.getOutputStream(); } - protected void fillOutputData( OutputData outputData ) - throws TransferFailedException - { - outputData.setOutputStream( new ByteArrayOutputStream() ); + protected void fillOutputData(OutputData outputData) throws TransferFailedException { + outputData.setOutputStream(new ByteArrayOutputStream()); } @Override - protected void finishPutTransfer( Resource resource, InputStream input, OutputStream output ) - throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException - { - String data = new String( ( (ByteArrayOutputStream) output ).toByteArray(), StandardCharsets.UTF_8 ); - fs.put( URI.create( resource.getName() ).getSchemeSpecificPart(), data ); + protected void finishPutTransfer(Resource resource, InputStream input, OutputStream output) + throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { + String data = new String(((ByteArrayOutputStream) output).toByteArray(), StandardCharsets.UTF_8); + fs.put(URI.create(resource.getName()).getSchemeSpecificPart(), data); } - } diff --git a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemWagonUtils.java b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemWagonUtils.java index 993a26af7..aae705737 100644 --- a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemWagonUtils.java +++ b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/MemWagonUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import java.net.URI; import java.util.Map; @@ -33,80 +32,65 @@ /** */ -class MemWagonUtils -{ +class MemWagonUtils { private static final ConcurrentMap> mounts = new ConcurrentHashMap<>(); - public static Map getFilesystem( String id ) - { - Map fs = mounts.get( id ); - if ( fs == null ) - { + public static Map getFilesystem(String id) { + Map fs = mounts.get(id); + if (fs == null) { fs = new ConcurrentHashMap<>(); - Map prev = mounts.putIfAbsent( id, fs ); - if ( prev != null ) - { + Map prev = mounts.putIfAbsent(id, fs); + if (prev != null) { fs = prev; } } return fs; } - public static Map openConnection( Wagon wagon, AuthenticationInfo auth, ProxyInfo proxy, - Properties headers ) - throws ConnectionException, AuthenticationException - { - URI uri = URI.create( wagon.getRepository().getUrl() ); + public static Map openConnection( + Wagon wagon, AuthenticationInfo auth, ProxyInfo proxy, Properties headers) + throws ConnectionException, AuthenticationException { + URI uri = URI.create(wagon.getRepository().getUrl()); String query = uri.getQuery(); - if ( query != null ) - { - verify( query, "config", String.valueOf( ( (Configurable) wagon ).getConfiguration() ) ); + if (query != null) { + verify(query, "config", String.valueOf(((Configurable) wagon).getConfiguration())); - verify( query, "userAgent", ( headers != null ) ? headers.getProperty( "User-Agent" ) : null ); - verify( query, "requestTimeout", Integer.toString( wagon.getTimeout() ) ); + verify(query, "userAgent", (headers != null) ? headers.getProperty("User-Agent") : null); + verify(query, "requestTimeout", Integer.toString(wagon.getTimeout())); - verify( query, "serverUsername", ( auth != null ) ? auth.getUserName() : null ); - verify( query, "serverPassword", ( auth != null ) ? auth.getPassword() : null ); - verify( query, "serverPrivateKey", ( auth != null ) ? auth.getPrivateKey() : null ); - verify( query, "serverPassphrase", ( auth != null ) ? auth.getPassphrase() : null ); + verify(query, "serverUsername", (auth != null) ? auth.getUserName() : null); + verify(query, "serverPassword", (auth != null) ? auth.getPassword() : null); + verify(query, "serverPrivateKey", (auth != null) ? auth.getPrivateKey() : null); + verify(query, "serverPassphrase", (auth != null) ? auth.getPassphrase() : null); - verify( query, "proxyHost", ( proxy != null ) ? proxy.getHost() : null ); - verify( query, "proxyPort", ( proxy != null ) ? Integer.toString( proxy.getPort() ) : null ); - verify( query, "proxyUsername", ( proxy != null ) ? proxy.getUserName() : null ); - verify( query, "proxyPassword", ( proxy != null ) ? proxy.getPassword() : null ); + verify(query, "proxyHost", (proxy != null) ? proxy.getHost() : null); + verify(query, "proxyPort", (proxy != null) ? Integer.toString(proxy.getPort()) : null); + verify(query, "proxyUsername", (proxy != null) ? proxy.getUserName() : null); + verify(query, "proxyPassword", (proxy != null) ? proxy.getPassword() : null); } - return getFilesystem( uri.getHost() ); + return getFilesystem(uri.getHost()); } - private static void verify( String query, String key, String value ) - throws ConnectionException - { - int index = query.indexOf( key + "=" ); - if ( index < 0 ) - { + private static void verify(String query, String key, String value) throws ConnectionException { + int index = query.indexOf(key + "="); + if (index < 0) { return; } - String expected = query.substring( index + key.length() + 1 ); - index = expected.indexOf( "&" ); - if ( index >= 0 ) - { - expected = expected.substring( 0, index ); + String expected = query.substring(index + key.length() + 1); + index = expected.indexOf("&"); + if (index >= 0) { + expected = expected.substring(0, index); } - if ( expected.length() == 0 ) - { - if ( value != null ) - { - throw new ConnectionException( "Bad " + key + ": " + value ); + if (expected.length() == 0) { + if (value != null) { + throw new ConnectionException("Bad " + key + ": " + value); } - } - else if ( !expected.equals( value ) ) - { - throw new ConnectionException( "Bad " + key + ": " + value ); + } else if (!expected.equals(value)) { + throw new ConnectionException("Bad " + key + ": " + value); } } - } diff --git a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/PlexusSupportTest.java b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/PlexusSupportTest.java index c82e6727f..694f25e0f 100644 --- a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/PlexusSupportTest.java +++ b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/PlexusSupportTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import org.codehaus.plexus.ContainerConfiguration; import org.codehaus.plexus.PlexusTestCase; @@ -25,22 +24,16 @@ /** */ -public class PlexusSupportTest - extends PlexusTestCase -{ +public class PlexusSupportTest extends PlexusTestCase { @Override - protected void customizeContainerConfiguration( ContainerConfiguration containerConfiguration ) - { - containerConfiguration.setClassPathScanning( "cache" ); + protected void customizeContainerConfiguration(ContainerConfiguration containerConfiguration) { + containerConfiguration.setClassPathScanning("cache"); } - public void testExistenceOfPlexusComponentMetadata() - throws Exception - { - TransporterFactory factory = lookup( TransporterFactory.class, "wagon" ); - assertNotNull( factory ); - assertEquals( WagonTransporterFactory.class, factory.getClass() ); + public void testExistenceOfPlexusComponentMetadata() throws Exception { + TransporterFactory factory = lookup(TransporterFactory.class, "wagon"); + assertNotNull(factory); + assertEquals(WagonTransporterFactory.class, factory.getClass()); } - } diff --git a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/RecordingTransportListener.java b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/RecordingTransportListener.java index 3f1859d22..ec40fd177 100644 --- a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/RecordingTransportListener.java +++ b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/RecordingTransportListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import java.io.ByteArrayOutputStream; import java.nio.Buffer; @@ -26,11 +25,9 @@ import org.eclipse.aether.spi.connector.transport.TransportListener; import org.eclipse.aether.transfer.TransferCancelledException; -class RecordingTransportListener - extends TransportListener -{ +class RecordingTransportListener extends TransportListener { - public final ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 ); + public final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); public long dataOffset; @@ -45,30 +42,23 @@ class RecordingTransportListener public boolean cancelProgress; @Override - public void transportStarted( long dataOffset, long dataLength ) - throws TransferCancelledException - { + public void transportStarted(long dataOffset, long dataLength) throws TransferCancelledException { startedCount++; progressedCount = 0; this.dataLength = dataLength; this.dataOffset = dataOffset; baos.reset(); - if ( cancelStart ) - { + if (cancelStart) { throw new TransferCancelledException(); } } @Override - public void transportProgressed( ByteBuffer data ) - throws TransferCancelledException - { + public void transportProgressed(ByteBuffer data) throws TransferCancelledException { progressedCount++; - baos.write( data.array(), data.arrayOffset() + ( (Buffer) data ).position(), data.remaining() ); - if ( cancelProgress ) - { + baos.write(data.array(), data.arrayOffset() + ((Buffer) data).position(), data.remaining()); + if (cancelProgress) { throw new TransferCancelledException(); } } - } diff --git a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/StreamWagonTransporterTest.java b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/StreamWagonTransporterTest.java index c3f3fd47c..40ab98617 100644 --- a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/StreamWagonTransporterTest.java +++ b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/StreamWagonTransporterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,19 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import org.apache.maven.wagon.Wagon; /** */ -public class StreamWagonTransporterTest - extends AbstractWagonTransporterTest -{ +public class StreamWagonTransporterTest extends AbstractWagonTransporterTest { @Override - protected Wagon newWagon() - { + protected Wagon newWagon() { return new MemStreamWagon(); } - } diff --git a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/WagonTransporterTest.java b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/WagonTransporterTest.java index 5a1039960..74e673bc6 100644 --- a/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/WagonTransporterTest.java +++ b/maven-resolver-transport-wagon/src/test/java/org/eclipse/aether/transport/wagon/WagonTransporterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.transport.wagon; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,19 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.transport.wagon; import org.apache.maven.wagon.Wagon; /** */ -public class WagonTransporterTest - extends AbstractWagonTransporterTest -{ +public class WagonTransporterTest extends AbstractWagonTransporterTest { @Override - protected Wagon newWagon() - { + protected Wagon newWagon() { return new MemWagon(); } - } diff --git a/maven-resolver-util/pom.xml b/maven-resolver-util/pom.xml index 00629c451..b57e19abf 100644 --- a/maven-resolver-util/pom.xml +++ b/maven-resolver-util/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 @@ -31,9 +29,7 @@ maven-resolver-util Maven Artifact Resolver Utilities - - A collection of utility classes to ease usage of the repository system. - + A collection of utility classes to ease usage of the repository system. org.apache.maven.resolver.util diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/ChecksumUtils.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/ChecksumUtils.java index 187edddbf..90c007e79 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/ChecksumUtils.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/ChecksumUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -36,58 +35,46 @@ /** * A utility class to assist in the verification and generation of checksums. */ -public final class ChecksumUtils -{ +public final class ChecksumUtils { - private ChecksumUtils() - { + private ChecksumUtils() { // hide constructor } /** * Extracts the checksum from the specified file. - * + * * @param checksumFile The path to the checksum file, must not be {@code null}. * @return The checksum stored in the file, never {@code null}. * @throws IOException If the checksum does not exist or could not be read for other reasons. * @deprecated Use SPI FileProcessor to read and write checksum files. */ @Deprecated - public static String read( File checksumFile ) - throws IOException - { + public static String read(File checksumFile) throws IOException { String checksum = ""; - try ( BufferedReader br = new BufferedReader( new InputStreamReader( - new FileInputStream( checksumFile ), StandardCharsets.UTF_8 ), 512 ) ) - { - while ( true ) - { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(checksumFile), StandardCharsets.UTF_8), 512)) { + while (true) { String line = br.readLine(); - if ( line == null ) - { + if (line == null) { break; } line = line.trim(); - if ( line.length() > 0 ) - { + if (line.length() > 0) { checksum = line; break; } } } - if ( checksum.matches( ".+= [0-9A-Fa-f]+" ) ) - { - int lastSpacePos = checksum.lastIndexOf( ' ' ); - checksum = checksum.substring( lastSpacePos + 1 ); - } - else - { - int spacePos = checksum.indexOf( ' ' ); + if (checksum.matches(".+= [0-9A-Fa-f]+")) { + int lastSpacePos = checksum.lastIndexOf(' '); + checksum = checksum.substring(lastSpacePos + 1); + } else { + int spacePos = checksum.indexOf(' '); - if ( spacePos != -1 ) - { - checksum = checksum.substring( 0, spacePos ); + if (spacePos != -1) { + checksum = checksum.substring(0, spacePos); } } @@ -96,7 +83,7 @@ public static String read( File checksumFile ) /** * Calculates checksums for the specified file. - * + * * @param dataFile The file for which to calculate checksums, must not be {@code null}. * @param algos The names of checksum algorithms (cf. {@link MessageDigest#getInstance(String)} to use, must not be * {@code null}. @@ -106,92 +93,72 @@ public static String read( File checksumFile ) * @deprecated Use SPI checksum selector instead. */ @Deprecated - public static Map calc( File dataFile, Collection algos ) - throws IOException - { - return calc( new FileInputStream( dataFile ), algos ); + public static Map calc(File dataFile, Collection algos) throws IOException { + return calc(new FileInputStream(dataFile), algos); } /** * @deprecated Use SPI checksum selector instead. */ @Deprecated - public static Map calc( byte[] dataBytes, Collection algos ) - throws IOException - { - return calc( new ByteArrayInputStream( dataBytes ), algos ); + public static Map calc(byte[] dataBytes, Collection algos) throws IOException { + return calc(new ByteArrayInputStream(dataBytes), algos); } - private static Map calc( InputStream data, Collection algos ) - throws IOException - { + private static Map calc(InputStream data, Collection algos) throws IOException { Map results = new LinkedHashMap<>(); Map digests = new LinkedHashMap<>(); - for ( String algo : algos ) - { - try - { - digests.put( algo, MessageDigest.getInstance( algo ) ); - } - catch ( NoSuchAlgorithmException e ) - { - results.put( algo, e ); + for (String algo : algos) { + try { + digests.put(algo, MessageDigest.getInstance(algo)); + } catch (NoSuchAlgorithmException e) { + results.put(algo, e); } } - try ( InputStream in = data ) - { - for ( byte[] buffer = new byte[ 32 * 1024 ];; ) - { - int read = in.read( buffer ); - if ( read < 0 ) - { + try (InputStream in = data) { + for (byte[] buffer = new byte[32 * 1024]; ; ) { + int read = in.read(buffer); + if (read < 0) { break; } - for ( MessageDigest digest : digests.values() ) - { - digest.update( buffer, 0, read ); + for (MessageDigest digest : digests.values()) { + digest.update(buffer, 0, read); } } } - for ( Map.Entry entry : digests.entrySet() ) - { + for (Map.Entry entry : digests.entrySet()) { byte[] bytes = entry.getValue().digest(); - results.put( entry.getKey(), toHexString( bytes ) ); + results.put(entry.getKey(), toHexString(bytes)); } return results; } - /** * Creates a hexadecimal representation of the specified bytes. Each byte is converted into a two-digit hex number * and appended to the result with no separator between consecutive bytes. - * + * * @param bytes The bytes to represent in hex notation, may be be {@code null}. * @return The hexadecimal representation of the input or {@code null} if the input was {@code null}. */ - @SuppressWarnings( "checkstyle:magicnumber" ) - public static String toHexString( byte[] bytes ) - { - if ( bytes == null ) - { + @SuppressWarnings("checkstyle:magicnumber") + public static String toHexString(byte[] bytes) { + if (bytes == null) { return null; } - StringBuilder buffer = new StringBuilder( bytes.length * 2 ); + StringBuilder buffer = new StringBuilder(bytes.length * 2); - for ( byte aByte : bytes ) - { + for (byte aByte : bytes) { int b = aByte & 0xFF; - if ( b < 0x10 ) - { - buffer.append( '0' ); + if (b < 0x10) { + buffer.append('0'); } - buffer.append( Integer.toHexString( b ) ); + buffer.append(Integer.toHexString(b)); } return buffer.toString(); @@ -205,29 +172,23 @@ public static String toHexString( byte[] bytes ) * @return The byte array of the input or {@code null} if the input was {@code null}. * @since 1.8.0 */ - @SuppressWarnings( "checkstyle:magicnumber" ) - public static byte[] fromHexString( String hexString ) - { - if ( hexString == null ) - { + @SuppressWarnings("checkstyle:magicnumber") + public static byte[] fromHexString(String hexString) { + if (hexString == null) { return null; } - if ( hexString.isEmpty() ) - { + if (hexString.isEmpty()) { return new byte[] {}; } int len = hexString.length(); - if ( len % 2 != 0 ) - { - throw new IllegalArgumentException( "hexString length not even" ); + if (len % 2 != 0) { + throw new IllegalArgumentException("hexString length not even"); } - byte[] data = new byte[ len / 2 ]; - for ( int i = 0; i < len; i += 2 ) - { - data[ i / 2 ] = (byte) ( ( Character.digit( hexString.charAt( i ), 16 ) << 4 ) - + Character.digit( hexString.charAt( i + 1 ), 16 ) ); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) + ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16)); } return data; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/ConfigUtils.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/ConfigUtils.java index bee9810c2..006cc8d1a 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/ConfigUtils.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/ConfigUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util; import java.util.ArrayList; import java.util.Arrays; @@ -35,11 +34,9 @@ * * @see RepositorySystemSession#getConfigProperties() */ -public final class ConfigUtils -{ +public final class ConfigUtils { - private ConfigUtils() - { + private ConfigUtils() { // hide constructor } @@ -52,14 +49,11 @@ private ConfigUtils() * a valid value is found. * @return The property value or {@code null} if none. */ - public static Object getObject( Map properties, Object defaultValue, String... keys ) - { - for ( String key : keys ) - { - Object value = properties.get( key ); - - if ( value != null ) - { + public static Object getObject(Map properties, Object defaultValue, String... keys) { + for (String key : keys) { + Object value = properties.get(key); + + if (value != null) { return value; } } @@ -77,9 +71,8 @@ public static Object getObject( Map properties, Object defaultValue, Strin * a valid value is found. * @return The property value or {@code null} if none. */ - public static Object getObject( RepositorySystemSession session, Object defaultValue, String... keys ) - { - return getObject( session.getConfigProperties(), defaultValue, keys ); + public static Object getObject(RepositorySystemSession session, Object defaultValue, String... keys) { + return getObject(session.getConfigProperties(), defaultValue, keys); } /** @@ -92,14 +85,11 @@ public static Object getObject( RepositorySystemSession session, Object defaultV * a string value is found. * @return The property value or {@code null} if none. */ - public static String getString( Map properties, String defaultValue, String... keys ) - { - for ( String key : keys ) - { - Object value = properties.get( key ); - - if ( value instanceof String ) - { + public static String getString(Map properties, String defaultValue, String... keys) { + for (String key : keys) { + Object value = properties.get(key); + + if (value instanceof String) { return (String) value; } } @@ -118,9 +108,8 @@ public static String getString( Map properties, String defaultValue, Strin * a string value is found. * @return The property value or {@code null} if none. */ - public static String getString( RepositorySystemSession session, String defaultValue, String... keys ) - { - return getString( session.getConfigProperties(), defaultValue, keys ); + public static String getString(RepositorySystemSession session, String defaultValue, String... keys) { + return getString(session.getConfigProperties(), defaultValue, keys); } /** @@ -132,24 +121,16 @@ public static String getString( RepositorySystemSession session, String defaultV * a {@link Number} or a string representation of an {@link Integer} is found. * @return The property value. */ - public static int getInteger( Map properties, int defaultValue, String... keys ) - { - for ( String key : keys ) - { - Object value = properties.get( key ); - - if ( value instanceof Number ) - { - return ( (Number) value ).intValue(); - } - else if ( value instanceof String ) - { - try - { - return Integer.parseInt( (String) value ); - } - catch ( NumberFormatException e ) - { + public static int getInteger(Map properties, int defaultValue, String... keys) { + for (String key : keys) { + Object value = properties.get(key); + + if (value instanceof Number) { + return ((Number) value).intValue(); + } else if (value instanceof String) { + try { + return Integer.parseInt((String) value); + } catch (NumberFormatException e) { // try next key } } @@ -168,9 +149,8 @@ else if ( value instanceof String ) * a {@link Number} or a string representation of an {@link Integer} is found. * @return The property value. */ - public static int getInteger( RepositorySystemSession session, int defaultValue, String... keys ) - { - return getInteger( session.getConfigProperties(), defaultValue, keys ); + public static int getInteger(RepositorySystemSession session, int defaultValue, String... keys) { + return getInteger(session.getConfigProperties(), defaultValue, keys); } /** @@ -182,24 +162,16 @@ public static int getInteger( RepositorySystemSession session, int defaultValue, * a {@link Number} or a string representation of a {@link Long} is found. * @return The property value. */ - public static long getLong( Map properties, long defaultValue, String... keys ) - { - for ( String key : keys ) - { - Object value = properties.get( key ); - - if ( value instanceof Number ) - { - return ( (Number) value ).longValue(); - } - else if ( value instanceof String ) - { - try - { - return Long.parseLong( (String) value ); - } - catch ( NumberFormatException e ) - { + public static long getLong(Map properties, long defaultValue, String... keys) { + for (String key : keys) { + Object value = properties.get(key); + + if (value instanceof Number) { + return ((Number) value).longValue(); + } else if (value instanceof String) { + try { + return Long.parseLong((String) value); + } catch (NumberFormatException e) { // try next key } } @@ -218,9 +190,8 @@ else if ( value instanceof String ) * a {@link Number} or a string representation of a {@link Long} is found. * @return The property value. */ - public static long getLong( RepositorySystemSession session, long defaultValue, String... keys ) - { - return getLong( session.getConfigProperties(), defaultValue, keys ); + public static long getLong(RepositorySystemSession session, long defaultValue, String... keys) { + return getLong(session.getConfigProperties(), defaultValue, keys); } /** @@ -232,24 +203,16 @@ public static long getLong( RepositorySystemSession session, long defaultValue, * a {@link Number} or a string representation of a {@link Float} is found. * @return The property value. */ - public static float getFloat( Map properties, float defaultValue, String... keys ) - { - for ( String key : keys ) - { - Object value = properties.get( key ); - - if ( value instanceof Number ) - { - return ( (Number) value ).floatValue(); - } - else if ( value instanceof String ) - { - try - { - return Float.parseFloat( (String) value ); - } - catch ( NumberFormatException e ) - { + public static float getFloat(Map properties, float defaultValue, String... keys) { + for (String key : keys) { + Object value = properties.get(key); + + if (value instanceof Number) { + return ((Number) value).floatValue(); + } else if (value instanceof String) { + try { + return Float.parseFloat((String) value); + } catch (NumberFormatException e) { // try next key } } @@ -268,9 +231,8 @@ else if ( value instanceof String ) * a {@link Number} or a string representation of a {@link Float} is found. * @return The property value. */ - public static float getFloat( RepositorySystemSession session, float defaultValue, String... keys ) - { - return getFloat( session.getConfigProperties(), defaultValue, keys ); + public static float getFloat(RepositorySystemSession session, float defaultValue, String... keys) { + return getFloat(session.getConfigProperties(), defaultValue, keys); } /** @@ -282,19 +244,14 @@ public static float getFloat( RepositorySystemSession session, float defaultValu * a {@link Boolean} or a string (to be {@link Boolean#parseBoolean(String) parsed as boolean}) is found. * @return The property value. */ - public static boolean getBoolean( Map properties, boolean defaultValue, String... keys ) - { - for ( String key : keys ) - { - Object value = properties.get( key ); - - if ( value instanceof Boolean ) - { + public static boolean getBoolean(Map properties, boolean defaultValue, String... keys) { + for (String key : keys) { + Object value = properties.get(key); + + if (value instanceof Boolean) { return (Boolean) value; - } - else if ( value instanceof String ) - { - return Boolean.parseBoolean( (String) value ); + } else if (value instanceof String) { + return Boolean.parseBoolean((String) value); } } @@ -311,9 +268,8 @@ else if ( value instanceof String ) * a {@link Boolean} or a string (to be {@link Boolean#parseBoolean(String) parsed as boolean}) is found. * @return The property value. */ - public static boolean getBoolean( RepositorySystemSession session, boolean defaultValue, String... keys ) - { - return getBoolean( session.getConfigProperties(), defaultValue, keys ); + public static boolean getBoolean(RepositorySystemSession session, boolean defaultValue, String... keys) { + return getBoolean(session.getConfigProperties(), defaultValue, keys); } /** @@ -325,19 +281,14 @@ public static boolean getBoolean( RepositorySystemSession session, boolean defau * a collection is found. * @return The property value or {@code null} if none. */ - public static List getList( Map properties, List defaultValue, String... keys ) - { - for ( String key : keys ) - { - Object value = properties.get( key ); - - if ( value instanceof List ) - { + public static List getList(Map properties, List defaultValue, String... keys) { + for (String key : keys) { + Object value = properties.get(key); + + if (value instanceof List) { return (List) value; - } - else if ( value instanceof Collection ) - { - return Collections.unmodifiableList( new ArrayList<>( (Collection) value ) ); + } else if (value instanceof Collection) { + return Collections.unmodifiableList(new ArrayList<>((Collection) value)); } } @@ -354,9 +305,8 @@ else if ( value instanceof Collection ) * a collection is found. * @return The property value or {@code null} if none. */ - public static List getList( RepositorySystemSession session, List defaultValue, String... keys ) - { - return getList( session.getConfigProperties(), defaultValue, keys ); + public static List getList(RepositorySystemSession session, List defaultValue, String... keys) { + return getList(session.getConfigProperties(), defaultValue, keys); } /** @@ -368,14 +318,11 @@ public static List getList( RepositorySystemSession session, List defaultV * a map is found. * @return The property value or {@code null} if none. */ - public static Map getMap( Map properties, Map defaultValue, String... keys ) - { - for ( String key : keys ) - { - Object value = properties.get( key ); - - if ( value instanceof Map ) - { + public static Map getMap(Map properties, Map defaultValue, String... keys) { + for (String key : keys) { + Object value = properties.get(key); + + if (value instanceof Map) { return (Map) value; } } @@ -393,9 +340,8 @@ public static List getList( RepositorySystemSession session, List defaultV * a map is found. * @return The property value or {@code null} if none. */ - public static Map getMap( RepositorySystemSession session, Map defaultValue, String... keys ) - { - return getMap( session.getConfigProperties(), defaultValue, keys ); + public static Map getMap(RepositorySystemSession session, Map defaultValue, String... keys) { + return getMap(session.getConfigProperties(), defaultValue, keys); } /** @@ -404,15 +350,13 @@ public static List getList( RepositorySystemSession session, List defaultV * * @since 1.9.0 */ - public static List parseCommaSeparatedNames( String commaSeparatedNames ) - { - if ( commaSeparatedNames == null || commaSeparatedNames.trim().isEmpty() ) - { + public static List parseCommaSeparatedNames(String commaSeparatedNames) { + if (commaSeparatedNames == null || commaSeparatedNames.trim().isEmpty()) { return Collections.emptyList(); } - return Arrays.stream( commaSeparatedNames.split( "," ) ) - .filter( s -> s != null && !s.trim().isEmpty() ) - .collect( toList() ); + return Arrays.stream(commaSeparatedNames.split(",")) + .filter(s -> s != null && !s.trim().isEmpty()) + .collect(toList()); } /** @@ -421,8 +365,7 @@ public static List parseCommaSeparatedNames( String commaSeparatedNames * * @since 1.9.0 */ - public static List parseCommaSeparatedUniqueNames( String commaSeparatedNames ) - { - return parseCommaSeparatedNames( commaSeparatedNames ).stream().distinct().collect( toList() ); + public static List parseCommaSeparatedUniqueNames(String commaSeparatedNames) { + return parseCommaSeparatedNames(commaSeparatedNames).stream().distinct().collect(toList()); } } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/DirectoryUtils.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/DirectoryUtils.java index 3821b0a5f..244c7bd34 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/DirectoryUtils.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/DirectoryUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util; import java.io.IOException; import java.nio.file.Files; @@ -36,10 +35,8 @@ * @see RepositorySystemSession#getLocalRepository() * @since 1.9.0 */ -public final class DirectoryUtils -{ - private DirectoryUtils() - { +public final class DirectoryUtils { + private DirectoryUtils() { // hide constructor } @@ -62,31 +59,23 @@ private DirectoryUtils() * @return The {@link Path} instance that is resolved and backed by existing directory. * @throws IOException If some IO related errors happens. */ - public static Path resolveDirectory( String name, Path base, boolean mayCreate ) throws IOException - { - requireNonNull( name, "name is null" ); - requireNonNull( base, "base is null" ); - final Path namePath = Paths.get( name ); + public static Path resolveDirectory(String name, Path base, boolean mayCreate) throws IOException { + requireNonNull(name, "name is null"); + requireNonNull(base, "base is null"); + final Path namePath = Paths.get(name); final Path result; - if ( namePath.isAbsolute() ) - { + if (namePath.isAbsolute()) { result = namePath.normalize(); - } - else - { - result = base.resolve( namePath ).normalize(); + } else { + result = base.resolve(namePath).normalize(); } - if ( !Files.exists( result ) ) - { - if ( mayCreate ) - { - Files.createDirectories( result ); + if (!Files.exists(result)) { + if (mayCreate) { + Files.createDirectories(result); } - } - else if ( !Files.isDirectory( result ) ) - { - throw new IOException( "Path exists, but is not a directory: " + result ); + } else if (!Files.isDirectory(result)) { + throw new IOException("Path exists, but is not a directory: " + result); } return result; } @@ -106,17 +95,15 @@ else if ( !Files.isDirectory( result ) ) * @throws IOException If some IO related errors happens. * @see #resolveDirectory(String, Path, boolean) */ - public static Path resolveDirectory( RepositorySystemSession session, - String defaultName, - String nameKey, - boolean mayCreate ) - throws IOException - { - requireNonNull( session, "session is null" ); - requireNonNull( defaultName, "defaultName is null" ); - requireNonNull( nameKey, "nameKey is null" ); - requireNonNull( session.getLocalRepository().getBasedir(), "session.localRepository.basedir is null" ); - return resolveDirectory( ConfigUtils.getString( session, defaultName, nameKey ), - session.getLocalRepository().getBasedir().toPath(), mayCreate ); + public static Path resolveDirectory( + RepositorySystemSession session, String defaultName, String nameKey, boolean mayCreate) throws IOException { + requireNonNull(session, "session is null"); + requireNonNull(defaultName, "defaultName is null"); + requireNonNull(nameKey, "nameKey is null"); + requireNonNull(session.getLocalRepository().getBasedir(), "session.localRepository.basedir is null"); + return resolveDirectory( + ConfigUtils.getString(session, defaultName, nameKey), + session.getLocalRepository().getBasedir().toPath(), + mayCreate); } } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/FileUtils.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/FileUtils.java index f12d5b822..dc260d768 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/FileUtils.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/FileUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util; import java.io.Closeable; import java.io.IOException; @@ -33,18 +32,15 @@ * * @since 1.9.0 */ -public final class FileUtils -{ - private FileUtils() - { +public final class FileUtils { + private FileUtils() { // hide constructor } /** * A temporary file, that is removed when closed. */ - public interface TempFile extends Closeable - { + public interface TempFile extends Closeable { /** * Returns the path of the created temp file. */ @@ -54,8 +50,7 @@ public interface TempFile extends Closeable /** * A collocated temporary file, that resides next to a "target" file, and is removed when closed. */ - public interface CollocatedTempFile extends TempFile - { + public interface CollocatedTempFile extends TempFile { /** * Atomically moves temp file to target file it is collocated with. */ @@ -70,21 +65,17 @@ public interface CollocatedTempFile extends TempFile * This method uses {@link Files#createTempFile(String, String, java.nio.file.attribute.FileAttribute[])} to create * the temporary file on file system. */ - public static TempFile newTempFile() throws IOException - { - Path tempFile = Files.createTempFile( "resolver", "tmp" ); - return new TempFile() - { + public static TempFile newTempFile() throws IOException { + Path tempFile = Files.createTempFile("resolver", "tmp"); + return new TempFile() { @Override - public Path getPath() - { + public Path getPath() { return tempFile; } @Override - public void close() throws IOException - { - Files.deleteIfExists( tempFile ); + public void close() throws IOException { + Files.deleteIfExists(tempFile); } }; } @@ -101,30 +92,25 @@ public void close() throws IOException * This method uses {@link Path#resolve(String)} to create the temporary file path in passed in file parent * directory, but it does NOT create backing file on file system. */ - public static CollocatedTempFile newTempFile( Path file ) throws IOException - { - Path parent = requireNonNull( file.getParent(), "file must have parent" ); - Files.createDirectories( parent ); - Path tempFile = parent.resolve( file.getFileName() + "." - + Long.toUnsignedString( ThreadLocalRandom.current().nextLong() ) + ".tmp" ); - return new CollocatedTempFile() - { + public static CollocatedTempFile newTempFile(Path file) throws IOException { + Path parent = requireNonNull(file.getParent(), "file must have parent"); + Files.createDirectories(parent); + Path tempFile = parent.resolve(file.getFileName() + "." + + Long.toUnsignedString(ThreadLocalRandom.current().nextLong()) + ".tmp"); + return new CollocatedTempFile() { @Override - public Path getPath() - { + public Path getPath() { return tempFile; } @Override - public void move() throws IOException - { - Files.move( tempFile, file, StandardCopyOption.ATOMIC_MOVE ); + public void move() throws IOException { + Files.move(tempFile, file, StandardCopyOption.ATOMIC_MOVE); } @Override - public void close() throws IOException - { - Files.deleteIfExists( tempFile ); + public void close() throws IOException { + Files.deleteIfExists(tempFile); } }; } @@ -135,9 +121,8 @@ public void close() throws IOException * should be used). */ @FunctionalInterface - public interface FileWriter - { - void write( Path path ) throws IOException; + public interface FileWriter { + void write(Path path) throws IOException; } /** @@ -147,9 +132,8 @@ public interface FileWriter * @param writer the writer that will accept a {@link Path} to write content to. * @throws IOException if at any step IO problem occurs. */ - public static void writeFile( Path target, FileWriter writer ) throws IOException - { - writeFile( target, writer, false ); + public static void writeFile(Path target, FileWriter writer) throws IOException { + writeFile(target, writer, false); } /** @@ -159,9 +143,8 @@ public static void writeFile( Path target, FileWriter writer ) throws IOExceptio * @param writer the writer that will accept a {@link Path} to write content to. * @throws IOException if at any step IO problem occurs. */ - public static void writeFileWithBackup( Path target, FileWriter writer ) throws IOException - { - writeFile( target, writer, true ); + public static void writeFileWithBackup(Path target, FileWriter writer) throws IOException { + writeFile(target, writer, true); } /** @@ -175,19 +158,15 @@ public static void writeFileWithBackup( Path target, FileWriter writer ) throws * be created/overwritten. * @throws IOException if at any step IO problem occurs. */ - private static void writeFile( Path target, FileWriter writer, boolean doBackup ) throws IOException - { - requireNonNull( target, "target is null" ); - requireNonNull( writer, "writer is null" ); - Path parent = requireNonNull( target.getParent(), "target must have parent" ); - - try ( CollocatedTempFile tempFile = newTempFile( target ) ) - { - writer.write( tempFile.getPath() ); - if ( doBackup && Files.isRegularFile( target ) ) - { - Files.copy( target, parent.resolve( target.getFileName() + ".bak" ), - StandardCopyOption.REPLACE_EXISTING ); + private static void writeFile(Path target, FileWriter writer, boolean doBackup) throws IOException { + requireNonNull(target, "target is null"); + requireNonNull(writer, "writer is null"); + Path parent = requireNonNull(target.getParent(), "target must have parent"); + + try (CollocatedTempFile tempFile = newTempFile(target)) { + writer.write(tempFile.getPath()); + if (doBackup && Files.isRegularFile(target)) { + Files.copy(target, parent.resolve(target.getFileName() + ".bak"), StandardCopyOption.REPLACE_EXISTING); } tempFile.move(); } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/StringDigestUtil.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/StringDigestUtil.java index 9392fab44..6f89246fe 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/StringDigestUtil.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/StringDigestUtil.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -29,8 +28,7 @@ * * @since 1.9.0 */ -public final class StringDigestUtil -{ +public final class StringDigestUtil { private final MessageDigest digest; /** @@ -39,26 +37,20 @@ public final class StringDigestUtil * @see #sha1() * @see #sha1(String) */ - public StringDigestUtil( final String alg ) - { - try - { - this.digest = MessageDigest.getInstance( alg ); - } - catch ( NoSuchAlgorithmException e ) - { - throw new IllegalStateException( "Not supported digest algorithm: " + alg ); + public StringDigestUtil(final String alg) { + try { + this.digest = MessageDigest.getInstance(alg); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("Not supported digest algorithm: " + alg); } } /** * Updates instance with passed in string. */ - public StringDigestUtil update( String data ) - { - if ( data != null && !data.isEmpty() ) - { - digest.update( data.getBytes( StandardCharsets.UTF_8 ) ); + public StringDigestUtil update(String data) { + if (data != null && !data.isEmpty()) { + digest.update(data.getBytes(StandardCharsets.UTF_8)); } return this; } @@ -70,24 +62,21 @@ public StringDigestUtil update( String data ) * * @see MessageDigest#digest() */ - public String digest() - { - return ChecksumUtils.toHexString( digest.digest() ); + public String digest() { + return ChecksumUtils.toHexString(digest.digest()); } /** * Helper method to create {@link StringDigestUtil} using SHA-1 digest algorithm. */ - public static StringDigestUtil sha1() - { - return new StringDigestUtil( "SHA-1" ); + public static StringDigestUtil sha1() { + return new StringDigestUtil("SHA-1"); } /** * Helper method to calculate SHA-1 digest and hex encode it. */ - public static String sha1( final String string ) - { - return sha1().update( string ).digest(); + public static String sha1(final String string) { + return sha1().update(string).digest(); } } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/StringUtils.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/StringUtils.java index 410652b8f..5a14bc8d1 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/StringUtils.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/StringUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,29 +16,26 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util; /** * A utility class to ease string processing. */ @Deprecated -public final class StringUtils -{ +public final class StringUtils { - private StringUtils() - { + private StringUtils() { // hide constructor } /** * Checks whether a string is {@code null} or of zero length. - * + * * @param string The string to check, may be {@code null}. * @return {@code true} if the string is {@code null} or of zero length, {@code false} otherwise. * @deprecated use {@code org.apache.commons.lang3.StringUtils.isEmpty()} instead */ - public static boolean isEmpty( String string ) - { + public static boolean isEmpty(String string) { return string == null || string.isEmpty(); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/ArtifactIdUtils.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/ArtifactIdUtils.java index 27a1f0d01..49901a73d 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/ArtifactIdUtils.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/ArtifactIdUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,45 +16,45 @@ * specific language governing permissions and limitations * under the License. */ - -import org.eclipse.aether.artifact.Artifact; +package org.eclipse.aether.util.artifact; import java.util.Objects; +import org.eclipse.aether.artifact.Artifact; + /** * A utility class for artifact identifiers. */ -public final class ArtifactIdUtils -{ +public final class ArtifactIdUtils { private static final char SEP = ':'; - private ArtifactIdUtils() - { + private ArtifactIdUtils() { // hide constructor } /** * Creates an artifact identifier of the form {@code ::[:]:}. - * + * * @param artifact The artifact to create an identifer for, may be {@code null}. * @return The artifact identifier or {@code null} if the input was {@code null}. */ - public static String toId( Artifact artifact ) - { + public static String toId(Artifact artifact) { String id = null; - if ( artifact != null ) - { - id = - toId( artifact.getGroupId(), artifact.getArtifactId(), artifact.getExtension(), - artifact.getClassifier(), artifact.getVersion() ); + if (artifact != null) { + id = toId( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getExtension(), + artifact.getClassifier(), + artifact.getVersion()); } return id; } /** * Creates an artifact identifier of the form {@code ::[:]:}. - * + * * @param groupId The group id, may be {@code null}. * @param artifactId The artifact id, may be {@code null}. * @param extension The file extensiion, may be {@code null}. @@ -64,13 +62,11 @@ public static String toId( Artifact artifact ) * @param version The version, may be {@code null}. * @return The artifact identifier, never {@code null}. */ - public static String toId( String groupId, String artifactId, String extension, String classifier, String version ) - { - StringBuilder buffer = concat( groupId, artifactId, extension, classifier ); - buffer.append( SEP ); - if ( version != null ) - { - buffer.append( version ); + public static String toId(String groupId, String artifactId, String extension, String classifier, String version) { + StringBuilder buffer = concat(groupId, artifactId, extension, classifier); + buffer.append(SEP); + if (version != null) { + buffer.append(version); } return buffer.toString(); } @@ -78,75 +74,67 @@ public static String toId( String groupId, String artifactId, String extension, /** * Creates an artifact identifier of the form * {@code ::[:]:}. - * + * * @param artifact The artifact to create an identifer for, may be {@code null}. * @return The artifact identifier or {@code null} if the input was {@code null}. */ - public static String toBaseId( Artifact artifact ) - { + public static String toBaseId(Artifact artifact) { String id = null; - if ( artifact != null ) - { - id = - toId( artifact.getGroupId(), artifact.getArtifactId(), artifact.getExtension(), - artifact.getClassifier(), artifact.getBaseVersion() ); + if (artifact != null) { + id = toId( + artifact.getGroupId(), + artifact.getArtifactId(), + artifact.getExtension(), + artifact.getClassifier(), + artifact.getBaseVersion()); } return id; } /** * Creates an artifact identifier of the form {@code ::[:]}. - * + * * @param artifact The artifact to create an identifer for, may be {@code null}. * @return The artifact identifier or {@code null} if the input was {@code null}. */ - public static String toVersionlessId( Artifact artifact ) - { + public static String toVersionlessId(Artifact artifact) { String id = null; - if ( artifact != null ) - { - id = - toVersionlessId( artifact.getGroupId(), artifact.getArtifactId(), artifact.getExtension(), - artifact.getClassifier() ); + if (artifact != null) { + id = toVersionlessId( + artifact.getGroupId(), artifact.getArtifactId(), artifact.getExtension(), artifact.getClassifier()); } return id; } /** * Creates an artifact identifier of the form {@code ::[:]}. - * + * * @param groupId The group id, may be {@code null}. * @param artifactId The artifact id, may be {@code null}. * @param extension The file extensiion, may be {@code null}. * @param classifier The classifier, may be {@code null}. * @return The artifact identifier, never {@code null}. */ - public static String toVersionlessId( String groupId, String artifactId, String extension, String classifier ) - { - return concat( groupId, artifactId, extension, classifier ).toString(); + public static String toVersionlessId(String groupId, String artifactId, String extension, String classifier) { + return concat(groupId, artifactId, extension, classifier).toString(); } - private static StringBuilder concat( String groupId, String artifactId, String extension, String classifier ) - { - StringBuilder buffer = new StringBuilder( 128 ); + private static StringBuilder concat(String groupId, String artifactId, String extension, String classifier) { + StringBuilder buffer = new StringBuilder(128); - if ( groupId != null ) - { - buffer.append( groupId ); + if (groupId != null) { + buffer.append(groupId); } - buffer.append( SEP ); - if ( artifactId != null ) - { - buffer.append( artifactId ); + buffer.append(SEP); + if (artifactId != null) { + buffer.append(artifactId); } - buffer.append( SEP ); - if ( extension != null ) - { - buffer.append( extension ); + buffer.append(SEP); + if (extension != null) { + buffer.append(extension); } - if ( classifier != null && classifier.length() > 0 ) - { - buffer.append( SEP ).append( classifier ); + if (classifier != null && classifier.length() > 0) { + buffer.append(SEP).append(classifier); } return buffer; @@ -156,35 +144,28 @@ private static StringBuilder concat( String groupId, String artifactId, String e * Determines whether two artifacts have the same identifier. This method is equivalent to calling * {@link String#equals(Object)} on the return values from {@link #toId(Artifact)} for the artifacts but does not * incur the overhead of creating temporary strings. - * + * * @param artifact1 The first artifact, may be {@code null}. * @param artifact2 The second artifact, may be {@code null}. * @return {@code true} if both artifacts are not {@code null} and have equal ids, {@code false} otherwise. */ - public static boolean equalsId( Artifact artifact1, Artifact artifact2 ) - { - if ( artifact1 == null || artifact2 == null ) - { + public static boolean equalsId(Artifact artifact1, Artifact artifact2) { + if (artifact1 == null || artifact2 == null) { return false; } - if ( !Objects.equals( artifact1.getArtifactId(), artifact2.getArtifactId() ) ) - { + if (!Objects.equals(artifact1.getArtifactId(), artifact2.getArtifactId())) { return false; } - if ( !Objects.equals( artifact1.getGroupId(), artifact2.getGroupId() ) ) - { + if (!Objects.equals(artifact1.getGroupId(), artifact2.getGroupId())) { return false; } - if ( !Objects.equals( artifact1.getExtension(), artifact2.getExtension() ) ) - { + if (!Objects.equals(artifact1.getExtension(), artifact2.getExtension())) { return false; } - if ( !Objects.equals( artifact1.getClassifier(), artifact2.getClassifier() ) ) - { + if (!Objects.equals(artifact1.getClassifier(), artifact2.getClassifier())) { return false; } - if ( !Objects.equals( artifact1.getVersion(), artifact2.getVersion() ) ) - { + if (!Objects.equals(artifact1.getVersion(), artifact2.getVersion())) { return false; } return true; @@ -194,35 +175,28 @@ public static boolean equalsId( Artifact artifact1, Artifact artifact2 ) * Determines whether two artifacts have the same base identifier. This method is equivalent to calling * {@link String#equals(Object)} on the return values from {@link #toBaseId(Artifact)} for the artifacts but does * not incur the overhead of creating temporary strings. - * + * * @param artifact1 The first artifact, may be {@code null}. * @param artifact2 The second artifact, may be {@code null}. * @return {@code true} if both artifacts are not {@code null} and have equal base ids, {@code false} otherwise. */ - public static boolean equalsBaseId( Artifact artifact1, Artifact artifact2 ) - { - if ( artifact1 == null || artifact2 == null ) - { + public static boolean equalsBaseId(Artifact artifact1, Artifact artifact2) { + if (artifact1 == null || artifact2 == null) { return false; } - if ( !Objects.equals( artifact1.getArtifactId(), artifact2.getArtifactId() ) ) - { + if (!Objects.equals(artifact1.getArtifactId(), artifact2.getArtifactId())) { return false; } - if ( !Objects.equals( artifact1.getGroupId(), artifact2.getGroupId() ) ) - { + if (!Objects.equals(artifact1.getGroupId(), artifact2.getGroupId())) { return false; } - if ( !Objects.equals( artifact1.getExtension(), artifact2.getExtension() ) ) - { + if (!Objects.equals(artifact1.getExtension(), artifact2.getExtension())) { return false; } - if ( !Objects.equals( artifact1.getClassifier(), artifact2.getClassifier() ) ) - { + if (!Objects.equals(artifact1.getClassifier(), artifact2.getClassifier())) { return false; } - if ( !Objects.equals( artifact1.getBaseVersion(), artifact2.getBaseVersion() ) ) - { + if (!Objects.equals(artifact1.getBaseVersion(), artifact2.getBaseVersion())) { return false; } return true; @@ -232,32 +206,26 @@ public static boolean equalsBaseId( Artifact artifact1, Artifact artifact2 ) * Determines whether two artifacts have the same versionless identifier. This method is equivalent to calling * {@link String#equals(Object)} on the return values from {@link #toVersionlessId(Artifact)} for the artifacts but * does not incur the overhead of creating temporary strings. - * + * * @param artifact1 The first artifact, may be {@code null}. * @param artifact2 The second artifact, may be {@code null}. * @return {@code true} if both artifacts are not {@code null} and have equal versionless ids, {@code false} * otherwise. */ - public static boolean equalsVersionlessId( Artifact artifact1, Artifact artifact2 ) - { - if ( artifact1 == null || artifact2 == null ) - { + public static boolean equalsVersionlessId(Artifact artifact1, Artifact artifact2) { + if (artifact1 == null || artifact2 == null) { return false; } - if ( !Objects.equals( artifact1.getArtifactId(), artifact2.getArtifactId() ) ) - { + if (!Objects.equals(artifact1.getArtifactId(), artifact2.getArtifactId())) { return false; } - if ( !Objects.equals( artifact1.getGroupId(), artifact2.getGroupId() ) ) - { + if (!Objects.equals(artifact1.getGroupId(), artifact2.getGroupId())) { return false; } - if ( !Objects.equals( artifact1.getExtension(), artifact2.getExtension() ) ) - { + if (!Objects.equals(artifact1.getExtension(), artifact2.getExtension())) { return false; } - if ( !Objects.equals( artifact1.getClassifier(), artifact2.getClassifier() ) ) - { + if (!Objects.equals(artifact1.getClassifier(), artifact2.getClassifier())) { return false; } return true; diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/DefaultArtifactTypeRegistry.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/DefaultArtifactTypeRegistry.java index 9fb29af82..cc20904f1 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/DefaultArtifactTypeRegistry.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/DefaultArtifactTypeRegistry.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,34 +16,29 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.artifact; import org.eclipse.aether.artifact.ArtifactType; /** * A simple artifact type registry. */ -public final class DefaultArtifactTypeRegistry - extends SimpleArtifactTypeRegistry -{ +public final class DefaultArtifactTypeRegistry extends SimpleArtifactTypeRegistry { /** * Creates a new artifact type registry with initally no registered artifact types. Use {@link #add(ArtifactType)} * to populate the registry. */ - public DefaultArtifactTypeRegistry() - { - } + public DefaultArtifactTypeRegistry() {} /** * Adds the specified artifact type to the registry. - * + * * @param type The artifact type to add, must not be {@code null}. * @return This registry for chaining, never {@code null}. */ - public DefaultArtifactTypeRegistry add( ArtifactType type ) - { - super.add( type ); + public DefaultArtifactTypeRegistry add(ArtifactType type) { + super.add(type); return this; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/DelegatingArtifact.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/DelegatingArtifact.java index 00fbcd488..ef48e8b50 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/DelegatingArtifact.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/DelegatingArtifact.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,21 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.artifact; import java.io.File; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.artifact.AbstractArtifact; import org.eclipse.aether.artifact.Artifact; +import static java.util.Objects.requireNonNull; + /** * An artifact that delegates to another artifact instance. This class serves as a base for subclasses that want to * carry additional data fields. */ -public abstract class DelegatingArtifact - extends AbstractArtifact -{ +public abstract class DelegatingArtifact extends AbstractArtifact { private final Artifact delegate; @@ -41,9 +39,8 @@ public abstract class DelegatingArtifact * * @param delegate The artifact to delegate to, must not be {@code null}. */ - protected DelegatingArtifact( Artifact delegate ) - { - this.delegate = requireNonNull( delegate, "delegate artifact cannot be null" ); + protected DelegatingArtifact(Artifact delegate) { + this.delegate = requireNonNull(delegate, "delegate artifact cannot be null"); } /** @@ -53,114 +50,92 @@ protected DelegatingArtifact( Artifact delegate ) * @param delegate The artifact to delegate to, must not be {@code null}. * @return The new delegating artifact, never {@code null}. */ - protected abstract DelegatingArtifact newInstance( Artifact delegate ); + protected abstract DelegatingArtifact newInstance(Artifact delegate); - public String getGroupId() - { + public String getGroupId() { return delegate.getGroupId(); } - public String getArtifactId() - { + public String getArtifactId() { return delegate.getArtifactId(); } - public String getVersion() - { + public String getVersion() { return delegate.getVersion(); } - public Artifact setVersion( String version ) - { - Artifact artifact = delegate.setVersion( version ); - if ( artifact != delegate ) - { - return newInstance( artifact ); + public Artifact setVersion(String version) { + Artifact artifact = delegate.setVersion(version); + if (artifact != delegate) { + return newInstance(artifact); } return this; } - public String getBaseVersion() - { + public String getBaseVersion() { return delegate.getBaseVersion(); } - public boolean isSnapshot() - { + public boolean isSnapshot() { return delegate.isSnapshot(); } - public String getClassifier() - { + public String getClassifier() { return delegate.getClassifier(); } - public String getExtension() - { + public String getExtension() { return delegate.getExtension(); } - public File getFile() - { + public File getFile() { return delegate.getFile(); } - public Artifact setFile( File file ) - { - Artifact artifact = delegate.setFile( file ); - if ( artifact != delegate ) - { - return newInstance( artifact ); + public Artifact setFile(File file) { + Artifact artifact = delegate.setFile(file); + if (artifact != delegate) { + return newInstance(artifact); } return this; } - public String getProperty( String key, String defaultValue ) - { - return delegate.getProperty( key, defaultValue ); + public String getProperty(String key, String defaultValue) { + return delegate.getProperty(key, defaultValue); } - public Map getProperties() - { + public Map getProperties() { return delegate.getProperties(); } - public Artifact setProperties( Map properties ) - { - Artifact artifact = delegate.setProperties( properties ); - if ( artifact != delegate ) - { - return newInstance( artifact ); + public Artifact setProperties(Map properties) { + Artifact artifact = delegate.setProperties(properties); + if (artifact != delegate) { + return newInstance(artifact); } return this; } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; } - if ( obj instanceof DelegatingArtifact ) - { - return delegate.equals( ( (DelegatingArtifact) obj ).delegate ); + if (obj instanceof DelegatingArtifact) { + return delegate.equals(((DelegatingArtifact) obj).delegate); } - return delegate.equals( obj ); + return delegate.equals(obj); } @Override - public int hashCode() - { + public int hashCode() { return delegate.hashCode(); } @Override - public String toString() - { + public String toString() { return delegate.toString(); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/JavaScopes.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/JavaScopes.java index bf4894cf7..6238d924f 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/JavaScopes.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/JavaScopes.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,14 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.artifact; /** * The dependency scopes used for Java dependencies. - * + * * @see org.eclipse.aether.graph.Dependency#getScope() */ -public final class JavaScopes -{ +public final class JavaScopes { public static final String COMPILE = "compile"; @@ -37,9 +35,7 @@ public final class JavaScopes public static final String TEST = "test"; - private JavaScopes() - { + private JavaScopes() { // hide constructor } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/OverlayArtifactTypeRegistry.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/OverlayArtifactTypeRegistry.java index 6768b1691..99ae3131d 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/OverlayArtifactTypeRegistry.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/OverlayArtifactTypeRegistry.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.artifact; import org.eclipse.aether.artifact.ArtifactType; import org.eclipse.aether.artifact.ArtifactTypeRegistry; @@ -26,45 +25,38 @@ * An artifact type registry which first consults its own mappings and in case of an unknown type falls back to another * type registry. */ -public final class OverlayArtifactTypeRegistry - extends SimpleArtifactTypeRegistry -{ +public final class OverlayArtifactTypeRegistry extends SimpleArtifactTypeRegistry { private final ArtifactTypeRegistry delegate; /** * Creates a new artifact type registry with initially no registered artifact types and the specified fallback * registry. Use {@link #add(ArtifactType)} to populate the registry. - * + * * @param delegate The artifact type registry to fall back to, may be {@code null}. */ - public OverlayArtifactTypeRegistry( ArtifactTypeRegistry delegate ) - { + public OverlayArtifactTypeRegistry(ArtifactTypeRegistry delegate) { this.delegate = delegate; } /** * Adds the specified artifact type to the registry. - * + * * @param type The artifact type to add, must not be {@code null}. * @return This registry for chaining, never {@code null}. */ - public OverlayArtifactTypeRegistry add( ArtifactType type ) - { - super.add( type ); + public OverlayArtifactTypeRegistry add(ArtifactType type) { + super.add(type); return this; } - public ArtifactType get( String typeId ) - { - ArtifactType type = super.get( typeId ); + public ArtifactType get(String typeId) { + ArtifactType type = super.get(typeId); - if ( type == null && delegate != null ) - { - type = delegate.get( typeId ); + if (type == null && delegate != null) { + type = delegate.get(typeId); } return type; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/SimpleArtifactTypeRegistry.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/SimpleArtifactTypeRegistry.java index 269e42bd7..9d868797b 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/SimpleArtifactTypeRegistry.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/SimpleArtifactTypeRegistry.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.artifact; import java.util.HashMap; import java.util.Map; @@ -28,9 +27,7 @@ /** * A simple map-based artifact type registry. */ -class SimpleArtifactTypeRegistry - implements ArtifactTypeRegistry -{ +class SimpleArtifactTypeRegistry implements ArtifactTypeRegistry { private final Map types; @@ -38,32 +35,27 @@ class SimpleArtifactTypeRegistry * Creates a new artifact type registry with initally no registered artifact types. Use {@link #add(ArtifactType)} * to populate the registry. */ - SimpleArtifactTypeRegistry() - { + SimpleArtifactTypeRegistry() { types = new HashMap<>(); } /** * Adds the specified artifact type to the registry. - * + * * @param type The artifact type to add, must not be {@code null}. * @return This registry for chaining, never {@code null}. */ - public SimpleArtifactTypeRegistry add( ArtifactType type ) - { - types.put( type.getId(), type ); + public SimpleArtifactTypeRegistry add(ArtifactType type) { + types.put(type.getId(), type); return this; } - public ArtifactType get( String typeId ) - { - return types.get( typeId ); + public ArtifactType get(String typeId) { + return types.get(typeId); } @Override - public String toString() - { + public String toString() { return types.toString(); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/SubArtifact.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/SubArtifact.java index 950ccc470..1e3282ad8 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/SubArtifact.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/SubArtifact.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,23 +16,22 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.artifact; import java.io.File; import java.util.Map; import java.util.Objects; -import static java.util.Objects.requireNonNull; - import org.eclipse.aether.artifact.AbstractArtifact; import org.eclipse.aether.artifact.Artifact; +import static java.util.Objects.requireNonNull; + /** * An artifact whose identity is derived from another artifact. Note: Instances of this class are immutable and * the exposed mutators return new objects rather than changing the current instance. */ -public final class SubArtifact - extends AbstractArtifact -{ +public final class SubArtifact extends AbstractArtifact { private final Artifact mainArtifact; @@ -51,14 +48,13 @@ public final class SubArtifact * character "*" to refer to the corresponding property of the main artifact. For instance, the classifier * "*-sources" can be used to refer to the source attachment of an artifact. Likewise, the extension "*.asc" can be * used to refer to the GPG signature of an artifact. - * + * * @param mainArtifact The artifact from which to derive the identity, must not be {@code null}. * @param classifier The classifier for this artifact, may be {@code null} if none. * @param extension The extension for this artifact, may be {@code null} if none. */ - public SubArtifact( Artifact mainArtifact, String classifier, String extension ) - { - this( mainArtifact, classifier, extension, (File) null ); + public SubArtifact(Artifact mainArtifact, String classifier, String extension) { + this(mainArtifact, classifier, extension, (File) null); } /** @@ -66,15 +62,14 @@ public SubArtifact( Artifact mainArtifact, String classifier, String extension ) * character "*" to refer to the corresponding property of the main artifact. For instance, the classifier * "*-sources" can be used to refer to the source attachment of an artifact. Likewise, the extension "*.asc" can be * used to refer to the GPG signature of an artifact. - * + * * @param mainArtifact The artifact from which to derive the identity, must not be {@code null}. * @param classifier The classifier for this artifact, may be {@code null} if none. * @param extension The extension for this artifact, may be {@code null} if none. * @param file The file for this artifact, may be {@code null} if unresolved. */ - public SubArtifact( Artifact mainArtifact, String classifier, String extension, File file ) - { - this( mainArtifact, classifier, extension, null, file ); + public SubArtifact(Artifact mainArtifact, String classifier, String extension, File file) { + this(mainArtifact, classifier, extension, null, file); } /** @@ -82,15 +77,14 @@ public SubArtifact( Artifact mainArtifact, String classifier, String extension, * character "*" to refer to the corresponding property of the main artifact. For instance, the classifier * "*-sources" can be used to refer to the source attachment of an artifact. Likewise, the extension "*.asc" can be * used to refer to the GPG signature of an artifact. - * + * * @param mainArtifact The artifact from which to derive the identity, must not be {@code null}. * @param classifier The classifier for this artifact, may be {@code null} if none. * @param extension The extension for this artifact, may be {@code null} if none. * @param properties The properties of the artifact, may be {@code null}. */ - public SubArtifact( Artifact mainArtifact, String classifier, String extension, Map properties ) - { - this( mainArtifact, classifier, extension, properties, null ); + public SubArtifact(Artifact mainArtifact, String classifier, String extension, Map properties) { + this(mainArtifact, classifier, extension, properties, null); } /** @@ -98,26 +92,24 @@ public SubArtifact( Artifact mainArtifact, String classifier, String extension, * character "*" to refer to the corresponding property of the main artifact. For instance, the classifier * "*-sources" can be used to refer to the source attachment of an artifact. Likewise, the extension "*.asc" can be * used to refer to the GPG signature of an artifact. - * + * * @param mainArtifact The artifact from which to derive the identity, must not be {@code null}. * @param classifier The classifier for this artifact, may be {@code null} if none. * @param extension The extension for this artifact, may be {@code null} if none. * @param properties The properties of the artifact, may be {@code null}. * @param file The file for this artifact, may be {@code null} if unresolved. */ - public SubArtifact( Artifact mainArtifact, String classifier, String extension, Map properties, - File file ) - { - this.mainArtifact = requireNonNull( mainArtifact, "main artifact cannot be null" ); + public SubArtifact( + Artifact mainArtifact, String classifier, String extension, Map properties, File file) { + this.mainArtifact = requireNonNull(mainArtifact, "main artifact cannot be null"); this.classifier = classifier; this.extension = extension; this.file = file; - this.properties = copyProperties( properties ); + this.properties = copyProperties(properties); } - private SubArtifact( Artifact mainArtifact, String classifier, String extension, File file, - Map properties ) - { + private SubArtifact( + Artifact mainArtifact, String classifier, String extension, File file, Map properties) { // NOTE: This constructor assumes immutability of the provided properties, for internal use only this.mainArtifact = mainArtifact; this.classifier = classifier; @@ -126,107 +118,84 @@ private SubArtifact( Artifact mainArtifact, String classifier, String extension, this.properties = properties; } - public String getGroupId() - { + public String getGroupId() { return mainArtifact.getGroupId(); } - public String getArtifactId() - { + public String getArtifactId() { return mainArtifact.getArtifactId(); } - public String getVersion() - { + public String getVersion() { return mainArtifact.getVersion(); } - public String getBaseVersion() - { + public String getBaseVersion() { return mainArtifact.getBaseVersion(); } - public boolean isSnapshot() - { + public boolean isSnapshot() { return mainArtifact.isSnapshot(); } - public String getClassifier() - { - return expand( classifier, mainArtifact.getClassifier() ); + public String getClassifier() { + return expand(classifier, mainArtifact.getClassifier()); } - public String getExtension() - { - return expand( extension, mainArtifact.getExtension() ); + public String getExtension() { + return expand(extension, mainArtifact.getExtension()); } - public File getFile() - { + public File getFile() { return file; } - public Artifact setFile( File file ) - { - if ( Objects.equals( this.file, file ) ) - { + public Artifact setFile(File file) { + if (Objects.equals(this.file, file)) { return this; } - return new SubArtifact( mainArtifact, classifier, extension, file, properties ); + return new SubArtifact(mainArtifact, classifier, extension, file, properties); } - public Map getProperties() - { + public Map getProperties() { return properties; } - public Artifact setProperties( Map properties ) - { - if ( this.properties.equals( properties ) || ( properties == null && this.properties.isEmpty() ) ) - { + public Artifact setProperties(Map properties) { + if (this.properties.equals(properties) || (properties == null && this.properties.isEmpty())) { return this; } - return new SubArtifact( mainArtifact, classifier, extension, properties, file ); + return new SubArtifact(mainArtifact, classifier, extension, properties, file); } - private static String expand( String pattern, String replacement ) - { + private static String expand(String pattern, String replacement) { String result = ""; - if ( pattern != null ) - { - result = pattern.replace( "*", replacement ); - - if ( replacement.isEmpty() ) - { - if ( pattern.startsWith( "*" ) ) - { + if (pattern != null) { + result = pattern.replace("*", replacement); + + if (replacement.isEmpty()) { + if (pattern.startsWith("*")) { int i = 0; - for ( ; i < result.length(); i++ ) - { - char c = result.charAt( i ); - if ( c != '-' && c != '.' ) - { + for (; i < result.length(); i++) { + char c = result.charAt(i); + if (c != '-' && c != '.') { break; } } - result = result.substring( i ); + result = result.substring(i); } - if ( pattern.endsWith( "*" ) ) - { + if (pattern.endsWith("*")) { int i = result.length() - 1; - for ( ; i >= 0; i-- ) - { - char c = result.charAt( i ); - if ( c != '-' && c != '.' ) - { + for (; i >= 0; i--) { + char c = result.charAt(i); + if (c != '-' && c != '.') { break; } } - result = result.substring( 0, i + 1 ); + result = result.substring(0, i + 1); } } } return result; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/package-info.java index 153159fa9..75baa5aa4 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/artifact/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Utilities around artifacts and artifact type registries. */ package org.eclipse.aether.util.artifact; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/ExecutorUtils.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/ExecutorUtils.java index 716cfecba..cb2a734be 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/ExecutorUtils.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/ExecutorUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.concurrency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.concurrency; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; @@ -33,8 +32,7 @@ * * @since 1.9.5 */ -public final class ExecutorUtils -{ +public final class ExecutorUtils { /** * Shared instance of "direct executor". */ @@ -43,32 +41,28 @@ public final class ExecutorUtils /** * Creates new thread pool {@link ExecutorService}. The {@code poolSize} parameter but be greater than 1. */ - public static ExecutorService threadPool( int poolSize, String namePrefix ) - { - if ( poolSize < 2 ) - { - throw new IllegalArgumentException( - "Invalid poolSize: " + poolSize + ". Must be greater than 1." ); + public static ExecutorService threadPool(int poolSize, String namePrefix) { + if (poolSize < 2) { + throw new IllegalArgumentException("Invalid poolSize: " + poolSize + ". Must be greater than 1."); } - return new ThreadPoolExecutor( poolSize, poolSize, 3L, TimeUnit.SECONDS, + return new ThreadPoolExecutor( + poolSize, + poolSize, + 3L, + TimeUnit.SECONDS, new LinkedBlockingQueue<>(), - new WorkerThreadFactory( namePrefix ) - ); + new WorkerThreadFactory(namePrefix)); } /** * Returns {@link #DIRECT_EXECUTOR} or result of {@link #threadPool(int, String)} depending on value of * {@code size} parameter. */ - public static Executor executor( int size, String namePrefix ) - { - if ( size <= 1 ) - { + public static Executor executor(int size, String namePrefix) { + if (size <= 1) { return DIRECT_EXECUTOR; - } - else - { - return threadPool( size, namePrefix ); + } else { + return threadPool(size, namePrefix); } } @@ -76,11 +70,9 @@ public static Executor executor( int size, String namePrefix ) * To be used with result of {@link #executor(int, String)} method, shuts down instance if it is * {@link ExecutorService}. */ - public static void shutdown( Executor executor ) - { - if ( executor instanceof ExecutorService ) - { - ( (ExecutorService) executor ).shutdown(); + public static void shutdown(Executor executor) { + if (executor instanceof ExecutorService) { + ((ExecutorService) executor).shutdown(); } } @@ -91,18 +83,13 @@ public static void shutdown( Executor executor ) * @throws IllegalArgumentException if default value is less than 1. * @see ConfigUtils#getInteger(RepositorySystemSession, int, String...) */ - public static int threadCount( RepositorySystemSession session, int defaultValue, String... keys ) - { - if ( defaultValue < 1 ) - { - throw new IllegalArgumentException( - "Invalid defaultValue: " + defaultValue + ". Must be greater than 0." ); + public static int threadCount(RepositorySystemSession session, int defaultValue, String... keys) { + if (defaultValue < 1) { + throw new IllegalArgumentException("Invalid defaultValue: " + defaultValue + ". Must be greater than 0."); } - int threadCount = ConfigUtils.getInteger( session, defaultValue, keys ); - if ( threadCount < 1 ) - { - throw new IllegalArgumentException( - "Invalid value: " + threadCount + ". Must be greater than 0." ); + int threadCount = ConfigUtils.getInteger(session, defaultValue, keys); + if (threadCount < 1) { + throw new IllegalArgumentException("Invalid value: " + threadCount + ". Must be greater than 0."); } return threadCount; } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/RunnableErrorForwarder.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/RunnableErrorForwarder.java index 6f219f1c2..ab566f14c 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/RunnableErrorForwarder.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/RunnableErrorForwarder.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.concurrency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,17 +16,18 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Objects.requireNonNull; +package org.eclipse.aether.util.concurrency; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.LockSupport; +import static java.util.Objects.requireNonNull; + /** * A utility class to forward any uncaught {@link Error} or {@link RuntimeException} from a {@link Runnable} executed in * a worker thread back to the parent thread. The simplified usage pattern looks like this: - * + * *

      * RunnableErrorForwarder errorForwarder = new RunnableErrorForwarder();
      * for ( Runnable task : tasks )
    @@ -38,8 +37,7 @@
      * errorForwarder.await();
      * 
    */ -public final class RunnableErrorForwarder -{ +public final class RunnableErrorForwarder { private final Thread thread = Thread.currentThread(); @@ -50,9 +48,7 @@ public final class RunnableErrorForwarder /** * Creates a new error forwarder for worker threads spawned by the current thread. */ - public RunnableErrorForwarder() - { - } + public RunnableErrorForwarder() {} /** * Wraps the specified runnable into an equivalent runnable that will allow forwarding of uncaught errors. @@ -60,27 +56,20 @@ public RunnableErrorForwarder() * @param runnable The runnable from which to forward errors, must not be {@code null}. * @return The error-forwarding runnable to eventually execute, never {@code null}. */ - public Runnable wrap( final Runnable runnable ) - { - requireNonNull( runnable, "runnable cannot be null" ); + public Runnable wrap(final Runnable runnable) { + requireNonNull(runnable, "runnable cannot be null"); counter.incrementAndGet(); - return () -> - { - try - { + return () -> { + try { runnable.run(); - } - catch ( RuntimeException | Error e ) - { - error.compareAndSet( null, e ); + } catch (RuntimeException | Error e) { + error.compareAndSet(null, e); throw e; - } - finally - { + } finally { counter.decrementAndGet(); - LockSupport.unpark( thread ); + LockSupport.unpark(thread); } }; } @@ -91,53 +80,40 @@ public Runnable wrap( final Runnable runnable ) * case multiple runnables encountered uncaught errors, one error is arbitrarily selected. Note: This * method must be called from the same thread that created this error forwarder instance. */ - public void await() - { + public void await() { awaitTerminationOfAllRunnables(); Throwable error = this.error.get(); - if ( error != null ) - { - if ( error instanceof RuntimeException ) - { + if (error != null) { + if (error instanceof RuntimeException) { throw (RuntimeException) error; - } - else if ( error instanceof ThreadDeath ) - { - throw new IllegalStateException( error ); - } - else if ( error instanceof Error ) - { + } else if (error instanceof ThreadDeath) { + throw new IllegalStateException(error); + } else if (error instanceof Error) { throw (Error) error; } - throw new IllegalStateException( error ); + throw new IllegalStateException(error); } } - private void awaitTerminationOfAllRunnables() - { - if ( !thread.equals( Thread.currentThread() ) ) - { - throw new IllegalStateException( "wrong caller thread, expected " + thread + " and not " - + Thread.currentThread() ); + private void awaitTerminationOfAllRunnables() { + if (!thread.equals(Thread.currentThread())) { + throw new IllegalStateException( + "wrong caller thread, expected " + thread + " and not " + Thread.currentThread()); } boolean interrupted = false; - while ( counter.get() > 0 ) - { + while (counter.get() > 0) { LockSupport.park(); - if ( Thread.interrupted() ) - { + if (Thread.interrupted()) { interrupted = true; } } - if ( interrupted ) - { + if (interrupted) { Thread.currentThread().interrupt(); } } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/WorkerThreadFactory.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/WorkerThreadFactory.java index 26d0fb69c..0662ec650 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/WorkerThreadFactory.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/WorkerThreadFactory.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.concurrency; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.concurrency; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; @@ -26,9 +25,7 @@ /** * A factory to create worker threads with a given name prefix. */ -public final class WorkerThreadFactory - implements ThreadFactory -{ +public final class WorkerThreadFactory implements ThreadFactory { private final ThreadFactory factory; @@ -40,37 +37,33 @@ public final class WorkerThreadFactory /** * Creates a new thread factory whose threads will have names using the specified prefix. - * + * * @param namePrefix The prefix for the thread names, may be {@code null} or empty to derive the prefix from the * caller's simple class name. */ - public WorkerThreadFactory( String namePrefix ) - { + public WorkerThreadFactory(String namePrefix) { this.factory = Executors.defaultThreadFactory(); this.namePrefix = - ( ( namePrefix != null && namePrefix.length() > 0 ) ? namePrefix : getCallerSimpleClassName() + '-' ) - + POOL_INDEX.getAndIncrement() + '-'; + ((namePrefix != null && namePrefix.length() > 0) ? namePrefix : getCallerSimpleClassName() + '-') + + POOL_INDEX.getAndIncrement() + + '-'; threadIndex = new AtomicInteger(); } - private static String getCallerSimpleClassName() - { + private static String getCallerSimpleClassName() { StackTraceElement[] stack = new Exception().getStackTrace(); - if ( stack == null || stack.length <= 2 ) - { + if (stack == null || stack.length <= 2) { return "Worker-"; } String name = stack[2].getClassName(); - name = name.substring( name.lastIndexOf( '.' ) + 1 ); + name = name.substring(name.lastIndexOf('.') + 1); return name; } - public Thread newThread( Runnable r ) - { - Thread thread = factory.newThread( r ); - thread.setName( namePrefix + threadIndex.getAndIncrement() ); - thread.setDaemon( true ); + public Thread newThread(Runnable r) { + Thread thread = factory.newThread(r); + thread.setName(namePrefix + threadIndex.getAndIncrement()); + thread.setDaemon(true); return thread; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/package-info.java index 2bb7853ee..647e3e201 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/concurrency/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Utilities for concurrent task processing. */ package org.eclipse.aether.util.concurrency; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/AbstractPatternDependencyFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/AbstractPatternDependencyFilter.java index 9929074de..04e7d2087 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/AbstractPatternDependencyFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/AbstractPatternDependencyFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.filter; import java.util.Arrays; import java.util.Collection; @@ -39,9 +38,7 @@ /** */ -class AbstractPatternDependencyFilter - implements DependencyFilter -{ +class AbstractPatternDependencyFilter implements DependencyFilter { private final Set patterns = new HashSet<>(); @@ -49,188 +46,156 @@ class AbstractPatternDependencyFilter /** * Creates a new filter using the specified patterns. - * + * * @param patterns The include patterns, may be {@code null} or empty to include no artifacts. */ - AbstractPatternDependencyFilter( final String... patterns ) - { - this( null, patterns ); + AbstractPatternDependencyFilter(final String... patterns) { + this(null, patterns); } /** * Creates a new filter using the specified patterns. - * + * * @param versionScheme To be used for parsing versions/version ranges. If {@code null} and pattern specifies a * range no artifact will be included. * @param patterns The include patterns, may be {@code null} or empty to include no artifacts. */ - AbstractPatternDependencyFilter( final VersionScheme versionScheme, final String... patterns ) - { - this( versionScheme, patterns == null ? null : Arrays.asList( patterns ) ); + AbstractPatternDependencyFilter(final VersionScheme versionScheme, final String... patterns) { + this(versionScheme, patterns == null ? null : Arrays.asList(patterns)); } /** * Creates a new filter using the specified patterns. - * + * * @param patterns The include patterns, may be {@code null} or empty to include no artifacts. */ - AbstractPatternDependencyFilter( final Collection patterns ) - { - this( null, patterns ); + AbstractPatternDependencyFilter(final Collection patterns) { + this(null, patterns); } /** * Creates a new filter using the specified patterns and {@link VersionScheme} . - * + * * @param versionScheme To be used for parsing versions/version ranges. If {@code null} and pattern specifies a * range no artifact will be included. * @param patterns The include patterns, may be {@code null} or empty to include no artifacts. */ - AbstractPatternDependencyFilter( final VersionScheme versionScheme, final Collection patterns ) - { - if ( patterns != null ) - { - this.patterns.addAll( patterns ); + AbstractPatternDependencyFilter(final VersionScheme versionScheme, final Collection patterns) { + if (patterns != null) { + this.patterns.addAll(patterns); } this.versionScheme = versionScheme; } - public boolean accept( final DependencyNode node, List parents ) - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( parents, "parents cannot be null" ); + public boolean accept(final DependencyNode node, List parents) { + requireNonNull(node, "node cannot be null"); + requireNonNull(parents, "parents cannot be null"); final Dependency dependency = node.getDependency(); - if ( dependency == null ) - { + if (dependency == null) { return true; } - return accept( dependency.getArtifact() ); + return accept(dependency.getArtifact()); } - protected boolean accept( final Artifact artifact ) - { - for ( final String pattern : patterns ) - { - final boolean matched = accept( artifact, pattern ); - if ( matched ) - { + protected boolean accept(final Artifact artifact) { + for (final String pattern : patterns) { + final boolean matched = accept(artifact, pattern); + if (matched) { return true; } } return false; } - private boolean accept( final Artifact artifact, final String pattern ) - { - final String[] tokens = - new String[] { artifact.getGroupId(), artifact.getArtifactId(), artifact.getExtension(), - artifact.getBaseVersion() }; + private boolean accept(final Artifact artifact, final String pattern) { + final String[] tokens = new String[] { + artifact.getGroupId(), artifact.getArtifactId(), artifact.getExtension(), artifact.getBaseVersion() + }; - final String[] patternTokens = pattern.split( ":" ); + final String[] patternTokens = pattern.split(":"); // fail immediately if pattern tokens outnumber tokens to match - boolean matched = ( patternTokens.length <= tokens.length ); + boolean matched = (patternTokens.length <= tokens.length); - for ( int i = 0; matched && i < patternTokens.length; i++ ) - { - matched = matches( tokens[i], patternTokens[i] ); + for (int i = 0; matched && i < patternTokens.length; i++) { + matched = matches(tokens[i], patternTokens[i]); } return matched; } - private boolean matches( final String token, final String pattern ) - { + private boolean matches(final String token, final String pattern) { boolean matches; // support full wildcard and implied wildcard - if ( "*".equals( pattern ) || pattern.length() == 0 ) - { + if ("*".equals(pattern) || pattern.length() == 0) { matches = true; } // support contains wildcard - else if ( pattern.startsWith( "*" ) && pattern.endsWith( "*" ) ) - { - final String contains = pattern.substring( 1, pattern.length() - 1 ); + else if (pattern.startsWith("*") && pattern.endsWith("*")) { + final String contains = pattern.substring(1, pattern.length() - 1); - matches = ( token.contains( contains ) ); + matches = (token.contains(contains)); } // support leading wildcard - else if ( pattern.startsWith( "*" ) ) - { - final String suffix = pattern.substring( 1 ); + else if (pattern.startsWith("*")) { + final String suffix = pattern.substring(1); - matches = token.endsWith( suffix ); + matches = token.endsWith(suffix); } // support trailing wildcard - else if ( pattern.endsWith( "*" ) ) - { - final String prefix = pattern.substring( 0, pattern.length() - 1 ); + else if (pattern.endsWith("*")) { + final String prefix = pattern.substring(0, pattern.length() - 1); - matches = token.startsWith( prefix ); + matches = token.startsWith(prefix); } // support versions range - else if ( pattern.startsWith( "[" ) || pattern.startsWith( "(" ) ) - { - matches = isVersionIncludedInRange( token, pattern ); + else if (pattern.startsWith("[") || pattern.startsWith("(")) { + matches = isVersionIncludedInRange(token, pattern); } // support exact match - else - { - matches = token.equals( pattern ); + else { + matches = token.equals(pattern); } return matches; } - private boolean isVersionIncludedInRange( final String version, final String range ) - { - if ( versionScheme == null ) - { + private boolean isVersionIncludedInRange(final String version, final String range) { + if (versionScheme == null) { return false; - } - else - { - try - { - final Version parsedVersion = versionScheme.parseVersion( version ); - final VersionRange parsedRange = versionScheme.parseVersionRange( range ); - - return parsedRange.containsVersion( parsedVersion ); - } - catch ( final InvalidVersionSpecificationException e ) - { + } else { + try { + final Version parsedVersion = versionScheme.parseVersion(version); + final VersionRange parsedRange = versionScheme.parseVersionRange(range); + + return parsedRange.containsVersion(parsedVersion); + } catch (final InvalidVersionSpecificationException e) { return false; } } } @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { + public boolean equals(final Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } final AbstractPatternDependencyFilter that = (AbstractPatternDependencyFilter) obj; - return Objects.equals( this.patterns, that.patterns ) - && Objects.equals( this.versionScheme, that.versionScheme ); + return Objects.equals(this.patterns, that.patterns) && Objects.equals(this.versionScheme, that.versionScheme); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + patterns.hashCode(); - hash = hash * 31 + ( ( versionScheme == null ) ? 0 : versionScheme.hashCode() ); + hash = hash * 31 + ((versionScheme == null) ? 0 : versionScheme.hashCode()); return hash; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/AndDependencyFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/AndDependencyFilter.java index 326607309..92af37092 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/AndDependencyFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/AndDependencyFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.filter; import java.util.Collection; import java.util.Collections; @@ -34,67 +33,54 @@ * A dependency filter that combines zero or more other filters using a logical {@code AND}. The resulting filter * accepts a given dependency node if and only if all constituent filters accept it. */ -public final class AndDependencyFilter - implements DependencyFilter -{ +public final class AndDependencyFilter implements DependencyFilter { private final Set filters = new LinkedHashSet<>(); /** * Creates a new filter from the specified filters. Prefer {@link #newInstance(DependencyFilter, DependencyFilter)} * if any of the input filters might be {@code null}. - * + * * @param filters The filters to combine, may be {@code null} but must not contain {@code null} elements. */ - public AndDependencyFilter( DependencyFilter... filters ) - { - if ( filters != null ) - { - Collections.addAll( this.filters, filters ); + public AndDependencyFilter(DependencyFilter... filters) { + if (filters != null) { + Collections.addAll(this.filters, filters); } } /** * Creates a new filter from the specified filters. - * + * * @param filters The filters to combine, may be {@code null} but must not contain {@code null} elements. */ - public AndDependencyFilter( Collection filters ) - { - if ( filters != null ) - { - this.filters.addAll( filters ); + public AndDependencyFilter(Collection filters) { + if (filters != null) { + this.filters.addAll(filters); } } /** * Creates a new filter from the specified filters. - * + * * @param filter1 The first filter to combine, may be {@code null}. * @param filter2 The second filter to combine, may be {@code null}. * @return The combined filter or {@code null} if both filter were {@code null}. */ - public static DependencyFilter newInstance( DependencyFilter filter1, DependencyFilter filter2 ) - { - if ( filter1 == null ) - { + public static DependencyFilter newInstance(DependencyFilter filter1, DependencyFilter filter2) { + if (filter1 == null) { return filter2; - } - else if ( filter2 == null ) - { + } else if (filter2 == null) { return filter1; } - return new AndDependencyFilter( filter1, filter2 ); + return new AndDependencyFilter(filter1, filter2); } - public boolean accept( DependencyNode node, List parents ) - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( parents, "parents cannot be null" ); - for ( DependencyFilter filter : filters ) - { - if ( !filter.accept( node, parents ) ) - { + public boolean accept(DependencyNode node, List parents) { + requireNonNull(node, "node cannot be null"); + requireNonNull(parents, "parents cannot be null"); + for (DependencyFilter filter : filters) { + if (!filter.accept(node, parents)) { return false; } } @@ -102,29 +88,24 @@ public boolean accept( DependencyNode node, List parents ) } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } AndDependencyFilter that = (AndDependencyFilter) obj; - return this.filters.equals( that.filters ); + return this.filters.equals(that.filters); } @Override - public int hashCode() - { + public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + filters.hashCode(); return hash; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/DependencyFilterUtils.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/DependencyFilterUtils.java index f178d0b5a..596d6efa1 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/DependencyFilterUtils.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/DependencyFilterUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.filter; import java.util.Arrays; import java.util.Collection; @@ -30,170 +29,146 @@ /** * A utility class assisting in the creation of dependency node filters. */ -public final class DependencyFilterUtils -{ +public final class DependencyFilterUtils { - private DependencyFilterUtils() - { + private DependencyFilterUtils() { // hide constructor } /** * Creates a new filter that negates the specified filter. - * + * * @param filter The filter to negate, must not be {@code null}. * @return The new filter, never {@code null}. */ - public static DependencyFilter notFilter( DependencyFilter filter ) - { - return new NotDependencyFilter( filter ); + public static DependencyFilter notFilter(DependencyFilter filter) { + return new NotDependencyFilter(filter); } /** * Creates a new filter that combines the specified filters using a logical {@code AND}. If no filters are * specified, the resulting filter accepts everything. - * + * * @param filters The filters to combine, may be {@code null}. * @return The new filter, never {@code null}. */ - public static DependencyFilter andFilter( DependencyFilter... filters ) - { - if ( filters != null && filters.length == 1 ) - { + public static DependencyFilter andFilter(DependencyFilter... filters) { + if (filters != null && filters.length == 1) { return filters[0]; - } - else - { - return new AndDependencyFilter( filters ); + } else { + return new AndDependencyFilter(filters); } } /** * Creates a new filter that combines the specified filters using a logical {@code AND}. If no filters are * specified, the resulting filter accepts everything. - * + * * @param filters The filters to combine, may be {@code null}. * @return The new filter, never {@code null}. */ - public static DependencyFilter andFilter( Collection filters ) - { - if ( filters != null && filters.size() == 1 ) - { + public static DependencyFilter andFilter(Collection filters) { + if (filters != null && filters.size() == 1) { return filters.iterator().next(); - } - else - { - return new AndDependencyFilter( filters ); + } else { + return new AndDependencyFilter(filters); } } /** * Creates a new filter that combines the specified filters using a logical {@code OR}. If no filters are specified, * the resulting filter accepts nothing. - * + * * @param filters The filters to combine, may be {@code null}. * @return The new filter, never {@code null}. */ - public static DependencyFilter orFilter( DependencyFilter... filters ) - { - if ( filters != null && filters.length == 1 ) - { + public static DependencyFilter orFilter(DependencyFilter... filters) { + if (filters != null && filters.length == 1) { return filters[0]; - } - else - { - return new OrDependencyFilter( filters ); + } else { + return new OrDependencyFilter(filters); } } /** * Creates a new filter that combines the specified filters using a logical {@code OR}. If no filters are specified, * the resulting filter accepts nothing. - * + * * @param filters The filters to combine, may be {@code null}. * @return The new filter, never {@code null}. */ - public static DependencyFilter orFilter( Collection filters ) - { - if ( filters != null && filters.size() == 1 ) - { + public static DependencyFilter orFilter(Collection filters) { + if (filters != null && filters.size() == 1) { return filters.iterator().next(); - } - else - { - return new OrDependencyFilter( filters ); + } else { + return new OrDependencyFilter(filters); } } /** * Creates a new filter that selects dependencies whose scope matches one or more of the specified classpath types. * A classpath type is a set of scopes separated by either {@code ','} or {@code '+'}. - * + * * @param classpathTypes The classpath types, may be {@code null} or empty to match no dependency. * @return The new filter, never {@code null}. * @see JavaScopes */ - public static DependencyFilter classpathFilter( String... classpathTypes ) - { - return classpathFilter( ( classpathTypes != null ) ? Arrays.asList( classpathTypes ) : null ); + public static DependencyFilter classpathFilter(String... classpathTypes) { + return classpathFilter((classpathTypes != null) ? Arrays.asList(classpathTypes) : null); } /** * Creates a new filter that selects dependencies whose scope matches one or more of the specified classpath types. * A classpath type is a set of scopes separated by either {@code ','} or {@code '+'}. - * + * * @param classpathTypes The classpath types, may be {@code null} or empty to match no dependency. * @return The new filter, never {@code null}. * @see JavaScopes */ - public static DependencyFilter classpathFilter( Collection classpathTypes ) - { + public static DependencyFilter classpathFilter(Collection classpathTypes) { Collection types = new HashSet<>(); - if ( classpathTypes != null ) - { - for ( String classpathType : classpathTypes ) - { - String[] tokens = classpathType.split( "[+,]" ); - for ( String token : tokens ) - { + if (classpathTypes != null) { + for (String classpathType : classpathTypes) { + String[] tokens = classpathType.split("[+,]"); + for (String token : tokens) { token = token.trim(); - if ( token.length() > 0 ) - { - types.add( token ); + if (token.length() > 0) { + types.add(token); } } } } Collection included = new HashSet<>(); - for ( String type : types ) - { - if ( JavaScopes.COMPILE.equals( type ) ) - { - Collections.addAll( included, JavaScopes.COMPILE, JavaScopes.PROVIDED, JavaScopes.SYSTEM ); - } - else if ( JavaScopes.RUNTIME.equals( type ) ) - { - Collections.addAll( included, JavaScopes.COMPILE, JavaScopes.RUNTIME ); - } - else if ( JavaScopes.TEST.equals( type ) ) - { - Collections.addAll( included, JavaScopes.COMPILE, JavaScopes.PROVIDED, JavaScopes.SYSTEM, - JavaScopes.RUNTIME, JavaScopes.TEST ); - } - else - { - included.add( type ); + for (String type : types) { + if (JavaScopes.COMPILE.equals(type)) { + Collections.addAll(included, JavaScopes.COMPILE, JavaScopes.PROVIDED, JavaScopes.SYSTEM); + } else if (JavaScopes.RUNTIME.equals(type)) { + Collections.addAll(included, JavaScopes.COMPILE, JavaScopes.RUNTIME); + } else if (JavaScopes.TEST.equals(type)) { + Collections.addAll( + included, + JavaScopes.COMPILE, + JavaScopes.PROVIDED, + JavaScopes.SYSTEM, + JavaScopes.RUNTIME, + JavaScopes.TEST); + } else { + included.add(type); } } Collection excluded = new HashSet<>(); - Collections.addAll( excluded, JavaScopes.COMPILE, JavaScopes.PROVIDED, JavaScopes.SYSTEM, JavaScopes.RUNTIME, - JavaScopes.TEST ); - excluded.removeAll( included ); - - return new ScopeDependencyFilter( null, excluded ); + Collections.addAll( + excluded, + JavaScopes.COMPILE, + JavaScopes.PROVIDED, + JavaScopes.SYSTEM, + JavaScopes.RUNTIME, + JavaScopes.TEST); + excluded.removeAll(included); + + return new ScopeDependencyFilter(null, excluded); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/ExclusionsDependencyFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/ExclusionsDependencyFilter.java index 7513949e7..12d745af3 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/ExclusionsDependencyFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/ExclusionsDependencyFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.filter; import java.util.Collection; import java.util.HashSet; @@ -33,48 +32,40 @@ /** * A simple filter to exclude artifacts based on either artifact id or group id and artifact id. */ -public final class ExclusionsDependencyFilter - implements DependencyFilter -{ +public final class ExclusionsDependencyFilter implements DependencyFilter { private final Set excludes = new HashSet<>(); /** * Creates a new filter using the specified exclude patterns. A pattern can either be of the form * {@code groupId:artifactId} (recommended) or just {@code artifactId} (deprecated). - * + * * @param excludes The exclude patterns, may be {@code null} or empty to exclude no artifacts. */ - public ExclusionsDependencyFilter( Collection excludes ) - { - if ( excludes != null ) - { - this.excludes.addAll( excludes ); + public ExclusionsDependencyFilter(Collection excludes) { + if (excludes != null) { + this.excludes.addAll(excludes); } } - public boolean accept( DependencyNode node, List parents ) - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( parents, "parents cannot be null" ); + public boolean accept(DependencyNode node, List parents) { + requireNonNull(node, "node cannot be null"); + requireNonNull(parents, "parents cannot be null"); Dependency dependency = node.getDependency(); - if ( dependency == null ) - { + if (dependency == null) { return true; } String id = dependency.getArtifact().getArtifactId(); - if ( excludes.contains( id ) ) - { + if (excludes.contains(id)) { return false; } id = dependency.getArtifact().getGroupId() + ':' + id; - if ( excludes.contains( id ) ) - { + if (excludes.contains(id)) { return false; } @@ -82,29 +73,24 @@ public boolean accept( DependencyNode node, List parents ) } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } ExclusionsDependencyFilter that = (ExclusionsDependencyFilter) obj; - return this.excludes.equals( that.excludes ); + return this.excludes.equals(that.excludes); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + excludes.hashCode(); return hash; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/NotDependencyFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/NotDependencyFilter.java index dcb419a63..2ad13255c 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/NotDependencyFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/NotDependencyFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,19 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.filter; import java.util.List; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.graph.DependencyFilter; import org.eclipse.aether.graph.DependencyNode; +import static java.util.Objects.requireNonNull; + /** * A dependency filter that negates another filter. */ -public final class NotDependencyFilter - implements DependencyFilter -{ +public final class NotDependencyFilter implements DependencyFilter { private final DependencyFilter filter; @@ -39,40 +37,33 @@ public final class NotDependencyFilter * * @param filter The filter to negate, must not be {@code null}. */ - public NotDependencyFilter( DependencyFilter filter ) - { - this.filter = requireNonNull( filter, "dependency filter cannot be null" ); + public NotDependencyFilter(DependencyFilter filter) { + this.filter = requireNonNull(filter, "dependency filter cannot be null"); } - public boolean accept( DependencyNode node, List parents ) - { - return !filter.accept( node, parents ); + public boolean accept(DependencyNode node, List parents) { + return !filter.accept(node, parents); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } NotDependencyFilter that = (NotDependencyFilter) obj; - return this.filter.equals( that.filter ); + return this.filter.equals(that.filter); } @Override - public int hashCode() - { + public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + filter.hashCode(); return hash; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/OrDependencyFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/OrDependencyFilter.java index 2c408e7b6..fa2fce327 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/OrDependencyFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/OrDependencyFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.filter; import java.util.Collection; import java.util.Collections; @@ -31,64 +30,51 @@ /** * A dependency filter that combines zero or more other filters using a logical {@code OR}. */ -public final class OrDependencyFilter - implements DependencyFilter -{ +public final class OrDependencyFilter implements DependencyFilter { private final Set filters = new LinkedHashSet<>(); /** * Creates a new filter from the specified filters. - * + * * @param filters The filters to combine, may be {@code null}. */ - public OrDependencyFilter( DependencyFilter... filters ) - { - if ( filters != null ) - { - Collections.addAll( this.filters, filters ); + public OrDependencyFilter(DependencyFilter... filters) { + if (filters != null) { + Collections.addAll(this.filters, filters); } } /** * Creates a new filter from the specified filters. - * + * * @param filters The filters to combine, may be {@code null}. */ - public OrDependencyFilter( Collection filters ) - { - if ( filters != null ) - { - this.filters.addAll( filters ); + public OrDependencyFilter(Collection filters) { + if (filters != null) { + this.filters.addAll(filters); } } /** * Creates a new filter from the specified filters. - * + * * @param filter1 The first filter to combine, may be {@code null}. * @param filter2 The first filter to combine, may be {@code null}. * @return The combined filter or {@code null} if both filter were {@code null}. */ - public static DependencyFilter newInstance( DependencyFilter filter1, DependencyFilter filter2 ) - { - if ( filter1 == null ) - { + public static DependencyFilter newInstance(DependencyFilter filter1, DependencyFilter filter2) { + if (filter1 == null) { return filter2; - } - else if ( filter2 == null ) - { + } else if (filter2 == null) { return filter1; } - return new OrDependencyFilter( filter1, filter2 ); + return new OrDependencyFilter(filter1, filter2); } - public boolean accept( DependencyNode node, List parents ) - { - for ( DependencyFilter filter : filters ) - { - if ( filter.accept( node, parents ) ) - { + public boolean accept(DependencyNode node, List parents) { + for (DependencyFilter filter : filters) { + if (filter.accept(node, parents)) { return true; } } @@ -96,29 +82,24 @@ public boolean accept( DependencyNode node, List parents ) } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } OrDependencyFilter that = (OrDependencyFilter) obj; - return this.filters.equals( that.filters ); + return this.filters.equals(that.filters); } @Override - public int hashCode() - { + public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + filters.hashCode(); return hash; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/PatternExclusionsDependencyFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/PatternExclusionsDependencyFilter.java index e7686147a..8175cb0cd 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/PatternExclusionsDependencyFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/PatternExclusionsDependencyFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.filter; import java.util.Collection; @@ -26,7 +25,7 @@ /** * A simple filter to exclude artifacts from a list of patterns. The artifact pattern syntax is of the form: - * + * *
      * [groupId]:[artifactId]:[extension]:[version]
      * 
    @@ -39,58 +38,50 @@ * org.eclipse. , and :::*-SNAPSHOT would match all snapshot artifacts. *

    */ -public final class PatternExclusionsDependencyFilter - extends AbstractPatternDependencyFilter -{ +public final class PatternExclusionsDependencyFilter extends AbstractPatternDependencyFilter { /** * Creates a new filter using the specified patterns. - * + * * @param patterns The exclude patterns, may be {@code null} or empty to exclude no artifacts. */ - public PatternExclusionsDependencyFilter( final String... patterns ) - { - super( patterns ); + public PatternExclusionsDependencyFilter(final String... patterns) { + super(patterns); } /** * Creates a new filter using the specified patterns. - * + * * @param versionScheme To be used for parsing versions/version ranges. If {@code null} and pattern specifies a * range no artifact will be excluded. * @param patterns The exclude patterns, may be {@code null} or empty to exclude no artifacts. */ - public PatternExclusionsDependencyFilter( final VersionScheme versionScheme, final String... patterns ) - { - super( versionScheme, patterns ); + public PatternExclusionsDependencyFilter(final VersionScheme versionScheme, final String... patterns) { + super(versionScheme, patterns); } /** * Creates a new filter using the specified patterns. - * + * * @param patterns The include patterns, may be {@code null} or empty to include no artifacts. */ - public PatternExclusionsDependencyFilter( final Collection patterns ) - { - super( patterns ); + public PatternExclusionsDependencyFilter(final Collection patterns) { + super(patterns); } /** * Creates a new filter using the specified patterns and {@link VersionScheme} . - * + * * @param versionScheme To be used for parsing versions/version ranges. If {@code null} and pattern specifies a * range no artifact will be excluded. * @param patterns The exclude patterns, may be {@code null} or empty to exclude no artifacts. */ - public PatternExclusionsDependencyFilter( final VersionScheme versionScheme, final Collection patterns ) - { - super( versionScheme, patterns ); + public PatternExclusionsDependencyFilter(final VersionScheme versionScheme, final Collection patterns) { + super(versionScheme, patterns); } @Override - protected boolean accept( Artifact artifact ) - { - return !super.accept( artifact ); + protected boolean accept(Artifact artifact) { + return !super.accept(artifact); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/PatternInclusionsDependencyFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/PatternInclusionsDependencyFilter.java index e30600b0d..d99434dbf 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/PatternInclusionsDependencyFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/PatternInclusionsDependencyFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.filter; import java.util.Collection; @@ -25,7 +24,7 @@ /** * A simple filter to include artifacts from a list of patterns. The artifact pattern syntax is of the form: - * + * *
      * [groupId]:[artifactId]:[extension]:[version]
      * 
    @@ -38,52 +37,45 @@ * org.eclipse. , and :::*-SNAPSHOT would match all snapshot artifacts. *

    */ -public final class PatternInclusionsDependencyFilter - extends AbstractPatternDependencyFilter -{ +public final class PatternInclusionsDependencyFilter extends AbstractPatternDependencyFilter { /** * Creates a new filter using the specified patterns. - * + * * @param patterns The include patterns, may be {@code null} or empty to include no artifacts. */ - public PatternInclusionsDependencyFilter( final String... patterns ) - { - super( patterns ); + public PatternInclusionsDependencyFilter(final String... patterns) { + super(patterns); } /** * Creates a new filter using the specified patterns. - * + * * @param versionScheme To be used for parsing versions/version ranges. If {@code null} and pattern specifies a * range no artifact will be included. * @param patterns The include patterns, may be {@code null} or empty to include no artifacts. */ - public PatternInclusionsDependencyFilter( final VersionScheme versionScheme, final String... patterns ) - { - super( versionScheme, patterns ); + public PatternInclusionsDependencyFilter(final VersionScheme versionScheme, final String... patterns) { + super(versionScheme, patterns); } /** * Creates a new filter using the specified patterns. - * + * * @param patterns The include patterns, may be {@code null} or empty to include no artifacts. */ - public PatternInclusionsDependencyFilter( final Collection patterns ) - { - super( patterns ); + public PatternInclusionsDependencyFilter(final Collection patterns) { + super(patterns); } /** * Creates a new filter using the specified patterns and {@link VersionScheme} . - * + * * @param versionScheme To be used for parsing versions/version ranges. If {@code null} and pattern specifies a * range no artifact will be included. * @param patterns The include patterns, may be {@code null} or empty to include no artifacts. */ - public PatternInclusionsDependencyFilter( final VersionScheme versionScheme, final Collection patterns ) - { - super( versionScheme, patterns ); + public PatternInclusionsDependencyFilter(final VersionScheme versionScheme, final Collection patterns) { + super(versionScheme, patterns); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/ScopeDependencyFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/ScopeDependencyFilter.java index d2657d36a..276b176a1 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/ScopeDependencyFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/ScopeDependencyFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.filter; import java.util.Arrays; import java.util.Collection; @@ -32,12 +31,10 @@ /** * A dependency filter based on dependency scopes. Note: This filter does not assume any relationships between * the scopes. In particular, the filter is not aware of scopes that logically include other scopes. - * + * * @see Dependency#getScope() */ -public final class ScopeDependencyFilter - implements DependencyFilter -{ +public final class ScopeDependencyFilter implements DependencyFilter { private final Set included = new HashSet<>(); @@ -45,74 +42,61 @@ public final class ScopeDependencyFilter /** * Creates a new filter using the specified includes and excludes. - * + * * @param included The set of scopes to include, may be {@code null} or empty to include any scope. * @param excluded The set of scopes to exclude, may be {@code null} or empty to exclude no scope. */ - public ScopeDependencyFilter( Collection included, Collection excluded ) - { - if ( included != null ) - { - this.included.addAll( included ); + public ScopeDependencyFilter(Collection included, Collection excluded) { + if (included != null) { + this.included.addAll(included); } - if ( excluded != null ) - { - this.excluded.addAll( excluded ); + if (excluded != null) { + this.excluded.addAll(excluded); } } /** * Creates a new filter using the specified excludes. - * + * * @param excluded The set of scopes to exclude, may be {@code null} or empty to exclude no scope. */ - public ScopeDependencyFilter( String... excluded ) - { - if ( excluded != null ) - { - this.excluded.addAll( Arrays.asList( excluded ) ); + public ScopeDependencyFilter(String... excluded) { + if (excluded != null) { + this.excluded.addAll(Arrays.asList(excluded)); } } - public boolean accept( DependencyNode node, List parents ) - { + public boolean accept(DependencyNode node, List parents) { Dependency dependency = node.getDependency(); - if ( dependency == null ) - { + if (dependency == null) { return true; } String scope = node.getDependency().getScope(); - return ( included.isEmpty() || included.contains( scope ) ) - && ( excluded.isEmpty() || !excluded.contains( scope ) ); + return (included.isEmpty() || included.contains(scope)) && (excluded.isEmpty() || !excluded.contains(scope)); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } ScopeDependencyFilter that = (ScopeDependencyFilter) obj; - return this.included.equals( that.included ) && this.excluded.equals( that.excluded ); + return this.included.equals(that.included) && this.excluded.equals(that.excluded); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + included.hashCode(); hash = hash * 31 + excluded.hashCode(); return hash; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/package-info.java index 6547d2ebc..43aab6a58 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/filter/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Various dependency filters for selecting nodes in a dependency graph. */ package org.eclipse.aether.util.filter; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/ClassicDependencyManager.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/ClassicDependencyManager.java index aec953629..56518c0ff 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/ClassicDependencyManager.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/ClassicDependencyManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.manager; import java.util.Collection; import java.util.Collections; @@ -39,9 +38,7 @@ /** * A dependency manager that mimics the way Maven 2.x works. */ -public final class ClassicDependencyManager - implements DependencyManager -{ +public final class ClassicDependencyManager implements DependencyManager { private final int depth; @@ -60,18 +57,23 @@ public final class ClassicDependencyManager /** * Creates a new dependency manager without any management information. */ - public ClassicDependencyManager() - { - this( 0, Collections.emptyMap(), Collections.emptyMap(), - Collections.emptyMap(), Collections.emptyMap(), - Collections.>emptyMap() ); + public ClassicDependencyManager() { + this( + 0, + Collections.emptyMap(), + Collections.emptyMap(), + Collections.emptyMap(), + Collections.emptyMap(), + Collections.>emptyMap()); } - private ClassicDependencyManager( int depth, Map managedVersions, - Map managedScopes, Map managedOptionals, - Map managedLocalPaths, - Map> managedExclusions ) - { + private ClassicDependencyManager( + int depth, + Map managedVersions, + Map managedScopes, + Map managedOptionals, + Map managedLocalPaths, + Map> managedExclusions) { this.depth = depth; this.managedVersions = managedVersions; this.managedScopes = managedScopes; @@ -80,17 +82,13 @@ private ClassicDependencyManager( int depth, Map managedVersions this.managedExclusions = managedExclusions; } - public DependencyManager deriveChildManager( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); - if ( depth >= 2 ) - { + public DependencyManager deriveChildManager(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); + if (depth >= 2) { return this; - } - else if ( depth == 1 ) - { - return new ClassicDependencyManager( depth + 1, managedVersions, managedScopes, managedOptionals, - managedLocalPaths, managedExclusions ); + } else if (depth == 1) { + return new ClassicDependencyManager( + depth + 1, managedVersions, managedScopes, managedOptionals, managedLocalPaths, managedExclusions); } Map managedVersions = this.managedVersions; @@ -99,173 +97,144 @@ else if ( depth == 1 ) Map managedLocalPaths = this.managedLocalPaths; Map> managedExclusions = this.managedExclusions; - for ( Dependency managedDependency : context.getManagedDependencies() ) - { + for (Dependency managedDependency : context.getManagedDependencies()) { Artifact artifact = managedDependency.getArtifact(); - Object key = getKey( artifact ); + Object key = getKey(artifact); String version = artifact.getVersion(); - if ( version.length() > 0 && !managedVersions.containsKey( key ) ) - { - if ( managedVersions == this.managedVersions ) - { - managedVersions = new HashMap<>( this.managedVersions ); + if (version.length() > 0 && !managedVersions.containsKey(key)) { + if (managedVersions == this.managedVersions) { + managedVersions = new HashMap<>(this.managedVersions); } - managedVersions.put( key, version ); + managedVersions.put(key, version); } String scope = managedDependency.getScope(); - if ( scope.length() > 0 && !managedScopes.containsKey( key ) ) - { - if ( managedScopes == this.managedScopes ) - { - managedScopes = new HashMap<>( this.managedScopes ); + if (scope.length() > 0 && !managedScopes.containsKey(key)) { + if (managedScopes == this.managedScopes) { + managedScopes = new HashMap<>(this.managedScopes); } - managedScopes.put( key, scope ); + managedScopes.put(key, scope); } Boolean optional = managedDependency.getOptional(); - if ( optional != null && !managedOptionals.containsKey( key ) ) - { - if ( managedOptionals == this.managedOptionals ) - { - managedOptionals = new HashMap<>( this.managedOptionals ); + if (optional != null && !managedOptionals.containsKey(key)) { + if (managedOptionals == this.managedOptionals) { + managedOptionals = new HashMap<>(this.managedOptionals); } - managedOptionals.put( key, optional ); + managedOptionals.put(key, optional); } - String localPath = managedDependency.getArtifact().getProperty( ArtifactProperties.LOCAL_PATH, null ); - if ( localPath != null && !managedLocalPaths.containsKey( key ) ) - { - if ( managedLocalPaths == this.managedLocalPaths ) - { - managedLocalPaths = new HashMap<>( this.managedLocalPaths ); + String localPath = managedDependency.getArtifact().getProperty(ArtifactProperties.LOCAL_PATH, null); + if (localPath != null && !managedLocalPaths.containsKey(key)) { + if (managedLocalPaths == this.managedLocalPaths) { + managedLocalPaths = new HashMap<>(this.managedLocalPaths); } - managedLocalPaths.put( key, localPath ); + managedLocalPaths.put(key, localPath); } Collection exclusions = managedDependency.getExclusions(); - if ( !exclusions.isEmpty() ) - { - if ( managedExclusions == this.managedExclusions ) - { - managedExclusions = new HashMap<>( this.managedExclusions ); + if (!exclusions.isEmpty()) { + if (managedExclusions == this.managedExclusions) { + managedExclusions = new HashMap<>(this.managedExclusions); } - Collection managed = managedExclusions.computeIfAbsent( key, k -> new LinkedHashSet<>() ); - managed.addAll( exclusions ); + Collection managed = managedExclusions.computeIfAbsent(key, k -> new LinkedHashSet<>()); + managed.addAll(exclusions); } } - return new ClassicDependencyManager( depth + 1, managedVersions, managedScopes, managedOptionals, - managedLocalPaths, managedExclusions ); + return new ClassicDependencyManager( + depth + 1, managedVersions, managedScopes, managedOptionals, managedLocalPaths, managedExclusions); } - public DependencyManagement manageDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); + public DependencyManagement manageDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); DependencyManagement management = null; - Object key = getKey( dependency.getArtifact() ); + Object key = getKey(dependency.getArtifact()); - if ( depth >= 2 ) - { - String version = managedVersions.get( key ); - if ( version != null ) - { + if (depth >= 2) { + String version = managedVersions.get(key); + if (version != null) { management = new DependencyManagement(); - management.setVersion( version ); + management.setVersion(version); } - String scope = managedScopes.get( key ); - if ( scope != null ) - { - if ( management == null ) - { + String scope = managedScopes.get(key); + if (scope != null) { + if (management == null) { management = new DependencyManagement(); } - management.setScope( scope ); + management.setScope(scope); - if ( !JavaScopes.SYSTEM.equals( scope ) - && dependency.getArtifact().getProperty( ArtifactProperties.LOCAL_PATH, null ) != null ) - { + if (!JavaScopes.SYSTEM.equals(scope) + && dependency.getArtifact().getProperty(ArtifactProperties.LOCAL_PATH, null) != null) { Map properties = - new HashMap<>( dependency.getArtifact().getProperties() ); - properties.remove( ArtifactProperties.LOCAL_PATH ); - management.setProperties( properties ); + new HashMap<>(dependency.getArtifact().getProperties()); + properties.remove(ArtifactProperties.LOCAL_PATH); + management.setProperties(properties); } } - if ( ( JavaScopes.SYSTEM.equals( scope ) ) - || ( scope == null && JavaScopes.SYSTEM.equals( dependency.getScope() ) ) ) - { - String localPath = managedLocalPaths.get( key ); - if ( localPath != null ) - { - if ( management == null ) - { + if ((JavaScopes.SYSTEM.equals(scope)) + || (scope == null && JavaScopes.SYSTEM.equals(dependency.getScope()))) { + String localPath = managedLocalPaths.get(key); + if (localPath != null) { + if (management == null) { management = new DependencyManagement(); } Map properties = - new HashMap<>( dependency.getArtifact().getProperties() ); - properties.put( ArtifactProperties.LOCAL_PATH, localPath ); - management.setProperties( properties ); + new HashMap<>(dependency.getArtifact().getProperties()); + properties.put(ArtifactProperties.LOCAL_PATH, localPath); + management.setProperties(properties); } } - Boolean optional = managedOptionals.get( key ); - if ( optional != null ) - { - if ( management == null ) - { + Boolean optional = managedOptionals.get(key); + if (optional != null) { + if (management == null) { management = new DependencyManagement(); } - management.setOptional( optional ); + management.setOptional(optional); } } - Collection exclusions = managedExclusions.get( key ); - if ( exclusions != null ) - { - if ( management == null ) - { + Collection exclusions = managedExclusions.get(key); + if (exclusions != null) { + if (management == null) { management = new DependencyManagement(); } - Collection result = new LinkedHashSet<>( dependency.getExclusions() ); - result.addAll( exclusions ); - management.setExclusions( result ); + Collection result = new LinkedHashSet<>(dependency.getExclusions()); + result.addAll(exclusions); + management.setExclusions(result); } return management; } - private Object getKey( Artifact a ) - { - return new Key( a ); + private Object getKey(Artifact a) { + return new Key(a); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } ClassicDependencyManager that = (ClassicDependencyManager) obj; - return depth == that.depth && managedVersions.equals( that.managedVersions ) - && managedScopes.equals( that.managedScopes ) && managedOptionals.equals( that.managedOptionals ) - && managedExclusions.equals( that.managedExclusions ); + return depth == that.depth + && managedVersions.equals(that.managedVersions) + && managedScopes.equals(that.managedScopes) + && managedOptionals.equals(that.managedOptionals) + && managedExclusions.equals(that.managedExclusions); } @Override - public int hashCode() - { - if ( hashCode == 0 ) - { + public int hashCode() { + if (hashCode == 0) { int hash = 17; hash = hash * 31 + depth; hash = hash * 31 + managedVersions.hashCode(); @@ -277,15 +246,13 @@ public int hashCode() return hashCode; } - static class Key - { + static class Key { private final Artifact artifact; private final int hashCode; - Key( Artifact artifact ) - { + Key(Artifact artifact) { this.artifact = artifact; int hash = 17; @@ -295,29 +262,22 @@ static class Key } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( !( obj instanceof Key ) ) - { + } else if (!(obj instanceof Key)) { return false; } Key that = (Key) obj; - return artifact.getArtifactId().equals( that.artifact.getArtifactId() ) - && artifact.getGroupId().equals( that.artifact.getGroupId() ) - && artifact.getExtension().equals( that.artifact.getExtension() ) - && artifact.getClassifier().equals( that.artifact.getClassifier() ); + return artifact.getArtifactId().equals(that.artifact.getArtifactId()) + && artifact.getGroupId().equals(that.artifact.getGroupId()) + && artifact.getExtension().equals(that.artifact.getExtension()) + && artifact.getClassifier().equals(that.artifact.getClassifier()); } @Override - public int hashCode() - { + public int hashCode() { return hashCode; } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/DefaultDependencyManager.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/DefaultDependencyManager.java index 2c9760470..af131038f 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/DefaultDependencyManager.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/DefaultDependencyManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.manager; import java.util.Collection; import java.util.Collections; @@ -48,9 +47,7 @@ * @author Christian Schulte * @since 1.4.0 */ -public final class DefaultDependencyManager - implements DependencyManager -{ +public final class DefaultDependencyManager implements DependencyManager { private final Map managedVersions; @@ -67,19 +64,21 @@ public final class DefaultDependencyManager /** * Creates a new dependency manager without any management information. */ - public DefaultDependencyManager() - { - this( Collections.emptyMap(), Collections.emptyMap(), - Collections.emptyMap(), Collections.emptyMap(), - Collections.>emptyMap() ); + public DefaultDependencyManager() { + this( + Collections.emptyMap(), + Collections.emptyMap(), + Collections.emptyMap(), + Collections.emptyMap(), + Collections.>emptyMap()); } - private DefaultDependencyManager( final Map managedVersions, - final Map managedScopes, - final Map managedOptionals, - final Map managedLocalPaths, - final Map> managedExclusions ) - { + private DefaultDependencyManager( + final Map managedVersions, + final Map managedScopes, + final Map managedOptionals, + final Map managedLocalPaths, + final Map> managedExclusions) { super(); this.managedVersions = managedVersions; this.managedScopes = managedScopes; @@ -88,222 +87,184 @@ private DefaultDependencyManager( final Map managedVersions, this.managedExclusions = managedExclusions; } - public DependencyManager deriveChildManager( final DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencyManager deriveChildManager(final DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); Map versions = this.managedVersions; Map scopes = this.managedScopes; Map optionals = this.managedOptionals; Map localPaths = this.managedLocalPaths; Map> exclusions = this.managedExclusions; - for ( Dependency managedDependency : context.getManagedDependencies() ) - { + for (Dependency managedDependency : context.getManagedDependencies()) { Artifact artifact = managedDependency.getArtifact(); - Object key = getKey( artifact ); + Object key = getKey(artifact); String version = artifact.getVersion(); - if ( version.length() > 0 && !versions.containsKey( key ) ) - { - if ( versions == this.managedVersions ) - { - versions = new HashMap<>( this.managedVersions ); + if (version.length() > 0 && !versions.containsKey(key)) { + if (versions == this.managedVersions) { + versions = new HashMap<>(this.managedVersions); } - versions.put( key, version ); + versions.put(key, version); } String scope = managedDependency.getScope(); - if ( scope.length() > 0 && !scopes.containsKey( key ) ) - { - if ( scopes == this.managedScopes ) - { - scopes = new HashMap<>( this.managedScopes ); + if (scope.length() > 0 && !scopes.containsKey(key)) { + if (scopes == this.managedScopes) { + scopes = new HashMap<>(this.managedScopes); } - scopes.put( key, scope ); + scopes.put(key, scope); } Boolean optional = managedDependency.getOptional(); - if ( optional != null && !optionals.containsKey( key ) ) - { - if ( optionals == this.managedOptionals ) - { - optionals = new HashMap<>( this.managedOptionals ); + if (optional != null && !optionals.containsKey(key)) { + if (optionals == this.managedOptionals) { + optionals = new HashMap<>(this.managedOptionals); } - optionals.put( key, optional ); + optionals.put(key, optional); } - String localPath = managedDependency.getArtifact().getProperty( ArtifactProperties.LOCAL_PATH, null ); - if ( localPath != null && !localPaths.containsKey( key ) ) - { - if ( localPaths == this.managedLocalPaths ) - { - localPaths = new HashMap<>( this.managedLocalPaths ); + String localPath = managedDependency.getArtifact().getProperty(ArtifactProperties.LOCAL_PATH, null); + if (localPath != null && !localPaths.containsKey(key)) { + if (localPaths == this.managedLocalPaths) { + localPaths = new HashMap<>(this.managedLocalPaths); } - localPaths.put( key, localPath ); + localPaths.put(key, localPath); } - if ( !managedDependency.getExclusions().isEmpty() ) - { - if ( exclusions == this.managedExclusions ) - { - exclusions = new HashMap<>( this.managedExclusions ); + if (!managedDependency.getExclusions().isEmpty()) { + if (exclusions == this.managedExclusions) { + exclusions = new HashMap<>(this.managedExclusions); } - Collection managed = exclusions.computeIfAbsent( key, k -> new LinkedHashSet<>() ); - managed.addAll( managedDependency.getExclusions() ); + Collection managed = exclusions.computeIfAbsent(key, k -> new LinkedHashSet<>()); + managed.addAll(managedDependency.getExclusions()); } } - return new DefaultDependencyManager( versions, scopes, optionals, localPaths, exclusions ); + return new DefaultDependencyManager(versions, scopes, optionals, localPaths, exclusions); } - public DependencyManagement manageDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); + public DependencyManagement manageDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); DependencyManagement management = null; - Object key = getKey( dependency.getArtifact() ); + Object key = getKey(dependency.getArtifact()); - String version = managedVersions.get( key ); - if ( version != null ) - { + String version = managedVersions.get(key); + if (version != null) { management = new DependencyManagement(); - management.setVersion( version ); + management.setVersion(version); } - String scope = managedScopes.get( key ); - if ( scope != null ) - { - if ( management == null ) - { + String scope = managedScopes.get(key); + if (scope != null) { + if (management == null) { management = new DependencyManagement(); } - management.setScope( scope ); + management.setScope(scope); - if ( !JavaScopes.SYSTEM.equals( scope ) - && dependency.getArtifact().getProperty( ArtifactProperties.LOCAL_PATH, null ) != null ) - { + if (!JavaScopes.SYSTEM.equals(scope) + && dependency.getArtifact().getProperty(ArtifactProperties.LOCAL_PATH, null) != null) { Map properties = - new HashMap<>( dependency.getArtifact().getProperties() ); + new HashMap<>(dependency.getArtifact().getProperties()); - properties.remove( ArtifactProperties.LOCAL_PATH ); - management.setProperties( properties ); + properties.remove(ArtifactProperties.LOCAL_PATH); + management.setProperties(properties); } } - if ( ( scope != null && JavaScopes.SYSTEM.equals( scope ) ) - || ( scope == null && JavaScopes.SYSTEM.equals( dependency.getScope() ) ) ) - { - String localPath = managedLocalPaths.get( key ); - if ( localPath != null ) - { - if ( management == null ) - { + if ((scope != null && JavaScopes.SYSTEM.equals(scope)) + || (scope == null && JavaScopes.SYSTEM.equals(dependency.getScope()))) { + String localPath = managedLocalPaths.get(key); + if (localPath != null) { + if (management == null) { management = new DependencyManagement(); } Map properties = - new HashMap<>( dependency.getArtifact().getProperties() ); + new HashMap<>(dependency.getArtifact().getProperties()); - properties.put( ArtifactProperties.LOCAL_PATH, localPath ); - management.setProperties( properties ); + properties.put(ArtifactProperties.LOCAL_PATH, localPath); + management.setProperties(properties); } } - Boolean optional = managedOptionals.get( key ); - if ( optional != null ) - { - if ( management == null ) - { + Boolean optional = managedOptionals.get(key); + if (optional != null) { + if (management == null) { management = new DependencyManagement(); } - management.setOptional( optional ); + management.setOptional(optional); } - Collection exclusions = managedExclusions.get( key ); - if ( exclusions != null ) - { - if ( management == null ) - { + Collection exclusions = managedExclusions.get(key); + if (exclusions != null) { + if (management == null) { management = new DependencyManagement(); } - Collection result = new LinkedHashSet<>( dependency.getExclusions() ); - result.addAll( exclusions ); - management.setExclusions( result ); + Collection result = new LinkedHashSet<>(dependency.getExclusions()); + result.addAll(exclusions); + management.setExclusions(result); } return management; } - private Object getKey( Artifact a ) - { - return new Key( a ); + private Object getKey(Artifact a) { + return new Key(a); } @Override - public boolean equals( final Object obj ) - { + public boolean equals(final Object obj) { boolean equal = obj instanceof DefaultDependencyManager; - if ( equal ) - { + if (equal) { final DefaultDependencyManager that = (DefaultDependencyManager) obj; - equal = Objects.equals( managedVersions, that.managedVersions ) - && Objects.equals( managedScopes, that.managedScopes ) - && Objects.equals( managedOptionals, that.managedOptionals ) - && Objects.equals( managedExclusions, that.managedExclusions ); - + equal = Objects.equals(managedVersions, that.managedVersions) + && Objects.equals(managedScopes, that.managedScopes) + && Objects.equals(managedOptionals, that.managedOptionals) + && Objects.equals(managedExclusions, that.managedExclusions); } return equal; } @Override - public int hashCode() - { - if ( hashCode == 0 ) - { - hashCode = Objects.hash( managedVersions, managedScopes, managedOptionals, managedExclusions ); + public int hashCode() { + if (hashCode == 0) { + hashCode = Objects.hash(managedVersions, managedScopes, managedOptionals, managedExclusions); } return hashCode; } - static class Key - { + static class Key { private final Artifact artifact; private final int hashCode; - Key( final Artifact artifact ) - { + Key(final Artifact artifact) { this.artifact = artifact; - this.hashCode = Objects.hash( artifact.getGroupId(), artifact.getArtifactId() ); + this.hashCode = Objects.hash(artifact.getGroupId(), artifact.getArtifactId()); } @Override - public boolean equals( final Object obj ) - { + public boolean equals(final Object obj) { boolean equal = obj instanceof Key; - if ( equal ) - { + if (equal) { final Key that = (Key) obj; - return Objects.equals( artifact.getArtifactId(), that.artifact.getArtifactId() ) - && Objects.equals( artifact.getGroupId(), that.artifact.getGroupId() ) - && Objects.equals( artifact.getExtension(), that.artifact.getExtension() ) - && Objects.equals( artifact.getClassifier(), that.artifact.getClassifier() ); - + return Objects.equals(artifact.getArtifactId(), that.artifact.getArtifactId()) + && Objects.equals(artifact.getGroupId(), that.artifact.getGroupId()) + && Objects.equals(artifact.getExtension(), that.artifact.getExtension()) + && Objects.equals(artifact.getClassifier(), that.artifact.getClassifier()); } return false; } @Override - public int hashCode() - { + public int hashCode() { return this.hashCode; } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/DependencyManagerUtils.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/DependencyManagerUtils.java index 3afcacc27..da47f127e 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/DependencyManagerUtils.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/DependencyManagerUtils.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.manager; import java.util.Collection; import java.util.Map; @@ -28,8 +27,7 @@ /** * A utility class assisting in analyzing the effects of dependency management. */ -public final class DependencyManagerUtils -{ +public final class DependencyManagerUtils { /** * The key in the repository session's {@link org.eclipse.aether.RepositorySystemSession#getConfigProperties() @@ -82,13 +80,11 @@ public final class DependencyManagerUtils * @return The node's dependency version before dependency management or {@code null} if the version was not managed * or if {@link #CONFIG_PROP_VERBOSE} was not enabled. */ - public static String getPremanagedVersion( DependencyNode node ) - { - if ( ( node.getManagedBits() & DependencyNode.MANAGED_VERSION ) == 0 ) - { + public static String getPremanagedVersion(DependencyNode node) { + if ((node.getManagedBits() & DependencyNode.MANAGED_VERSION) == 0) { return null; } - return cast( node.getData().get( NODE_DATA_PREMANAGED_VERSION ), String.class ); + return cast(node.getData().get(NODE_DATA_PREMANAGED_VERSION), String.class); } /** @@ -99,13 +95,11 @@ public static String getPremanagedVersion( DependencyNode node ) * @return The node's dependency scope before dependency management or {@code null} if the scope was not managed or * if {@link #CONFIG_PROP_VERBOSE} was not enabled. */ - public static String getPremanagedScope( DependencyNode node ) - { - if ( ( node.getManagedBits() & DependencyNode.MANAGED_SCOPE ) == 0 ) - { + public static String getPremanagedScope(DependencyNode node) { + if ((node.getManagedBits() & DependencyNode.MANAGED_SCOPE) == 0) { return null; } - return cast( node.getData().get( NODE_DATA_PREMANAGED_SCOPE ), String.class ); + return cast(node.getData().get(NODE_DATA_PREMANAGED_SCOPE), String.class); } /** @@ -116,13 +110,11 @@ public static String getPremanagedScope( DependencyNode node ) * @return The node's optional flag before dependency management or {@code null} if the flag was not managed or if * {@link #CONFIG_PROP_VERBOSE} was not enabled. */ - public static Boolean getPremanagedOptional( DependencyNode node ) - { - if ( ( node.getManagedBits() & DependencyNode.MANAGED_OPTIONAL ) == 0 ) - { + public static Boolean getPremanagedOptional(DependencyNode node) { + if ((node.getManagedBits() & DependencyNode.MANAGED_OPTIONAL) == 0) { return null; } - return cast( node.getData().get( NODE_DATA_PREMANAGED_OPTIONAL ), Boolean.class ); + return cast(node.getData().get(NODE_DATA_PREMANAGED_OPTIONAL), Boolean.class); } /** @@ -135,14 +127,12 @@ public static Boolean getPremanagedOptional( DependencyNode node ) * * @since 1.1.0 */ - @SuppressWarnings( "unchecked" ) - public static Collection getPremanagedExclusions( DependencyNode node ) - { - if ( ( node.getManagedBits() & DependencyNode.MANAGED_EXCLUSIONS ) == 0 ) - { + @SuppressWarnings("unchecked") + public static Collection getPremanagedExclusions(DependencyNode node) { + if ((node.getManagedBits() & DependencyNode.MANAGED_EXCLUSIONS) == 0) { return null; } - return cast( node.getData().get( NODE_DATA_PREMANAGED_EXCLUSIONS ), Collection.class ); + return cast(node.getData().get(NODE_DATA_PREMANAGED_EXCLUSIONS), Collection.class); } /** @@ -155,19 +145,15 @@ public static Collection getPremanagedExclusions( DependencyNode node * * @since 1.1.0 */ - @SuppressWarnings( "unchecked" ) - public static Map getPremanagedProperties( DependencyNode node ) - { - if ( ( node.getManagedBits() & DependencyNode.MANAGED_PROPERTIES ) == 0 ) - { + @SuppressWarnings("unchecked") + public static Map getPremanagedProperties(DependencyNode node) { + if ((node.getManagedBits() & DependencyNode.MANAGED_PROPERTIES) == 0) { return null; } - return cast( node.getData().get( NODE_DATA_PREMANAGED_PROPERTIES ), Map.class ); + return cast(node.getData().get(NODE_DATA_PREMANAGED_PROPERTIES), Map.class); } - private static T cast( Object obj, Class type ) - { - return type.isInstance( obj ) ? type.cast( obj ) : null; + private static T cast(Object obj, Class type) { + return type.isInstance(obj) ? type.cast(obj) : null; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/NoopDependencyManager.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/NoopDependencyManager.java index 245c02433..58511a0c6 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/NoopDependencyManager.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/NoopDependencyManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.manager; import org.eclipse.aether.collection.DependencyCollectionContext; import org.eclipse.aether.collection.DependencyManagement; @@ -29,9 +28,7 @@ /** * A dependency manager that does not do any dependency management. */ -public final class NoopDependencyManager - implements DependencyManager -{ +public final class NoopDependencyManager implements DependencyManager { /** * A ready-made instance of this dependency manager which can safely be reused throughout an entire application @@ -42,40 +39,30 @@ public final class NoopDependencyManager /** * Creates a new instance of this dependency manager. Usually, {@link #INSTANCE} should be used instead. */ - public NoopDependencyManager() - { - } + public NoopDependencyManager() {} - public DependencyManager deriveChildManager( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencyManager deriveChildManager(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); return this; } - public DependencyManagement manageDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); + public DependencyManagement manageDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); return null; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } return true; } @Override - public int hashCode() - { + public int hashCode() { return getClass().hashCode(); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/TransitiveDependencyManager.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/TransitiveDependencyManager.java index 56e00170e..09e01c924 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/TransitiveDependencyManager.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/TransitiveDependencyManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.manager; import java.util.Collection; import java.util.Collections; @@ -43,9 +42,7 @@ * @author Christian Schulte * @since 1.4.0 */ -public final class TransitiveDependencyManager - implements DependencyManager -{ +public final class TransitiveDependencyManager implements DependencyManager { private final Map managedVersions; @@ -64,20 +61,23 @@ public final class TransitiveDependencyManager /** * Creates a new dependency manager without any management information. */ - public TransitiveDependencyManager() - { - this( 0, Collections.emptyMap(), Collections.emptyMap(), - Collections.emptyMap(), Collections.emptyMap(), - Collections.>emptyMap() ); + public TransitiveDependencyManager() { + this( + 0, + Collections.emptyMap(), + Collections.emptyMap(), + Collections.emptyMap(), + Collections.emptyMap(), + Collections.>emptyMap()); } - private TransitiveDependencyManager( final int depth, - final Map managedVersions, - final Map managedScopes, - final Map managedOptionals, - final Map managedLocalPaths, - final Map> managedExclusions ) - { + private TransitiveDependencyManager( + final int depth, + final Map managedVersions, + final Map managedScopes, + final Map managedOptionals, + final Map managedLocalPaths, + final Map> managedExclusions) { super(); this.depth = depth; this.managedVersions = managedVersions; @@ -87,220 +87,183 @@ private TransitiveDependencyManager( final int depth, this.managedExclusions = managedExclusions; } - public DependencyManager deriveChildManager( final DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencyManager deriveChildManager(final DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); Map versions = managedVersions; Map scopes = managedScopes; Map optionals = managedOptionals; Map localPaths = managedLocalPaths; Map> exclusions = managedExclusions; - for ( Dependency managedDependency : context.getManagedDependencies() ) - { + for (Dependency managedDependency : context.getManagedDependencies()) { Artifact artifact = managedDependency.getArtifact(); - Object key = getKey( artifact ); + Object key = getKey(artifact); String version = artifact.getVersion(); - if ( version.length() > 0 && !versions.containsKey( key ) ) - { - if ( versions == managedVersions ) - { - versions = new HashMap<>( managedVersions ); + if (version.length() > 0 && !versions.containsKey(key)) { + if (versions == managedVersions) { + versions = new HashMap<>(managedVersions); } - versions.put( key, version ); + versions.put(key, version); } String scope = managedDependency.getScope(); - if ( scope.length() > 0 && !scopes.containsKey( key ) ) - { - if ( scopes == this.managedScopes ) - { - scopes = new HashMap<>( this.managedScopes ); + if (scope.length() > 0 && !scopes.containsKey(key)) { + if (scopes == this.managedScopes) { + scopes = new HashMap<>(this.managedScopes); } - scopes.put( key, scope ); + scopes.put(key, scope); } Boolean optional = managedDependency.getOptional(); - if ( optional != null && !optionals.containsKey( key ) ) - { - if ( optionals == managedOptionals ) - { - optionals = new HashMap<>( managedOptionals ); + if (optional != null && !optionals.containsKey(key)) { + if (optionals == managedOptionals) { + optionals = new HashMap<>(managedOptionals); } - optionals.put( key, optional ); + optionals.put(key, optional); } - String localPath = managedDependency.getArtifact().getProperty( ArtifactProperties.LOCAL_PATH, null ); - if ( localPath != null && !localPaths.containsKey( key ) ) - { - if ( localPaths == this.managedLocalPaths ) - { - localPaths = new HashMap<>( managedLocalPaths ); + String localPath = managedDependency.getArtifact().getProperty(ArtifactProperties.LOCAL_PATH, null); + if (localPath != null && !localPaths.containsKey(key)) { + if (localPaths == this.managedLocalPaths) { + localPaths = new HashMap<>(managedLocalPaths); } - localPaths.put( key, localPath ); + localPaths.put(key, localPath); } - if ( !managedDependency.getExclusions().isEmpty() ) - { - if ( exclusions == managedExclusions ) - { - exclusions = new HashMap<>( managedExclusions ); + if (!managedDependency.getExclusions().isEmpty()) { + if (exclusions == managedExclusions) { + exclusions = new HashMap<>(managedExclusions); } - Collection managed = exclusions.computeIfAbsent( key, k -> new LinkedHashSet<>() ); - managed.addAll( managedDependency.getExclusions() ); + Collection managed = exclusions.computeIfAbsent(key, k -> new LinkedHashSet<>()); + managed.addAll(managedDependency.getExclusions()); } } - return new TransitiveDependencyManager( depth + 1, versions, scopes, optionals, localPaths, - exclusions ); - + return new TransitiveDependencyManager(depth + 1, versions, scopes, optionals, localPaths, exclusions); } - public DependencyManagement manageDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); + public DependencyManagement manageDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); DependencyManagement management = null; - Object key = getKey( dependency.getArtifact() ); + Object key = getKey(dependency.getArtifact()); - if ( depth >= 2 ) - { - String version = managedVersions.get( key ); - if ( version != null ) - { + if (depth >= 2) { + String version = managedVersions.get(key); + if (version != null) { management = new DependencyManagement(); - management.setVersion( version ); + management.setVersion(version); } - String scope = managedScopes.get( key ); - if ( scope != null ) - { - if ( management == null ) - { + String scope = managedScopes.get(key); + if (scope != null) { + if (management == null) { management = new DependencyManagement(); } - management.setScope( scope ); - - if ( !JavaScopes.SYSTEM.equals( scope ) && dependency.getArtifact().getProperty( - ArtifactProperties.LOCAL_PATH, null ) != null ) - { - Map properties = new HashMap<>( dependency.getArtifact().getProperties() ); - properties.remove( ArtifactProperties.LOCAL_PATH ); - management.setProperties( properties ); + management.setScope(scope); + + if (!JavaScopes.SYSTEM.equals(scope) + && dependency.getArtifact().getProperty(ArtifactProperties.LOCAL_PATH, null) != null) { + Map properties = + new HashMap<>(dependency.getArtifact().getProperties()); + properties.remove(ArtifactProperties.LOCAL_PATH); + management.setProperties(properties); } } - if ( ( JavaScopes.SYSTEM.equals( scope ) ) - || ( scope == null && JavaScopes.SYSTEM.equals( dependency.getScope() ) ) ) - { - String localPath = managedLocalPaths.get( key ); - if ( localPath != null ) - { - if ( management == null ) - { + if ((JavaScopes.SYSTEM.equals(scope)) + || (scope == null && JavaScopes.SYSTEM.equals(dependency.getScope()))) { + String localPath = managedLocalPaths.get(key); + if (localPath != null) { + if (management == null) { management = new DependencyManagement(); } - Map properties = new HashMap<>( dependency.getArtifact().getProperties() ); - properties.put( ArtifactProperties.LOCAL_PATH, localPath ); - management.setProperties( properties ); + Map properties = + new HashMap<>(dependency.getArtifact().getProperties()); + properties.put(ArtifactProperties.LOCAL_PATH, localPath); + management.setProperties(properties); } } - Boolean optional = managedOptionals.get( key ); - if ( optional != null ) - { - if ( management == null ) - { + Boolean optional = managedOptionals.get(key); + if (optional != null) { + if (management == null) { management = new DependencyManagement(); } - management.setOptional( optional ); + management.setOptional(optional); } } - Collection exclusions = managedExclusions.get( key ); - if ( exclusions != null ) - { - if ( management == null ) - { + Collection exclusions = managedExclusions.get(key); + if (exclusions != null) { + if (management == null) { management = new DependencyManagement(); } - Collection result = new LinkedHashSet<>( dependency.getExclusions() ); - result.addAll( exclusions ); - management.setExclusions( result ); + Collection result = new LinkedHashSet<>(dependency.getExclusions()); + result.addAll(exclusions); + management.setExclusions(result); } return management; } - private Object getKey( Artifact a ) - { - return new Key( a ); + private Object getKey(Artifact a) { + return new Key(a); } @Override - public boolean equals( final Object obj ) - { + public boolean equals(final Object obj) { boolean equal = obj instanceof TransitiveDependencyManager; - if ( equal ) - { + if (equal) { final TransitiveDependencyManager that = (TransitiveDependencyManager) obj; return depth == that.depth - && Objects.equals( managedVersions, that.managedVersions ) - && Objects.equals( managedScopes, that.managedScopes ) - && Objects.equals( managedOptionals, that.managedOptionals ) - && Objects.equals( managedExclusions, that.managedExclusions ); + && Objects.equals(managedVersions, that.managedVersions) + && Objects.equals(managedScopes, that.managedScopes) + && Objects.equals(managedOptionals, that.managedOptionals) + && Objects.equals(managedExclusions, that.managedExclusions); } return false; } @Override - public int hashCode() - { - if ( hashCode == 0 ) - { - hashCode = Objects.hash( depth, managedVersions, managedScopes, managedOptionals, managedExclusions ); + public int hashCode() { + if (hashCode == 0) { + hashCode = Objects.hash(depth, managedVersions, managedScopes, managedOptionals, managedExclusions); } return hashCode; } - static class Key - { + static class Key { private final Artifact artifact; private final int hashCode; - Key( final Artifact artifact ) - { + Key(final Artifact artifact) { this.artifact = artifact; - this.hashCode = Objects.hash( artifact.getGroupId(), artifact.getArtifactId() ); + this.hashCode = Objects.hash(artifact.getGroupId(), artifact.getArtifactId()); } @Override - public boolean equals( final Object obj ) - { + public boolean equals(final Object obj) { boolean equal = obj instanceof Key; - if ( equal ) - { + if (equal) { final Key that = (Key) obj; - return Objects.equals( artifact.getArtifactId(), that.artifact.getArtifactId() ) - && Objects.equals( artifact.getGroupId(), that.artifact.getGroupId() ) - && Objects.equals( artifact.getExtension(), that.artifact.getExtension() ) - && Objects.equals( artifact.getClassifier(), that.artifact.getClassifier() ); + return Objects.equals(artifact.getArtifactId(), that.artifact.getArtifactId()) + && Objects.equals(artifact.getGroupId(), that.artifact.getGroupId()) + && Objects.equals(artifact.getExtension(), that.artifact.getExtension()) + && Objects.equals(artifact.getClassifier(), that.artifact.getClassifier()); } return false; } @Override - public int hashCode() - { + public int hashCode() { return this.hashCode; } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/package-info.java index 7c7ae1282..f2f9a5bab 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/manager/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Various dependency managers for building a dependency graph. */ package org.eclipse.aether.util.graph.manager; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/AndDependencySelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/AndDependencySelector.java index 7e5845820..f1169dd46 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/AndDependencySelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/AndDependencySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.selector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.selector; import java.util.Arrays; import java.util.Collection; @@ -36,9 +35,7 @@ * A dependency selector that combines zero or more other selectors using a logical {@code AND}. The resulting selector * selects a given dependency if and only if all constituent selectors do so. */ -public final class AndDependencySelector - implements DependencySelector -{ +public final class AndDependencySelector implements DependencySelector { private final Set selectors; @@ -47,160 +44,120 @@ public final class AndDependencySelector /** * Creates a new selector from the specified selectors. Prefer * {@link #newInstance(DependencySelector, DependencySelector)} if any of the input selectors might be {@code null}. - * + * * @param selectors The selectors to combine, may be {@code null} but must not contain {@code null} elements. */ - public AndDependencySelector( DependencySelector... selectors ) - { - if ( selectors != null && selectors.length > 0 ) - { - this.selectors = new LinkedHashSet<>( Arrays.asList( selectors ) ); - } - else - { + public AndDependencySelector(DependencySelector... selectors) { + if (selectors != null && selectors.length > 0) { + this.selectors = new LinkedHashSet<>(Arrays.asList(selectors)); + } else { this.selectors = Collections.emptySet(); } } /** * Creates a new selector from the specified selectors. - * + * * @param selectors The selectors to combine, may be {@code null} but must not contain {@code null} elements. */ - public AndDependencySelector( Collection selectors ) - { - if ( selectors != null && !selectors.isEmpty() ) - { - this.selectors = new LinkedHashSet<>( selectors ); - } - else - { + public AndDependencySelector(Collection selectors) { + if (selectors != null && !selectors.isEmpty()) { + this.selectors = new LinkedHashSet<>(selectors); + } else { this.selectors = Collections.emptySet(); } } - private AndDependencySelector( Set selectors ) - { - if ( selectors != null && !selectors.isEmpty() ) - { + private AndDependencySelector(Set selectors) { + if (selectors != null && !selectors.isEmpty()) { this.selectors = selectors; - } - else - { + } else { this.selectors = Collections.emptySet(); } } /** * Creates a new selector from the specified selectors. - * + * * @param selector1 The first selector to combine, may be {@code null}. * @param selector2 The second selector to combine, may be {@code null}. * @return The combined selector or {@code null} if both selectors were {@code null}. */ - public static DependencySelector newInstance( DependencySelector selector1, DependencySelector selector2 ) - { - if ( selector1 == null ) - { + public static DependencySelector newInstance(DependencySelector selector1, DependencySelector selector2) { + if (selector1 == null) { return selector2; - } - else if ( selector2 == null || selector2.equals( selector1 ) ) - { + } else if (selector2 == null || selector2.equals(selector1)) { return selector1; } - return new AndDependencySelector( selector1, selector2 ); + return new AndDependencySelector(selector1, selector2); } - public boolean selectDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); - for ( DependencySelector selector : selectors ) - { - if ( !selector.selectDependency( dependency ) ) - { + public boolean selectDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); + for (DependencySelector selector : selectors) { + if (!selector.selectDependency(dependency)) { return false; } } return true; } - public DependencySelector deriveChildSelector( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencySelector deriveChildSelector(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); int seen = 0; Set childSelectors = null; - for ( DependencySelector selector : selectors ) - { - DependencySelector childSelector = selector.deriveChildSelector( context ); - if ( childSelectors != null ) - { - if ( childSelector != null ) - { - childSelectors.add( childSelector ); + for (DependencySelector selector : selectors) { + DependencySelector childSelector = selector.deriveChildSelector(context); + if (childSelectors != null) { + if (childSelector != null) { + childSelectors.add(childSelector); } - } - else if ( selector != childSelector ) - { + } else if (selector != childSelector) { childSelectors = new LinkedHashSet<>(); - if ( seen > 0 ) - { - for ( DependencySelector s : selectors ) - { - if ( childSelectors.size() >= seen ) - { + if (seen > 0) { + for (DependencySelector s : selectors) { + if (childSelectors.size() >= seen) { break; } - childSelectors.add( s ); + childSelectors.add(s); } } - if ( childSelector != null ) - { - childSelectors.add( childSelector ); + if (childSelector != null) { + childSelectors.add(childSelector); } - } - else - { + } else { seen++; } } - if ( childSelectors == null ) - { + if (childSelectors == null) { return this; } - if ( childSelectors.size() <= 1 ) - { - if ( childSelectors.isEmpty() ) - { + if (childSelectors.size() <= 1) { + if (childSelectors.isEmpty()) { return null; } return childSelectors.iterator().next(); } - return new AndDependencySelector( childSelectors ); + return new AndDependencySelector(childSelectors); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } AndDependencySelector that = (AndDependencySelector) obj; - return selectors.equals( that.selectors ); + return selectors.equals(that.selectors); } @Override - public int hashCode() - { - if ( hashCode == 0 ) - { + public int hashCode() { + if (hashCode == 0) { int hash = 17; hash = hash * 31 + selectors.hashCode(); hashCode = hash; @@ -209,20 +166,18 @@ public int hashCode() } @Override - public String toString() - { - StringBuilder builder = new StringBuilder().append( this.getClass().getSimpleName() ).append( '(' ); + public String toString() { + StringBuilder builder = + new StringBuilder().append(this.getClass().getSimpleName()).append('('); Iterator iterator = this.selectors.iterator(); - while ( iterator.hasNext() ) - { + while (iterator.hasNext()) { final DependencySelector selector = iterator.next(); - builder.append( selector.toString() ); - if ( iterator.hasNext() ) // not last + builder.append(selector.toString()); + if (iterator.hasNext()) // not last { - builder.append( " && " ); + builder.append(" && "); } } - return builder.append( ')' ).toString(); + return builder.append(')').toString(); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/ExclusionDependencySelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/ExclusionDependencySelector.java index 74cf501a2..a9d5a7efb 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/ExclusionDependencySelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/ExclusionDependencySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.selector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.selector; import java.util.Arrays; import java.util.Collection; @@ -34,12 +33,10 @@ /** * A dependency selector that applies exclusions based on artifact coordinates. - * + * * @see Dependency#getExclusions() */ -public final class ExclusionDependencySelector - implements DependencySelector -{ +public final class ExclusionDependencySelector implements DependencySelector { // sorted and dupe-free array, faster to iterate than LinkedHashSet private final Exclusion[] exclusions; @@ -49,198 +46,155 @@ public final class ExclusionDependencySelector /** * Creates a new selector without any exclusions. */ - public ExclusionDependencySelector() - { + public ExclusionDependencySelector() { this.exclusions = new Exclusion[0]; } /** * Creates a new selector with the specified exclusions. - * + * * @param exclusions The exclusions, may be {@code null}. */ - public ExclusionDependencySelector( Collection exclusions ) - { - if ( exclusions != null && !exclusions.isEmpty() ) - { - TreeSet sorted = new TreeSet<>( ExclusionComparator.INSTANCE ); - sorted.addAll( exclusions ); - this.exclusions = sorted.toArray( new Exclusion[0] ); - } - else - { + public ExclusionDependencySelector(Collection exclusions) { + if (exclusions != null && !exclusions.isEmpty()) { + TreeSet sorted = new TreeSet<>(ExclusionComparator.INSTANCE); + sorted.addAll(exclusions); + this.exclusions = sorted.toArray(new Exclusion[0]); + } else { this.exclusions = new Exclusion[0]; } } - private ExclusionDependencySelector( Exclusion[] exclusions ) - { + private ExclusionDependencySelector(Exclusion[] exclusions) { this.exclusions = exclusions; } - public boolean selectDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); + public boolean selectDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); Artifact artifact = dependency.getArtifact(); - for ( Exclusion exclusion : exclusions ) - { - if ( matches( exclusion, artifact ) ) - { + for (Exclusion exclusion : exclusions) { + if (matches(exclusion, artifact)) { return false; } } return true; } - private boolean matches( Exclusion exclusion, Artifact artifact ) - { - if ( !matches( exclusion.getArtifactId(), artifact.getArtifactId() ) ) - { + private boolean matches(Exclusion exclusion, Artifact artifact) { + if (!matches(exclusion.getArtifactId(), artifact.getArtifactId())) { return false; } - if ( !matches( exclusion.getGroupId(), artifact.getGroupId() ) ) - { + if (!matches(exclusion.getGroupId(), artifact.getGroupId())) { return false; } - if ( !matches( exclusion.getExtension(), artifact.getExtension() ) ) - { + if (!matches(exclusion.getExtension(), artifact.getExtension())) { return false; } - if ( !matches( exclusion.getClassifier(), artifact.getClassifier() ) ) - { + if (!matches(exclusion.getClassifier(), artifact.getClassifier())) { return false; } return true; } - private boolean matches( String pattern, String value ) - { - return "*".equals( pattern ) || pattern.equals( value ); + private boolean matches(String pattern, String value) { + return "*".equals(pattern) || pattern.equals(value); } - public DependencySelector deriveChildSelector( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencySelector deriveChildSelector(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); Dependency dependency = context.getDependency(); - Collection exclusions = ( dependency != null ) ? dependency.getExclusions() : null; - if ( exclusions == null || exclusions.isEmpty() ) - { + Collection exclusions = (dependency != null) ? dependency.getExclusions() : null; + if (exclusions == null || exclusions.isEmpty()) { return this; } Exclusion[] merged = this.exclusions; int count = merged.length; - for ( Exclusion exclusion : exclusions ) - { - int index = Arrays.binarySearch( merged, exclusion, ExclusionComparator.INSTANCE ); - if ( index < 0 ) - { - index = -( index + 1 ); - if ( count >= merged.length ) - { + for (Exclusion exclusion : exclusions) { + int index = Arrays.binarySearch(merged, exclusion, ExclusionComparator.INSTANCE); + if (index < 0) { + index = -(index + 1); + if (count >= merged.length) { Exclusion[] tmp = new Exclusion[merged.length + exclusions.size()]; - System.arraycopy( merged, 0, tmp, 0, index ); + System.arraycopy(merged, 0, tmp, 0, index); tmp[index] = exclusion; - System.arraycopy( merged, index, tmp, index + 1, count - index ); + System.arraycopy(merged, index, tmp, index + 1, count - index); merged = tmp; - } - else - { - System.arraycopy( merged, index, merged, index + 1, count - index ); + } else { + System.arraycopy(merged, index, merged, index + 1, count - index); merged[index] = exclusion; } count++; } } - if ( merged == this.exclusions ) - { + if (merged == this.exclusions) { return this; } - if ( merged.length != count ) - { + if (merged.length != count) { Exclusion[] tmp = new Exclusion[count]; - System.arraycopy( merged, 0, tmp, 0, count ); + System.arraycopy(merged, 0, tmp, 0, count); merged = tmp; } - return new ExclusionDependencySelector( merged ); + return new ExclusionDependencySelector(merged); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } ExclusionDependencySelector that = (ExclusionDependencySelector) obj; - return Arrays.equals( exclusions, that.exclusions ); + return Arrays.equals(exclusions, that.exclusions); } @Override - public int hashCode() - { - if ( hashCode == 0 ) - { + public int hashCode() { + if (hashCode == 0) { int hash = getClass().hashCode(); - hash = hash * 31 + Arrays.hashCode( exclusions ); + hash = hash * 31 + Arrays.hashCode(exclusions); hashCode = hash; } return hashCode; } @Override - public String toString() - { - StringBuilder builder = new StringBuilder().append( this.getClass().getSimpleName() ).append( '(' ); - for ( int i = 0; i < this.exclusions.length; i++ ) - { - builder.append( this.exclusions[i] ); - if ( i < this.exclusions.length - 1 ) - { - builder.append( ", " ); + public String toString() { + StringBuilder builder = + new StringBuilder().append(this.getClass().getSimpleName()).append('('); + for (int i = 0; i < this.exclusions.length; i++) { + builder.append(this.exclusions[i]); + if (i < this.exclusions.length - 1) { + builder.append(", "); } } - return builder.append( ')' ).toString(); + return builder.append(')').toString(); } - private static class ExclusionComparator - implements Comparator - { + private static class ExclusionComparator implements Comparator { static final ExclusionComparator INSTANCE = new ExclusionComparator(); - public int compare( Exclusion e1, Exclusion e2 ) - { - if ( e1 == null ) - { - return ( e2 == null ) ? 0 : 1; - } - else if ( e2 == null ) - { + public int compare(Exclusion e1, Exclusion e2) { + if (e1 == null) { + return (e2 == null) ? 0 : 1; + } else if (e2 == null) { return -1; } - int rel = e1.getArtifactId().compareTo( e2.getArtifactId() ); - if ( rel == 0 ) - { - rel = e1.getGroupId().compareTo( e2.getGroupId() ); - if ( rel == 0 ) - { - rel = e1.getExtension().compareTo( e2.getExtension() ); - if ( rel == 0 ) - { - rel = e1.getClassifier().compareTo( e2.getClassifier() ); + int rel = e1.getArtifactId().compareTo(e2.getArtifactId()); + if (rel == 0) { + rel = e1.getGroupId().compareTo(e2.getGroupId()); + if (rel == 0) { + rel = e1.getExtension().compareTo(e2.getExtension()); + if (rel == 0) { + rel = e1.getClassifier().compareTo(e2.getClassifier()); } } } return rel; } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/OptionalDependencySelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/OptionalDependencySelector.java index d384eb4a3..64c5abfcb 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/OptionalDependencySelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/OptionalDependencySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.selector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.selector; import org.eclipse.aether.collection.DependencyCollectionContext; import org.eclipse.aether.collection.DependencySelector; @@ -27,54 +26,43 @@ /** * A dependency selector that excludes optional dependencies which occur beyond level one of the dependency graph. - * + * * @see Dependency#isOptional() */ -public final class OptionalDependencySelector - implements DependencySelector -{ +public final class OptionalDependencySelector implements DependencySelector { private final int depth; /** * Creates a new selector to exclude optional transitive dependencies. */ - public OptionalDependencySelector() - { + public OptionalDependencySelector() { depth = 0; } - private OptionalDependencySelector( int depth ) - { + private OptionalDependencySelector(int depth) { this.depth = depth; } - public boolean selectDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); + public boolean selectDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); return depth < 2 || !dependency.isOptional(); } - public DependencySelector deriveChildSelector( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); - if ( depth >= 2 ) - { + public DependencySelector deriveChildSelector(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); + if (depth >= 2) { return this; } - return new OptionalDependencySelector( depth + 1 ); + return new OptionalDependencySelector(depth + 1); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } @@ -83,17 +71,14 @@ else if ( null == obj || !getClass().equals( obj.getClass() ) ) } @Override - public int hashCode() - { + public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + depth; return hash; } @Override - public String toString() - { - return String.format( "%s(depth: %d)", this.getClass().getSimpleName(), this.depth ); + public String toString() { + return String.format("%s(depth: %d)", this.getClass().getSimpleName(), this.depth); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/ScopeDependencySelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/ScopeDependencySelector.java index 00fc26d00..adcb60ef5 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/ScopeDependencySelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/ScopeDependencySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.selector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.selector; import java.util.ArrayList; import java.util.Arrays; @@ -36,12 +35,10 @@ * A dependency selector that filters transitive dependencies based on their scope. Direct dependencies are always * included regardless of their scope. Note: This filter does not assume any relationships between the scopes. * In particular, the filter is not aware of scopes that logically include other scopes. - * + * * @see Dependency#getScope() */ -public final class ScopeDependencySelector - implements DependencySelector -{ +public final class ScopeDependencySelector implements DependencySelector { private final boolean transitive; @@ -51,32 +48,26 @@ public final class ScopeDependencySelector /** * Creates a new selector using the specified includes and excludes. - * + * * @param included The set of scopes to include, may be {@code null} or empty to include any scope. * @param excluded The set of scopes to exclude, may be {@code null} or empty to exclude no scope. */ - public ScopeDependencySelector( Collection included, Collection excluded ) - { + public ScopeDependencySelector(Collection included, Collection excluded) { transitive = false; - this.included = clone( included ); - this.excluded = clone( excluded ); + this.included = clone(included); + this.excluded = clone(excluded); } - private static Collection clone( Collection scopes ) - { + private static Collection clone(Collection scopes) { Collection copy; - if ( scopes == null || scopes.isEmpty() ) - { + if (scopes == null || scopes.isEmpty()) { // checking for null is faster than isEmpty() copy = null; - } - else - { - copy = new HashSet<>( scopes ); - if ( copy.size() <= 2 ) - { + } else { + copy = new HashSet<>(scopes); + if (copy.size() <= 2) { // contains() is faster for smallish array (sorted for equals()!) - copy = new ArrayList<>( new TreeSet<>( copy ) ); + copy = new ArrayList<>(new TreeSet<>(copy)); } } return copy; @@ -84,78 +75,65 @@ private static Collection clone( Collection scopes ) /** * Creates a new selector using the specified excludes. - * + * * @param excluded The set of scopes to exclude, may be {@code null} or empty to exclude no scope. */ - public ScopeDependencySelector( String... excluded ) - { - this( null, ( excluded != null ) ? Arrays.asList( excluded ) : null ); + public ScopeDependencySelector(String... excluded) { + this(null, (excluded != null) ? Arrays.asList(excluded) : null); } - private ScopeDependencySelector( boolean transitive, Collection included, Collection excluded ) - { + private ScopeDependencySelector(boolean transitive, Collection included, Collection excluded) { this.transitive = transitive; this.included = included; this.excluded = excluded; } - public boolean selectDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); - if ( !transitive ) - { + public boolean selectDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); + if (!transitive) { return true; } String scope = dependency.getScope(); - return ( included == null || included.contains( scope ) ) - && ( excluded == null || !excluded.contains( scope ) ); + return (included == null || included.contains(scope)) && (excluded == null || !excluded.contains(scope)); } - public DependencySelector deriveChildSelector( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); - if ( this.transitive || context.getDependency() == null ) - { + public DependencySelector deriveChildSelector(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); + if (this.transitive || context.getDependency() == null) { return this; } - return new ScopeDependencySelector( true, included, excluded ); + return new ScopeDependencySelector(true, included, excluded); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } ScopeDependencySelector that = (ScopeDependencySelector) obj; - return transitive == that.transitive && Objects.equals( included, that.included ) - && Objects.equals( excluded, that.excluded ); + return transitive == that.transitive + && Objects.equals(included, that.included) + && Objects.equals(excluded, that.excluded); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + ( transitive ? 1 : 0 ); - hash = hash * 31 + ( included != null ? included.hashCode() : 0 ); - hash = hash * 31 + ( excluded != null ? excluded.hashCode() : 0 ); + hash = hash * 31 + (transitive ? 1 : 0); + hash = hash * 31 + (included != null ? included.hashCode() : 0); + hash = hash * 31 + (excluded != null ? excluded.hashCode() : 0); return hash; } @Override - public String toString() - { + public String toString() { return String.format( - "%s(included: %s, excluded: %s, transitive: %s)", getClass().getSimpleName(), included, excluded, transitive - ); + "%s(included: %s, excluded: %s, transitive: %s)", + getClass().getSimpleName(), included, excluded, transitive); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/StaticDependencySelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/StaticDependencySelector.java index edcee4481..531d423db 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/StaticDependencySelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/StaticDependencySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.selector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.selector; import org.eclipse.aether.collection.DependencyCollectionContext; import org.eclipse.aether.collection.DependencySelector; @@ -28,43 +27,34 @@ /** * A dependency selector that always includes or excludes dependencies. */ -public final class StaticDependencySelector - implements DependencySelector -{ +public final class StaticDependencySelector implements DependencySelector { private final boolean select; /** * Creates a new selector with the specified selection behavior. - * + * * @param select {@code true} to select all dependencies, {@code false} to exclude all dependencies. */ - public StaticDependencySelector( boolean select ) - { + public StaticDependencySelector(boolean select) { this.select = select; } - public boolean selectDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); + public boolean selectDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); return select; } - public DependencySelector deriveChildSelector( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencySelector deriveChildSelector(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); return this; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } @@ -73,17 +63,14 @@ else if ( null == obj || !getClass().equals( obj.getClass() ) ) } @Override - public int hashCode() - { + public int hashCode() { int hash = getClass().hashCode(); - hash = hash * 31 + ( select ? 1 : 0 ); + hash = hash * 31 + (select ? 1 : 0); return hash; } @Override - public String toString() - { - return String.format( "%s(%s)", this.getClass().getSimpleName(), this.select ? "Select all" : "Exclude all" ); + public String toString() { + return String.format("%s(%s)", this.getClass().getSimpleName(), this.select ? "Select all" : "Exclude all"); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/package-info.java index 3c3cf3c76..3a17025c7 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/selector/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Various dependency selectors for building a dependency graph. */ package org.eclipse.aether.util.graph.selector; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ChainedDependencyGraphTransformer.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ChainedDependencyGraphTransformer.java index 449eeeb4a..c3ef08637 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ChainedDependencyGraphTransformer.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ChainedDependencyGraphTransformer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.collection.DependencyGraphTransformationContext; @@ -29,25 +28,19 @@ /** * A dependency graph transformer that chains other transformers. */ -public final class ChainedDependencyGraphTransformer - implements DependencyGraphTransformer -{ +public final class ChainedDependencyGraphTransformer implements DependencyGraphTransformer { private final DependencyGraphTransformer[] transformers; /** * Creates a new transformer that chains the specified transformers. - * + * * @param transformers The transformers to chain, may be {@code null} or empty. */ - public ChainedDependencyGraphTransformer( DependencyGraphTransformer... transformers ) - { - if ( transformers == null ) - { + public ChainedDependencyGraphTransformer(DependencyGraphTransformer... transformers) { + if (transformers == null) { this.transformers = new DependencyGraphTransformer[0]; - } - else - { + } else { this.transformers = transformers; } } @@ -55,35 +48,28 @@ public ChainedDependencyGraphTransformer( DependencyGraphTransformer... transfor /** * Creates a new transformer that chains the specified transformers or simply returns one of them if the other one * is {@code null}. - * + * * @param transformer1 The first transformer of the chain, may be {@code null}. * @param transformer2 The second transformer of the chain, may be {@code null}. * @return The chained transformer or {@code null} if both input transformers are {@code null}. */ - public static DependencyGraphTransformer newInstance( DependencyGraphTransformer transformer1, - DependencyGraphTransformer transformer2 ) - { - if ( transformer1 == null ) - { + public static DependencyGraphTransformer newInstance( + DependencyGraphTransformer transformer1, DependencyGraphTransformer transformer2) { + if (transformer1 == null) { return transformer2; - } - else if ( transformer2 == null ) - { + } else if (transformer2 == null) { return transformer1; } - return new ChainedDependencyGraphTransformer( transformer1, transformer2 ); + return new ChainedDependencyGraphTransformer(transformer1, transformer2); } - public DependencyNode transformGraph( DependencyNode node, DependencyGraphTransformationContext context ) - throws RepositoryException - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( context, "context cannot be null" ); - for ( DependencyGraphTransformer transformer : transformers ) - { - node = transformer.transformGraph( node, context ); + public DependencyNode transformGraph(DependencyNode node, DependencyGraphTransformationContext context) + throws RepositoryException { + requireNonNull(node, "node cannot be null"); + requireNonNull(context, "context cannot be null"); + for (DependencyGraphTransformer transformer : transformers) { + node = transformer.transformGraph(node, context); } return node; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictIdSorter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictIdSorter.java index b8cc3addc..760077f71 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictIdSorter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictIdSorter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; import java.util.ArrayList; import java.util.Collection; @@ -28,13 +27,14 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.collection.DependencyGraphTransformationContext; import org.eclipse.aether.collection.DependencyGraphTransformer; import org.eclipse.aether.graph.DependencyNode; +import static java.util.Objects.requireNonNull; + /** * A dependency graph transformer that creates a topological sorting of the conflict ids which have been assigned to the * dependency nodes. Conflict ids are sorted according to the dependency relation induced by the dependency graph. This @@ -46,209 +46,182 @@ * {@code Collection>} using the key {@link TransformationContextKeys#CYCLIC_CONFLICT_IDS} that * describes cycles among conflict ids. */ -public final class ConflictIdSorter - implements DependencyGraphTransformer -{ - - public DependencyNode transformGraph( DependencyNode node, DependencyGraphTransformationContext context ) - throws RepositoryException - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( context, "context cannot be null" ); - Map conflictIds = (Map) context.get( TransformationContextKeys.CONFLICT_IDS ); - if ( conflictIds == null ) - { +public final class ConflictIdSorter implements DependencyGraphTransformer { + + public DependencyNode transformGraph(DependencyNode node, DependencyGraphTransformationContext context) + throws RepositoryException { + requireNonNull(node, "node cannot be null"); + requireNonNull(context, "context cannot be null"); + Map conflictIds = (Map) context.get(TransformationContextKeys.CONFLICT_IDS); + if (conflictIds == null) { ConflictMarker marker = new ConflictMarker(); - marker.transformGraph( node, context ); + marker.transformGraph(node, context); - conflictIds = (Map) context.get( TransformationContextKeys.CONFLICT_IDS ); + conflictIds = (Map) context.get(TransformationContextKeys.CONFLICT_IDS); } - @SuppressWarnings( "unchecked" ) - Map stats = (Map) context.get( TransformationContextKeys.STATS ); + @SuppressWarnings("unchecked") + Map stats = (Map) context.get(TransformationContextKeys.STATS); long time1 = System.nanoTime(); - Map ids = new LinkedHashMap<>( 256 ); + Map ids = new LinkedHashMap<>(256); ConflictId id = null; - Object key = conflictIds.get( node ); - if ( key != null ) - { - id = new ConflictId( key, 0 ); - ids.put( key, id ); + Object key = conflictIds.get(node); + if (key != null) { + id = new ConflictId(key, 0); + ids.put(key, id); } - Map visited = new IdentityHashMap<>( conflictIds.size() ); + Map visited = new IdentityHashMap<>(conflictIds.size()); - buildConflitIdDAG( ids, node, id, 0, visited, conflictIds ); + buildConflitIdDAG(ids, node, id, 0, visited, conflictIds); long time2 = System.nanoTime(); - int cycles = topsortConflictIds( ids.values(), context ); + int cycles = topsortConflictIds(ids.values(), context); - if ( stats != null ) - { + if (stats != null) { long time3 = System.nanoTime(); - stats.put( "ConflictIdSorter.graphTime", time2 - time1 ); - stats.put( "ConflictIdSorter.topsortTime", time3 - time2 ); - stats.put( "ConflictIdSorter.conflictIdCount", ids.size() ); - stats.put( "ConflictIdSorter.conflictIdCycleCount", cycles ); + stats.put("ConflictIdSorter.graphTime", time2 - time1); + stats.put("ConflictIdSorter.topsortTime", time3 - time2); + stats.put("ConflictIdSorter.conflictIdCount", ids.size()); + stats.put("ConflictIdSorter.conflictIdCycleCount", cycles); } return node; } - private void buildConflitIdDAG( Map ids, DependencyNode node, ConflictId id, int depth, - Map visited, Map conflictIds ) - { - if ( visited.put( node, Boolean.TRUE ) != null ) - { + private void buildConflitIdDAG( + Map ids, + DependencyNode node, + ConflictId id, + int depth, + Map visited, + Map conflictIds) { + if (visited.put(node, Boolean.TRUE) != null) { return; } depth++; - for ( DependencyNode child : node.getChildren() ) - { - Object key = conflictIds.get( child ); - ConflictId childId = ids.get( key ); - if ( childId == null ) - { - childId = new ConflictId( key, depth ); - ids.put( key, childId ); - } - else - { - childId.pullup( depth ); + for (DependencyNode child : node.getChildren()) { + Object key = conflictIds.get(child); + ConflictId childId = ids.get(key); + if (childId == null) { + childId = new ConflictId(key, depth); + ids.put(key, childId); + } else { + childId.pullup(depth); } - if ( id != null ) - { - id.add( childId ); + if (id != null) { + id.add(childId); } - buildConflitIdDAG( ids, child, childId, depth, visited, conflictIds ); + buildConflitIdDAG(ids, child, childId, depth, visited, conflictIds); } } - private int topsortConflictIds( Collection conflictIds, DependencyGraphTransformationContext context ) - { - List sorted = new ArrayList<>( conflictIds.size() ); + private int topsortConflictIds(Collection conflictIds, DependencyGraphTransformationContext context) { + List sorted = new ArrayList<>(conflictIds.size()); - RootQueue roots = new RootQueue( conflictIds.size() / 2 ); - for ( ConflictId id : conflictIds ) - { - if ( id.inDegree <= 0 ) - { - roots.add( id ); + RootQueue roots = new RootQueue(conflictIds.size() / 2); + for (ConflictId id : conflictIds) { + if (id.inDegree <= 0) { + roots.add(id); } } - processRoots( sorted, roots ); + processRoots(sorted, roots); boolean cycle = sorted.size() < conflictIds.size(); - while ( sorted.size() < conflictIds.size() ) - { + while (sorted.size() < conflictIds.size()) { // cycle -> deal gracefully with nodes still having positive in-degree ConflictId nearest = null; - for ( ConflictId id : conflictIds ) - { - if ( id.inDegree <= 0 ) - { + for (ConflictId id : conflictIds) { + if (id.inDegree <= 0) { continue; } - if ( nearest == null || id.minDepth < nearest.minDepth - || ( id.minDepth == nearest.minDepth && id.inDegree < nearest.inDegree ) ) - { + if (nearest == null + || id.minDepth < nearest.minDepth + || (id.minDepth == nearest.minDepth && id.inDegree < nearest.inDegree)) { nearest = id; } } nearest.inDegree = 0; - roots.add( nearest ); + roots.add(nearest); - processRoots( sorted, roots ); + processRoots(sorted, roots); } Collection> cycles = Collections.emptySet(); - if ( cycle ) - { - cycles = findCycles( conflictIds ); + if (cycle) { + cycles = findCycles(conflictIds); } - context.put( TransformationContextKeys.SORTED_CONFLICT_IDS, sorted ); - context.put( TransformationContextKeys.CYCLIC_CONFLICT_IDS, cycles ); + context.put(TransformationContextKeys.SORTED_CONFLICT_IDS, sorted); + context.put(TransformationContextKeys.CYCLIC_CONFLICT_IDS, cycles); return cycles.size(); } - private void processRoots( List sorted, RootQueue roots ) - { - while ( !roots.isEmpty() ) - { + private void processRoots(List sorted, RootQueue roots) { + while (!roots.isEmpty()) { ConflictId root = roots.remove(); - sorted.add( root.key ); + sorted.add(root.key); - for ( ConflictId child : root.children ) - { + for (ConflictId child : root.children) { child.inDegree--; - if ( child.inDegree == 0 ) - { - roots.add( child ); + if (child.inDegree == 0) { + roots.add(child); } } } } - private Collection> findCycles( Collection conflictIds ) - { + private Collection> findCycles(Collection conflictIds) { Collection> cycles = new HashSet<>(); - Map stack = new HashMap<>( 128 ); - Map visited = new IdentityHashMap<>( conflictIds.size() ); - for ( ConflictId id : conflictIds ) - { - findCycles( id, visited, stack, cycles ); + Map stack = new HashMap<>(128); + Map visited = new IdentityHashMap<>(conflictIds.size()); + for (ConflictId id : conflictIds) { + findCycles(id, visited, stack, cycles); } return cycles; } - private void findCycles( ConflictId id, Map visited, Map stack, - Collection> cycles ) - { - Integer depth = stack.put( id.key, stack.size() ); - if ( depth != null ) - { - stack.put( id.key, depth ); + private void findCycles( + ConflictId id, + Map visited, + Map stack, + Collection> cycles) { + Integer depth = stack.put(id.key, stack.size()); + if (depth != null) { + stack.put(id.key, depth); Collection cycle = new HashSet<>(); - for ( Map.Entry entry : stack.entrySet() ) - { - if ( entry.getValue() >= depth ) - { - cycle.add( entry.getKey() ); + for (Map.Entry entry : stack.entrySet()) { + if (entry.getValue() >= depth) { + cycle.add(entry.getKey()); } } - cycles.add( cycle ); - } - else - { - if ( visited.put( id, Boolean.TRUE ) == null ) - { - for ( ConflictId childId : id.children ) - { - findCycles( childId, visited, stack, cycles ); + cycles.add(cycle); + } else { + if (visited.put(id, Boolean.TRUE) == null) { + for (ConflictId childId : id.children) { + findCycles(childId, visited, stack, cycles); } } - stack.remove( id.key ); + stack.remove(id.key); } } - static final class ConflictId - { + static final class ConflictId { final Object key; @@ -258,68 +231,53 @@ static final class ConflictId int minDepth; - ConflictId( Object key, int depth ) - { + ConflictId(Object key, int depth) { this.key = key; this.minDepth = depth; } - public void add( ConflictId child ) - { - if ( children.isEmpty() ) - { + public void add(ConflictId child) { + if (children.isEmpty()) { children = new HashSet<>(); } - if ( children.add( child ) ) - { + if (children.add(child)) { child.inDegree++; } } - public void pullup( int depth ) - { - if ( depth < minDepth ) - { + public void pullup(int depth) { + if (depth < minDepth) { minDepth = depth; depth++; - for ( ConflictId child : children ) - { - child.pullup( depth ); + for (ConflictId child : children) { + child.pullup(depth); } } } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( !( obj instanceof ConflictId ) ) - { + } else if (!(obj instanceof ConflictId)) { return false; } ConflictId that = (ConflictId) obj; - return this.key.equals( that.key ); + return this.key.equals(that.key); } @Override - public int hashCode() - { + public int hashCode() { return key.hashCode(); } @Override - public String toString() - { + public String toString() { return key + " @ " + minDepth + " <" + inDegree; } - } - static final class RootQueue - { + static final class RootQueue { private int nextOut; @@ -327,45 +285,36 @@ static final class RootQueue private ConflictId[] ids; - RootQueue( int capacity ) - { + RootQueue(int capacity) { ids = new ConflictId[capacity + 16]; } - boolean isEmpty() - { + boolean isEmpty() { return nextOut >= nextIn; } - void add( ConflictId id ) - { - if ( nextOut >= nextIn && nextOut > 0 ) - { + void add(ConflictId id) { + if (nextOut >= nextIn && nextOut > 0) { nextIn -= nextOut; nextOut = 0; } - if ( nextIn >= ids.length ) - { + if (nextIn >= ids.length) { ConflictId[] tmp = new ConflictId[ids.length + ids.length / 2 + 16]; - System.arraycopy( ids, nextOut, tmp, 0, nextIn - nextOut ); + System.arraycopy(ids, nextOut, tmp, 0, nextIn - nextOut); ids = tmp; nextIn -= nextOut; nextOut = 0; } int i; - for ( i = nextIn - 1; i >= nextOut && id.minDepth < ids[i].minDepth; i-- ) - { + for (i = nextIn - 1; i >= nextOut && id.minDepth < ids[i].minDepth; i--) { ids[i + 1] = ids[i]; } ids[i + 1] = id; nextIn++; } - ConflictId remove() - { + ConflictId remove() { return ids[nextOut++]; } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictMarker.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictMarker.java index 5a0092c65..4fb4cdbd0 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictMarker.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictMarker.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; import java.util.Collection; import java.util.Collections; @@ -26,7 +25,6 @@ import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.artifact.Artifact; @@ -35,188 +33,151 @@ import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.DependencyNode; +import static java.util.Objects.requireNonNull; + /** * A dependency graph transformer that identifies conflicting dependencies. When this transformer has executed, the * transformation context holds a {@code Map} where dependency nodes that belong to the same * conflict group will have an equal conflict identifier. This map is stored using the key * {@link TransformationContextKeys#CONFLICT_IDS}. */ -public final class ConflictMarker - implements DependencyGraphTransformer -{ +public final class ConflictMarker implements DependencyGraphTransformer { /** * After the execution of this method, every DependencyNode with an attached dependency is member of one conflict * group. - * + * * @see DependencyGraphTransformer#transformGraph(DependencyNode, DependencyGraphTransformationContext) */ - public DependencyNode transformGraph( DependencyNode node, DependencyGraphTransformationContext context ) - throws RepositoryException - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( context, "context cannot be null" ); - @SuppressWarnings( "unchecked" ) - Map stats = (Map) context.get( TransformationContextKeys.STATS ); + public DependencyNode transformGraph(DependencyNode node, DependencyGraphTransformationContext context) + throws RepositoryException { + requireNonNull(node, "node cannot be null"); + requireNonNull(context, "context cannot be null"); + @SuppressWarnings("unchecked") + Map stats = (Map) context.get(TransformationContextKeys.STATS); long time1 = System.nanoTime(); - Map nodes = new IdentityHashMap<>( 1024 ); - Map groups = new HashMap<>( 1024 ); + Map nodes = new IdentityHashMap<>(1024); + Map groups = new HashMap<>(1024); - analyze( node, nodes, groups, new int[] { 0 } ); + analyze(node, nodes, groups, new int[] {0}); long time2 = System.nanoTime(); - Map conflictIds = mark( nodes.keySet(), groups ); + Map conflictIds = mark(nodes.keySet(), groups); - context.put( TransformationContextKeys.CONFLICT_IDS, conflictIds ); + context.put(TransformationContextKeys.CONFLICT_IDS, conflictIds); - if ( stats != null ) - { + if (stats != null) { long time3 = System.nanoTime(); - stats.put( "ConflictMarker.analyzeTime", time2 - time1 ); - stats.put( "ConflictMarker.markTime", time3 - time2 ); - stats.put( "ConflictMarker.nodeCount", nodes.size() ); + stats.put("ConflictMarker.analyzeTime", time2 - time1); + stats.put("ConflictMarker.markTime", time3 - time2); + stats.put("ConflictMarker.nodeCount", nodes.size()); } return node; } - private void analyze( DependencyNode node, Map nodes, Map groups, - int[] counter ) - { - if ( nodes.put( node, Boolean.TRUE ) != null ) - { + private void analyze( + DependencyNode node, Map nodes, Map groups, int[] counter) { + if (nodes.put(node, Boolean.TRUE) != null) { return; } - Set keys = getKeys( node ); - if ( !keys.isEmpty() ) - { + Set keys = getKeys(node); + if (!keys.isEmpty()) { ConflictGroup group = null; boolean fixMappings = false; - for ( Object key : keys ) - { - ConflictGroup g = groups.get( key ); - - if ( group != g ) - { - if ( group == null ) - { - Set newKeys = merge( g.keys, keys ); - if ( newKeys == g.keys ) - { + for (Object key : keys) { + ConflictGroup g = groups.get(key); + + if (group != g) { + if (group == null) { + Set newKeys = merge(g.keys, keys); + if (newKeys == g.keys) { group = g; break; - } - else - { - group = new ConflictGroup( newKeys, counter[0]++ ); + } else { + group = new ConflictGroup(newKeys, counter[0]++); fixMappings = true; } - } - else if ( g == null ) - { + } else if (g == null) { fixMappings = true; - } - else - { - Set newKeys = merge( g.keys, group.keys ); - if ( newKeys == g.keys ) - { + } else { + Set newKeys = merge(g.keys, group.keys); + if (newKeys == g.keys) { group = g; fixMappings = false; break; - } - else if ( newKeys != group.keys ) - { - group = new ConflictGroup( newKeys, counter[0]++ ); + } else if (newKeys != group.keys) { + group = new ConflictGroup(newKeys, counter[0]++); fixMappings = true; } } } } - if ( group == null ) - { - group = new ConflictGroup( keys, counter[0]++ ); + if (group == null) { + group = new ConflictGroup(keys, counter[0]++); fixMappings = true; } - if ( fixMappings ) - { - for ( Object key : group.keys ) - { - groups.put( key, group ); + if (fixMappings) { + for (Object key : group.keys) { + groups.put(key, group); } } } - for ( DependencyNode child : node.getChildren() ) - { - analyze( child, nodes, groups, counter ); + for (DependencyNode child : node.getChildren()) { + analyze(child, nodes, groups, counter); } } - private Set merge( Set keys1, Set keys2 ) - { + private Set merge(Set keys1, Set keys2) { int size1 = keys1.size(); int size2 = keys2.size(); - if ( size1 < size2 ) - { - if ( keys2.containsAll( keys1 ) ) - { + if (size1 < size2) { + if (keys2.containsAll(keys1)) { return keys2; } - } - else - { - if ( keys1.containsAll( keys2 ) ) - { + } else { + if (keys1.containsAll(keys2)) { return keys1; } } Set keys = new HashSet<>(); - keys.addAll( keys1 ); - keys.addAll( keys2 ); + keys.addAll(keys1); + keys.addAll(keys2); return keys; } - private Set getKeys( DependencyNode node ) - { + private Set getKeys(DependencyNode node) { Set keys; Dependency dependency = node.getDependency(); - if ( dependency == null ) - { + if (dependency == null) { keys = Collections.emptySet(); - } - else - { - Object key = toKey( dependency.getArtifact() ); + } else { + Object key = toKey(dependency.getArtifact()); - if ( node.getRelocations().isEmpty() && node.getAliases().isEmpty() ) - { - keys = Collections.singleton( key ); - } - else - { + if (node.getRelocations().isEmpty() && node.getAliases().isEmpty()) { + keys = Collections.singleton(key); + } else { keys = new HashSet<>(); - keys.add( key ); + keys.add(key); - for ( Artifact relocation : node.getRelocations() ) - { - key = toKey( relocation ); - keys.add( key ); + for (Artifact relocation : node.getRelocations()) { + key = toKey(relocation); + keys.add(key); } - for ( Artifact alias : node.getAliases() ) - { - key = toKey( alias ); - keys.add( key ); + for (Artifact alias : node.getAliases()) { + key = toKey(alias); + keys.add(key); } } } @@ -224,80 +185,65 @@ private Set getKeys( DependencyNode node ) return keys; } - private Map mark( Collection nodes, Map groups ) - { - Map conflictIds = new IdentityHashMap<>( nodes.size() + 1 ); + private Map mark(Collection nodes, Map groups) { + Map conflictIds = new IdentityHashMap<>(nodes.size() + 1); - for ( DependencyNode node : nodes ) - { + for (DependencyNode node : nodes) { Dependency dependency = node.getDependency(); - if ( dependency != null ) - { - Object key = toKey( dependency.getArtifact() ); - conflictIds.put( node, groups.get( key ).index ); + if (dependency != null) { + Object key = toKey(dependency.getArtifact()); + conflictIds.put(node, groups.get(key).index); } } return conflictIds; } - private static Object toKey( Artifact artifact ) - { - return new Key( artifact ); + private static Object toKey(Artifact artifact) { + return new Key(artifact); } - static class ConflictGroup - { + static class ConflictGroup { final Set keys; final int index; - ConflictGroup( Set keys, int index ) - { + ConflictGroup(Set keys, int index) { this.keys = keys; this.index = index; } @Override - public String toString() - { - return String.valueOf( keys ); + public String toString() { + return String.valueOf(keys); } - } - static class Key - { + static class Key { private final Artifact artifact; - Key( Artifact artifact ) - { + Key(Artifact artifact) { this.artifact = artifact; } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( !( obj instanceof Key ) ) - { + } else if (!(obj instanceof Key)) { return false; } Key that = (Key) obj; - return artifact.getArtifactId().equals( that.artifact.getArtifactId() ) - && artifact.getGroupId().equals( that.artifact.getGroupId() ) - && artifact.getExtension().equals( that.artifact.getExtension() ) - && artifact.getClassifier().equals( that.artifact.getClassifier() ); + return artifact.getArtifactId().equals(that.artifact.getArtifactId()) + && artifact.getGroupId().equals(that.artifact.getGroupId()) + && artifact.getExtension().equals(that.artifact.getExtension()) + && artifact.getClassifier().equals(that.artifact.getClassifier()); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + artifact.getArtifactId().hashCode(); hash = hash * 31 + artifact.getGroupId().hashCode(); @@ -307,12 +253,14 @@ public int hashCode() } @Override - public String toString() - { - return artifact.getGroupId() + ':' + artifact.getArtifactId() + ':' + artifact.getClassifier() + ':' - + artifact.getExtension(); + public String toString() { + return artifact.getGroupId() + + ':' + + artifact.getArtifactId() + + ':' + + artifact.getClassifier() + + ':' + + artifact.getExtension(); } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictResolver.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictResolver.java index 50ef2f765..7289c9bc1 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictResolver.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/ConflictResolver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; import java.util.ArrayList; import java.util.Arrays; @@ -30,7 +29,6 @@ import java.util.List; import java.util.ListIterator; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.artifact.Artifact; @@ -41,6 +39,8 @@ import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.util.ConfigUtils; +import static java.util.Objects.requireNonNull; + /** * A dependency graph transformer that resolves version and scope conflicts among dependencies. For a given set of * conflicting nodes, one node will be chosen as the winner and the other nodes are removed from the dependency graph. @@ -61,9 +61,7 @@ * existing information about conflict ids. In absence of this information, it will automatically invoke the * {@link ConflictIdSorter} to calculate it. */ -public final class ConflictResolver - implements DependencyGraphTransformer -{ +public final class ConflictResolver implements DependencyGraphTransformer { /** * The key in the repository session's {@link org.eclipse.aether.RepositorySystemSession#getConfigProperties() @@ -99,151 +97,133 @@ public final class ConflictResolver /** * Creates a new conflict resolver instance with the specified hooks. - * + * * @param versionSelector The version selector to use, must not be {@code null}. * @param scopeSelector The scope selector to use, must not be {@code null}. * @param optionalitySelector The optionality selector ot use, must not be {@code null}. * @param scopeDeriver The scope deriver to use, must not be {@code null}. */ - public ConflictResolver( VersionSelector versionSelector, ScopeSelector scopeSelector, - OptionalitySelector optionalitySelector, ScopeDeriver scopeDeriver ) - { - this.versionSelector = requireNonNull( versionSelector, "version selector cannot be null" ); - this.scopeSelector = requireNonNull( scopeSelector, "scope selector cannot be null" ); - this.optionalitySelector = requireNonNull( optionalitySelector, "optionality selector cannot be null" ); - this.scopeDeriver = requireNonNull( scopeDeriver, "scope deriver cannot be null" ); + public ConflictResolver( + VersionSelector versionSelector, + ScopeSelector scopeSelector, + OptionalitySelector optionalitySelector, + ScopeDeriver scopeDeriver) { + this.versionSelector = requireNonNull(versionSelector, "version selector cannot be null"); + this.scopeSelector = requireNonNull(scopeSelector, "scope selector cannot be null"); + this.optionalitySelector = requireNonNull(optionalitySelector, "optionality selector cannot be null"); + this.scopeDeriver = requireNonNull(scopeDeriver, "scope deriver cannot be null"); } - public DependencyNode transformGraph( DependencyNode node, DependencyGraphTransformationContext context ) - throws RepositoryException - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( context, "context cannot be null" ); - List sortedConflictIds = (List) context.get( TransformationContextKeys.SORTED_CONFLICT_IDS ); - if ( sortedConflictIds == null ) - { + public DependencyNode transformGraph(DependencyNode node, DependencyGraphTransformationContext context) + throws RepositoryException { + requireNonNull(node, "node cannot be null"); + requireNonNull(context, "context cannot be null"); + List sortedConflictIds = (List) context.get(TransformationContextKeys.SORTED_CONFLICT_IDS); + if (sortedConflictIds == null) { ConflictIdSorter sorter = new ConflictIdSorter(); - sorter.transformGraph( node, context ); + sorter.transformGraph(node, context); - sortedConflictIds = (List) context.get( TransformationContextKeys.SORTED_CONFLICT_IDS ); + sortedConflictIds = (List) context.get(TransformationContextKeys.SORTED_CONFLICT_IDS); } - @SuppressWarnings( "unchecked" ) - Map stats = (Map) context.get( TransformationContextKeys.STATS ); + @SuppressWarnings("unchecked") + Map stats = (Map) context.get(TransformationContextKeys.STATS); long time1 = System.nanoTime(); - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") Collection> conflictIdCycles = - (Collection>) context.get( TransformationContextKeys.CYCLIC_CONFLICT_IDS ); - if ( conflictIdCycles == null ) - { - throw new RepositoryException( "conflict id cycles have not been identified" ); + (Collection>) context.get(TransformationContextKeys.CYCLIC_CONFLICT_IDS); + if (conflictIdCycles == null) { + throw new RepositoryException("conflict id cycles have not been identified"); } - Map conflictIds = (Map) context.get( TransformationContextKeys.CONFLICT_IDS ); - if ( conflictIds == null ) - { - throw new RepositoryException( "conflict groups have not been identified" ); + Map conflictIds = (Map) context.get(TransformationContextKeys.CONFLICT_IDS); + if (conflictIds == null) { + throw new RepositoryException("conflict groups have not been identified"); } Map> cyclicPredecessors = new HashMap<>(); - for ( Collection cycle : conflictIdCycles ) - { - for ( Object conflictId : cycle ) - { - Collection predecessors = cyclicPredecessors. - computeIfAbsent( conflictId, k -> new HashSet<>() ); - predecessors.addAll( cycle ); + for (Collection cycle : conflictIdCycles) { + for (Object conflictId : cycle) { + Collection predecessors = cyclicPredecessors.computeIfAbsent(conflictId, k -> new HashSet<>()); + predecessors.addAll(cycle); } } - State state = new State( node, conflictIds, sortedConflictIds.size(), context ); - for ( Iterator it = sortedConflictIds.iterator(); it.hasNext(); ) - { + State state = new State(node, conflictIds, sortedConflictIds.size(), context); + for (Iterator it = sortedConflictIds.iterator(); it.hasNext(); ) { Object conflictId = it.next(); // reset data structures for next graph walk - state.prepare( conflictId, cyclicPredecessors.get( conflictId ) ); + state.prepare(conflictId, cyclicPredecessors.get(conflictId)); // find nodes with the current conflict id and while walking the graph (more deeply), nuke leftover losers - gatherConflictItems( node, state ); + gatherConflictItems(node, state); // now that we know the min depth of the parents, update depth of conflict items state.finish(); // earlier runs might have nuked all parents of the current conflict id, so it might not exist anymore - if ( !state.items.isEmpty() ) - { + if (!state.items.isEmpty()) { ConflictContext ctx = state.conflictCtx; - state.versionSelector.selectVersion( ctx ); - if ( ctx.winner == null ) - { - throw new RepositoryException( "conflict resolver did not select winner among " + state.items ); + state.versionSelector.selectVersion(ctx); + if (ctx.winner == null) { + throw new RepositoryException("conflict resolver did not select winner among " + state.items); } DependencyNode winner = ctx.winner.node; - state.scopeSelector.selectScope( ctx ); - if ( state.verbose ) - { - winner.setData( NODE_DATA_ORIGINAL_SCOPE, winner.getDependency().getScope() ); + state.scopeSelector.selectScope(ctx); + if (state.verbose) { + winner.setData( + NODE_DATA_ORIGINAL_SCOPE, winner.getDependency().getScope()); } - winner.setScope( ctx.scope ); + winner.setScope(ctx.scope); - state.optionalitySelector.selectOptionality( ctx ); - if ( state.verbose ) - { - winner.setData( NODE_DATA_ORIGINAL_OPTIONALITY, winner.getDependency().isOptional() ); + state.optionalitySelector.selectOptionality(ctx); + if (state.verbose) { + winner.setData( + NODE_DATA_ORIGINAL_OPTIONALITY, + winner.getDependency().isOptional()); } - winner.setOptional( ctx.optional ); + winner.setOptional(ctx.optional); - removeLosers( state ); + removeLosers(state); } // record the winner so we can detect leftover losers during future graph walks state.winner(); // in case of cycles, trigger final graph walk to ensure all leftover losers are gone - if ( !it.hasNext() && !conflictIdCycles.isEmpty() && state.conflictCtx.winner != null ) - { + if (!it.hasNext() && !conflictIdCycles.isEmpty() && state.conflictCtx.winner != null) { DependencyNode winner = state.conflictCtx.winner.node; - state.prepare( state, null ); - gatherConflictItems( winner, state ); + state.prepare(state, null); + gatherConflictItems(winner, state); } } - if ( stats != null ) - { + if (stats != null) { long time2 = System.nanoTime(); - stats.put( "ConflictResolver.totalTime", time2 - time1 ); - stats.put( "ConflictResolver.conflictItemCount", state.totalConflictItems ); + stats.put("ConflictResolver.totalTime", time2 - time1); + stats.put("ConflictResolver.conflictItemCount", state.totalConflictItems); } return node; } - private boolean gatherConflictItems( DependencyNode node, State state ) - throws RepositoryException - { - Object conflictId = state.conflictIds.get( node ); - if ( state.currentId.equals( conflictId ) ) - { + private boolean gatherConflictItems(DependencyNode node, State state) throws RepositoryException { + Object conflictId = state.conflictIds.get(node); + if (state.currentId.equals(conflictId)) { // found it, add conflict item (if not already done earlier by another path) - state.add( node ); + state.add(node); // we don't recurse here so we might miss losers beneath us, those will be nuked during future walks below - } - else if ( state.loser( node, conflictId ) ) - { + } else if (state.loser(node, conflictId)) { // found a leftover loser (likely in a cycle) of an already processed conflict id, tell caller to nuke it return false; - } - else if ( state.push( node, conflictId ) ) - { + } else if (state.push(node, conflictId)) { // found potential parent, no cycle and not visisted before with the same derived scope, so recurse - for ( Iterator it = node.getChildren().iterator(); it.hasNext(); ) - { + for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { DependencyNode child = it.next(); - if ( !gatherConflictItems( child, state ) ) - { + if (!gatherConflictItems(child, state)) { it.remove(); } } @@ -252,42 +232,36 @@ else if ( state.push( node, conflictId ) ) return true; } - private void removeLosers( State state ) - { + private void removeLosers(State state) { ConflictItem winner = state.conflictCtx.winner; List previousParent = null; ListIterator childIt = null; boolean conflictVisualized = false; - for ( ConflictItem item : state.items ) - { - if ( item == winner ) - { + for (ConflictItem item : state.items) { + if (item == winner) { continue; } - if ( item.parent != previousParent ) - { + if (item.parent != previousParent) { childIt = item.parent.listIterator(); previousParent = item.parent; conflictVisualized = false; } - while ( childIt.hasNext() ) - { + while (childIt.hasNext()) { DependencyNode child = childIt.next(); - if ( child == item.node ) - { - if ( state.verbose && !conflictVisualized && item.parent != winner.parent ) - { + if (child == item.node) { + if (state.verbose && !conflictVisualized && item.parent != winner.parent) { conflictVisualized = true; - DependencyNode loser = new DefaultDependencyNode( child ); - loser.setData( NODE_DATA_WINNER, winner.node ); - loser.setData( NODE_DATA_ORIGINAL_SCOPE, loser.getDependency().getScope() ); - loser.setData( NODE_DATA_ORIGINAL_OPTIONALITY, loser.getDependency().isOptional() ); - loser.setScope( item.getScopes().iterator().next() ); - loser.setChildren( Collections.emptyList() ); - childIt.set( loser ); - } - else - { + DependencyNode loser = new DefaultDependencyNode(child); + loser.setData(NODE_DATA_WINNER, winner.node); + loser.setData( + NODE_DATA_ORIGINAL_SCOPE, loser.getDependency().getScope()); + loser.setData( + NODE_DATA_ORIGINAL_OPTIONALITY, + loser.getDependency().isOptional()); + loser.setScope(item.getScopes().iterator().next()); + loser.setChildren(Collections.emptyList()); + childIt.set(loser); + } else { childIt.remove(); } break; @@ -298,8 +272,7 @@ private void removeLosers( State state ) // those will be nuked during future graph walks when we include the winner in the recursion } - static final class NodeInfo - { + static final class NodeInfo { /** * The smallest depth at which the node was seen, used for "the" depth of its conflict items. @@ -334,59 +307,46 @@ static final class NodeInfo private static final int OPT_TRUE = 0x02; - NodeInfo( int depth, String derivedScope, boolean optional ) - { + NodeInfo(int depth, String derivedScope, boolean optional) { minDepth = depth; derivedScopes = derivedScope; derivedOptionalities = optional ? OPT_TRUE : OPT_FALSE; } - @SuppressWarnings( "unchecked" ) - int update( int depth, String derivedScope, boolean optional ) - { - if ( depth < minDepth ) - { + @SuppressWarnings("unchecked") + int update(int depth, String derivedScope, boolean optional) { + if (depth < minDepth) { minDepth = depth; } int changes; - if ( derivedScopes.equals( derivedScope ) ) - { + if (derivedScopes.equals(derivedScope)) { changes = 0; - } - else if ( derivedScopes instanceof Collection ) - { - changes = ( (Collection) derivedScopes ).add( derivedScope ) ? CHANGE_SCOPE : 0; - } - else - { + } else if (derivedScopes instanceof Collection) { + changes = ((Collection) derivedScopes).add(derivedScope) ? CHANGE_SCOPE : 0; + } else { Collection scopes = new HashSet<>(); - scopes.add( (String) derivedScopes ); - scopes.add( derivedScope ); + scopes.add((String) derivedScopes); + scopes.add(derivedScope); derivedScopes = scopes; changes = CHANGE_SCOPE; } int bit = optional ? OPT_TRUE : OPT_FALSE; - if ( ( derivedOptionalities & bit ) == 0 ) - { + if ((derivedOptionalities & bit) == 0) { derivedOptionalities |= bit; changes |= CHANGE_OPTIONAL; } return changes; } - void add( ConflictItem item ) - { - if ( children == null ) - { - children = new ArrayList<>( 1 ); + void add(ConflictItem item) { + if (children == null) { + children = new ArrayList<>(1); } - children.add( item ); + children.add(item); } - } - final class State - { + final class State { /** * The conflict id currently processed. @@ -491,31 +451,32 @@ final class State */ final OptionalitySelector optionalitySelector; - State( DependencyNode root, Map conflictIds, int conflictIdCount, - DependencyGraphTransformationContext context ) - throws RepositoryException - { + State( + DependencyNode root, + Map conflictIds, + int conflictIdCount, + DependencyGraphTransformationContext context) + throws RepositoryException { this.conflictIds = conflictIds; - verbose = ConfigUtils.getBoolean( context.getSession(), false, CONFIG_PROP_VERBOSE ); - potentialAncestorIds = new HashSet<>( conflictIdCount * 2 ); - resolvedIds = new HashMap<>( conflictIdCount * 2 ); - items = new ArrayList<>( 256 ); - infos = new IdentityHashMap<>( 64 ); - stack = new IdentityHashMap<>( 64 ); - parentNodes = new ArrayList<>( 64 ); - parentScopes = new ArrayList<>( 64 ); - parentOptionals = new ArrayList<>( 64 ); - parentInfos = new ArrayList<>( 64 ); - conflictCtx = new ConflictContext( root, conflictIds, items ); - scopeCtx = new ScopeContext( null, null ); - versionSelector = ConflictResolver.this.versionSelector.getInstance( root, context ); - scopeSelector = ConflictResolver.this.scopeSelector.getInstance( root, context ); - scopeDeriver = ConflictResolver.this.scopeDeriver.getInstance( root, context ); - optionalitySelector = ConflictResolver.this.optionalitySelector.getInstance( root, context ); + verbose = ConfigUtils.getBoolean(context.getSession(), false, CONFIG_PROP_VERBOSE); + potentialAncestorIds = new HashSet<>(conflictIdCount * 2); + resolvedIds = new HashMap<>(conflictIdCount * 2); + items = new ArrayList<>(256); + infos = new IdentityHashMap<>(64); + stack = new IdentityHashMap<>(64); + parentNodes = new ArrayList<>(64); + parentScopes = new ArrayList<>(64); + parentOptionals = new ArrayList<>(64); + parentInfos = new ArrayList<>(64); + conflictCtx = new ConflictContext(root, conflictIds, items); + scopeCtx = new ScopeContext(null, null); + versionSelector = ConflictResolver.this.versionSelector.getInstance(root, context); + scopeSelector = ConflictResolver.this.scopeSelector.getInstance(root, context); + scopeDeriver = ConflictResolver.this.scopeDeriver.getInstance(root, context); + optionalitySelector = ConflictResolver.this.optionalitySelector.getInstance(root, context); } - void prepare( Object conflictId, Collection cyclicPredecessors ) - { + void prepare(Object conflictId, Collection cyclicPredecessors) { currentId = conflictId; conflictCtx.conflictId = conflictId; conflictCtx.winner = null; @@ -523,116 +484,91 @@ void prepare( Object conflictId, Collection cyclicPredecessors ) conflictCtx.optional = null; items.clear(); infos.clear(); - if ( cyclicPredecessors != null ) - { - potentialAncestorIds.addAll( cyclicPredecessors ); + if (cyclicPredecessors != null) { + potentialAncestorIds.addAll(cyclicPredecessors); } } - void finish() - { + void finish() { List previousParent = null; int previousDepth = 0; totalConflictItems += items.size(); - for ( ListIterator iterator = items.listIterator( items.size() ); iterator.hasPrevious(); ) - { + for (ListIterator iterator = items.listIterator(items.size()); iterator.hasPrevious(); ) { ConflictItem item = iterator.previous(); - if ( item.parent == previousParent ) - { + if (item.parent == previousParent) { item.depth = previousDepth; - } - else if ( item.parent != null ) - { + } else if (item.parent != null) { previousParent = item.parent; - NodeInfo info = infos.get( previousParent ); + NodeInfo info = infos.get(previousParent); previousDepth = info.minDepth + 1; item.depth = previousDepth; } } - potentialAncestorIds.add( currentId ); + potentialAncestorIds.add(currentId); } - void winner() - { - resolvedIds.put( currentId, ( conflictCtx.winner != null ) ? conflictCtx.winner.node : null ); + void winner() { + resolvedIds.put(currentId, (conflictCtx.winner != null) ? conflictCtx.winner.node : null); } - boolean loser( DependencyNode node, Object conflictId ) - { - DependencyNode winner = resolvedIds.get( conflictId ); + boolean loser(DependencyNode node, Object conflictId) { + DependencyNode winner = resolvedIds.get(conflictId); return winner != null && winner != node; } - boolean push( DependencyNode node, Object conflictId ) - throws RepositoryException - { - if ( conflictId == null ) - { - if ( node.getDependency() != null ) - { - if ( node.getData().get( NODE_DATA_WINNER ) != null ) - { + boolean push(DependencyNode node, Object conflictId) throws RepositoryException { + if (conflictId == null) { + if (node.getDependency() != null) { + if (node.getData().get(NODE_DATA_WINNER) != null) { return false; } - throw new RepositoryException( "missing conflict id for node " + node ); + throw new RepositoryException("missing conflict id for node " + node); } - } - else if ( !potentialAncestorIds.contains( conflictId ) ) - { + } else if (!potentialAncestorIds.contains(conflictId)) { return false; } List graphNode = node.getChildren(); - if ( stack.put( graphNode, Boolean.TRUE ) != null ) - { + if (stack.put(graphNode, Boolean.TRUE) != null) { return false; } int depth = depth(); - String scope = deriveScope( node, conflictId ); - boolean optional = deriveOptional( node, conflictId ); - NodeInfo info = infos.get( graphNode ); - if ( info == null ) - { - info = new NodeInfo( depth, scope, optional ); - infos.put( graphNode, info ); - parentInfos.add( info ); - parentNodes.add( node ); - parentScopes.add( scope ); - parentOptionals.add( optional ); - } - else - { - int changes = info.update( depth, scope, optional ); - if ( changes == 0 ) - { - stack.remove( graphNode ); + String scope = deriveScope(node, conflictId); + boolean optional = deriveOptional(node, conflictId); + NodeInfo info = infos.get(graphNode); + if (info == null) { + info = new NodeInfo(depth, scope, optional); + infos.put(graphNode, info); + parentInfos.add(info); + parentNodes.add(node); + parentScopes.add(scope); + parentOptionals.add(optional); + } else { + int changes = info.update(depth, scope, optional); + if (changes == 0) { + stack.remove(graphNode); return false; } - parentInfos.add( null ); // disable creating new conflict items, we update the existing ones below - parentNodes.add( node ); - parentScopes.add( scope ); - parentOptionals.add( optional ); - if ( info.children != null ) - { - if ( ( changes & NodeInfo.CHANGE_SCOPE ) != 0 ) - { - ListIterator itemIterator = info.children.listIterator( info.children.size() ); - while ( itemIterator.hasPrevious() ) - { + parentInfos.add(null); // disable creating new conflict items, we update the existing ones below + parentNodes.add(node); + parentScopes.add(scope); + parentOptionals.add(optional); + if (info.children != null) { + if ((changes & NodeInfo.CHANGE_SCOPE) != 0) { + ListIterator itemIterator = info.children.listIterator(info.children.size()); + while (itemIterator.hasPrevious()) { ConflictItem item = itemIterator.previous(); - String childScope = deriveScope( item.node, null ); - item.addScope( childScope ); + String childScope = deriveScope(item.node, null); + item.addScope(childScope); } } - if ( ( changes & NodeInfo.CHANGE_OPTIONAL ) != 0 ) - { - ListIterator itemIterator = info.children.listIterator( info.children.size() ); - while ( itemIterator.hasPrevious() ) - { + if ((changes & NodeInfo.CHANGE_OPTIONAL) != 0) { + ListIterator itemIterator = info.children.listIterator(info.children.size()); + while (itemIterator.hasPrevious()) { ConflictItem item = itemIterator.previous(); - boolean childOptional = deriveOptional( item.node, null ); - item.addOptional( childOptional ); + boolean childOptional = deriveOptional(item.node, null); + item.addOptional(childOptional); } } } @@ -641,108 +577,88 @@ else if ( !potentialAncestorIds.contains( conflictId ) ) return true; } - void pop() - { + void pop() { int last = parentInfos.size() - 1; - parentInfos.remove( last ); - parentScopes.remove( last ); - parentOptionals.remove( last ); - DependencyNode node = parentNodes.remove( last ); - stack.remove( node.getChildren() ); + parentInfos.remove(last); + parentScopes.remove(last); + parentOptionals.remove(last); + DependencyNode node = parentNodes.remove(last); + stack.remove(node.getChildren()); } - void add( DependencyNode node ) - throws RepositoryException - { + void add(DependencyNode node) throws RepositoryException { DependencyNode parent = parent(); - if ( parent == null ) - { - ConflictItem item = newConflictItem( parent, node ); - items.add( item ); - } - else - { - NodeInfo info = parentInfos.get( parentInfos.size() - 1 ); - if ( info != null ) - { - ConflictItem item = newConflictItem( parent, node ); - info.add( item ); - items.add( item ); + if (parent == null) { + ConflictItem item = newConflictItem(parent, node); + items.add(item); + } else { + NodeInfo info = parentInfos.get(parentInfos.size() - 1); + if (info != null) { + ConflictItem item = newConflictItem(parent, node); + info.add(item); + items.add(item); } } } - private ConflictItem newConflictItem( DependencyNode parent, DependencyNode node ) - throws RepositoryException - { - return new ConflictItem( parent, node, deriveScope( node, null ), deriveOptional( node, null ) ); + private ConflictItem newConflictItem(DependencyNode parent, DependencyNode node) throws RepositoryException { + return new ConflictItem(parent, node, deriveScope(node, null), deriveOptional(node, null)); } - private int depth() - { + private int depth() { return parentNodes.size(); } - private DependencyNode parent() - { + private DependencyNode parent() { int size = parentNodes.size(); - return ( size <= 0 ) ? null : parentNodes.get( size - 1 ); + return (size <= 0) ? null : parentNodes.get(size - 1); } - private String deriveScope( DependencyNode node, Object conflictId ) - throws RepositoryException - { - if ( ( node.getManagedBits() & DependencyNode.MANAGED_SCOPE ) != 0 - || ( conflictId != null && resolvedIds.containsKey( conflictId ) ) ) - { - return scope( node.getDependency() ); + private String deriveScope(DependencyNode node, Object conflictId) throws RepositoryException { + if ((node.getManagedBits() & DependencyNode.MANAGED_SCOPE) != 0 + || (conflictId != null && resolvedIds.containsKey(conflictId))) { + return scope(node.getDependency()); } int depth = parentNodes.size(); - scopes( depth, node.getDependency() ); - if ( depth > 0 ) - { - scopeDeriver.deriveScope( scopeCtx ); + scopes(depth, node.getDependency()); + if (depth > 0) { + scopeDeriver.deriveScope(scopeCtx); } return scopeCtx.derivedScope; } - private void scopes( int parent, Dependency child ) - { - scopeCtx.parentScope = ( parent > 0 ) ? parentScopes.get( parent - 1 ) : null; - scopeCtx.derivedScope = scope( child ); - scopeCtx.childScope = scope( child ); + private void scopes(int parent, Dependency child) { + scopeCtx.parentScope = (parent > 0) ? parentScopes.get(parent - 1) : null; + scopeCtx.derivedScope = scope(child); + scopeCtx.childScope = scope(child); } - private String scope( Dependency dependency ) - { - return ( dependency != null ) ? dependency.getScope() : null; + private String scope(Dependency dependency) { + return (dependency != null) ? dependency.getScope() : null; } - private boolean deriveOptional( DependencyNode node, Object conflictId ) - { + private boolean deriveOptional(DependencyNode node, Object conflictId) { Dependency dep = node.getDependency(); - boolean optional = ( dep != null ) && dep.isOptional(); - if ( optional || ( node.getManagedBits() & DependencyNode.MANAGED_OPTIONAL ) != 0 - || ( conflictId != null && resolvedIds.containsKey( conflictId ) ) ) - { + boolean optional = (dep != null) && dep.isOptional(); + if (optional + || (node.getManagedBits() & DependencyNode.MANAGED_OPTIONAL) != 0 + || (conflictId != null && resolvedIds.containsKey(conflictId))) { return optional; } int depth = parentNodes.size(); - return ( depth > 0 ) ? parentOptionals.get( depth - 1 ) : false; + return (depth > 0) ? parentOptionals.get(depth - 1) : false; } - } /** * A context used to hold information that is relevant for deriving the scope of a child dependency. - * + * * @see ScopeDeriver * @noinstantiate This class is not intended to be instantiated by clients in production code, the constructor may * change without notice and only exists to enable unit testing. */ - public static final class ScopeContext - { + public static final class ScopeContext { String parentScope; @@ -752,72 +668,65 @@ public static final class ScopeContext /** * Creates a new scope context with the specified properties. - * + * * @param parentScope The scope of the parent dependency, may be {@code null}. * @param childScope The scope of the child dependency, may be {@code null}. * @noreference This class is not intended to be instantiated by clients in production code, the constructor may * change without notice and only exists to enable unit testing. */ - public ScopeContext( String parentScope, String childScope ) - { - this.parentScope = ( parentScope != null ) ? parentScope : ""; - derivedScope = ( childScope != null ) ? childScope : ""; - this.childScope = ( childScope != null ) ? childScope : ""; + public ScopeContext(String parentScope, String childScope) { + this.parentScope = (parentScope != null) ? parentScope : ""; + derivedScope = (childScope != null) ? childScope : ""; + this.childScope = (childScope != null) ? childScope : ""; } /** * Gets the scope of the parent dependency. This is usually the scope that was derived by earlier invocations of * the scope deriver. - * + * * @return The scope of the parent dependency, never {@code null}. */ - public String getParentScope() - { + public String getParentScope() { return parentScope; } /** * Gets the original scope of the child dependency. This is the scope that was declared in the artifact * descriptor of the parent dependency. - * + * * @return The original scope of the child dependency, never {@code null}. */ - public String getChildScope() - { + public String getChildScope() { return childScope; } /** * Gets the derived scope of the child dependency. This is initially equal to {@link #getChildScope()} until the * scope deriver makes changes. - * + * * @return The derived scope of the child dependency, never {@code null}. */ - public String getDerivedScope() - { + public String getDerivedScope() { return derivedScope; } /** * Sets the derived scope of the child dependency. - * + * * @param derivedScope The derived scope of the dependency, may be {@code null}. */ - public void setDerivedScope( String derivedScope ) - { - this.derivedScope = ( derivedScope != null ) ? derivedScope : ""; + public void setDerivedScope(String derivedScope) { + this.derivedScope = (derivedScope != null) ? derivedScope : ""; } - } /** * A conflicting dependency. - * + * * @noinstantiate This class is not intended to be instantiated by clients in production code, the constructor may * change without notice and only exists to enable unit testing. */ - public static final class ConflictItem - { + public static final class ConflictItem { // nodes can share child lists, we care about the unique owner of a child node which is the child list final List parent; @@ -845,15 +754,11 @@ public static final class ConflictItem */ public static final int OPTIONAL_TRUE = 0x02; - ConflictItem( DependencyNode parent, DependencyNode node, String scope, boolean optional ) - { - if ( parent != null ) - { + ConflictItem(DependencyNode parent, DependencyNode node, String scope, boolean optional) { + if (parent != null) { this.parent = parent.getChildren(); this.artifact = parent.getArtifact(); - } - else - { + } else { this.parent = null; this.artifact = null; } @@ -864,7 +769,7 @@ public static final class ConflictItem /** * Creates a new conflict item with the specified properties. - * + * * @param parent The parent node of the conflicting dependency, may be {@code null}. * @param node The conflicting dependency, must not be {@code null}. * @param depth The zero-based depth of the conflicting dependency. @@ -875,45 +780,41 @@ public static final class ConflictItem * @noreference This class is not intended to be instantiated by clients in production code, the constructor may * change without notice and only exists to enable unit testing. */ - public ConflictItem( DependencyNode parent, DependencyNode node, int depth, int optionalities, - String... scopes ) - { - this.parent = ( parent != null ) ? parent.getChildren() : null; - this.artifact = ( parent != null ) ? parent.getArtifact() : null; + public ConflictItem( + DependencyNode parent, DependencyNode node, int depth, int optionalities, String... scopes) { + this.parent = (parent != null) ? parent.getChildren() : null; + this.artifact = (parent != null) ? parent.getArtifact() : null; this.node = node; this.depth = depth; this.optionalities = optionalities; - this.scopes = Arrays.asList( scopes ); + this.scopes = Arrays.asList(scopes); } /** * Determines whether the specified conflict item is a sibling of this item. - * + * * @param item The other conflict item, must not be {@code null}. * @return {@code true} if the given item has the same parent as this item, {@code false} otherwise. */ - public boolean isSibling( ConflictItem item ) - { + public boolean isSibling(ConflictItem item) { return parent == item.parent; } /** * Gets the dependency node involved in the conflict. - * + * * @return The involved dependency node, never {@code null}. */ - public DependencyNode getNode() - { + public DependencyNode getNode() { return node; } /** * Gets the dependency involved in the conflict, short for {@code getNode.getDependency()}. - * + * * @return The involved dependency, never {@code null}. */ - public Dependency getDependency() - { + public Dependency getDependency() { return node.getDependency(); } @@ -921,43 +822,36 @@ public Dependency getDependency() * Gets the zero-based depth at which the conflicting node occurs in the graph. As such, the depth denotes the * number of parent nodes. If actually multiple paths lead to the node, the return value denotes the smallest * possible depth. - * + * * @return The zero-based depth of the node in the graph. */ - public int getDepth() - { + public int getDepth() { return depth; } /** * Gets the derived scopes of the dependency. In general, the same dependency node could be reached via * different paths and each path might result in a different derived scope. - * + * * @see ScopeDeriver * @return The (read-only) set of derived scopes of the dependency, never {@code null}. */ - @SuppressWarnings( "unchecked" ) - public Collection getScopes() - { - if ( scopes instanceof String ) - { - return Collections.singleton( (String) scopes ); + @SuppressWarnings("unchecked") + public Collection getScopes() { + if (scopes instanceof String) { + return Collections.singleton((String) scopes); } return (Collection) scopes; } - @SuppressWarnings( "unchecked" ) - void addScope( String scope ) - { - if ( scopes instanceof Collection ) - { - ( (Collection) scopes ).add( scope ); - } - else if ( !scopes.equals( scope ) ) - { + @SuppressWarnings("unchecked") + void addScope(String scope) { + if (scopes instanceof Collection) { + ((Collection) scopes).add(scope); + } else if (!scopes.equals(scope)) { Collection set = new HashSet<>(); - set.add( scopes ); - set.add( scope ); + set.add(scopes); + set.add(scope); scopes = set; } } @@ -965,39 +859,34 @@ else if ( !scopes.equals( scope ) ) /** * Gets the derived optionalities of the dependency. In general, the same dependency node could be reached via * different paths and each path might result in a different derived optionality. - * + * * @return A bit field consisting of {@link ConflictResolver.ConflictItem#OPTIONAL_FALSE} and/or * {@link ConflictResolver.ConflictItem#OPTIONAL_TRUE} indicating the derived optionalities the * dependency was encountered with. */ - public int getOptionalities() - { + public int getOptionalities() { return optionalities; } - void addOptional( boolean optional ) - { + void addOptional(boolean optional) { optionalities |= optional ? OPTIONAL_TRUE : OPTIONAL_FALSE; } @Override - public String toString() - { + public String toString() { return node + " @ " + depth + " < " + artifact; } - } /** * A context used to hold information that is relevant for resolving version and scope conflicts. - * + * * @see VersionSelector * @see ScopeSelector * @noinstantiate This class is not intended to be instantiated by clients in production code, the constructor may * change without notice and only exists to enable unit testing. */ - public static final class ConflictContext - { + public static final class ConflictContext { final DependencyNode root; @@ -1013,16 +902,15 @@ public static final class ConflictContext Boolean optional; - ConflictContext( DependencyNode root, Map conflictIds, Collection items ) - { + ConflictContext(DependencyNode root, Map conflictIds, Collection items) { this.root = root; this.conflictIds = conflictIds; - this.items = Collections.unmodifiableCollection( items ); + this.items = Collections.unmodifiableCollection(items); } /** * Creates a new conflict context. - * + * * @param root The root node of the dependency graph, must not be {@code null}. * @param conflictId The conflict id for the set of conflicting dependencies in this context, must not be * {@code null}. @@ -1031,110 +919,101 @@ public static final class ConflictContext * @noreference This class is not intended to be instantiated by clients in production code, the constructor may * change without notice and only exists to enable unit testing. */ - public ConflictContext( DependencyNode root, Object conflictId, Map conflictIds, - Collection items ) - { - this( root, conflictIds, items ); + public ConflictContext( + DependencyNode root, + Object conflictId, + Map conflictIds, + Collection items) { + this(root, conflictIds, items); this.conflictId = conflictId; } /** * Gets the root node of the dependency graph being transformed. - * + * * @return The root node of the dependeny graph, never {@code null}. */ - public DependencyNode getRoot() - { + public DependencyNode getRoot() { return root; } /** * Determines whether the specified dependency node belongs to this conflict context. - * + * * @param node The dependency node to check, must not be {@code null}. * @return {@code true} if the given node belongs to this conflict context, {@code false} otherwise. */ - public boolean isIncluded( DependencyNode node ) - { - return conflictId.equals( conflictIds.get( node ) ); + public boolean isIncluded(DependencyNode node) { + return conflictId.equals(conflictIds.get(node)); } /** * Gets the collection of conflict items in this context. - * + * * @return The (read-only) collection of conflict items in this context, never {@code null}. */ - public Collection getItems() - { + public Collection getItems() { return items; } /** * Gets the conflict item which has been selected as the winner among the conflicting dependencies. - * + * * @return The winning conflict item or {@code null} if not set yet. */ - public ConflictItem getWinner() - { + public ConflictItem getWinner() { return winner; } /** * Sets the conflict item which has been selected as the winner among the conflicting dependencies. - * + * * @param winner The winning conflict item, may be {@code null}. */ - public void setWinner( ConflictItem winner ) - { + public void setWinner(ConflictItem winner) { this.winner = winner; } /** * Gets the effective scope of the winning dependency. - * + * * @return The effective scope of the winning dependency or {@code null} if none. */ - public String getScope() - { + public String getScope() { return scope; } /** * Sets the effective scope of the winning dependency. - * + * * @param scope The effective scope, may be {@code null}. */ - public void setScope( String scope ) - { + public void setScope(String scope) { this.scope = scope; } /** * Gets the effective optional flag of the winning dependency. - * + * * @return The effective optional flag or {@code null} if none. */ - public Boolean getOptional() - { + public Boolean getOptional() { return optional; } /** * Sets the effective optional flag of the winning dependency. - * + * * @param optional The effective optional flag, may be {@code null}. */ - public void setOptional( Boolean optional ) - { + public void setOptional(Boolean optional) { this.optional = optional; } @Override - public String toString() - { + public String toString() { return winner + " @ " + scope + " < " + items; } - } /** @@ -1145,8 +1024,7 @@ public String toString() *

    * Note: Implementations must be stateless. */ - public abstract static class VersionSelector - { + public abstract static class VersionSelector { /** * Retrieves the version selector for use during the specified graph transformation. The conflict resolver calls @@ -1156,15 +1034,14 @@ public abstract static class VersionSelector * implementations must be stateless, a new instance needs to be returned to hold such auxiliary data. The * default implementation simply returns the current instance which is appropriate for implementations which do * not require auxiliary data. - * + * * @param root The root node of the (possibly cyclic!) graph to transform, must not be {@code null}. * @param context The graph transformation context, must not be {@code null}. * @return The scope deriver to use for the given graph transformation, never {@code null}. * @throws RepositoryException If the instance could not be retrieved. */ - public VersionSelector getInstance( DependencyNode root, DependencyGraphTransformationContext context ) - throws RepositoryException - { + public VersionSelector getInstance(DependencyNode root, DependencyGraphTransformationContext context) + throws RepositoryException { return this; } @@ -1173,13 +1050,11 @@ public VersionSelector getInstance( DependencyNode root, DependencyGraphTransfor * {@link ConflictContext#getItems()}, inspect {@link ConflictItem#getNode()} and eventually call * {@link ConflictContext#setWinner(ConflictResolver.ConflictItem)} to deliver the winner. Failure to select a * winner will automatically fail the entire conflict resolution. - * + * * @param context The conflict context, must not be {@code null}. * @throws RepositoryException If the version selection failed. */ - public abstract void selectVersion( ConflictContext context ) - throws RepositoryException; - + public abstract void selectVersion(ConflictContext context) throws RepositoryException; } /** @@ -1189,8 +1064,7 @@ public abstract void selectVersion( ConflictContext context ) *

    * Note: Implementations must be stateless. */ - public abstract static class ScopeSelector - { + public abstract static class ScopeSelector { /** * Retrieves the scope selector for use during the specified graph transformation. The conflict resolver calls @@ -1200,15 +1074,14 @@ public abstract static class ScopeSelector * implementations must be stateless, a new instance needs to be returned to hold such auxiliary data. The * default implementation simply returns the current instance which is appropriate for implementations which do * not require auxiliary data. - * + * * @param root The root node of the (possibly cyclic!) graph to transform, must not be {@code null}. * @param context The graph transformation context, must not be {@code null}. * @return The scope selector to use for the given graph transformation, never {@code null}. * @throws RepositoryException If the instance could not be retrieved. */ - public ScopeSelector getInstance( DependencyNode root, DependencyGraphTransformationContext context ) - throws RepositoryException - { + public ScopeSelector getInstance(DependencyNode root, DependencyGraphTransformationContext context) + throws RepositoryException { return this; } @@ -1217,13 +1090,11 @@ public ScopeSelector getInstance( DependencyNode root, DependencyGraphTransforma * Implementations will usually iterate {@link ConflictContext#getItems()}, inspect * {@link ConflictItem#getScopes()} and eventually call {@link ConflictContext#setScope(String)} to deliver the * effective scope. - * + * * @param context The conflict context, must not be {@code null}. * @throws RepositoryException If the scope selection failed. */ - public abstract void selectScope( ConflictContext context ) - throws RepositoryException; - + public abstract void selectScope(ConflictContext context) throws RepositoryException; } /** @@ -1232,8 +1103,7 @@ public abstract void selectScope( ConflictContext context ) *

    * Note: Implementations must be stateless. */ - public abstract static class ScopeDeriver - { + public abstract static class ScopeDeriver { /** * Retrieves the scope deriver for use during the specified graph transformation. The conflict resolver calls @@ -1243,15 +1113,14 @@ public abstract static class ScopeDeriver * implementations must be stateless, a new instance needs to be returned to hold such auxiliary data. The * default implementation simply returns the current instance which is appropriate for implementations which do * not require auxiliary data. - * + * * @param root The root node of the (possibly cyclic!) graph to transform, must not be {@code null}. * @param context The graph transformation context, must not be {@code null}. * @return The scope deriver to use for the given graph transformation, never {@code null}. * @throws RepositoryException If the instance could not be retrieved. */ - public ScopeDeriver getInstance( DependencyNode root, DependencyGraphTransformationContext context ) - throws RepositoryException - { + public ScopeDeriver getInstance(DependencyNode root, DependencyGraphTransformationContext context) + throws RepositoryException { return this; } @@ -1259,13 +1128,11 @@ public ScopeDeriver getInstance( DependencyNode root, DependencyGraphTransformat * Determines the scope of a dependency in relation to the scope of its parent. Implementors need to call * {@link ScopeContext#setDerivedScope(String)} to deliver the result of their calculation. If said method is * not invoked, the conflict resolver will assume the scope of the child dependency remains unchanged. - * + * * @param context The scope context, must not be {@code null}. * @throws RepositoryException If the scope deriviation failed. */ - public abstract void deriveScope( ScopeContext context ) - throws RepositoryException; - + public abstract void deriveScope(ScopeContext context) throws RepositoryException; } /** @@ -1275,8 +1142,7 @@ public abstract void deriveScope( ScopeContext context ) *

    * Note: Implementations must be stateless. */ - public abstract static class OptionalitySelector - { + public abstract static class OptionalitySelector { /** * Retrieves the optionality selector for use during the specified graph transformation. The conflict resolver @@ -1286,15 +1152,14 @@ public abstract static class OptionalitySelector * implementations must be stateless, a new instance needs to be returned to hold such auxiliary data. The * default implementation simply returns the current instance which is appropriate for implementations which do * not require auxiliary data. - * + * * @param root The root node of the (possibly cyclic!) graph to transform, must not be {@code null}. * @param context The graph transformation context, must not be {@code null}. * @return The optionality selector to use for the given graph transformation, never {@code null}. * @throws RepositoryException If the instance could not be retrieved. */ - public OptionalitySelector getInstance( DependencyNode root, DependencyGraphTransformationContext context ) - throws RepositoryException - { + public OptionalitySelector getInstance(DependencyNode root, DependencyGraphTransformationContext context) + throws RepositoryException { return this; } @@ -1303,13 +1168,10 @@ public OptionalitySelector getInstance( DependencyNode root, DependencyGraphTran * Implementations will usually iterate {@link ConflictContext#getItems()}, inspect * {@link ConflictItem#getOptionalities()} and eventually call {@link ConflictContext#setOptional(Boolean)} to * deliver the effective optional flag. - * + * * @param context The conflict context, must not be {@code null}. * @throws RepositoryException If the optionality selection failed. */ - public abstract void selectOptionality( ConflictContext context ) - throws RepositoryException; - + public abstract void selectOptionality(ConflictContext context) throws RepositoryException; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaDependencyContextRefiner.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaDependencyContextRefiner.java index 5d5b0cc0e..0b8c93dcb 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaDependencyContextRefiner.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaDependencyContextRefiner.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.collection.DependencyGraphTransformationContext; @@ -32,63 +31,48 @@ * A dependency graph transformer that refines the request context for nodes that belong to the "project" context by * appending the classpath type to which the node belongs. For instance, a compile-time project dependency will be * assigned the request context "project/compile". - * + * * @see DependencyNode#getRequestContext() */ -public final class JavaDependencyContextRefiner - implements DependencyGraphTransformer -{ +public final class JavaDependencyContextRefiner implements DependencyGraphTransformer { - public DependencyNode transformGraph( DependencyNode node, DependencyGraphTransformationContext context ) - throws RepositoryException - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( context, "context cannot be null" ); + public DependencyNode transformGraph(DependencyNode node, DependencyGraphTransformationContext context) + throws RepositoryException { + requireNonNull(node, "node cannot be null"); + requireNonNull(context, "context cannot be null"); String ctx = node.getRequestContext(); - if ( "project".equals( ctx ) ) - { - String scope = getClasspathScope( node ); - if ( scope != null ) - { + if ("project".equals(ctx)) { + String scope = getClasspathScope(node); + if (scope != null) { ctx += '/' + scope; - node.setRequestContext( ctx ); + node.setRequestContext(ctx); } } - for ( DependencyNode child : node.getChildren() ) - { - transformGraph( child, context ); + for (DependencyNode child : node.getChildren()) { + transformGraph(child, context); } return node; } - private String getClasspathScope( DependencyNode node ) - { + private String getClasspathScope(DependencyNode node) { Dependency dependency = node.getDependency(); - if ( dependency == null ) - { + if (dependency == null) { return null; } String scope = dependency.getScope(); - if ( JavaScopes.COMPILE.equals( scope ) || JavaScopes.SYSTEM.equals( scope ) - || JavaScopes.PROVIDED.equals( scope ) ) - { + if (JavaScopes.COMPILE.equals(scope) || JavaScopes.SYSTEM.equals(scope) || JavaScopes.PROVIDED.equals(scope)) { return JavaScopes.COMPILE; - } - else if ( JavaScopes.RUNTIME.equals( scope ) ) - { + } else if (JavaScopes.RUNTIME.equals(scope)) { return JavaScopes.RUNTIME; - } - else if ( JavaScopes.TEST.equals( scope ) ) - { + } else if (JavaScopes.TEST.equals(scope)) { return JavaScopes.TEST; } return null; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaScopeDeriver.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaScopeDeriver.java index 1132f800f..050af9f0a 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaScopeDeriver.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaScopeDeriver.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.util.artifact.JavaScopes; @@ -27,50 +26,33 @@ /** * A scope deriver for use with {@link ConflictResolver} that supports the scopes from {@link JavaScopes}. */ -public final class JavaScopeDeriver - extends ScopeDeriver -{ +public final class JavaScopeDeriver extends ScopeDeriver { /** * Creates a new instance of this scope deriver. */ - public JavaScopeDeriver() - { - } + public JavaScopeDeriver() {} @Override - public void deriveScope( ScopeContext context ) - throws RepositoryException - { - context.setDerivedScope( getDerivedScope( context.getParentScope(), context.getChildScope() ) ); + public void deriveScope(ScopeContext context) throws RepositoryException { + context.setDerivedScope(getDerivedScope(context.getParentScope(), context.getChildScope())); } - private String getDerivedScope( String parentScope, String childScope ) - { + private String getDerivedScope(String parentScope, String childScope) { String derivedScope; - if ( JavaScopes.SYSTEM.equals( childScope ) || JavaScopes.TEST.equals( childScope ) ) - { + if (JavaScopes.SYSTEM.equals(childScope) || JavaScopes.TEST.equals(childScope)) { derivedScope = childScope; - } - else if ( parentScope == null || parentScope.isEmpty() || JavaScopes.COMPILE.equals( parentScope ) ) - { + } else if (parentScope == null || parentScope.isEmpty() || JavaScopes.COMPILE.equals(parentScope)) { derivedScope = childScope; - } - else if ( JavaScopes.TEST.equals( parentScope ) || JavaScopes.RUNTIME.equals( parentScope ) ) - { + } else if (JavaScopes.TEST.equals(parentScope) || JavaScopes.RUNTIME.equals(parentScope)) { derivedScope = parentScope; - } - else if ( JavaScopes.SYSTEM.equals( parentScope ) || JavaScopes.PROVIDED.equals( parentScope ) ) - { + } else if (JavaScopes.SYSTEM.equals(parentScope) || JavaScopes.PROVIDED.equals(parentScope)) { derivedScope = JavaScopes.PROVIDED; - } - else - { + } else { derivedScope = JavaScopes.RUNTIME; } return derivedScope; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaScopeSelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaScopeSelector.java index 0f923a746..0e80671b6 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaScopeSelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/JavaScopeSelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; import java.util.Collection; import java.util.HashSet; @@ -34,74 +33,52 @@ * this selector picks the widest scope present among conflicting dependencies where e.g. "compile" is wider than * "runtime" which is wider than "test". If however a direct dependency is involved, its scope is selected. */ -public final class JavaScopeSelector - extends ScopeSelector -{ +public final class JavaScopeSelector extends ScopeSelector { /** * Creates a new instance of this scope selector. */ - public JavaScopeSelector() - { - } + public JavaScopeSelector() {} @Override - public void selectScope( ConflictContext context ) - throws RepositoryException - { + public void selectScope(ConflictContext context) throws RepositoryException { String scope = context.getWinner().getDependency().getScope(); - if ( !JavaScopes.SYSTEM.equals( scope ) ) - { - scope = chooseEffectiveScope( context.getItems() ); + if (!JavaScopes.SYSTEM.equals(scope)) { + scope = chooseEffectiveScope(context.getItems()); } - context.setScope( scope ); + context.setScope(scope); } - private String chooseEffectiveScope( Collection items ) - { + private String chooseEffectiveScope(Collection items) { Set scopes = new HashSet<>(); - for ( ConflictItem item : items ) - { - if ( item.getDepth() <= 1 ) - { + for (ConflictItem item : items) { + if (item.getDepth() <= 1) { return item.getDependency().getScope(); } - scopes.addAll( item.getScopes() ); + scopes.addAll(item.getScopes()); } - return chooseEffectiveScope( scopes ); + return chooseEffectiveScope(scopes); } - private String chooseEffectiveScope( Set scopes ) - { - if ( scopes.size() > 1 ) - { - scopes.remove( JavaScopes.SYSTEM ); + private String chooseEffectiveScope(Set scopes) { + if (scopes.size() > 1) { + scopes.remove(JavaScopes.SYSTEM); } String effectiveScope = ""; - if ( scopes.size() == 1 ) - { + if (scopes.size() == 1) { effectiveScope = scopes.iterator().next(); - } - else if ( scopes.contains( JavaScopes.COMPILE ) ) - { + } else if (scopes.contains(JavaScopes.COMPILE)) { effectiveScope = JavaScopes.COMPILE; - } - else if ( scopes.contains( JavaScopes.RUNTIME ) ) - { + } else if (scopes.contains(JavaScopes.RUNTIME)) { effectiveScope = JavaScopes.RUNTIME; - } - else if ( scopes.contains( JavaScopes.PROVIDED ) ) - { + } else if (scopes.contains(JavaScopes.PROVIDED)) { effectiveScope = JavaScopes.PROVIDED; - } - else if ( scopes.contains( JavaScopes.TEST ) ) - { + } else if (scopes.contains(JavaScopes.TEST)) { effectiveScope = JavaScopes.TEST; } return effectiveScope; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/NearestVersionSelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/NearestVersionSelector.java index 824c32627..1bca82400 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/NearestVersionSelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/NearestVersionSelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; import java.util.ArrayList; import java.util.Collection; @@ -42,126 +41,95 @@ * A version selector for use with {@link ConflictResolver} that resolves version conflicts using a nearest-wins * strategy. If there is no single node that satisfies all encountered version ranges, the selector will fail. */ -public final class NearestVersionSelector - extends VersionSelector -{ +public final class NearestVersionSelector extends VersionSelector { /** * Creates a new instance of this version selector. */ - public NearestVersionSelector() - { - } + public NearestVersionSelector() {} @Override - public void selectVersion( ConflictContext context ) - throws RepositoryException - { + public void selectVersion(ConflictContext context) throws RepositoryException { ConflictGroup group = new ConflictGroup(); - for ( ConflictItem item : context.getItems() ) - { + for (ConflictItem item : context.getItems()) { DependencyNode node = item.getNode(); VersionConstraint constraint = node.getVersionConstraint(); boolean backtrack = false; boolean hardConstraint = constraint.getRange() != null; - if ( hardConstraint ) - { - if ( group.constraints.add( constraint ) ) - { - if ( group.winner != null && !constraint.containsVersion( group.winner.getNode().getVersion() ) ) - { + if (hardConstraint) { + if (group.constraints.add(constraint)) { + if (group.winner != null + && !constraint.containsVersion( + group.winner.getNode().getVersion())) { backtrack = true; } } } - if ( isAcceptable( group, node.getVersion() ) ) - { - group.candidates.add( item ); + if (isAcceptable(group, node.getVersion())) { + group.candidates.add(item); - if ( backtrack ) - { - backtrack( group, context ); - } - else if ( group.winner == null || isNearer( item, group.winner ) ) - { + if (backtrack) { + backtrack(group, context); + } else if (group.winner == null || isNearer(item, group.winner)) { group.winner = item; } - } - else if ( backtrack ) - { - backtrack( group, context ); + } else if (backtrack) { + backtrack(group, context); } } - context.setWinner( group.winner ); + context.setWinner(group.winner); } - private void backtrack( ConflictGroup group, ConflictContext context ) - throws UnsolvableVersionConflictException - { + private void backtrack(ConflictGroup group, ConflictContext context) throws UnsolvableVersionConflictException { group.winner = null; - for ( Iterator it = group.candidates.iterator(); it.hasNext(); ) - { + for (Iterator it = group.candidates.iterator(); it.hasNext(); ) { ConflictItem candidate = it.next(); - if ( !isAcceptable( group, candidate.getNode().getVersion() ) ) - { + if (!isAcceptable(group, candidate.getNode().getVersion())) { it.remove(); - } - else if ( group.winner == null || isNearer( candidate, group.winner ) ) - { + } else if (group.winner == null || isNearer(candidate, group.winner)) { group.winner = candidate; } } - if ( group.winner == null ) - { - throw newFailure( context ); + if (group.winner == null) { + throw newFailure(context); } } - private boolean isAcceptable( ConflictGroup group, Version version ) - { - for ( VersionConstraint constraint : group.constraints ) - { - if ( !constraint.containsVersion( version ) ) - { + private boolean isAcceptable(ConflictGroup group, Version version) { + for (VersionConstraint constraint : group.constraints) { + if (!constraint.containsVersion(version)) { return false; } } return true; } - private boolean isNearer( ConflictItem item1, ConflictItem item2 ) - { - if ( item1.isSibling( item2 ) ) - { - return item1.getNode().getVersion().compareTo( item2.getNode().getVersion() ) > 0; - } - else - { + private boolean isNearer(ConflictItem item1, ConflictItem item2) { + if (item1.isSibling(item2)) { + return item1.getNode().getVersion().compareTo(item2.getNode().getVersion()) > 0; + } else { return item1.getDepth() < item2.getDepth(); } } - private UnsolvableVersionConflictException newFailure( final ConflictContext context ) - { - DependencyFilter filter = ( node, parents ) -> - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( parents, "parents cannot be null" ); - return context.isIncluded( node ); + private UnsolvableVersionConflictException newFailure(final ConflictContext context) { + DependencyFilter filter = (node, parents) -> { + requireNonNull(node, "node cannot be null"); + requireNonNull(parents, "parents cannot be null"); + return context.isIncluded(node); }; - PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor( filter ); - context.getRoot().accept( new TreeDependencyVisitor( visitor ) ); - return new UnsolvableVersionConflictException( visitor.getPaths() ); + PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor(filter); + context.getRoot().accept(new TreeDependencyVisitor(visitor)); + return new UnsolvableVersionConflictException(visitor.getPaths()); } - static final class ConflictGroup - { + static final class ConflictGroup { final Collection constraints; @@ -169,18 +137,14 @@ static final class ConflictGroup ConflictItem winner; - ConflictGroup() - { + ConflictGroup() { constraints = new HashSet<>(); - candidates = new ArrayList<>( 64 ); + candidates = new ArrayList<>(64); } @Override - public String toString() - { - return String.valueOf( winner ); + public String toString() { + return String.valueOf(winner); } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/NoopDependencyGraphTransformer.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/NoopDependencyGraphTransformer.java index f217c4f3c..cc63922fc 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/NoopDependencyGraphTransformer.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/NoopDependencyGraphTransformer.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.collection.DependencyGraphTransformationContext; @@ -29,9 +28,7 @@ /** * A dependency graph transformer that does not perform any changes on its input. */ -public final class NoopDependencyGraphTransformer - implements DependencyGraphTransformer -{ +public final class NoopDependencyGraphTransformer implements DependencyGraphTransformer { /** * A ready-made instance of this dependency graph transformer which can safely be reused throughout an entire @@ -42,16 +39,12 @@ public final class NoopDependencyGraphTransformer /** * Creates a new instance of this graph transformer. Usually, {@link #INSTANCE} should be used instead. */ - public NoopDependencyGraphTransformer() - { - } + public NoopDependencyGraphTransformer() {} - public DependencyNode transformGraph( DependencyNode node, DependencyGraphTransformationContext context ) - throws RepositoryException - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( context, "context cannot be null" ); + public DependencyNode transformGraph(DependencyNode node, DependencyGraphTransformationContext context) + throws RepositoryException { + requireNonNull(node, "node cannot be null"); + requireNonNull(context, "context cannot be null"); return node; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/SimpleOptionalitySelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/SimpleOptionalitySelector.java index 0cc7a730f..4021f6a6b 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/SimpleOptionalitySelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/SimpleOptionalitySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; import java.util.Collection; @@ -31,40 +30,29 @@ * optional if all its occurrences are optional. If however a direct dependency is involved, its optional flag is * selected. */ -public final class SimpleOptionalitySelector - extends OptionalitySelector -{ +public final class SimpleOptionalitySelector extends OptionalitySelector { /** * Creates a new instance of this optionality selector. */ - public SimpleOptionalitySelector() - { - } + public SimpleOptionalitySelector() {} @Override - public void selectOptionality( ConflictContext context ) - throws RepositoryException - { - boolean optional = chooseEffectiveOptionality( context.getItems() ); - context.setOptional( optional ); + public void selectOptionality(ConflictContext context) throws RepositoryException { + boolean optional = chooseEffectiveOptionality(context.getItems()); + context.setOptional(optional); } - private boolean chooseEffectiveOptionality( Collection items ) - { + private boolean chooseEffectiveOptionality(Collection items) { boolean optional = true; - for ( ConflictItem item : items ) - { - if ( item.getDepth() <= 1 ) - { + for (ConflictItem item : items) { + if (item.getDepth() <= 1) { return item.getDependency().isOptional(); } - if ( ( item.getOptionalities() & ConflictItem.OPTIONAL_FALSE ) != 0 ) - { + if ((item.getOptionalities() & ConflictItem.OPTIONAL_FALSE) != 0) { optional = false; } } return optional; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/TransformationContextKeys.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/TransformationContextKeys.java index a9ebf68de..9a8826e6a 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/TransformationContextKeys.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/TransformationContextKeys.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,21 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; /** * A collection of keys used by the dependency graph transformers when exchanging information via the graph * transformation context. - * + * * @see org.eclipse.aether.collection.DependencyGraphTransformationContext#get(Object) */ -public final class TransformationContextKeys -{ +public final class TransformationContextKeys { /** * The key in the graph transformation context where a {@code Map} is stored which maps * dependency nodes to their conflict ids. All nodes that map to an equal conflict id belong to the same group of * conflicting dependencies. Note that the map keys use reference equality. - * + * * @see ConflictMarker */ public static final Object CONFLICT_IDS = "conflictIds"; @@ -40,7 +38,7 @@ public final class TransformationContextKeys /** * The key in the graph transformation context where a {@code List} is stored that denotes a topological * sorting of the conflict ids. - * + * * @see ConflictIdSorter */ public static final Object SORTED_CONFLICT_IDS = "sortedConflictIds"; @@ -49,7 +47,7 @@ public final class TransformationContextKeys * The key in the graph transformation context where a {@code Collection>} is stored that denotes * cycles among conflict ids. Each element in the outer collection denotes one cycle, i.e. if the collection is * empty, the conflict ids have no cyclic dependencies. - * + * * @see ConflictIdSorter */ public static final Object CYCLIC_CONFLICT_IDS = "cyclicConflictIds"; @@ -60,9 +58,7 @@ public final class TransformationContextKeys */ public static final Object STATS = "stats"; - private TransformationContextKeys() - { + private TransformationContextKeys() { // hide constructor } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/package-info.java index a41adcd59..7765790d7 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/transformer/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Various dependency graph transformers for post-processing a dependency graph. */ package org.eclipse.aether.util.graph.transformer; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/AndDependencyTraverser.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/AndDependencyTraverser.java index eda5a9d4e..58a077ef6 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/AndDependencyTraverser.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/AndDependencyTraverser.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.traverser; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.traverser; import java.util.Arrays; import java.util.Collection; @@ -35,9 +34,7 @@ * A dependency traverser that combines zero or more other traversers using a logical {@code AND}. The resulting * traverser enables processing of child dependencies if and only if all constituent traversers request traversal. */ -public final class AndDependencyTraverser - implements DependencyTraverser -{ +public final class AndDependencyTraverser implements DependencyTraverser { private final Set traversers; @@ -47,165 +44,124 @@ public final class AndDependencyTraverser * Creates a new traverser from the specified traversers. Prefer * {@link #newInstance(DependencyTraverser, DependencyTraverser)} if any of the input traversers might be * {@code null}. - * + * * @param traversers The traversers to combine, may be {@code null} but must not contain {@code null} elements. */ - public AndDependencyTraverser( DependencyTraverser... traversers ) - { - if ( traversers != null && traversers.length > 0 ) - { - this.traversers = new LinkedHashSet<>( Arrays.asList( traversers ) ); - } - else - { + public AndDependencyTraverser(DependencyTraverser... traversers) { + if (traversers != null && traversers.length > 0) { + this.traversers = new LinkedHashSet<>(Arrays.asList(traversers)); + } else { this.traversers = Collections.emptySet(); } } /** * Creates a new traverser from the specified traversers. - * + * * @param traversers The traversers to combine, may be {@code null} but must not contain {@code null} elements. */ - public AndDependencyTraverser( Collection traversers ) - { - if ( traversers != null && !traversers.isEmpty() ) - { - this.traversers = new LinkedHashSet<>( traversers ); - } - else - { + public AndDependencyTraverser(Collection traversers) { + if (traversers != null && !traversers.isEmpty()) { + this.traversers = new LinkedHashSet<>(traversers); + } else { this.traversers = Collections.emptySet(); } } - private AndDependencyTraverser( Set traversers ) - { - if ( traversers != null && !traversers.isEmpty() ) - { + private AndDependencyTraverser(Set traversers) { + if (traversers != null && !traversers.isEmpty()) { this.traversers = traversers; - } - else - { + } else { this.traversers = Collections.emptySet(); } } /** * Creates a new traverser from the specified traversers. - * + * * @param traverser1 The first traverser to combine, may be {@code null}. * @param traverser2 The second traverser to combine, may be {@code null}. * @return The combined traverser or {@code null} if both traversers were {@code null}. */ - public static DependencyTraverser newInstance( DependencyTraverser traverser1, DependencyTraverser traverser2 ) - { - if ( traverser1 == null ) - { + public static DependencyTraverser newInstance(DependencyTraverser traverser1, DependencyTraverser traverser2) { + if (traverser1 == null) { return traverser2; - } - else if ( traverser2 == null || traverser2.equals( traverser1 ) ) - { + } else if (traverser2 == null || traverser2.equals(traverser1)) { return traverser1; } - return new AndDependencyTraverser( traverser1, traverser2 ); + return new AndDependencyTraverser(traverser1, traverser2); } - public boolean traverseDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); - for ( DependencyTraverser traverser : traversers ) - { - if ( !traverser.traverseDependency( dependency ) ) - { + public boolean traverseDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); + for (DependencyTraverser traverser : traversers) { + if (!traverser.traverseDependency(dependency)) { return false; } } return true; } - public DependencyTraverser deriveChildTraverser( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencyTraverser deriveChildTraverser(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); int seen = 0; Set childTraversers = null; - for ( DependencyTraverser traverser : traversers ) - { - DependencyTraverser childTraverser = traverser.deriveChildTraverser( context ); - if ( childTraversers != null ) - { - if ( childTraverser != null ) - { - childTraversers.add( childTraverser ); + for (DependencyTraverser traverser : traversers) { + DependencyTraverser childTraverser = traverser.deriveChildTraverser(context); + if (childTraversers != null) { + if (childTraverser != null) { + childTraversers.add(childTraverser); } - } - else if ( traverser != childTraverser ) - { + } else if (traverser != childTraverser) { childTraversers = new LinkedHashSet<>(); - if ( seen > 0 ) - { - for ( DependencyTraverser s : traversers ) - { - if ( childTraversers.size() >= seen ) - { + if (seen > 0) { + for (DependencyTraverser s : traversers) { + if (childTraversers.size() >= seen) { break; } - childTraversers.add( s ); + childTraversers.add(s); } } - if ( childTraverser != null ) - { - childTraversers.add( childTraverser ); + if (childTraverser != null) { + childTraversers.add(childTraverser); } - } - else - { + } else { seen++; } } - if ( childTraversers == null ) - { + if (childTraversers == null) { return this; } - if ( childTraversers.size() <= 1 ) - { - if ( childTraversers.isEmpty() ) - { + if (childTraversers.size() <= 1) { + if (childTraversers.isEmpty()) { return null; } return childTraversers.iterator().next(); } - return new AndDependencyTraverser( childTraversers ); + return new AndDependencyTraverser(childTraversers); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } AndDependencyTraverser that = (AndDependencyTraverser) obj; - return traversers.equals( that.traversers ); + return traversers.equals(that.traversers); } @Override - public int hashCode() - { - if ( hashCode == 0 ) - { + public int hashCode() { + if (hashCode == 0) { int hash = 17; hash = hash * 31 + traversers.hashCode(); hashCode = hash; } return hashCode; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/FatArtifactTraverser.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/FatArtifactTraverser.java index 67ba4e33a..72cc94a7e 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/FatArtifactTraverser.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/FatArtifactTraverser.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.traverser; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.traverser; import org.eclipse.aether.artifact.ArtifactProperties; import org.eclipse.aether.collection.DependencyCollectionContext; @@ -30,51 +29,39 @@ * A dependency traverser that excludes the dependencies of fat artifacts from the traversal. Fat artifacts are * artifacts that have the property {@link org.eclipse.aether.artifact.ArtifactProperties#INCLUDES_DEPENDENCIES} set to * {@code true}. - * + * * @see org.eclipse.aether.artifact.Artifact#getProperties() */ -public final class FatArtifactTraverser - implements DependencyTraverser -{ +public final class FatArtifactTraverser implements DependencyTraverser { /** * Creates a new instance of this dependency traverser. */ - public FatArtifactTraverser() - { - } + public FatArtifactTraverser() {} - public boolean traverseDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); - String prop = dependency.getArtifact().getProperty( ArtifactProperties.INCLUDES_DEPENDENCIES, "" ); - return !Boolean.parseBoolean( prop ); + public boolean traverseDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); + String prop = dependency.getArtifact().getProperty(ArtifactProperties.INCLUDES_DEPENDENCIES, ""); + return !Boolean.parseBoolean(prop); } - public DependencyTraverser deriveChildTraverser( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencyTraverser deriveChildTraverser(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); return this; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } return true; } @Override - public int hashCode() - { + public int hashCode() { return getClass().hashCode(); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/StaticDependencyTraverser.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/StaticDependencyTraverser.java index 3d605ae6f..f15a303a4 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/StaticDependencyTraverser.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/StaticDependencyTraverser.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.traverser; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.traverser; import org.eclipse.aether.collection.DependencyCollectionContext; import org.eclipse.aether.collection.DependencyTraverser; @@ -28,43 +27,34 @@ /** * A dependency traverser which always or never traverses children. */ -public final class StaticDependencyTraverser - implements DependencyTraverser -{ +public final class StaticDependencyTraverser implements DependencyTraverser { private final boolean traverse; /** * Creates a new traverser with the specified traversal behavior. - * + * * @param traverse {@code true} to traverse all dependencies, {@code false} to never traverse. */ - public StaticDependencyTraverser( boolean traverse ) - { + public StaticDependencyTraverser(boolean traverse) { this.traverse = traverse; } - public boolean traverseDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); + public boolean traverseDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); return traverse; } - public DependencyTraverser deriveChildTraverser( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencyTraverser deriveChildTraverser(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); return this; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } @@ -73,11 +63,9 @@ else if ( null == obj || !getClass().equals( obj.getClass() ) ) } @Override - public int hashCode() - { + public int hashCode() { int hash = getClass().hashCode(); - hash = hash * 31 + ( traverse ? 1 : 0 ); + hash = hash * 31 + (traverse ? 1 : 0); return hash; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/package-info.java index a1b71e04f..8e5c7bcea 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/traverser/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Various dependency traversers for building a dependency graph. */ package org.eclipse.aether.util.graph.traverser; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/ChainedVersionFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/ChainedVersionFilter.java index 9be3f6095..38ecf650d 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/ChainedVersionFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/ChainedVersionFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.version; import java.util.Arrays; import java.util.Collection; @@ -30,9 +29,7 @@ * A version filter that combines multiple version filters into a chain where each filter gets invoked one after the * other, thereby accumulating their filtering effects. */ -public final class ChainedVersionFilter - implements VersionFilter -{ +public final class ChainedVersionFilter implements VersionFilter { private final VersionFilter[] filters; @@ -40,146 +37,116 @@ public final class ChainedVersionFilter /** * Chains the specified version filters. - * + * * @param filter1 The first version filter, may be {@code null}. * @param filter2 The second version filter, may be {@code null}. * @return The chained version filter or {@code null} if both input filters are {@code null}. */ - public static VersionFilter newInstance( VersionFilter filter1, VersionFilter filter2 ) - { - if ( filter1 == null ) - { + public static VersionFilter newInstance(VersionFilter filter1, VersionFilter filter2) { + if (filter1 == null) { return filter2; } - if ( filter2 == null ) - { + if (filter2 == null) { return filter1; } - return new ChainedVersionFilter( new VersionFilter[] { filter1, filter2 } ); + return new ChainedVersionFilter(new VersionFilter[] {filter1, filter2}); } /** * Chains the specified version filters. - * + * * @param filters The version filters to chain, must not be {@code null} or contain {@code null}. * @return The chained version filter or {@code null} if the input array is empty. */ - public static VersionFilter newInstance( VersionFilter... filters ) - { - if ( filters.length <= 1 ) - { - if ( filters.length <= 0 ) - { + public static VersionFilter newInstance(VersionFilter... filters) { + if (filters.length <= 1) { + if (filters.length <= 0) { return null; } return filters[0]; } - return new ChainedVersionFilter( filters.clone() ); + return new ChainedVersionFilter(filters.clone()); } /** * Chains the specified version filters. - * + * * @param filters The version filters to chain, must not be {@code null} or contain {@code null}. * @return The chained version filter or {@code null} if the input collection is empty. */ - public static VersionFilter newInstance( Collection filters ) - { - if ( filters.size() <= 1 ) - { - if ( filters.isEmpty() ) - { + public static VersionFilter newInstance(Collection filters) { + if (filters.size() <= 1) { + if (filters.isEmpty()) { return null; } return filters.iterator().next(); } - return new ChainedVersionFilter( filters.toArray( new VersionFilter[0] ) ); + return new ChainedVersionFilter(filters.toArray(new VersionFilter[0])); } - private ChainedVersionFilter( VersionFilter[] filters ) - { + private ChainedVersionFilter(VersionFilter[] filters) { this.filters = filters; } - public void filterVersions( VersionFilterContext context ) - throws RepositoryException - { - for ( int i = 0, n = filters.length; i < n && context.getCount() > 0; i++ ) - { - filters[i].filterVersions( context ); + public void filterVersions(VersionFilterContext context) throws RepositoryException { + for (int i = 0, n = filters.length; i < n && context.getCount() > 0; i++) { + filters[i].filterVersions(context); } } - public VersionFilter deriveChildFilter( DependencyCollectionContext context ) - { + public VersionFilter deriveChildFilter(DependencyCollectionContext context) { VersionFilter[] children = null; int removed = 0; - for ( int i = 0, n = filters.length; i < n; i++ ) - { - VersionFilter child = filters[i].deriveChildFilter( context ); - if ( children != null ) - { + for (int i = 0, n = filters.length; i < n; i++) { + VersionFilter child = filters[i].deriveChildFilter(context); + if (children != null) { children[i - removed] = child; - } - else if ( child != filters[i] ) - { + } else if (child != filters[i]) { children = new VersionFilter[filters.length]; - System.arraycopy( filters, 0, children, 0, i ); + System.arraycopy(filters, 0, children, 0, i); children[i - removed] = child; } - if ( child == null ) - { + if (child == null) { removed++; } } - if ( children == null ) - { + if (children == null) { return this; } - if ( removed > 0 ) - { + if (removed > 0) { int count = filters.length - removed; - if ( count <= 0 ) - { + if (count <= 0) { return null; } - if ( count == 1 ) - { + if (count == 1) { return children[0]; } VersionFilter[] tmp = new VersionFilter[count]; - System.arraycopy( children, 0, tmp, 0, count ); + System.arraycopy(children, 0, tmp, 0, count); children = tmp; } - return new ChainedVersionFilter( children ); + return new ChainedVersionFilter(children); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } ChainedVersionFilter that = (ChainedVersionFilter) obj; - return Arrays.equals( filters, that.filters ); + return Arrays.equals(filters, that.filters); } @Override - public int hashCode() - { - if ( hashCode == 0 ) - { + public int hashCode() { + if (hashCode == 0) { int hash = getClass().hashCode(); - hash = hash * 31 + Arrays.hashCode( filters ); + hash = hash * 31 + Arrays.hashCode(filters); hashCode = hash; } return hashCode; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/ContextualSnapshotVersionFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/ContextualSnapshotVersionFilter.java index 569bf4cbe..1c78f3f57 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/ContextualSnapshotVersionFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/ContextualSnapshotVersionFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.version; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -32,9 +31,7 @@ * {@link RepositorySystemSession#getConfigProperties() configuration property} {@link #CONFIG_PROP_ENABLE} to * {@code true}. */ -public final class ContextualSnapshotVersionFilter - implements VersionFilter -{ +public final class ContextualSnapshotVersionFilter implements VersionFilter { /** * The key in the repository session's {@link RepositorySystemSession#getConfigProperties() configuration @@ -48,36 +45,28 @@ public final class ContextualSnapshotVersionFilter /** * Creates a new instance of this version filter. */ - public ContextualSnapshotVersionFilter() - { + public ContextualSnapshotVersionFilter() { filter = new SnapshotVersionFilter(); } - private boolean isEnabled( RepositorySystemSession session ) - { - return ConfigUtils.getBoolean( session, false, CONFIG_PROP_ENABLE ); + private boolean isEnabled(RepositorySystemSession session) { + return ConfigUtils.getBoolean(session, false, CONFIG_PROP_ENABLE); } - public void filterVersions( VersionFilterContext context ) - { - if ( isEnabled( context.getSession() ) ) - { - filter.filterVersions( context ); + public void filterVersions(VersionFilterContext context) { + if (isEnabled(context.getSession())) { + filter.filterVersions(context); } } - public VersionFilter deriveChildFilter( DependencyCollectionContext context ) - { - if ( !isEnabled( context.getSession() ) ) - { + public VersionFilter deriveChildFilter(DependencyCollectionContext context) { + if (!isEnabled(context.getSession())) { Artifact artifact = context.getArtifact(); - if ( artifact == null ) - { + if (artifact == null) { // no root artifact to test, allow snapshots and recheck once we reach the direct dependencies return this; } - if ( artifact.isSnapshot() ) - { + if (artifact.isSnapshot()) { // root is a snapshot, allow snapshots all the way down return null; } @@ -87,23 +76,17 @@ public VersionFilter deriveChildFilter( DependencyCollectionContext context ) } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } return true; } @Override - public int hashCode() - { + public int hashCode() { return getClass().hashCode(); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/HighestVersionFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/HighestVersionFilter.java index 0731c46c7..eba1e0461 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/HighestVersionFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/HighestVersionFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.version; import java.util.Iterator; @@ -28,54 +27,40 @@ /** * A version filter that excludes any version except the highest one. */ -public final class HighestVersionFilter - implements VersionFilter -{ +public final class HighestVersionFilter implements VersionFilter { /** * Creates a new instance of this version filter. */ - public HighestVersionFilter() - { - } + public HighestVersionFilter() {} - public void filterVersions( VersionFilterContext context ) - { + public void filterVersions(VersionFilterContext context) { Iterator it = context.iterator(); - for ( boolean hasNext = it.hasNext(); hasNext; ) - { + for (boolean hasNext = it.hasNext(); hasNext; ) { it.next(); hasNext = it.hasNext(); - if ( hasNext ) - { + if (hasNext) { it.remove(); } } } - public VersionFilter deriveChildFilter( DependencyCollectionContext context ) - { + public VersionFilter deriveChildFilter(DependencyCollectionContext context) { return this; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } return true; } @Override - public int hashCode() - { + public int hashCode() { return getClass().hashCode(); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/SnapshotVersionFilter.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/SnapshotVersionFilter.java index 6af7cf57d..662000347 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/SnapshotVersionFilter.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/SnapshotVersionFilter.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.version; import java.util.Iterator; @@ -29,52 +28,38 @@ * A version filter that (unconditionally) blocks "*-SNAPSHOT" versions. For practical purposes, * {@link ContextualSnapshotVersionFilter} is usually more desirable. */ -public final class SnapshotVersionFilter - implements VersionFilter -{ +public final class SnapshotVersionFilter implements VersionFilter { /** * Creates a new instance of this version filter. */ - public SnapshotVersionFilter() - { - } + public SnapshotVersionFilter() {} - public void filterVersions( VersionFilterContext context ) - { - for ( Iterator it = context.iterator(); it.hasNext(); ) - { + public void filterVersions(VersionFilterContext context) { + for (Iterator it = context.iterator(); it.hasNext(); ) { String version = it.next().toString(); - if ( version.endsWith( "SNAPSHOT" ) ) - { + if (version.endsWith("SNAPSHOT")) { it.remove(); } } } - public VersionFilter deriveChildFilter( DependencyCollectionContext context ) - { + public VersionFilter deriveChildFilter(DependencyCollectionContext context) { return this; } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; - } - else if ( null == obj || !getClass().equals( obj.getClass() ) ) - { + } else if (null == obj || !getClass().equals(obj.getClass())) { return false; } return true; } @Override - public int hashCode() - { + public int hashCode() { return getClass().hashCode(); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/package-info.java index a9f4649cf..79c30c566 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/version/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Various version filters for building a dependency graph. */ package org.eclipse.aether.util.graph.version; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/AbstractDepthFirstNodeListGenerator.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/AbstractDepthFirstNodeListGenerator.java index cf519625d..97b3342a3 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/AbstractDepthFirstNodeListGenerator.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/AbstractDepthFirstNodeListGenerator.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,11 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.eclipse.aether.artifact.Artifact; -import org.eclipse.aether.graph.Dependency; -import org.eclipse.aether.graph.DependencyNode; -import org.eclipse.aether.graph.DependencyVisitor; +package org.eclipse.aether.util.graph.visitor; import java.io.File; import java.util.ArrayList; @@ -31,6 +25,11 @@ import java.util.List; import java.util.Map; +import org.eclipse.aether.artifact.Artifact; +import org.eclipse.aether.graph.Dependency; +import org.eclipse.aether.graph.DependencyNode; +import org.eclipse.aether.graph.DependencyVisitor; + /** * Abstract base class for depth first dependency tree traversers. Subclasses of this visitor will visit each node * exactly once regardless how many paths within the dependency graph lead to the node such that the resulting node @@ -40,48 +39,40 @@ * implementations for {@link #visitEnter(org.eclipse.aether.graph.DependencyNode)} and * {@link #visitLeave(org.eclipse.aether.graph.DependencyNode)} */ -abstract class AbstractDepthFirstNodeListGenerator - implements DependencyVisitor -{ +abstract class AbstractDepthFirstNodeListGenerator implements DependencyVisitor { private final Map visitedNodes; protected final List nodes; - AbstractDepthFirstNodeListGenerator() - { - nodes = new ArrayList<>( 128 ); - visitedNodes = new IdentityHashMap<>( 512 ); + AbstractDepthFirstNodeListGenerator() { + nodes = new ArrayList<>(128); + visitedNodes = new IdentityHashMap<>(512); } /** * Gets the list of dependency nodes that was generated during the graph traversal. - * + * * @return The list of dependency nodes, never {@code null}. */ - public List getNodes() - { + public List getNodes() { return nodes; } /** * Gets the dependencies seen during the graph traversal. - * + * * @param includeUnresolved Whether unresolved dependencies shall be included in the result or not. * @return The list of dependencies, never {@code null}. */ - public List getDependencies( boolean includeUnresolved ) - { - List dependencies = new ArrayList<>( getNodes().size() ); + public List getDependencies(boolean includeUnresolved) { + List dependencies = new ArrayList<>(getNodes().size()); - for ( DependencyNode node : getNodes() ) - { + for (DependencyNode node : getNodes()) { Dependency dependency = node.getDependency(); - if ( dependency != null ) - { - if ( includeUnresolved || dependency.getArtifact().getFile() != null ) - { - dependencies.add( dependency ); + if (dependency != null) { + if (includeUnresolved || dependency.getArtifact().getFile() != null) { + dependencies.add(dependency); } } } @@ -91,22 +82,18 @@ public List getDependencies( boolean includeUnresolved ) /** * Gets the artifacts associated with the list of dependency nodes generated during the graph traversal. - * + * * @param includeUnresolved Whether unresolved artifacts shall be included in the result or not. * @return The list of artifacts, never {@code null}. */ - public List getArtifacts( boolean includeUnresolved ) - { - List artifacts = new ArrayList<>( getNodes().size() ); - - for ( DependencyNode node : getNodes() ) - { - if ( node.getDependency() != null ) - { + public List getArtifacts(boolean includeUnresolved) { + List artifacts = new ArrayList<>(getNodes().size()); + + for (DependencyNode node : getNodes()) { + if (node.getDependency() != null) { Artifact artifact = node.getDependency().getArtifact(); - if ( includeUnresolved || artifact.getFile() != null ) - { - artifacts.add( artifact ); + if (includeUnresolved || artifact.getFile() != null) { + artifacts.add(artifact); } } } @@ -116,21 +103,17 @@ public List getArtifacts( boolean includeUnresolved ) /** * Gets the files of resolved artifacts seen during the graph traversal. - * + * * @return The list of artifact files, never {@code null}. */ - public List getFiles() - { - List files = new ArrayList<>( getNodes().size() ); - - for ( DependencyNode node : getNodes() ) - { - if ( node.getDependency() != null ) - { + public List getFiles() { + List files = new ArrayList<>(getNodes().size()); + + for (DependencyNode node : getNodes()) { + if (node.getDependency() != null) { File file = node.getDependency().getArtifact().getFile(); - if ( file != null ) - { - files.add( file ); + if (file != null) { + files.add(file); } } } @@ -141,25 +124,20 @@ public List getFiles() /** * Gets a class path by concatenating the artifact files of the visited dependency nodes. Nodes with unresolved * artifacts are automatically skipped. - * + * * @return The class path, using the platform-specific path separator, never {@code null}. */ - public String getClassPath() - { - StringBuilder buffer = new StringBuilder( 1024 ); + public String getClassPath() { + StringBuilder buffer = new StringBuilder(1024); - for ( Iterator it = getNodes().iterator(); it.hasNext(); ) - { + for (Iterator it = getNodes().iterator(); it.hasNext(); ) { DependencyNode node = it.next(); - if ( node.getDependency() != null ) - { + if (node.getDependency() != null) { Artifact artifact = node.getDependency().getArtifact(); - if ( artifact.getFile() != null ) - { - buffer.append( artifact.getFile().getAbsolutePath() ); - if ( it.hasNext() ) - { - buffer.append( File.pathSeparatorChar ); + if (artifact.getFile() != null) { + buffer.append(artifact.getFile().getAbsolutePath()); + if (it.hasNext()) { + buffer.append(File.pathSeparatorChar); } } } @@ -170,17 +148,15 @@ public String getClassPath() /** * Marks the specified node as being visited and determines whether the node has been visited before. - * + * * @param node The node being visited, must not be {@code null}. * @return {@code true} if the node has not been visited before, {@code false} if the node was already visited. */ - protected boolean setVisited( DependencyNode node ) - { - return visitedNodes.put( node, Boolean.TRUE ) == null; + protected boolean setVisited(DependencyNode node) { + return visitedNodes.put(node, Boolean.TRUE) == null; } - public abstract boolean visitEnter( DependencyNode node ); - - public abstract boolean visitLeave( DependencyNode node ); + public abstract boolean visitEnter(DependencyNode node); + public abstract boolean visitLeave(DependencyNode node); } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/CloningDependencyVisitor.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/CloningDependencyVisitor.java index 7c57db1cf..0da5649fa 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/CloningDependencyVisitor.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/CloningDependencyVisitor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.visitor; import java.util.IdentityHashMap; import java.util.Map; @@ -32,9 +31,7 @@ * dependency nodes (via {@link DefaultDependencyNode#DefaultDependencyNode(DependencyNode)}) but clients can create a * subclass and override {@link #clone(DependencyNode)} to alter the clone process. */ -public class CloningDependencyVisitor - implements DependencyVisitor -{ +public class CloningDependencyVisitor implements DependencyVisitor { private final Map clones; @@ -45,69 +42,57 @@ public class CloningDependencyVisitor /** * Creates a new visitor that clones the visited nodes. */ - public CloningDependencyVisitor() - { + public CloningDependencyVisitor() { parents = new Stack<>(); - clones = new IdentityHashMap<>( 256 ); + clones = new IdentityHashMap<>(256); } /** * Gets the root node of the cloned dependency graph. - * + * * @return The root node of the cloned dependency graph or {@code null}. */ - public final DependencyNode getRootNode() - { + public final DependencyNode getRootNode() { return root; } /** * Creates a clone of the specified node. - * + * * @param node The node to clone, must not be {@code null}. * @return The cloned node, never {@code null}. */ - protected DependencyNode clone( DependencyNode node ) - { - return new DefaultDependencyNode( node ); + protected DependencyNode clone(DependencyNode node) { + return new DefaultDependencyNode(node); } - public final boolean visitEnter( DependencyNode node ) - { + public final boolean visitEnter(DependencyNode node) { boolean recurse = true; - DependencyNode clone = clones.get( node ); - if ( clone == null ) - { - clone = clone( node ); - clones.put( node, clone ); - } - else - { + DependencyNode clone = clones.get(node); + if (clone == null) { + clone = clone(node); + clones.put(node, clone); + } else { recurse = false; } DependencyNode parent = parents.peek(); - if ( parent == null ) - { + if (parent == null) { root = clone; - } - else - { - parent.getChildren().add( clone ); + } else { + parent.getChildren().add(clone); } - parents.push( clone ); + parents.push(clone); return recurse; } - public final boolean visitLeave( DependencyNode node ) - { + public final boolean visitLeave(DependencyNode node) { parents.pop(); return true; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/FilteringDependencyVisitor.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/FilteringDependencyVisitor.java index 130fc575f..16a851028 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/FilteringDependencyVisitor.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/FilteringDependencyVisitor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,20 +16,19 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Objects.requireNonNull; +package org.eclipse.aether.util.graph.visitor; import org.eclipse.aether.graph.DependencyFilter; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.graph.DependencyVisitor; +import static java.util.Objects.requireNonNull; + /** * A dependency visitor that delegates to another visitor if nodes match a filter. Note that in case of a mismatching * node, the children of that node are still visisted and presented to the filter. */ -public final class FilteringDependencyVisitor - implements DependencyVisitor -{ +public final class FilteringDependencyVisitor implements DependencyVisitor { private final DependencyFilter filter; @@ -47,9 +44,8 @@ public final class FilteringDependencyVisitor * @param visitor The visitor to delegate to, must not be {@code null}. * @param filter The filter to apply, may be {@code null} to not filter. */ - public FilteringDependencyVisitor( DependencyVisitor visitor, DependencyFilter filter ) - { - this.visitor = requireNonNull( visitor, "dependency visitor delegate cannot be null" ); + public FilteringDependencyVisitor(DependencyVisitor visitor, DependencyFilter filter) { + this.visitor = requireNonNull(visitor, "dependency visitor delegate cannot be null"); this.filter = filter; this.accepts = new Stack<>(); this.parents = new Stack<>(); @@ -57,56 +53,45 @@ public FilteringDependencyVisitor( DependencyVisitor visitor, DependencyFilter f /** * Gets the visitor to which this visitor delegates to. - * + * * @return The visitor being delegated to, never {@code null}. */ - public DependencyVisitor getVisitor() - { + public DependencyVisitor getVisitor() { return visitor; } /** * Gets the filter being applied before delegation. - * + * * @return The filter being applied or {@code null} if none. */ - public DependencyFilter getFilter() - { + public DependencyFilter getFilter() { return filter; } - public boolean visitEnter( DependencyNode node ) - { - boolean accept = filter == null || filter.accept( node, parents ); + public boolean visitEnter(DependencyNode node) { + boolean accept = filter == null || filter.accept(node, parents); - accepts.push( accept ); + accepts.push(accept); - parents.push( node ); + parents.push(node); - if ( accept ) - { - return visitor.visitEnter( node ); - } - else - { + if (accept) { + return visitor.visitEnter(node); + } else { return true; } } - public boolean visitLeave( DependencyNode node ) - { + public boolean visitLeave(DependencyNode node) { parents.pop(); Boolean accept = accepts.pop(); - if ( accept ) - { - return visitor.visitLeave( node ); - } - else - { + if (accept) { + return visitor.visitLeave(node); + } else { return true; } } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PathRecordingDependencyVisitor.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PathRecordingDependencyVisitor.java index 3f1c8e2a2..119323851 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PathRecordingDependencyVisitor.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PathRecordingDependencyVisitor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.visitor; import java.util.ArrayList; import java.util.Arrays; @@ -30,9 +29,7 @@ /** * A dependency visitor that records all paths leading to nodes matching a certain filter criteria. */ -public final class PathRecordingDependencyVisitor - implements DependencyVisitor -{ +public final class PathRecordingDependencyVisitor implements DependencyVisitor { private final DependencyFilter filter; @@ -45,25 +42,23 @@ public final class PathRecordingDependencyVisitor /** * Creates a new visitor that uses the specified filter to identify terminal nodes of interesting paths. The visitor * will not search for paths going beyond an already matched node. - * + * * @param filter The filter used to select terminal nodes of paths to record, may be {@code null} to match any node. */ - public PathRecordingDependencyVisitor( DependencyFilter filter ) - { - this( filter, true ); + public PathRecordingDependencyVisitor(DependencyFilter filter) { + this(filter, true); } /** * Creates a new visitor that uses the specified filter to identify terminal nodes of interesting paths. - * + * * @param filter The filter used to select terminal nodes of paths to record, may be {@code null} to match any node. * @param excludeChildrenOfMatches Flag controlling whether children of matched nodes should be excluded from the * traversal, thereby ignoring any potential paths to other matching nodes beneath a matching ancestor * node. If {@code true}, all recorded paths will have only one matching node (namely the terminal node), * if {@code false} a recorded path can consist of multiple matching nodes. */ - public PathRecordingDependencyVisitor( DependencyFilter filter, boolean excludeChildrenOfMatches ) - { + public PathRecordingDependencyVisitor(DependencyFilter filter, boolean excludeChildrenOfMatches) { this.filter = filter; this.excludeChildrenOfMatches = excludeChildrenOfMatches; paths = new ArrayList<>(); @@ -72,11 +67,10 @@ public PathRecordingDependencyVisitor( DependencyFilter filter, boolean excludeC /** * Gets the filter being used to select terminal nodes. - * + * * @return The filter being used or {@code null} if none. */ - public DependencyFilter getFilter() - { + public DependencyFilter getFilter() { return filter; } @@ -84,32 +78,27 @@ public DependencyFilter getFilter() * Gets the paths leading to nodes matching the filter that have been recorded during the graph visit. A path is * given as a sequence of nodes, starting with the root node of the graph and ending with a node that matched the * filter. - * + * * @return The recorded paths, never {@code null}. */ - public List> getPaths() - { + public List> getPaths() { return paths; } - public boolean visitEnter( DependencyNode node ) - { - boolean accept = filter == null || filter.accept( node, parents ); + public boolean visitEnter(DependencyNode node) { + boolean accept = filter == null || filter.accept(node, parents); - boolean hasDuplicateNodeInParent = parents.contains( node ); - parents.push( node ); + boolean hasDuplicateNodeInParent = parents.contains(node); + parents.push(node); - if ( accept ) - { + if (accept) { DependencyNode[] path = new DependencyNode[parents.size()]; - for ( int i = 0, n = parents.size(); i < n; i++ ) - { - path[n - i - 1] = parents.get( i ); + for (int i = 0, n = parents.size(); i < n; i++) { + path[n - i - 1] = parents.get(i); } - paths.add( Arrays.asList( path ) ); + paths.add(Arrays.asList(path)); - if ( excludeChildrenOfMatches ) - { + if (excludeChildrenOfMatches) { return false; } } @@ -117,11 +106,9 @@ public boolean visitEnter( DependencyNode node ) return !hasDuplicateNodeInParent; } - public boolean visitLeave( DependencyNode node ) - { + public boolean visitLeave(DependencyNode node) { parents.pop(); return true; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PostorderNodeListGenerator.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PostorderNodeListGenerator.java index b9ed7ad25..b8ba0dae5 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PostorderNodeListGenerator.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PostorderNodeListGenerator.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.visitor; import org.eclipse.aether.graph.DependencyNode; @@ -26,29 +25,24 @@ * visits each node exactly once regardless how many paths within the dependency graph lead to the node such that the * resulting node sequence is free of duplicates. */ -public final class PostorderNodeListGenerator - extends AbstractDepthFirstNodeListGenerator -{ +public final class PostorderNodeListGenerator extends AbstractDepthFirstNodeListGenerator { private final Stack visits; /** * Creates a new postorder list generator. */ - public PostorderNodeListGenerator() - { + public PostorderNodeListGenerator() { visits = new Stack<>(); } @Override - public boolean visitEnter( DependencyNode node ) - { - boolean visited = !setVisited( node ); + public boolean visitEnter(DependencyNode node) { + boolean visited = !setVisited(node); - visits.push( visited ); + visits.push(visited); - if ( visited ) - { + if (visited) { return false; } @@ -56,21 +50,17 @@ public boolean visitEnter( DependencyNode node ) } @Override - public boolean visitLeave( DependencyNode node ) - { + public boolean visitLeave(DependencyNode node) { Boolean visited = visits.pop(); - if ( visited ) - { + if (visited) { return true; } - if ( node.getDependency() != null ) - { - nodes.add( node ); + if (node.getDependency() != null) { + nodes.add(node); } return true; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PreorderNodeListGenerator.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PreorderNodeListGenerator.java index bd9b52abf..f8370b1a3 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PreorderNodeListGenerator.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/PreorderNodeListGenerator.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.visitor; import org.eclipse.aether.graph.DependencyNode; @@ -26,37 +25,28 @@ * visits each node exactly once regardless how many paths within the dependency graph lead to the node such that the * resulting node sequence is free of duplicates. */ -public final class PreorderNodeListGenerator - extends AbstractDepthFirstNodeListGenerator -{ +public final class PreorderNodeListGenerator extends AbstractDepthFirstNodeListGenerator { /** * Creates a new preorder list generator. */ - public PreorderNodeListGenerator() - { - } + public PreorderNodeListGenerator() {} @Override - public boolean visitEnter( DependencyNode node ) - { - if ( !setVisited( node ) ) - { + public boolean visitEnter(DependencyNode node) { + if (!setVisited(node)) { return false; } - if ( node.getDependency() != null ) - { - nodes.add( node ); + if (node.getDependency() != null) { + nodes.add(node); } return true; } @Override - public boolean visitLeave( DependencyNode node ) - { + public boolean visitLeave(DependencyNode node) { return true; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/Stack.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/Stack.java index 5abdc5a42..0f443951f 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/Stack.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/Stack.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.visitor; import java.util.AbstractList; import java.util.NoSuchElementException; @@ -27,62 +26,49 @@ * A non-synchronized stack with a non-modifiable list view which starts at the top of the stack. While * {@code LinkedList} can provide the same behavior, it creates many temp objects upon frequent pushes/pops. */ -class Stack - extends AbstractList - implements RandomAccess -{ +class Stack extends AbstractList implements RandomAccess { - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") // CHECKSTYLE_OFF: MagicNumber private E[] elements = (E[]) new Object[96]; // CHECKSTYLE_ON: MagicNumber private int size; - public void push( E element ) - { - if ( size >= elements.length ) - { - @SuppressWarnings( "unchecked" ) + public void push(E element) { + if (size >= elements.length) { + @SuppressWarnings("unchecked") E[] tmp = (E[]) new Object[size + 64]; - System.arraycopy( elements, 0, tmp, 0, elements.length ); + System.arraycopy(elements, 0, tmp, 0, elements.length); elements = tmp; } elements[size++] = element; } - public E pop() - { - if ( size <= 0 ) - { + public E pop() { + if (size <= 0) { throw new NoSuchElementException(); } return elements[--size]; } - public E peek() - { - if ( size <= 0 ) - { + public E peek() { + if (size <= 0) { return null; } return elements[size - 1]; } @Override - public E get( int index ) - { - if ( index < 0 || index >= size ) - { - throw new IndexOutOfBoundsException( "Index: " + index + ", Size: " + size ); + public E get(int index) { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } return elements[size - index - 1]; } @Override - public int size() - { + public int size() { return size; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/TreeDependencyVisitor.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/TreeDependencyVisitor.java index 70a2664c7..94cc382ea 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/TreeDependencyVisitor.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/TreeDependencyVisitor.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,22 +16,22 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.visitor; import java.util.IdentityHashMap; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.graph.DependencyVisitor; +import static java.util.Objects.requireNonNull; + /** * A dependency visitor that delegates to another visitor if a node hasn't been visited before. In other words, this * visitor provides a tree-view of a dependency graph which generally can have multiple paths to the same node or even * cycles. */ -public final class TreeDependencyVisitor - implements DependencyVisitor -{ +public final class TreeDependencyVisitor implements DependencyVisitor { private final Map visitedNodes; @@ -46,37 +44,31 @@ public final class TreeDependencyVisitor * * @param visitor The visitor to delegate to, must not be {@code null}. */ - public TreeDependencyVisitor( DependencyVisitor visitor ) - { - this.visitor = requireNonNull( visitor, "dependency visitor delegate cannot be null" ); - visitedNodes = new IdentityHashMap<>( 512 ); + public TreeDependencyVisitor(DependencyVisitor visitor) { + this.visitor = requireNonNull(visitor, "dependency visitor delegate cannot be null"); + visitedNodes = new IdentityHashMap<>(512); visits = new Stack<>(); } - public boolean visitEnter( DependencyNode node ) - { - boolean visited = visitedNodes.put( node, Boolean.TRUE ) != null; + public boolean visitEnter(DependencyNode node) { + boolean visited = visitedNodes.put(node, Boolean.TRUE) != null; - visits.push( visited ); + visits.push(visited); - if ( visited ) - { + if (visited) { return false; } - return visitor.visitEnter( node ); + return visitor.visitEnter(node); } - public boolean visitLeave( DependencyNode node ) - { + public boolean visitLeave(DependencyNode node) { Boolean visited = visits.pop(); - if ( visited ) - { + if (visited) { return true; } - return visitor.visitLeave( node ); + return visitor.visitLeave(node); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/package-info.java index 3ea9968b1..efde7fcbe 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/graph/visitor/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Various dependency visitors for inspecting a dependency graph. */ package org.eclipse.aether.util.graph.visitor; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/ChainedRepositoryListener.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/ChainedRepositoryListener.java index 1b310fed9..e263129d9 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/ChainedRepositoryListener.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/ChainedRepositoryListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.listener; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.listener; import java.util.Arrays; import java.util.Collection; @@ -34,9 +33,7 @@ * A repository listener that delegates to zero or more other listeners (multicast). The list of target listeners is * thread-safe, i.e. target listeners can be added or removed by any thread at any time. */ -public final class ChainedRepositoryListener - extends AbstractRepositoryListener -{ +public final class ChainedRepositoryListener extends AbstractRepositoryListener { private final List listeners = new CopyOnWriteArrayList<>(); @@ -44,416 +41,305 @@ public final class ChainedRepositoryListener * Creates a new multicast listener that delegates to the specified listeners. In contrast to the constructor, this * factory method will avoid creating an actual chained listener if one of the specified readers is actually * {@code null}. - * + * * @param listener1 The first listener, may be {@code null}. * @param listener2 The second listener, may be {@code null}. * @return The chained listener or {@code null} if no listener was supplied. */ - public static RepositoryListener newInstance( RepositoryListener listener1, RepositoryListener listener2 ) - { - if ( listener1 == null ) - { + public static RepositoryListener newInstance(RepositoryListener listener1, RepositoryListener listener2) { + if (listener1 == null) { return listener2; - } - else if ( listener2 == null ) - { + } else if (listener2 == null) { return listener1; } - return new ChainedRepositoryListener( listener1, listener2 ); + return new ChainedRepositoryListener(listener1, listener2); } /** * Creates a new multicast listener that delegates to the specified listeners. - * + * * @param listeners The listeners to delegate to, may be {@code null} or empty. */ - public ChainedRepositoryListener( RepositoryListener... listeners ) - { - if ( listeners != null ) - { - add( Arrays.asList( listeners ) ); + public ChainedRepositoryListener(RepositoryListener... listeners) { + if (listeners != null) { + add(Arrays.asList(listeners)); } } /** * Creates a new multicast listener that delegates to the specified listeners. - * + * * @param listeners The listeners to delegate to, may be {@code null} or empty. */ - public ChainedRepositoryListener( Collection listeners ) - { - add( listeners ); + public ChainedRepositoryListener(Collection listeners) { + add(listeners); } /** * Adds the specified listeners to the end of the multicast chain. - * + * * @param listeners The listeners to add, may be {@code null} or empty. */ - public void add( Collection listeners ) - { - if ( listeners != null ) - { - for ( RepositoryListener listener : listeners ) - { - add( listener ); + public void add(Collection listeners) { + if (listeners != null) { + for (RepositoryListener listener : listeners) { + add(listener); } } } /** * Adds the specified listener to the end of the multicast chain. - * + * * @param listener The listener to add, may be {@code null}. */ - public void add( RepositoryListener listener ) - { - if ( listener != null ) - { - listeners.add( listener ); + public void add(RepositoryListener listener) { + if (listener != null) { + listeners.add(listener); } } /** * Removes the specified listener from the multicast chain. Trying to remove a non-existing listener has no effect. - * + * * @param listener The listener to remove, may be {@code null}. */ - public void remove( RepositoryListener listener ) - { - if ( listener != null ) - { - listeners.remove( listener ); + public void remove(RepositoryListener listener) { + if (listener != null) { + listeners.remove(listener); } } - @SuppressWarnings( "EmptyMethod" ) - protected void handleError( RepositoryEvent event, RepositoryListener listener, RuntimeException error ) - { + @SuppressWarnings("EmptyMethod") + protected void handleError(RepositoryEvent event, RepositoryListener listener, RuntimeException error) { // default just swallows errors } @Override - public void artifactDeployed( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.artifactDeployed( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void artifactDeployed(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.artifactDeployed(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void artifactDeploying( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.artifactDeploying( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void artifactDeploying(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.artifactDeploying(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void artifactDescriptorInvalid( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.artifactDescriptorInvalid( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void artifactDescriptorInvalid(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.artifactDescriptorInvalid(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void artifactDescriptorMissing( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.artifactDescriptorMissing( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void artifactDescriptorMissing(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.artifactDescriptorMissing(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void artifactDownloaded( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.artifactDownloaded( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void artifactDownloaded(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.artifactDownloaded(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void artifactDownloading( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.artifactDownloading( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void artifactDownloading(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.artifactDownloading(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void artifactInstalled( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.artifactInstalled( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void artifactInstalled(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.artifactInstalled(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void artifactInstalling( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.artifactInstalling( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void artifactInstalling(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.artifactInstalling(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void artifactResolved( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.artifactResolved( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void artifactResolved(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.artifactResolved(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void artifactResolving( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.artifactResolving( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void artifactResolving(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.artifactResolving(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void metadataDeployed( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.metadataDeployed( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void metadataDeployed(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.metadataDeployed(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void metadataDeploying( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.metadataDeploying( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void metadataDeploying(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.metadataDeploying(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void metadataDownloaded( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.metadataDownloaded( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void metadataDownloaded(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.metadataDownloaded(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void metadataDownloading( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.metadataDownloading( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void metadataDownloading(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.metadataDownloading(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void metadataInstalled( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.metadataInstalled( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void metadataInstalled(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.metadataInstalled(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void metadataInstalling( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.metadataInstalling( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void metadataInstalling(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.metadataInstalling(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void metadataInvalid( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.metadataInvalid( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void metadataInvalid(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.metadataInvalid(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void metadataResolved( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.metadataResolved( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void metadataResolved(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.metadataResolved(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void metadataResolving( RepositoryEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( RepositoryListener listener : listeners ) - { - try - { - listener.metadataResolving( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void metadataResolving(RepositoryEvent event) { + requireNonNull(event, "event cannot be null"); + for (RepositoryListener listener : listeners) { + try { + listener.metadataResolving(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/ChainedTransferListener.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/ChainedTransferListener.java index d66488660..2c21d10ee 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/ChainedTransferListener.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/ChainedTransferListener.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.listener; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.listener; import java.util.Arrays; import java.util.Collection; @@ -35,9 +34,7 @@ * A transfer listener that delegates to zero or more other listeners (multicast). The list of target listeners is * thread-safe, i.e. target listeners can be added or removed by any thread at any time. */ -public final class ChainedTransferListener - extends AbstractTransferListener -{ +public final class ChainedTransferListener extends AbstractTransferListener { private final List listeners = new CopyOnWriteArrayList<>(); @@ -45,199 +42,149 @@ public final class ChainedTransferListener * Creates a new multicast listener that delegates to the specified listeners. In contrast to the constructor, this * factory method will avoid creating an actual chained listener if one of the specified readers is actually * {@code null}. - * + * * @param listener1 The first listener, may be {@code null}. * @param listener2 The second listener, may be {@code null}. * @return The chained listener or {@code null} if no listener was supplied. */ - public static TransferListener newInstance( TransferListener listener1, TransferListener listener2 ) - { - if ( listener1 == null ) - { + public static TransferListener newInstance(TransferListener listener1, TransferListener listener2) { + if (listener1 == null) { return listener2; - } - else if ( listener2 == null ) - { + } else if (listener2 == null) { return listener1; } - return new ChainedTransferListener( listener1, listener2 ); + return new ChainedTransferListener(listener1, listener2); } /** * Creates a new multicast listener that delegates to the specified listeners. - * + * * @param listeners The listeners to delegate to, may be {@code null} or empty. */ - public ChainedTransferListener( TransferListener... listeners ) - { - if ( listeners != null ) - { - add( Arrays.asList( listeners ) ); + public ChainedTransferListener(TransferListener... listeners) { + if (listeners != null) { + add(Arrays.asList(listeners)); } } /** * Creates a new multicast listener that delegates to the specified listeners. - * + * * @param listeners The listeners to delegate to, may be {@code null} or empty. */ - public ChainedTransferListener( Collection listeners ) - { - add( listeners ); + public ChainedTransferListener(Collection listeners) { + add(listeners); } /** * Adds the specified listeners to the end of the multicast chain. - * + * * @param listeners The listeners to add, may be {@code null} or empty. */ - public void add( Collection listeners ) - { - if ( listeners != null ) - { - for ( TransferListener listener : listeners ) - { - add( listener ); + public void add(Collection listeners) { + if (listeners != null) { + for (TransferListener listener : listeners) { + add(listener); } } } /** * Adds the specified listener to the end of the multicast chain. - * + * * @param listener The listener to add, may be {@code null}. */ - public void add( TransferListener listener ) - { - if ( listener != null ) - { - listeners.add( listener ); + public void add(TransferListener listener) { + if (listener != null) { + listeners.add(listener); } } /** * Removes the specified listener from the multicast chain. Trying to remove a non-existing listener has no effect. - * + * * @param listener The listener to remove, may be {@code null}. */ - public void remove( TransferListener listener ) - { - if ( listener != null ) - { - listeners.remove( listener ); + public void remove(TransferListener listener) { + if (listener != null) { + listeners.remove(listener); } } - @SuppressWarnings( "EmptyMethod" ) - protected void handleError( TransferEvent event, TransferListener listener, RuntimeException error ) - { + @SuppressWarnings("EmptyMethod") + protected void handleError(TransferEvent event, TransferListener listener, RuntimeException error) { // default just swallows errors } @Override - public void transferInitiated( TransferEvent event ) - throws TransferCancelledException - { - requireNonNull( event, "event cannot be null" ); - for ( TransferListener listener : listeners ) - { - try - { - listener.transferInitiated( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void transferInitiated(TransferEvent event) throws TransferCancelledException { + requireNonNull(event, "event cannot be null"); + for (TransferListener listener : listeners) { + try { + listener.transferInitiated(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void transferStarted( TransferEvent event ) - throws TransferCancelledException - { - requireNonNull( event, "event cannot be null" ); - for ( TransferListener listener : listeners ) - { - try - { - listener.transferStarted( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void transferStarted(TransferEvent event) throws TransferCancelledException { + requireNonNull(event, "event cannot be null"); + for (TransferListener listener : listeners) { + try { + listener.transferStarted(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void transferProgressed( TransferEvent event ) - throws TransferCancelledException - { - requireNonNull( event, "event cannot be null" ); - for ( TransferListener listener : listeners ) - { - try - { - listener.transferProgressed( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void transferProgressed(TransferEvent event) throws TransferCancelledException { + requireNonNull(event, "event cannot be null"); + for (TransferListener listener : listeners) { + try { + listener.transferProgressed(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void transferCorrupted( TransferEvent event ) - throws TransferCancelledException - { - requireNonNull( event, "event cannot be null" ); - for ( TransferListener listener : listeners ) - { - try - { - listener.transferCorrupted( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void transferCorrupted(TransferEvent event) throws TransferCancelledException { + requireNonNull(event, "event cannot be null"); + for (TransferListener listener : listeners) { + try { + listener.transferCorrupted(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void transferSucceeded( TransferEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( TransferListener listener : listeners ) - { - try - { - listener.transferSucceeded( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void transferSucceeded(TransferEvent event) { + requireNonNull(event, "event cannot be null"); + for (TransferListener listener : listeners) { + try { + listener.transferSucceeded(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } @Override - public void transferFailed( TransferEvent event ) - { - requireNonNull( event, "event cannot be null" ); - for ( TransferListener listener : listeners ) - { - try - { - listener.transferFailed( event ); - } - catch ( RuntimeException e ) - { - handleError( event, listener, e ); + public void transferFailed(TransferEvent event) { + requireNonNull(event, "event cannot be null"); + for (TransferListener listener : listeners) { + try { + listener.transferFailed(event); + } catch (RuntimeException e) { + handleError(event, listener, e); } } } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/package-info.java index 9f0be5800..b39761de7 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/listener/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Utilities to build repository and transfer listeners. */ package org.eclipse.aether.util.listener; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/package-info.java index 605e777ed..3ae45113e 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Miscellaneous utility classes. */ package org.eclipse.aether.util; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/AuthenticationBuilder.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/AuthenticationBuilder.java index 9988d777e..72ab96bde 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/AuthenticationBuilder.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/AuthenticationBuilder.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,110 +16,100 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; + +import javax.net.ssl.HostnameVerifier; import java.util.ArrayList; import java.util.List; -import javax.net.ssl.HostnameVerifier; - import org.eclipse.aether.repository.Authentication; import org.eclipse.aether.repository.AuthenticationContext; /** * A utility class to build authentication info for repositories and proxies. */ -public final class AuthenticationBuilder -{ +public final class AuthenticationBuilder { private final List authentications; /** * Creates a new authentication builder. */ - public AuthenticationBuilder() - { + public AuthenticationBuilder() { authentications = new ArrayList<>(); } /** * Builds a new authentication object from the current data of this builder. The state of the builder itself remains * unchanged. - * + * * @return The authentication or {@code null} if no authentication data was supplied to the builder. */ - public Authentication build() - { - if ( authentications.isEmpty() ) - { + public Authentication build() { + if (authentications.isEmpty()) { return null; } - if ( authentications.size() == 1 ) - { - return authentications.get( 0 ); + if (authentications.size() == 1) { + return authentications.get(0); } - return new ChainedAuthentication( authentications ); + return new ChainedAuthentication(authentications); } /** * Adds username data to the authentication. - * + * * @param username The username, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public AuthenticationBuilder addUsername( String username ) - { - return addString( AuthenticationContext.USERNAME, username ); + public AuthenticationBuilder addUsername(String username) { + return addString(AuthenticationContext.USERNAME, username); } /** * Adds password data to the authentication. - * + * * @param password The password, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public AuthenticationBuilder addPassword( String password ) - { - return addSecret( AuthenticationContext.PASSWORD, password ); + public AuthenticationBuilder addPassword(String password) { + return addSecret(AuthenticationContext.PASSWORD, password); } /** * Adds password data to the authentication. The resulting authentication object uses an encrypted copy of the * supplied character data and callers are advised to clear the input array soon after this method returns. - * + * * @param password The password, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public AuthenticationBuilder addPassword( char[] password ) - { - return addSecret( AuthenticationContext.PASSWORD, password ); + public AuthenticationBuilder addPassword(char[] password) { + return addSecret(AuthenticationContext.PASSWORD, password); } /** * Adds NTLM data to the authentication. - * + * * @param workstation The NTLM workstation name, may be {@code null}. * @param domain The NTLM domain name, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public AuthenticationBuilder addNtlm( String workstation, String domain ) - { - addString( AuthenticationContext.NTLM_WORKSTATION, workstation ); - return addString( AuthenticationContext.NTLM_DOMAIN, domain ); + public AuthenticationBuilder addNtlm(String workstation, String domain) { + addString(AuthenticationContext.NTLM_WORKSTATION, workstation); + return addString(AuthenticationContext.NTLM_DOMAIN, domain); } /** * Adds private key data to the authentication. - * + * * @param pathname The (absolute) path to the private key file, may be {@code null}. * @param passphrase The passphrase protecting the private key, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public AuthenticationBuilder addPrivateKey( String pathname, String passphrase ) - { - if ( pathname != null ) - { - addString( AuthenticationContext.PRIVATE_KEY_PATH, pathname ); - addSecret( AuthenticationContext.PRIVATE_KEY_PASSPHRASE, passphrase ); + public AuthenticationBuilder addPrivateKey(String pathname, String passphrase) { + if (pathname != null) { + addString(AuthenticationContext.PRIVATE_KEY_PATH, pathname); + addSecret(AuthenticationContext.PRIVATE_KEY_PASSPHRASE, passphrase); } return this; } @@ -129,17 +117,15 @@ public AuthenticationBuilder addPrivateKey( String pathname, String passphrase ) /** * Adds private key data to the authentication. The resulting authentication object uses an encrypted copy of the * supplied character data and callers are advised to clear the input array soon after this method returns. - * + * * @param pathname The (absolute) path to the private key file, may be {@code null}. * @param passphrase The passphrase protecting the private key, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public AuthenticationBuilder addPrivateKey( String pathname, char[] passphrase ) - { - if ( pathname != null ) - { - addString( AuthenticationContext.PRIVATE_KEY_PATH, pathname ); - addSecret( AuthenticationContext.PRIVATE_KEY_PASSPHRASE, passphrase ); + public AuthenticationBuilder addPrivateKey(String pathname, char[] passphrase) { + if (pathname != null) { + addString(AuthenticationContext.PRIVATE_KEY_PATH, pathname); + addSecret(AuthenticationContext.PRIVATE_KEY_PASSPHRASE, passphrase); } return this; } @@ -149,15 +135,13 @@ public AuthenticationBuilder addPrivateKey( String pathname, char[] passphrase ) * verifier's runtime type exhibit the exact same behavior, i.e. the behavior of the verifier depends solely on the * runtime type and not on any configuration. For verifiers that do not fit this assumption, use * {@link #addCustom(Authentication)} with a suitable implementation instead. - * + * * @param verifier The hostname verifier, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public AuthenticationBuilder addHostnameVerifier( HostnameVerifier verifier ) - { - if ( verifier != null ) - { - authentications.add( new ComponentAuthentication( AuthenticationContext.SSL_HOSTNAME_VERIFIER, verifier ) ); + public AuthenticationBuilder addHostnameVerifier(HostnameVerifier verifier) { + if (verifier != null) { + authentications.add(new ComponentAuthentication(AuthenticationContext.SSL_HOSTNAME_VERIFIER, verifier)); } return this; } @@ -165,32 +149,28 @@ public AuthenticationBuilder addHostnameVerifier( HostnameVerifier verifier ) /** * Adds custom string data to the authentication. Note: If the string data is confidential, use * {@link #addSecret(String, char[])} instead. - * + * * @param key The key for the authentication data, must not be {@code null}. * @param value The value for the authentication data, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public AuthenticationBuilder addString( String key, String value ) - { - if ( value != null ) - { - authentications.add( new StringAuthentication( key, value ) ); + public AuthenticationBuilder addString(String key, String value) { + if (value != null) { + authentications.add(new StringAuthentication(key, value)); } return this; } /** * Adds sensitive custom string data to the authentication. - * + * * @param key The key for the authentication data, must not be {@code null}. * @param value The value for the authentication data, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public AuthenticationBuilder addSecret( String key, String value ) - { - if ( value != null ) - { - authentications.add( new SecretAuthentication( key, value ) ); + public AuthenticationBuilder addSecret(String key, String value) { + if (value != null) { + authentications.add(new SecretAuthentication(key, value)); } return this; } @@ -199,33 +179,28 @@ public AuthenticationBuilder addSecret( String key, String value ) * Adds sensitive custom string data to the authentication. The resulting authentication object uses an encrypted * copy of the supplied character data and callers are advised to clear the input array soon after this method * returns. - * + * * @param key The key for the authentication data, must not be {@code null}. * @param value The value for the authentication data, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public AuthenticationBuilder addSecret( String key, char[] value ) - { - if ( value != null ) - { - authentications.add( new SecretAuthentication( key, value ) ); + public AuthenticationBuilder addSecret(String key, char[] value) { + if (value != null) { + authentications.add(new SecretAuthentication(key, value)); } return this; } /** * Adds custom authentication data to the authentication. - * + * * @param authentication The authentication to add, may be {@code null}. * @return This builder for chaining, never {@code null}. */ - public AuthenticationBuilder addCustom( Authentication authentication ) - { - if ( authentication != null ) - { - authentications.add( authentication ); + public AuthenticationBuilder addCustom(Authentication authentication) { + if (authentication != null) { + authentications.add(authentication); } return this; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedAuthentication.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedAuthentication.java index b7c2dd1dd..2ead9a8f6 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedAuthentication.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedAuthentication.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import java.util.Arrays; import java.util.Collection; @@ -33,88 +32,66 @@ * Authentication that aggregates other authentication blocks. When multiple input authentication blocks provide the * same authentication key, the last written value wins. */ -final class ChainedAuthentication - implements Authentication -{ +final class ChainedAuthentication implements Authentication { private final Authentication[] authentications; - ChainedAuthentication( Authentication... authentications ) - { - if ( authentications != null && authentications.length > 0 ) - { + ChainedAuthentication(Authentication... authentications) { + if (authentications != null && authentications.length > 0) { this.authentications = authentications.clone(); - } - else - { + } else { this.authentications = new Authentication[0]; } } - ChainedAuthentication( Collection authentications ) - { - if ( authentications != null && !authentications.isEmpty() ) - { - this.authentications = authentications.toArray( new Authentication[0] ); - } - else - { + ChainedAuthentication(Collection authentications) { + if (authentications != null && !authentications.isEmpty()) { + this.authentications = authentications.toArray(new Authentication[0]); + } else { this.authentications = new Authentication[0]; } } - public void fill( AuthenticationContext context, String key, Map data ) - { - requireNonNull( context, "context cannot be null" ); - for ( Authentication authentication : authentications ) - { - authentication.fill( context, key, data ); + public void fill(AuthenticationContext context, String key, Map data) { + requireNonNull(context, "context cannot be null"); + for (Authentication authentication : authentications) { + authentication.fill(context, key, data); } } - public void digest( AuthenticationDigest digest ) - { - requireNonNull( digest, "digest cannot be null" ); - for ( Authentication authentication : authentications ) - { - authentication.digest( digest ); + public void digest(AuthenticationDigest digest) { + requireNonNull(digest, "digest cannot be null"); + for (Authentication authentication : authentications) { + authentication.digest(digest); } } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } ChainedAuthentication that = (ChainedAuthentication) obj; - return Arrays.equals( authentications, that.authentications ); + return Arrays.equals(authentications, that.authentications); } @Override - public int hashCode() - { - return Arrays.hashCode( authentications ); + public int hashCode() { + return Arrays.hashCode(authentications); } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 256 ); - for ( Authentication authentication : authentications ) - { - if ( buffer.length() > 0 ) - { - buffer.append( ", " ); + public String toString() { + StringBuilder buffer = new StringBuilder(256); + for (Authentication authentication : authentications) { + if (buffer.length() > 0) { + buffer.append(", "); } - buffer.append( authentication ); + buffer.append(authentication); } return buffer.toString(); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedLocalRepositoryManager.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedLocalRepositoryManager.java index e50168012..d53b560f0 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedLocalRepositoryManager.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedLocalRepositoryManager.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import java.io.File; import java.nio.file.Files; @@ -50,146 +49,115 @@ * * @since 1.9.2 */ -public final class ChainedLocalRepositoryManager - implements LocalRepositoryManager -{ +public final class ChainedLocalRepositoryManager implements LocalRepositoryManager { private final LocalRepositoryManager head; private final List tail; private final boolean ignoreTailAvailability; - public ChainedLocalRepositoryManager( LocalRepositoryManager head, - List tail, - boolean ignoreTailAvailability ) - { - this.head = requireNonNull( head, "head cannot be null" ); - this.tail = requireNonNull( tail, "tail cannot be null" ); + public ChainedLocalRepositoryManager( + LocalRepositoryManager head, List tail, boolean ignoreTailAvailability) { + this.head = requireNonNull(head, "head cannot be null"); + this.tail = requireNonNull(tail, "tail cannot be null"); this.ignoreTailAvailability = ignoreTailAvailability; } @Override - public LocalRepository getRepository() - { + public LocalRepository getRepository() { return head.getRepository(); } @Override - public String getPathForLocalArtifact( Artifact artifact ) - { - return head.getPathForLocalArtifact( artifact ); + public String getPathForLocalArtifact(Artifact artifact) { + return head.getPathForLocalArtifact(artifact); } @Override - public String getPathForRemoteArtifact( Artifact artifact, RemoteRepository repository, String context ) - { - return head.getPathForRemoteArtifact( artifact, repository, context ); + public String getPathForRemoteArtifact(Artifact artifact, RemoteRepository repository, String context) { + return head.getPathForRemoteArtifact(artifact, repository, context); } @Override - public String getPathForLocalMetadata( Metadata metadata ) - { - return head.getPathForLocalMetadata( metadata ); + public String getPathForLocalMetadata(Metadata metadata) { + return head.getPathForLocalMetadata(metadata); } @Override - public String getPathForRemoteMetadata( Metadata metadata, RemoteRepository repository, String context ) - { - return head.getPathForRemoteMetadata( metadata, repository, context ); + public String getPathForRemoteMetadata(Metadata metadata, RemoteRepository repository, String context) { + return head.getPathForRemoteMetadata(metadata, repository, context); } @Override - public LocalArtifactResult find( RepositorySystemSession session, LocalArtifactRequest request ) - { - LocalArtifactResult result = head.find( session, request ); - if ( result.isAvailable() ) - { + public LocalArtifactResult find(RepositorySystemSession session, LocalArtifactRequest request) { + LocalArtifactResult result = head.find(session, request); + if (result.isAvailable()) { return result; } - for ( LocalRepositoryManager lrm : tail ) - { - result = lrm.find( session, request ); - if ( result.getFile() != null ) - { - if ( ignoreTailAvailability ) - { - result.setAvailable( true ); + for (LocalRepositoryManager lrm : tail) { + result = lrm.find(session, request); + if (result.getFile() != null) { + if (ignoreTailAvailability) { + result.setAvailable(true); return result; - } - else if ( result.isAvailable() ) - { + } else if (result.isAvailable()) { return result; } } } - return new LocalArtifactResult( request ); + return new LocalArtifactResult(request); } @Override - public void add( RepositorySystemSession session, LocalArtifactRegistration request ) - { + public void add(RepositorySystemSession session, LocalArtifactRegistration request) { String artifactPath; - if ( request.getRepository() != null ) - { - artifactPath = getPathForRemoteArtifact( request.getArtifact(), request.getRepository(), "check" ); - } - else - { - artifactPath = getPathForLocalArtifact( request.getArtifact() ); + if (request.getRepository() != null) { + artifactPath = getPathForRemoteArtifact(request.getArtifact(), request.getRepository(), "check"); + } else { + artifactPath = getPathForLocalArtifact(request.getArtifact()); } - Path file = new File( head.getRepository().getBasedir(), artifactPath ).toPath(); - if ( Files.isRegularFile( file ) ) - { - head.add( session, request ); + Path file = new File(head.getRepository().getBasedir(), artifactPath).toPath(); + if (Files.isRegularFile(file)) { + head.add(session, request); } } @Override - public LocalMetadataResult find( RepositorySystemSession session, LocalMetadataRequest request ) - { - LocalMetadataResult result = head.find( session, request ); - if ( result.getFile() != null ) - { + public LocalMetadataResult find(RepositorySystemSession session, LocalMetadataRequest request) { + LocalMetadataResult result = head.find(session, request); + if (result.getFile() != null) { return result; } - for ( LocalRepositoryManager lrm : tail ) - { - result = lrm.find( session, request ); - if ( result.getFile() != null ) - { + for (LocalRepositoryManager lrm : tail) { + result = lrm.find(session, request); + if (result.getFile() != null) { return result; } } - return new LocalMetadataResult( request ); + return new LocalMetadataResult(request); } @Override - public void add( RepositorySystemSession session, LocalMetadataRegistration request ) - { + public void add(RepositorySystemSession session, LocalMetadataRegistration request) { String metadataPath; - if ( request.getRepository() != null ) - { - metadataPath = getPathForRemoteMetadata( request.getMetadata(), request.getRepository(), "check" ); - } - else - { - metadataPath = getPathForLocalMetadata( request.getMetadata() ); + if (request.getRepository() != null) { + metadataPath = getPathForRemoteMetadata(request.getMetadata(), request.getRepository(), "check"); + } else { + metadataPath = getPathForLocalMetadata(request.getMetadata()); } - Path file = new File( head.getRepository().getBasedir(), metadataPath ).toPath(); - if ( Files.isRegularFile( file ) ) - { - head.add( session, request ); + Path file = new File(head.getRepository().getBasedir(), metadataPath).toPath(); + if (Files.isRegularFile(file)) { + head.add(session, request); } } @Override - public String toString() - { + public String toString() { return head.getRepository().toString() - + tail.stream().map( LocalRepositoryManager::getRepository ).collect( toList() ); + + tail.stream().map(LocalRepositoryManager::getRepository).collect(toList()); } } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedWorkspaceReader.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedWorkspaceReader.java index 024d718e7..9526988af 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedWorkspaceReader.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ChainedWorkspaceReader.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import java.io.File; import java.util.ArrayList; @@ -35,9 +34,7 @@ /** * A workspace reader that delegates to a chain of other readers, effectively aggregating their contents. */ -public final class ChainedWorkspaceReader - implements WorkspaceReader -{ +public final class ChainedWorkspaceReader implements WorkspaceReader { private final List readers = new ArrayList<>(); @@ -45,61 +42,50 @@ public final class ChainedWorkspaceReader /** * Creates a new workspace reader by chaining the specified readers. - * + * * @param readers The readers to chain, may be {@code null}. * @see #newInstance(WorkspaceReader, WorkspaceReader) */ - public ChainedWorkspaceReader( WorkspaceReader... readers ) - { - if ( readers != null ) - { - Collections.addAll( this.readers, readers ); + public ChainedWorkspaceReader(WorkspaceReader... readers) { + if (readers != null) { + Collections.addAll(this.readers, readers); } StringBuilder buffer = new StringBuilder(); - for ( WorkspaceReader reader : this.readers ) - { - if ( buffer.length() > 0 ) - { - buffer.append( '+' ); + for (WorkspaceReader reader : this.readers) { + if (buffer.length() > 0) { + buffer.append('+'); } - buffer.append( reader.getRepository().getContentType() ); + buffer.append(reader.getRepository().getContentType()); } - repository = new WorkspaceRepository( buffer.toString(), new Key( this.readers ) ); + repository = new WorkspaceRepository(buffer.toString(), new Key(this.readers)); } /** * Creates a new workspace reader by chaining the specified readers. In contrast to the constructor, this factory * method will avoid creating an actual chained reader if one of the specified readers is actually {@code null}. - * + * * @param reader1 The first workspace reader, may be {@code null}. * @param reader2 The second workspace reader, may be {@code null}. * @return The chained reader or {@code null} if no workspace reader was supplied. */ - public static WorkspaceReader newInstance( WorkspaceReader reader1, WorkspaceReader reader2 ) - { - if ( reader1 == null ) - { + public static WorkspaceReader newInstance(WorkspaceReader reader1, WorkspaceReader reader2) { + if (reader1 == null) { return reader2; - } - else if ( reader2 == null ) - { + } else if (reader2 == null) { return reader1; } - return new ChainedWorkspaceReader( reader1, reader2 ); + return new ChainedWorkspaceReader(reader1, reader2); } - public File findArtifact( Artifact artifact ) - { - requireNonNull( artifact, "artifact cannot be null" ); + public File findArtifact(Artifact artifact) { + requireNonNull(artifact, "artifact cannot be null"); File file = null; - for ( WorkspaceReader reader : readers ) - { - file = reader.findArtifact( artifact ); - if ( file != null ) - { + for (WorkspaceReader reader : readers) { + file = reader.findArtifact(artifact); + if (file != null) { break; } } @@ -107,62 +93,49 @@ public File findArtifact( Artifact artifact ) return file; } - public List findVersions( Artifact artifact ) - { - requireNonNull( artifact, "artifact cannot be null" ); + public List findVersions(Artifact artifact) { + requireNonNull(artifact, "artifact cannot be null"); Collection versions = new LinkedHashSet<>(); - for ( WorkspaceReader reader : readers ) - { - versions.addAll( reader.findVersions( artifact ) ); + for (WorkspaceReader reader : readers) { + versions.addAll(reader.findVersions(artifact)); } - return Collections.unmodifiableList( new ArrayList<>( versions ) ); + return Collections.unmodifiableList(new ArrayList<>(versions)); } - public WorkspaceRepository getRepository() - { - Key key = new Key( readers ); - if ( !key.equals( repository.getKey() ) ) - { - repository = new WorkspaceRepository( repository.getContentType(), key ); + public WorkspaceRepository getRepository() { + Key key = new Key(readers); + if (!key.equals(repository.getKey())) { + repository = new WorkspaceRepository(repository.getContentType(), key); } return repository; } - private static class Key - { + private static class Key { private final List keys = new ArrayList<>(); - Key( List readers ) - { - for ( WorkspaceReader reader : readers ) - { - keys.add( reader.getRepository().getKey() ); + Key(List readers) { + for (WorkspaceReader reader : readers) { + keys.add(reader.getRepository().getKey()); } } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } - return keys.equals( ( (Key) obj ).keys ); + return keys.equals(((Key) obj).keys); } @Override - public int hashCode() - { + public int hashCode() { return keys.hashCode(); } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ComponentAuthentication.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ComponentAuthentication.java index d73a0f503..8e30cf1c4 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ComponentAuthentication.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ComponentAuthentication.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,84 +16,72 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.repository.Authentication; import org.eclipse.aether.repository.AuthenticationContext; import org.eclipse.aether.repository.AuthenticationDigest; +import static java.util.Objects.requireNonNull; + /** * Authentication block that manages a single authentication key and its component value. In this context, component * refers to an object whose behavior is solely dependent on its implementation class. */ -final class ComponentAuthentication - implements Authentication -{ +final class ComponentAuthentication implements Authentication { private final String key; private final Object value; - ComponentAuthentication( String key, Object value ) - { - this.key = requireNonNull( key, "authentication key cannot be null" ); - if ( key.length() == 0 ) - { - throw new IllegalArgumentException( "authentication key cannot be empty" ); + ComponentAuthentication(String key, Object value) { + this.key = requireNonNull(key, "authentication key cannot be null"); + if (key.length() == 0) { + throw new IllegalArgumentException("authentication key cannot be empty"); } this.value = value; } - public void fill( AuthenticationContext context, String key, Map data ) - { - requireNonNull( context, "context cannot be null" ); - context.put( this.key, value ); + public void fill(AuthenticationContext context, String key, Map data) { + requireNonNull(context, "context cannot be null"); + context.put(this.key, value); } - public void digest( AuthenticationDigest digest ) - { - requireNonNull( digest, "digest cannot be null" ); - if ( value != null ) - { - digest.update( key, value.getClass().getName() ); + public void digest(AuthenticationDigest digest) { + requireNonNull(digest, "digest cannot be null"); + if (value != null) { + digest.update(key, value.getClass().getName()); } } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } ComponentAuthentication that = (ComponentAuthentication) obj; - return key.equals( that.key ) && eqClass( value, that.value ); + return key.equals(that.key) && eqClass(value, that.value); } - private static boolean eqClass( T s1, T s2 ) - { - return ( s1 == null ) ? s2 == null : s2 != null && s1.getClass().equals( s2.getClass() ); + private static boolean eqClass(T s1, T s2) { + return (s1 == null) ? s2 == null : s2 != null && s1.getClass().equals(s2.getClass()); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + key.hashCode(); - hash = hash * 31 + ( ( value != null ) ? value.getClass().hashCode() : 0 ); + hash = hash * 31 + ((value != null) ? value.getClass().hashCode() : 0); return hash; } @Override - public String toString() - { + public String toString() { return key + "=" + value; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ConservativeAuthenticationSelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ConservativeAuthenticationSelector.java index 04f60f8c4..65861441a 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ConservativeAuthenticationSelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ConservativeAuthenticationSelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,20 +16,19 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Objects.requireNonNull; +package org.eclipse.aether.util.repository; import org.eclipse.aether.repository.Authentication; import org.eclipse.aether.repository.AuthenticationSelector; import org.eclipse.aether.repository.RemoteRepository; +import static java.util.Objects.requireNonNull; + /** * An authentication selector that delegates to another selector but only if a repository has no authentication data * yet. If authentication has already been assigned to a repository, that is selected. */ -public final class ConservativeAuthenticationSelector - implements AuthenticationSelector -{ +public final class ConservativeAuthenticationSelector implements AuthenticationSelector { private final AuthenticationSelector selector; @@ -41,20 +38,16 @@ public final class ConservativeAuthenticationSelector * @param selector The selector to delegate to in case a repository has no authentication yet, must not be * {@code null}. */ - public ConservativeAuthenticationSelector( AuthenticationSelector selector ) - { - this.selector = requireNonNull( selector, "authentication selector cannot be null" ); + public ConservativeAuthenticationSelector(AuthenticationSelector selector) { + this.selector = requireNonNull(selector, "authentication selector cannot be null"); } - public Authentication getAuthentication( RemoteRepository repository ) - { - requireNonNull( repository, "repository cannot be null" ); + public Authentication getAuthentication(RemoteRepository repository) { + requireNonNull(repository, "repository cannot be null"); Authentication auth = repository.getAuthentication(); - if ( auth != null ) - { + if (auth != null) { return auth; } - return selector.getAuthentication( repository ); + return selector.getAuthentication(repository); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ConservativeProxySelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ConservativeProxySelector.java index bc7eebd91..98ec40aee 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ConservativeProxySelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/ConservativeProxySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,20 +16,19 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Objects.requireNonNull; +package org.eclipse.aether.util.repository; import org.eclipse.aether.repository.Proxy; import org.eclipse.aether.repository.ProxySelector; import org.eclipse.aether.repository.RemoteRepository; +import static java.util.Objects.requireNonNull; + /** * A proxy selector that delegates to another selector but only if a repository has no proxy yet. If a proxy has already * been assigned to a repository, that is selected. */ -public final class ConservativeProxySelector - implements ProxySelector -{ +public final class ConservativeProxySelector implements ProxySelector { private final ProxySelector selector; @@ -40,20 +37,16 @@ public final class ConservativeProxySelector * * @param selector The selector to delegate to in case a repository has no proxy yet, must not be {@code null}. */ - public ConservativeProxySelector( ProxySelector selector ) - { - this.selector = requireNonNull( selector, "proxy selector cannot be null" ); + public ConservativeProxySelector(ProxySelector selector) { + this.selector = requireNonNull(selector, "proxy selector cannot be null"); } - public Proxy getProxy( RemoteRepository repository ) - { - requireNonNull( repository, "repository cannot be null" ); + public Proxy getProxy(RemoteRepository repository) { + requireNonNull(repository, "repository cannot be null"); Proxy proxy = repository.getProxy(); - if ( proxy != null ) - { + if (proxy != null) { return proxy; } - return selector.getProxy( repository ); + return selector.getProxy(repository); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultAuthenticationSelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultAuthenticationSelector.java index d631222ee..547d44297 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultAuthenticationSelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultAuthenticationSelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import java.util.HashMap; import java.util.Map; @@ -31,37 +30,29 @@ /** * A simple authentication selector that selects authentication based on repository identifiers. */ -public final class DefaultAuthenticationSelector - implements AuthenticationSelector -{ +public final class DefaultAuthenticationSelector implements AuthenticationSelector { private final Map repos = new HashMap<>(); /** * Adds the specified authentication info for the given repository identifier. - * + * * @param id The identifier of the repository to add the authentication for, must not be {@code null}. * @param auth The authentication to add, may be {@code null}. * @return This selector for chaining, never {@code null}. */ - public DefaultAuthenticationSelector add( String id, Authentication auth ) - { - if ( auth != null ) - { - repos.put( id, auth ); - } - else - { - repos.remove( id ); + public DefaultAuthenticationSelector add(String id, Authentication auth) { + if (auth != null) { + repos.put(id, auth); + } else { + repos.remove(id); } return this; } - public Authentication getAuthentication( RemoteRepository repository ) - { - requireNonNull( repository, "repository cannot be null" ); - return repos.get( repository.getId() ); + public Authentication getAuthentication(RemoteRepository repository) { + requireNonNull(repository, "repository cannot be null"); + return repos.get(repository.getId()); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultMirrorSelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultMirrorSelector.java index dfb51c50d..f6f78088f 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultMirrorSelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultMirrorSelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import java.util.ArrayList; import java.util.Collections; @@ -31,9 +30,7 @@ /** * A simple mirror selector that selects mirrors based on repository identifiers. */ -public final class DefaultMirrorSelector - implements MirrorSelector -{ +public final class DefaultMirrorSelector implements MirrorSelector { private static final String WILDCARD = "*"; @@ -44,15 +41,14 @@ public final class DefaultMirrorSelector private final List mirrors = new ArrayList<>(); @Deprecated - public DefaultMirrorSelector add( String id, String url, String type, boolean repositoryManager, - String mirrorOfIds, String mirrorOfTypes ) - { - return add( id, url, type, repositoryManager, false, mirrorOfIds, mirrorOfTypes ); + public DefaultMirrorSelector add( + String id, String url, String type, boolean repositoryManager, String mirrorOfIds, String mirrorOfTypes) { + return add(id, url, type, repositoryManager, false, mirrorOfIds, mirrorOfTypes); } /** * Adds the specified mirror to this selector. - * + * * @param id The identifier of the mirror, must not be {@code null}. * @param url The URL of the mirror, must not be {@code null}. * @param type The content type of the mirror, must not be {@code null}. @@ -67,64 +63,60 @@ public DefaultMirrorSelector add( String id, String url, String type, boolean re * wildcard "*" and the "!" negation syntax are supported. For example "*,!p2". * @return This selector for chaining, never {@code null}. */ - public DefaultMirrorSelector add( String id, String url, String type, boolean repositoryManager, boolean blocked, - String mirrorOfIds, String mirrorOfTypes ) - { - mirrors.add( new MirrorDef( id, url, type, repositoryManager, blocked, mirrorOfIds, mirrorOfTypes ) ); + public DefaultMirrorSelector add( + String id, + String url, + String type, + boolean repositoryManager, + boolean blocked, + String mirrorOfIds, + String mirrorOfTypes) { + mirrors.add(new MirrorDef(id, url, type, repositoryManager, blocked, mirrorOfIds, mirrorOfTypes)); return this; } - public RemoteRepository getMirror( RemoteRepository repository ) - { - requireNonNull( repository, "repository cannot be null" ); - MirrorDef mirror = findMirror( repository ); + public RemoteRepository getMirror(RemoteRepository repository) { + requireNonNull(repository, "repository cannot be null"); + MirrorDef mirror = findMirror(repository); - if ( mirror == null ) - { + if (mirror == null) { return null; } RemoteRepository.Builder builder = - new RemoteRepository.Builder( mirror.id, repository.getContentType(), mirror.url ); + new RemoteRepository.Builder(mirror.id, repository.getContentType(), mirror.url); - builder.setRepositoryManager( mirror.repositoryManager ); + builder.setRepositoryManager(mirror.repositoryManager); - builder.setBlocked( mirror.blocked ); + builder.setBlocked(mirror.blocked); - if ( mirror.type != null && mirror.type.length() > 0 ) - { - builder.setContentType( mirror.type ); + if (mirror.type != null && mirror.type.length() > 0) { + builder.setContentType(mirror.type); } - builder.setSnapshotPolicy( repository.getPolicy( true ) ); - builder.setReleasePolicy( repository.getPolicy( false ) ); + builder.setSnapshotPolicy(repository.getPolicy(true)); + builder.setReleasePolicy(repository.getPolicy(false)); - builder.setMirroredRepositories( Collections.singletonList( repository ) ); + builder.setMirroredRepositories(Collections.singletonList(repository)); return builder.build(); } - private MirrorDef findMirror( RemoteRepository repository ) - { + private MirrorDef findMirror(RemoteRepository repository) { String repoId = repository.getId(); - if ( repoId != null && !mirrors.isEmpty() ) - { - for ( MirrorDef mirror : mirrors ) - { - if ( repoId.equals( mirror.mirrorOfIds ) && matchesType( repository.getContentType(), - mirror.mirrorOfTypes ) ) - { + if (repoId != null && !mirrors.isEmpty()) { + for (MirrorDef mirror : mirrors) { + if (repoId.equals(mirror.mirrorOfIds) + && matchesType(repository.getContentType(), mirror.mirrorOfTypes)) { return mirror; } } - for ( MirrorDef mirror : mirrors ) - { - if ( matchPattern( repository, mirror.mirrorOfIds ) && matchesType( repository.getContentType(), - mirror.mirrorOfTypes ) ) - { + for (MirrorDef mirror : mirrors) { + if (matchPattern(repository, mirror.mirrorOfIds) + && matchesType(repository.getContentType(), mirror.mirrorOfTypes)) { return mirror; } } @@ -142,57 +134,45 @@ private MirrorDef findMirror( RemoteRepository repository ) *
  • {@code repo,repo1} = {@code repo} or {@code repo1},
  • *
  • {@code *,!repo1} = everything except {@code repo1}.
  • * - * + * * @param repository to compare for a match. * @param pattern used for match. * @return true if the repository is a match to this pattern. */ - static boolean matchPattern( RemoteRepository repository, String pattern ) - { + static boolean matchPattern(RemoteRepository repository, String pattern) { boolean result = false; String originalId = repository.getId(); // simple checks first to short circuit processing below. - if ( WILDCARD.equals( pattern ) || pattern.equals( originalId ) ) - { + if (WILDCARD.equals(pattern) || pattern.equals(originalId)) { result = true; - } - else - { + } else { // process the list - String[] repos = pattern.split( "," ); - for ( String repo : repos ) - { + String[] repos = pattern.split(","); + for (String repo : repos) { // see if this is a negative match - if ( repo.length() > 1 && repo.startsWith( "!" ) ) - { - if ( repo.substring( 1 ).equals( originalId ) ) - { + if (repo.length() > 1 && repo.startsWith("!")) { + if (repo.substring(1).equals(originalId)) { // explicitly exclude. Set result and stop processing. result = false; break; } } // check for exact match - else if ( repo.equals( originalId ) ) - { + else if (repo.equals(originalId)) { result = true; break; } // check for external:* - else if ( EXTERNAL_WILDCARD.equals( repo ) && isExternalRepo( repository ) ) - { + else if (EXTERNAL_WILDCARD.equals(repo) && isExternalRepo(repository)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } // check for external:http:* - else if ( EXTERNAL_HTTP_WILDCARD.equals( repo ) && isExternalHttpRepo( repository ) ) - { + else if (EXTERNAL_HTTP_WILDCARD.equals(repo) && isExternalHttpRepo(repository)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo - } - else if ( WILDCARD.equals( repo ) ) - { + } else if (WILDCARD.equals(repo)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } @@ -203,81 +183,66 @@ else if ( WILDCARD.equals( repo ) ) /** * Checks the URL to see if this repository refers to an external repository. - * + * * @param repository The repository to check, must not be {@code null}. * @return {@code true} if external, {@code false} otherwise. */ - static boolean isExternalRepo( RemoteRepository repository ) - { - boolean local = isLocal( repository.getHost() ) || "file".equalsIgnoreCase( repository.getProtocol() ); + static boolean isExternalRepo(RemoteRepository repository) { + boolean local = isLocal(repository.getHost()) || "file".equalsIgnoreCase(repository.getProtocol()); return !local; } - private static boolean isLocal( String host ) - { - return "localhost".equals( host ) || "127.0.0.1".equals( host ); + private static boolean isLocal(String host) { + return "localhost".equals(host) || "127.0.0.1".equals(host); } /** * Checks the URL to see if this repository refers to a non-localhost repository using HTTP. - * + * * @param repository The repository to check, must not be {@code null}. * @return {@code true} if external, {@code false} otherwise. */ - static boolean isExternalHttpRepo( RemoteRepository repository ) - { - return ( "http".equalsIgnoreCase( repository.getProtocol() ) - || "dav".equalsIgnoreCase( repository.getProtocol() ) - || "dav:http".equalsIgnoreCase( repository.getProtocol() ) - || "dav+http".equalsIgnoreCase( repository.getProtocol() ) ) - && !isLocal( repository.getHost() ); + static boolean isExternalHttpRepo(RemoteRepository repository) { + return ("http".equalsIgnoreCase(repository.getProtocol()) + || "dav".equalsIgnoreCase(repository.getProtocol()) + || "dav:http".equalsIgnoreCase(repository.getProtocol()) + || "dav+http".equalsIgnoreCase(repository.getProtocol())) + && !isLocal(repository.getHost()); } /** * Checks whether the types configured for a mirror match with the type of the repository. - * + * * @param repoType The type of the repository, may be {@code null}. * @param mirrorType The types supported by the mirror, may be {@code null}. * @return {@code true} if the types associated with the mirror match the type of the original repository, * {@code false} otherwise. */ - static boolean matchesType( String repoType, String mirrorType ) - { + static boolean matchesType(String repoType, String mirrorType) { boolean result = false; // simple checks first to short circuit processing below. - if ( mirrorType == null || mirrorType.isEmpty() || WILDCARD.equals( mirrorType ) ) - { + if (mirrorType == null || mirrorType.isEmpty() || WILDCARD.equals(mirrorType)) { result = true; - } - else if ( mirrorType.equals( repoType ) ) - { + } else if (mirrorType.equals(repoType)) { result = true; - } - else - { + } else { // process the list - String[] layouts = mirrorType.split( "," ); - for ( String layout : layouts ) - { + String[] layouts = mirrorType.split(","); + for (String layout : layouts) { // see if this is a negative match - if ( layout.length() > 1 && layout.startsWith( "!" ) ) - { - if ( layout.substring( 1 ).equals( repoType ) ) - { + if (layout.length() > 1 && layout.startsWith("!")) { + if (layout.substring(1).equals(repoType)) { // explicitly exclude. Set result and stop processing. result = false; break; } } // check for exact match - else if ( layout.equals( repoType ) ) - { + else if (layout.equals(repoType)) { result = true; break; - } - else if ( WILDCARD.equals( layout ) ) - { + } else if (WILDCARD.equals(layout)) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } @@ -287,8 +252,7 @@ else if ( WILDCARD.equals( layout ) ) return result; } - static class MirrorDef - { + static class MirrorDef { final String id; @@ -304,9 +268,14 @@ static class MirrorDef final String mirrorOfTypes; - MirrorDef( String id, String url, String type, boolean repositoryManager, boolean blocked, String mirrorOfIds, - String mirrorOfTypes ) - { + MirrorDef( + String id, + String url, + String type, + boolean repositoryManager, + boolean blocked, + String mirrorOfIds, + String mirrorOfTypes) { this.id = id; this.url = url; this.type = type; @@ -315,7 +284,5 @@ static class MirrorDef this.mirrorOfIds = mirrorOfIds; this.mirrorOfTypes = mirrorOfTypes; } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultProxySelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultProxySelector.java index 9e0d52090..136b68554 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultProxySelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/DefaultProxySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; -import static java.util.Objects.requireNonNull; import java.util.StringTokenizer; import java.util.regex.Pattern; @@ -32,124 +30,99 @@ import org.eclipse.aether.repository.ProxySelector; import org.eclipse.aether.repository.RemoteRepository; +import static java.util.Objects.requireNonNull; + /** * A simple proxy selector that selects the first matching proxy from a list of configured proxies. */ -public final class DefaultProxySelector - implements ProxySelector -{ +public final class DefaultProxySelector implements ProxySelector { private final List proxies = new ArrayList<>(); /** * Adds the specified proxy definition to the selector. Proxy definitions are ordered, the first matching proxy for * a given repository will be used. - * + * * @param proxy The proxy definition to add, must not be {@code null}. * @param nonProxyHosts The list of (case-insensitive) host names to exclude from proxying, may be {@code null}. * @return This proxy selector for chaining, never {@code null}. */ - public DefaultProxySelector add( Proxy proxy, String nonProxyHosts ) - { - requireNonNull( proxy, "proxy cannot be null" ); - proxies.add( new ProxyDef( proxy, nonProxyHosts ) ); + public DefaultProxySelector add(Proxy proxy, String nonProxyHosts) { + requireNonNull(proxy, "proxy cannot be null"); + proxies.add(new ProxyDef(proxy, nonProxyHosts)); return this; } - public Proxy getProxy( RemoteRepository repository ) - { - requireNonNull( repository, "repository cannot be null" ); + public Proxy getProxy(RemoteRepository repository) { + requireNonNull(repository, "repository cannot be null"); Map candidates = new HashMap<>(); String host = repository.getHost(); - for ( ProxyDef proxy : proxies ) - { - if ( !proxy.nonProxyHosts.isNonProxyHost( host ) ) - { - String key = proxy.proxy.getType().toLowerCase( Locale.ENGLISH ); - if ( !candidates.containsKey( key ) ) - { - candidates.put( key, proxy ); + for (ProxyDef proxy : proxies) { + if (!proxy.nonProxyHosts.isNonProxyHost(host)) { + String key = proxy.proxy.getType().toLowerCase(Locale.ENGLISH); + if (!candidates.containsKey(key)) { + candidates.put(key, proxy); } } } - String protocol = repository.getProtocol().toLowerCase( Locale.ENGLISH ); + String protocol = repository.getProtocol().toLowerCase(Locale.ENGLISH); - if ( "davs".equals( protocol ) ) - { + if ("davs".equals(protocol)) { protocol = "https"; - } - else if ( "dav".equals( protocol ) ) - { + } else if ("dav".equals(protocol)) { protocol = "http"; - } - else if ( protocol.startsWith( "dav:" ) ) - { - protocol = protocol.substring( "dav:".length() ); + } else if (protocol.startsWith("dav:")) { + protocol = protocol.substring("dav:".length()); } - ProxyDef proxy = candidates.get( protocol ); - if ( proxy == null && "https".equals( protocol ) ) - { - proxy = candidates.get( "http" ); + ProxyDef proxy = candidates.get(protocol); + if (proxy == null && "https".equals(protocol)) { + proxy = candidates.get("http"); } - return ( proxy != null ) ? proxy.proxy : null; + return (proxy != null) ? proxy.proxy : null; } - static class NonProxyHosts - { + static class NonProxyHosts { private final Pattern[] patterns; - NonProxyHosts( String nonProxyHosts ) - { + NonProxyHosts(String nonProxyHosts) { List patterns = new ArrayList<>(); - if ( nonProxyHosts != null ) - { - for ( StringTokenizer tokenizer = new StringTokenizer( nonProxyHosts, "|" ); - tokenizer.hasMoreTokens(); ) - { + if (nonProxyHosts != null) { + for (StringTokenizer tokenizer = new StringTokenizer(nonProxyHosts, "|"); tokenizer.hasMoreTokens(); ) { String pattern = tokenizer.nextToken(); - pattern = pattern.replace( ".", "\\." ).replace( "*", ".*" ); - patterns.add( Pattern.compile( pattern, Pattern.CASE_INSENSITIVE ) ); + pattern = pattern.replace(".", "\\.").replace("*", ".*"); + patterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } } - this.patterns = patterns.toArray( new Pattern[0] ); + this.patterns = patterns.toArray(new Pattern[0]); } - boolean isNonProxyHost( String host ) - { - if ( host != null ) - { - for ( Pattern pattern : patterns ) - { - if ( pattern.matcher( host ).matches() ) - { + boolean isNonProxyHost(String host) { + if (host != null) { + for (Pattern pattern : patterns) { + if (pattern.matcher(host).matches()) { return true; } } } return false; } - } - static class ProxyDef - { + static class ProxyDef { final Proxy proxy; final NonProxyHosts nonProxyHosts; - ProxyDef( Proxy proxy, String nonProxyHosts ) - { + ProxyDef(Proxy proxy, String nonProxyHosts) { this.proxy = proxy; - this.nonProxyHosts = new NonProxyHosts( nonProxyHosts ); + this.nonProxyHosts = new NonProxyHosts(nonProxyHosts); } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/JreProxySelector.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/JreProxySelector.java index b99e7e880..cea50527d 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/JreProxySelector.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/JreProxySelector.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import java.net.Authenticator; import java.net.InetSocketAddress; @@ -46,64 +45,48 @@ * details. The {@link java.net.Authenticator JRE's global authenticator} is used to look up credentials for a proxy * when needed. */ -public final class JreProxySelector - implements ProxySelector -{ +public final class JreProxySelector implements ProxySelector { /** * Creates a new proxy selector that delegates to {@link java.net.ProxySelector#getDefault()}. */ - public JreProxySelector() - { - } + public JreProxySelector() {} - public Proxy getProxy( RemoteRepository repository ) - { - requireNonNull( repository, "repository cannot be null" ); + public Proxy getProxy(RemoteRepository repository) { + requireNonNull(repository, "repository cannot be null"); List proxies = null; - try - { - URI uri = new URI( repository.getUrl() ).parseServerAuthority(); - proxies = java.net.ProxySelector.getDefault().select( uri ); - } - catch ( Exception e ) - { + try { + URI uri = new URI(repository.getUrl()).parseServerAuthority(); + proxies = java.net.ProxySelector.getDefault().select(uri); + } catch (Exception e) { // URL invalid or not accepted by selector or no selector at all, simply use no proxy } - if ( proxies != null ) - { - for ( java.net.Proxy proxy : proxies ) - { - if ( java.net.Proxy.Type.DIRECT.equals( proxy.type() ) ) - { + if (proxies != null) { + for (java.net.Proxy proxy : proxies) { + if (java.net.Proxy.Type.DIRECT.equals(proxy.type())) { break; } - if ( java.net.Proxy.Type.HTTP.equals( proxy.type() ) && isValid( proxy.address() ) ) - { + if (java.net.Proxy.Type.HTTP.equals(proxy.type()) && isValid(proxy.address())) { InetSocketAddress addr = (InetSocketAddress) proxy.address(); - return new Proxy( Proxy.TYPE_HTTP, addr.getHostName(), addr.getPort(), - JreProxyAuthentication.INSTANCE ); + return new Proxy( + Proxy.TYPE_HTTP, addr.getHostName(), addr.getPort(), JreProxyAuthentication.INSTANCE); } } } return null; } - private static boolean isValid( SocketAddress address ) - { - if ( address instanceof InetSocketAddress ) - { + private static boolean isValid(SocketAddress address) { + if (address instanceof InetSocketAddress) { /* * NOTE: On some platforms with java.net.useSystemProxies=true, unconfigured proxies show up as proxy * objects with empty host and port 0. */ InetSocketAddress addr = (InetSocketAddress) address; - if ( addr.getPort() <= 0 ) - { + if (addr.getPort() <= 0) { return false; } - if ( addr.getHostName() == null || addr.getHostName().isEmpty() ) - { + if (addr.getHostName() == null || addr.getHostName().isEmpty()) { return false; } return true; @@ -111,77 +94,63 @@ private static boolean isValid( SocketAddress address ) return false; } - private static final class JreProxyAuthentication - implements Authentication - { + private static final class JreProxyAuthentication implements Authentication { public static final Authentication INSTANCE = new JreProxyAuthentication(); - public void fill( AuthenticationContext context, String key, Map data ) - { - requireNonNull( context, "digest cannot be null" ); + public void fill(AuthenticationContext context, String key, Map data) { + requireNonNull(context, "digest cannot be null"); Proxy proxy = context.getProxy(); - if ( proxy == null ) - { + if (proxy == null) { return; } - if ( !AuthenticationContext.USERNAME.equals( key ) && !AuthenticationContext.PASSWORD.equals( key ) ) - { + if (!AuthenticationContext.USERNAME.equals(key) && !AuthenticationContext.PASSWORD.equals(key)) { return; } - try - { + try { URL url; - try - { - url = new URL( context.getRepository().getUrl() ); - } - catch ( Exception e ) - { + try { + url = new URL(context.getRepository().getUrl()); + } catch (Exception e) { url = null; } - PasswordAuthentication auth = - Authenticator.requestPasswordAuthentication( proxy.getHost(), null, proxy.getPort(), "http", - "Credentials for proxy " + proxy, null, url, - Authenticator.RequestorType.PROXY ); - if ( auth != null ) - { - context.put( AuthenticationContext.USERNAME, auth.getUserName() ); - context.put( AuthenticationContext.PASSWORD, auth.getPassword() ); - } - else - { - context.put( AuthenticationContext.USERNAME, System.getProperty( "http.proxyUser" ) ); - context.put( AuthenticationContext.PASSWORD, System.getProperty( "http.proxyPassword" ) ); + PasswordAuthentication auth = Authenticator.requestPasswordAuthentication( + proxy.getHost(), + null, + proxy.getPort(), + "http", + "Credentials for proxy " + proxy, + null, + url, + Authenticator.RequestorType.PROXY); + if (auth != null) { + context.put(AuthenticationContext.USERNAME, auth.getUserName()); + context.put(AuthenticationContext.PASSWORD, auth.getPassword()); + } else { + context.put(AuthenticationContext.USERNAME, System.getProperty("http.proxyUser")); + context.put(AuthenticationContext.PASSWORD, System.getProperty("http.proxyPassword")); } - } - catch ( SecurityException e ) - { + } catch (SecurityException e) { // oh well, let's hope the proxy can do without auth } } - public void digest( AuthenticationDigest digest ) - { - requireNonNull( digest, "digest cannot be null" ); + public void digest(AuthenticationDigest digest) { + requireNonNull(digest, "digest cannot be null"); // we don't know anything about the JRE's current authenticator, assume the worst (i.e. interactive) - digest.update( UUID.randomUUID().toString() ); + digest.update(UUID.randomUUID().toString()); } @Override - public boolean equals( Object obj ) - { - return this == obj || ( obj != null && getClass().equals( obj.getClass() ) ); + public boolean equals(Object obj) { + return this == obj || (obj != null && getClass().equals(obj.getClass())); } @Override - public int hashCode() - { + public int hashCode() { return getClass().hashCode(); } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SecretAuthentication.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SecretAuthentication.java index bb7c5bc4b..2510fdaf0 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SecretAuthentication.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SecretAuthentication.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,33 +16,30 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import java.util.Arrays; import java.util.Map; import java.util.Objects; -import static java.util.Objects.requireNonNull; - import org.eclipse.aether.repository.Authentication; import org.eclipse.aether.repository.AuthenticationContext; import org.eclipse.aether.repository.AuthenticationDigest; +import static java.util.Objects.requireNonNull; + /** * Authentication block that manages a single authentication key and its secret string value (password, passphrase). * Unlike {@link StringAuthentication}, the string value is kept in an encrypted buffer and only decrypted when needed * to reduce the potential of leaking the secret in a heap dump. */ -final class SecretAuthentication - implements Authentication -{ +final class SecretAuthentication implements Authentication { private static final Object[] KEYS; - static - { + static { KEYS = new Object[16]; - for ( int i = 0; i < KEYS.length; i++ ) - { + for (int i = 0; i < KEYS.length; i++) { KEYS[i] = new Object(); } } @@ -55,117 +50,93 @@ final class SecretAuthentication private final int secretHash; - SecretAuthentication( String key, String value ) - { - this( ( value != null ) ? value.toCharArray() : null, key ); + SecretAuthentication(String key, String value) { + this((value != null) ? value.toCharArray() : null, key); } - SecretAuthentication( String key, char[] value ) - { - this( copy( value ), key ); + SecretAuthentication(String key, char[] value) { + this(copy(value), key); } - private SecretAuthentication( char[] value, String key ) - { - this.key = requireNonNull( key, "authentication key cannot be null" ); - if ( key.length() == 0 ) - { - throw new IllegalArgumentException( "authentication key cannot be empty" ); + private SecretAuthentication(char[] value, String key) { + this.key = requireNonNull(key, "authentication key cannot be null"); + if (key.length() == 0) { + throw new IllegalArgumentException("authentication key cannot be empty"); } - this.secretHash = Arrays.hashCode( value ) ^ KEYS[0].hashCode(); - this.value = xor( value ); + this.secretHash = Arrays.hashCode(value) ^ KEYS[0].hashCode(); + this.value = xor(value); } - private static char[] copy( char[] chars ) - { - return ( chars != null ) ? chars.clone() : null; + private static char[] copy(char[] chars) { + return (chars != null) ? chars.clone() : null; } - @SuppressWarnings( "checkstyle:magicnumber" ) - private char[] xor( char[] chars ) - { - if ( chars != null ) - { - int mask = System.identityHashCode( this ); - for ( int i = 0; i < chars.length; i++ ) - { - int key = KEYS[( i >> 1 ) % KEYS.length].hashCode(); + @SuppressWarnings("checkstyle:magicnumber") + private char[] xor(char[] chars) { + if (chars != null) { + int mask = System.identityHashCode(this); + for (int i = 0; i < chars.length; i++) { + int key = KEYS[(i >> 1) % KEYS.length].hashCode(); key ^= mask; - chars[i] ^= ( ( i & 1 ) == 0 ) ? ( key & 0xFFFF ) : ( key >>> 16 ); + chars[i] ^= ((i & 1) == 0) ? (key & 0xFFFF) : (key >>> 16); } } return chars; } - private static void clear( char[] chars ) - { - if ( chars != null ) - { - for ( int i = 0; i < chars.length; i++ ) - { + private static void clear(char[] chars) { + if (chars != null) { + for (int i = 0; i < chars.length; i++) { chars[i] = '\0'; } } } - public void fill( AuthenticationContext context, String key, Map data ) - { - requireNonNull( context, "context cannot be null" ); - char[] secret = copy( value ); - xor( secret ); - context.put( this.key, secret ); + public void fill(AuthenticationContext context, String key, Map data) { + requireNonNull(context, "context cannot be null"); + char[] secret = copy(value); + xor(secret); + context.put(this.key, secret); // secret will be cleared upon AuthenticationContext.close() } - public void digest( AuthenticationDigest digest ) - { - char[] secret = copy( value ); - try - { - xor( secret ); - digest.update( key ); - digest.update( secret ); - } - finally - { - clear( secret ); + public void digest(AuthenticationDigest digest) { + char[] secret = copy(value); + try { + xor(secret); + digest.update(key); + digest.update(secret); + } finally { + clear(secret); } } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } SecretAuthentication that = (SecretAuthentication) obj; - if ( !Objects.equals( key, that.key ) || secretHash != that.secretHash ) - { + if (!Objects.equals(key, that.key) || secretHash != that.secretHash) { return false; } - char[] secret = copy( value ); - char[] thatSecret = copy( that.value ); - try - { - xor( secret ); - that.xor( thatSecret ); - return Arrays.equals( secret, thatSecret ); - } - finally - { - clear( secret ); - clear( thatSecret ); + char[] secret = copy(value); + char[] thatSecret = copy(that.value); + try { + xor(secret); + that.xor(thatSecret); + return Arrays.equals(secret, thatSecret); + } finally { + clear(secret); + clear(thatSecret); } } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + key.hashCode(); hash = hash * 31 + secretHash; @@ -173,9 +144,7 @@ public int hashCode() } @Override - public String toString() - { - return key + "=" + ( ( value != null ) ? "***" : "null" ); + public String toString() { + return key + "=" + ((value != null) ? "***" : "null"); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SimpleArtifactDescriptorPolicy.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SimpleArtifactDescriptorPolicy.java index 3f6831d34..2007c37a5 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SimpleArtifactDescriptorPolicy.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SimpleArtifactDescriptorPolicy.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.resolution.ArtifactDescriptorPolicy; @@ -28,38 +27,32 @@ /** * An artifact descriptor error policy that allows to control error handling at a global level. */ -public final class SimpleArtifactDescriptorPolicy - implements ArtifactDescriptorPolicy -{ +public final class SimpleArtifactDescriptorPolicy implements ArtifactDescriptorPolicy { private final int policy; /** * Creates a new error policy with the specified behavior. - * + * * @param ignoreMissing {@code true} to ignore missing descriptors, {@code false} to fail resolution. * @param ignoreInvalid {@code true} to ignore invalid descriptors, {@code false} to fail resolution. */ - public SimpleArtifactDescriptorPolicy( boolean ignoreMissing, boolean ignoreInvalid ) - { - this( ( ignoreMissing ? IGNORE_MISSING : 0 ) | ( ignoreInvalid ? IGNORE_INVALID : 0 ) ); + public SimpleArtifactDescriptorPolicy(boolean ignoreMissing, boolean ignoreInvalid) { + this((ignoreMissing ? IGNORE_MISSING : 0) | (ignoreInvalid ? IGNORE_INVALID : 0)); } /** * Creates a new error policy with the specified bit mask. - * + * * @param policy The bit mask describing the policy. */ - public SimpleArtifactDescriptorPolicy( int policy ) - { + public SimpleArtifactDescriptorPolicy(int policy) { this.policy = policy; } - public int getPolicy( RepositorySystemSession session, ArtifactDescriptorPolicyRequest request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); + public int getPolicy(RepositorySystemSession session, ArtifactDescriptorPolicyRequest request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); return policy; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SimpleResolutionErrorPolicy.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SimpleResolutionErrorPolicy.java index d56266ee7..52681347c 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SimpleResolutionErrorPolicy.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/SimpleResolutionErrorPolicy.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; @@ -30,9 +29,7 @@ /** * A resolution error policy that allows to control caching for artifacts and metadata at a global level. */ -public final class SimpleResolutionErrorPolicy - implements ResolutionErrorPolicy -{ +public final class SimpleResolutionErrorPolicy implements ResolutionErrorPolicy { private final int artifactPolicy; @@ -40,49 +37,43 @@ public final class SimpleResolutionErrorPolicy /** * Creates a new error policy with the specified behavior for both artifacts and metadata. - * + * * @param cacheNotFound {@code true} to enable caching of missing items, {@code false} to disable it. * @param cacheTransferErrors {@code true} to enable chaching of transfer errors, {@code false} to disable it. */ - public SimpleResolutionErrorPolicy( boolean cacheNotFound, boolean cacheTransferErrors ) - { - this( ( cacheNotFound ? CACHE_NOT_FOUND : 0 ) | ( cacheTransferErrors ? CACHE_TRANSFER_ERROR : 0 ) ); + public SimpleResolutionErrorPolicy(boolean cacheNotFound, boolean cacheTransferErrors) { + this((cacheNotFound ? CACHE_NOT_FOUND : 0) | (cacheTransferErrors ? CACHE_TRANSFER_ERROR : 0)); } /** * Creates a new error policy with the specified bit mask for both artifacts and metadata. - * + * * @param policy The bit mask describing the policy for artifacts and metadata. */ - public SimpleResolutionErrorPolicy( int policy ) - { - this( policy, policy ); + public SimpleResolutionErrorPolicy(int policy) { + this(policy, policy); } /** * Creates a new error policy with the specified bit masks for artifacts and metadata. - * + * * @param artifactPolicy The bit mask describing the policy for artifacts. * @param metadataPolicy The bit mask describing the policy for metadata. */ - public SimpleResolutionErrorPolicy( int artifactPolicy, int metadataPolicy ) - { + public SimpleResolutionErrorPolicy(int artifactPolicy, int metadataPolicy) { this.artifactPolicy = artifactPolicy; this.metadataPolicy = metadataPolicy; } - public int getArtifactPolicy( RepositorySystemSession session, ResolutionErrorPolicyRequest request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); + public int getArtifactPolicy(RepositorySystemSession session, ResolutionErrorPolicyRequest request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); return artifactPolicy; } - public int getMetadataPolicy( RepositorySystemSession session, ResolutionErrorPolicyRequest request ) - { - requireNonNull( session, "session cannot be null" ); - requireNonNull( request, "request cannot be null" ); + public int getMetadataPolicy(RepositorySystemSession session, ResolutionErrorPolicyRequest request) { + requireNonNull(session, "session cannot be null"); + requireNonNull(request, "request cannot be null"); return metadataPolicy; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/StringAuthentication.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/StringAuthentication.java index 74edfb866..69d0f4553 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/StringAuthentication.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/StringAuthentication.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,78 +16,66 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; import java.util.Map; import java.util.Objects; -import static java.util.Objects.requireNonNull; - import org.eclipse.aether.repository.Authentication; import org.eclipse.aether.repository.AuthenticationContext; import org.eclipse.aether.repository.AuthenticationDigest; +import static java.util.Objects.requireNonNull; + /** * Authentication block that manages a single authentication key and its string value. */ -final class StringAuthentication - implements Authentication -{ +final class StringAuthentication implements Authentication { private final String key; private final String value; - StringAuthentication( String key, String value ) - { - this.key = requireNonNull( key, "authentication key cannot be null" ); - if ( key.length() == 0 ) - { - throw new IllegalArgumentException( "authentication key cannot be empty" ); + StringAuthentication(String key, String value) { + this.key = requireNonNull(key, "authentication key cannot be null"); + if (key.length() == 0) { + throw new IllegalArgumentException("authentication key cannot be empty"); } this.value = value; } - public void fill( AuthenticationContext context, String key, Map data ) - { - requireNonNull( context, "context cannot be null" ); - context.put( this.key, value ); + public void fill(AuthenticationContext context, String key, Map data) { + requireNonNull(context, "context cannot be null"); + context.put(this.key, value); } - public void digest( AuthenticationDigest digest ) - { - requireNonNull( digest, "digest cannot be null" ); - digest.update( key, value ); + public void digest(AuthenticationDigest digest) { + requireNonNull(digest, "digest cannot be null"); + digest.update(key, value); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } StringAuthentication that = (StringAuthentication) obj; - return Objects.equals( key, that.key ) - && Objects.equals( value, that.value ); + return Objects.equals(key, that.key) && Objects.equals(value, that.value); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; hash = hash * 31 + key.hashCode(); - hash = hash * 31 + ( ( value != null ) ? value.hashCode() : 0 ); + hash = hash * 31 + ((value != null) ? value.hashCode() : 0); return hash; } @Override - public String toString() - { + public String toString() { return key + "=" + value; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/package-info.java index 1c0a194a7..84b782306 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/repository/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,4 +21,3 @@ * Ready-to-use selectors for authentication, proxies and mirrors and a few other repository related utilities. */ package org.eclipse.aether.util.repository; - diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersion.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersion.java index b440dbc97..fc90ae270 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersion.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersion.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.version; import java.math.BigInteger; import java.util.ArrayList; @@ -35,9 +34,7 @@ * A generic version, that is a version that accepts any input string and tries to apply common sense sorting. See * {@link GenericVersionScheme} for details. */ -final class GenericVersion - implements Version -{ +final class GenericVersion implements Version { private final String version; @@ -47,13 +44,12 @@ final class GenericVersion /** * Creates a generic version from the specified string. - * + * * @param version The version string, must not be {@code null}. */ - GenericVersion( String version ) - { - this.version = requireNonNull( version, "version cannot be null" ); - items = parse( version ); + GenericVersion(String version) { + this.version = requireNonNull(version, "version cannot be null"); + items = parse(version); hash = items.hashCode(); } @@ -62,8 +58,7 @@ final class GenericVersion * * @since 1.9.5 */ - public String asString() - { + public String asString() { return version; } @@ -72,89 +67,69 @@ public String asString() * * @since 1.9.5 */ - public List asItems() - { + public List asItems() { return items; } - private static List parse( String version ) - { + private static List parse(String version) { List items = new ArrayList<>(); - for ( Tokenizer tokenizer = new Tokenizer( version ); tokenizer.next(); ) - { + for (Tokenizer tokenizer = new Tokenizer(version); tokenizer.next(); ) { Item item = tokenizer.toItem(); - items.add( item ); + items.add(item); } - trimPadding( items ); + trimPadding(items); - return Collections.unmodifiableList( items ); + return Collections.unmodifiableList(items); } - private static void trimPadding( List items ) - { + private static void trimPadding(List items) { Boolean number = null; int end = items.size() - 1; - for ( int i = end; i > 0; i-- ) - { - Item item = items.get( i ); - if ( !Boolean.valueOf( item.isNumber() ).equals( number ) ) - { + for (int i = end; i > 0; i--) { + Item item = items.get(i); + if (!Boolean.valueOf(item.isNumber()).equals(number)) { end = i; number = item.isNumber(); } - if ( end == i && ( i == items.size() - 1 || items.get( i - 1 ).isNumber() == item.isNumber() ) - && item.compareTo( null ) == 0 ) - { - items.remove( i ); + if (end == i + && (i == items.size() - 1 || items.get(i - 1).isNumber() == item.isNumber()) + && item.compareTo(null) == 0) { + items.remove(i); end--; } } } @Override - public int compareTo( Version obj ) - { + public int compareTo(Version obj) { final List these = items; - final List those = ( (GenericVersion) obj ).items; + final List those = ((GenericVersion) obj).items; boolean number = true; - for ( int index = 0;; index++ ) - { - if ( index >= these.size() && index >= those.size() ) - { + for (int index = 0; ; index++) { + if (index >= these.size() && index >= those.size()) { return 0; - } - else if ( index >= these.size() ) - { - return -comparePadding( those, index, null ); - } - else if ( index >= those.size() ) - { - return comparePadding( these, index, null ); + } else if (index >= these.size()) { + return -comparePadding(those, index, null); + } else if (index >= those.size()) { + return comparePadding(these, index, null); } - Item thisItem = these.get( index ); - Item thatItem = those.get( index ); + Item thisItem = these.get(index); + Item thatItem = those.get(index); - if ( thisItem.isNumber() != thatItem.isNumber() ) - { - if ( number == thisItem.isNumber() ) - { - return comparePadding( these, index, number ); + if (thisItem.isNumber() != thatItem.isNumber()) { + if (number == thisItem.isNumber()) { + return comparePadding(these, index, number); + } else { + return -comparePadding(those, index, number); } - else - { - return -comparePadding( those, index, number ); - } - } - else - { - int rel = thisItem.compareTo( thatItem ); - if ( rel != 0 ) - { + } else { + int rel = thisItem.compareTo(thatItem); + if (rel != 0) { return rel; } number = thisItem.isNumber(); @@ -162,20 +137,16 @@ else if ( index >= those.size() ) } } - private static int comparePadding( List items, int index, Boolean number ) - { + private static int comparePadding(List items, int index, Boolean number) { int rel = 0; - for ( int i = index; i < items.size(); i++ ) - { - Item item = items.get( i ); - if ( number != null && number != item.isNumber() ) - { + for (int i = index; i < items.size(); i++) { + Item item = items.get(i); + if (number != null && number != item.isNumber()) { // do not stop here, but continue, skipping non-number members continue; } - rel = item.compareTo( null ); - if ( rel != 0 ) - { + rel = item.compareTo(null); + if (rel != 0) { break; } } @@ -183,25 +154,21 @@ private static int comparePadding( List items, int index, Boolean number ) } @Override - public boolean equals( Object obj ) - { - return ( obj instanceof GenericVersion ) && compareTo( (GenericVersion) obj ) == 0; + public boolean equals(Object obj) { + return (obj instanceof GenericVersion) && compareTo((GenericVersion) obj) == 0; } @Override - public int hashCode() - { + public int hashCode() { return hash; } @Override - public String toString() - { + public String toString() { return version; } - static final class Tokenizer - { + static final class Tokenizer { private static final Integer QUALIFIER_ALPHA = -5; @@ -211,20 +178,19 @@ static final class Tokenizer private static final Map QUALIFIERS; - static - { - QUALIFIERS = new TreeMap<>( String.CASE_INSENSITIVE_ORDER ); - QUALIFIERS.put( "alpha", QUALIFIER_ALPHA ); - QUALIFIERS.put( "beta", QUALIFIER_BETA ); - QUALIFIERS.put( "milestone", QUALIFIER_MILESTONE ); - QUALIFIERS.put( "cr", -2 ); - QUALIFIERS.put( "rc", -2 ); - QUALIFIERS.put( "snapshot", -1 ); - QUALIFIERS.put( "ga", 0 ); - QUALIFIERS.put( "final", 0 ); - QUALIFIERS.put( "release", 0 ); - QUALIFIERS.put( "", 0 ); - QUALIFIERS.put( "sp", 1 ); + static { + QUALIFIERS = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + QUALIFIERS.put("alpha", QUALIFIER_ALPHA); + QUALIFIERS.put("beta", QUALIFIER_BETA); + QUALIFIERS.put("milestone", QUALIFIER_MILESTONE); + QUALIFIERS.put("cr", -2); + QUALIFIERS.put("rc", -2); + QUALIFIERS.put("snapshot", -1); + QUALIFIERS.put("ga", 0); + QUALIFIERS.put("final", 0); + QUALIFIERS.put("release", 0); + QUALIFIERS.put("", 0); + QUALIFIERS.put("sp", 1); } private final String version; @@ -239,16 +205,13 @@ static final class Tokenizer private boolean terminatedByNumber; - Tokenizer( String version ) - { - this.version = ( version.length() > 0 ) ? version : "0"; + Tokenizer(String version) { + this.version = (version.length() > 0) ? version : "0"; this.versionLength = this.version.length(); } - public boolean next() - { - if ( index >= versionLength ) - { + public boolean next() { + if (index >= versionLength) { return false; } @@ -258,54 +221,40 @@ public boolean next() int end = versionLength; terminatedByNumber = false; - for ( ; index < versionLength; index++ ) - { - char c = version.charAt( index ); + for (; index < versionLength; index++) { + char c = version.charAt(index); - if ( c == '.' || c == '-' || c == '_' ) - { + if (c == '.' || c == '-' || c == '_') { end = index; index++; break; - } - else - { - int digit = Character.digit( c, 10 ); - if ( digit >= 0 ) - { - if ( state == -1 ) - { + } else { + int digit = Character.digit(c, 10); + if (digit >= 0) { + if (state == -1) { end = index; terminatedByNumber = true; break; } - if ( state == 0 ) - { + if (state == 0) { // normalize numbers and strip leading zeros (prereq for Integer/BigInteger handling) start++; } - state = ( state > 0 || digit > 0 ) ? 1 : 0; - } - else - { - if ( state >= 0 ) - { + state = (state > 0 || digit > 0) ? 1 : 0; + } else { + if (state >= 0) { end = index; break; } state = -1; } } - } - if ( end - start > 0 ) - { - token = version.substring( start, end ); + if (end - start > 0) { + token = version.substring(start, end); number = state >= 0; - } - else - { + } else { token = "0"; number = true; } @@ -314,76 +263,54 @@ public boolean next() } @Override - public String toString() - { - return String.valueOf( token ); + public String toString() { + return String.valueOf(token); } - public Item toItem() - { - if ( number ) - { - try - { - if ( token.length() < 10 ) - { - return new Item( Item.KIND_INT, Integer.parseInt( token ) ); - } - else - { - return new Item( Item.KIND_BIGINT, new BigInteger( token ) ); + public Item toItem() { + if (number) { + try { + if (token.length() < 10) { + return new Item(Item.KIND_INT, Integer.parseInt(token)); + } else { + return new Item(Item.KIND_BIGINT, new BigInteger(token)); } + } catch (NumberFormatException e) { + throw new IllegalStateException(e); } - catch ( NumberFormatException e ) - { - throw new IllegalStateException( e ); - } - } - else - { - if ( index >= version.length() ) - { - if ( "min".equalsIgnoreCase( token ) ) - { + } else { + if (index >= version.length()) { + if ("min".equalsIgnoreCase(token)) { return Item.MIN; - } - else if ( "max".equalsIgnoreCase( token ) ) - { + } else if ("max".equalsIgnoreCase(token)) { return Item.MAX; } } - if ( terminatedByNumber && token.length() == 1 ) - { - switch ( token.charAt( 0 ) ) - { + if (terminatedByNumber && token.length() == 1) { + switch (token.charAt(0)) { case 'a': case 'A': - return new Item( Item.KIND_QUALIFIER, QUALIFIER_ALPHA ); + return new Item(Item.KIND_QUALIFIER, QUALIFIER_ALPHA); case 'b': case 'B': - return new Item( Item.KIND_QUALIFIER, QUALIFIER_BETA ); + return new Item(Item.KIND_QUALIFIER, QUALIFIER_BETA); case 'm': case 'M': - return new Item( Item.KIND_QUALIFIER, QUALIFIER_MILESTONE ); + return new Item(Item.KIND_QUALIFIER, QUALIFIER_MILESTONE); default: } } - Integer qualifier = QUALIFIERS.get( token ); - if ( qualifier != null ) - { - return new Item( Item.KIND_QUALIFIER, qualifier ); - } - else - { - return new Item( Item.KIND_STRING, token.toLowerCase( Locale.ENGLISH ) ); + Integer qualifier = QUALIFIERS.get(token); + if (qualifier != null) { + return new Item(Item.KIND_QUALIFIER, qualifier); + } else { + return new Item(Item.KIND_STRING, token.toLowerCase(Locale.ENGLISH)); } } } - } - static final class Item - { + static final class Item { static final int KIND_MAX = 8; @@ -397,33 +324,28 @@ static final class Item static final int KIND_MIN = 0; - static final Item MAX = new Item( KIND_MAX, "max" ); + static final Item MAX = new Item(KIND_MAX, "max"); - static final Item MIN = new Item( KIND_MIN, "min" ); + static final Item MIN = new Item(KIND_MIN, "min"); private final int kind; private final Object value; - Item( int kind, Object value ) - { + Item(int kind, Object value) { this.kind = kind; this.value = value; } - public boolean isNumber() - { - return ( kind & KIND_QUALIFIER ) == 0; // i.e. kind != string/qualifier + public boolean isNumber() { + return (kind & KIND_QUALIFIER) == 0; // i.e. kind != string/qualifier } - public int compareTo( Item that ) - { + public int compareTo(Item that) { int rel; - if ( that == null ) - { + if (that == null) { // null in this context denotes the pad item (0 or "ga") - switch ( kind ) - { + switch (kind) { case KIND_MIN: rel = -1; break; @@ -437,31 +359,27 @@ public int compareTo( Item that ) rel = (Integer) value; break; default: - throw new IllegalStateException( "unknown version item kind " + kind ); + throw new IllegalStateException("unknown version item kind " + kind); } - } - else - { + } else { rel = kind - that.kind; - if ( rel == 0 ) - { - switch ( kind ) - { + if (rel == 0) { + switch (kind) { case KIND_MAX: case KIND_MIN: break; case KIND_BIGINT: - rel = ( (BigInteger) value ).compareTo( (BigInteger) that.value ); + rel = ((BigInteger) value).compareTo((BigInteger) that.value); break; case KIND_INT: case KIND_QUALIFIER: - rel = ( (Integer) value ).compareTo( (Integer) that.value ); + rel = ((Integer) value).compareTo((Integer) that.value); break; case KIND_STRING: - rel = ( (String) value ).compareToIgnoreCase( (String) that.value ); + rel = ((String) value).compareToIgnoreCase((String) that.value); break; default: - throw new IllegalStateException( "unknown version item kind " + kind ); + throw new IllegalStateException("unknown version item kind " + kind); } } } @@ -469,23 +387,18 @@ public int compareTo( Item that ) } @Override - public boolean equals( Object obj ) - { - return ( obj instanceof Item ) && compareTo( (Item) obj ) == 0; + public boolean equals(Object obj) { + return (obj instanceof Item) && compareTo((Item) obj) == 0; } @Override - public int hashCode() - { + public int hashCode() { return value.hashCode() + kind * 31; } @Override - public String toString() - { - return String.valueOf( value ); + public String toString() { + return String.valueOf(value); } - } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionConstraint.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionConstraint.java index f4b6f570c..9199e071d 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionConstraint.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionConstraint.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,21 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.version; + +import java.util.Objects; import org.eclipse.aether.version.Version; import org.eclipse.aether.version.VersionConstraint; import org.eclipse.aether.version.VersionRange; -import java.util.Objects; - import static java.util.Objects.requireNonNull; /** * A constraint on versions for a dependency. */ -final class GenericVersionConstraint - implements VersionConstraint -{ +final class GenericVersionConstraint implements VersionConstraint { private final VersionRange range; @@ -43,9 +40,8 @@ final class GenericVersionConstraint * * @param range The version range, must not be {@code null}. */ - GenericVersionConstraint( VersionRange range ) - { - this.range = requireNonNull( range, "version range cannot be null" ); + GenericVersionConstraint(VersionRange range) { + this.range = requireNonNull(range, "version range cannot be null"); this.version = null; } @@ -54,72 +50,58 @@ final class GenericVersionConstraint * * @param version The version, must not be {@code null}. */ - GenericVersionConstraint( Version version ) - { - this.version = requireNonNull( version, "version cannot be null" ); + GenericVersionConstraint(Version version) { + this.version = requireNonNull(version, "version cannot be null"); this.range = null; } @Override - public VersionRange getRange() - { + public VersionRange getRange() { return range; } @Override - public Version getVersion() - { + public Version getVersion() { return version; } @Override - public boolean containsVersion( Version version ) - { - if ( range == null ) - { - return version.equals( this.version ); - } - else - { - return range.containsVersion( version ); + public boolean containsVersion(Version version) { + if (range == null) { + return version.equals(this.version); + } else { + return range.containsVersion(version); } } @Override - public String toString() - { - return String.valueOf( ( range == null ) ? version : range ); + public String toString() { + return String.valueOf((range == null) ? version : range); } @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + if (obj == null || !getClass().equals(obj.getClass())) { return false; } GenericVersionConstraint that = (GenericVersionConstraint) obj; - return Objects.equals( range, that.range ) && Objects.equals( version, that.getVersion() ); + return Objects.equals(range, that.range) && Objects.equals(version, that.getVersion()); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + hash( getRange() ); - hash = hash * 31 + hash( getVersion() ); + hash = hash * 31 + hash(getRange()); + hash = hash * 31 + hash(getVersion()); return hash; } - private static int hash( Object obj ) - { + private static int hash(Object obj) { return obj != null ? obj.hashCode() : 0; } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionRange.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionRange.java index b300d3738..fe8bf6e10 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionRange.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionRange.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,21 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.version; + +import java.util.Objects; import org.eclipse.aether.version.InvalidVersionSpecificationException; import org.eclipse.aether.version.Version; import org.eclipse.aether.version.VersionRange; -import java.util.Objects; - import static java.util.Objects.requireNonNull; /** * A version range inspired by mathematical range syntax. For example, "[1.0,2.0)", "[1.0,)" or "[1.0]". */ -final class GenericVersionRange - implements VersionRange -{ +final class GenericVersionRange implements VersionRange { private final Bound lowerBound; @@ -40,144 +37,113 @@ final class GenericVersionRange /** * Creates a version range from the specified range specification. - * + * * @param range The range specification to parse, must not be {@code null}. * @throws InvalidVersionSpecificationException If the range could not be parsed. */ - GenericVersionRange( String range ) - throws InvalidVersionSpecificationException - { - String process = requireNonNull( range, "version range cannot be null" ); + GenericVersionRange(String range) throws InvalidVersionSpecificationException { + String process = requireNonNull(range, "version range cannot be null"); boolean lowerBoundInclusive, upperBoundInclusive; Version lowerBound, upperBound; - if ( range.startsWith( "[" ) ) - { + if (range.startsWith("[")) { lowerBoundInclusive = true; - } - else if ( range.startsWith( "(" ) ) - { + } else if (range.startsWith("(")) { lowerBoundInclusive = false; - } - else - { - throw new InvalidVersionSpecificationException( range, "Invalid version range " + range - + ", a range must start with either [ or (" ); + } else { + throw new InvalidVersionSpecificationException( + range, "Invalid version range " + range + ", a range must start with either [ or ("); } - if ( range.endsWith( "]" ) ) - { + if (range.endsWith("]")) { upperBoundInclusive = true; - } - else if ( range.endsWith( ")" ) ) - { + } else if (range.endsWith(")")) { upperBoundInclusive = false; - } - else - { - throw new InvalidVersionSpecificationException( range, "Invalid version range " + range - + ", a range must end with either [ or (" ); + } else { + throw new InvalidVersionSpecificationException( + range, "Invalid version range " + range + ", a range must end with either [ or ("); } - process = process.substring( 1, process.length() - 1 ); + process = process.substring(1, process.length() - 1); - int index = process.indexOf( "," ); + int index = process.indexOf(","); - if ( index < 0 ) - { - if ( !lowerBoundInclusive || !upperBoundInclusive ) - { - throw new InvalidVersionSpecificationException( range, "Invalid version range " + range - + ", single version must be surrounded by []" ); + if (index < 0) { + if (!lowerBoundInclusive || !upperBoundInclusive) { + throw new InvalidVersionSpecificationException( + range, "Invalid version range " + range + ", single version must be surrounded by []"); } String version = process.trim(); - if ( version.endsWith( ".*" ) ) - { - String prefix = version.substring( 0, version.length() - 1 ); - lowerBound = parse( prefix + "min" ); - upperBound = parse( prefix + "max" ); - } - else - { - lowerBound = parse( version ); + if (version.endsWith(".*")) { + String prefix = version.substring(0, version.length() - 1); + lowerBound = parse(prefix + "min"); + upperBound = parse(prefix + "max"); + } else { + lowerBound = parse(version); upperBound = lowerBound; } - } - else - { - String parsedLowerBound = process.substring( 0, index ).trim(); - String parsedUpperBound = process.substring( index + 1 ).trim(); + } else { + String parsedLowerBound = process.substring(0, index).trim(); + String parsedUpperBound = process.substring(index + 1).trim(); // more than two bounds, e.g. (1,2,3) - if ( parsedUpperBound.contains( "," ) ) - { - throw new InvalidVersionSpecificationException( range, "Invalid version range " + range - + ", bounds may not contain additional ','" ); + if (parsedUpperBound.contains(",")) { + throw new InvalidVersionSpecificationException( + range, "Invalid version range " + range + ", bounds may not contain additional ','"); } - lowerBound = parsedLowerBound.length() > 0 ? parse( parsedLowerBound ) : null; - upperBound = parsedUpperBound.length() > 0 ? parse( parsedUpperBound ) : null; + lowerBound = parsedLowerBound.length() > 0 ? parse(parsedLowerBound) : null; + upperBound = parsedUpperBound.length() > 0 ? parse(parsedUpperBound) : null; - if ( upperBound != null && lowerBound != null ) - { - if ( upperBound.compareTo( lowerBound ) < 0 ) - { - throw new InvalidVersionSpecificationException( range, "Invalid version range " + range - + ", lower bound must not be greater than upper bound" ); + if (upperBound != null && lowerBound != null) { + if (upperBound.compareTo(lowerBound) < 0) { + throw new InvalidVersionSpecificationException( + range, + "Invalid version range " + range + ", lower bound must not be greater than upper bound"); } } } - this.lowerBound = ( lowerBound != null ) ? new Bound( lowerBound, lowerBoundInclusive ) : null; - this.upperBound = ( upperBound != null ) ? new Bound( upperBound, upperBoundInclusive ) : null; + this.lowerBound = (lowerBound != null) ? new Bound(lowerBound, lowerBoundInclusive) : null; + this.upperBound = (upperBound != null) ? new Bound(upperBound, upperBoundInclusive) : null; } - private Version parse( String version ) - { - return new GenericVersion( version ); + private Version parse(String version) { + return new GenericVersion(version); } @Override - public Bound getLowerBound() - { + public Bound getLowerBound() { return lowerBound; } @Override - public Bound getUpperBound() - { + public Bound getUpperBound() { return upperBound; } @Override - public boolean containsVersion( Version version ) - { - if ( lowerBound != null ) - { - int comparison = lowerBound.getVersion().compareTo( version ); - - if ( comparison == 0 && !lowerBound.isInclusive() ) - { + public boolean containsVersion(Version version) { + if (lowerBound != null) { + int comparison = lowerBound.getVersion().compareTo(version); + + if (comparison == 0 && !lowerBound.isInclusive()) { return false; } - if ( comparison > 0 ) - { + if (comparison > 0) { return false; } } - if ( upperBound != null ) - { - int comparison = upperBound.getVersion().compareTo( version ); + if (upperBound != null) { + int comparison = upperBound.getVersion().compareTo(version); - if ( comparison == 0 && !upperBound.isInclusive() ) - { + if (comparison == 0 && !upperBound.isInclusive()) { return false; } - if ( comparison < 0 ) - { + if (comparison < 0) { return false; } } @@ -186,61 +152,46 @@ public boolean containsVersion( Version version ) } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + } else if (obj == null || !getClass().equals(obj.getClass())) { return false; } GenericVersionRange that = (GenericVersionRange) obj; - return Objects.equals( upperBound, that.upperBound ) - && Objects.equals( lowerBound, that.lowerBound ); + return Objects.equals(upperBound, that.upperBound) && Objects.equals(lowerBound, that.lowerBound); } @Override - public int hashCode() - { + public int hashCode() { int hash = 17; - hash = hash * 31 + hash( upperBound ); - hash = hash * 31 + hash( lowerBound ); + hash = hash * 31 + hash(upperBound); + hash = hash * 31 + hash(lowerBound); return hash; } - private static int hash( Object obj ) - { + private static int hash(Object obj) { return obj != null ? obj.hashCode() : 0; } @Override - public String toString() - { - StringBuilder buffer = new StringBuilder( 64 ); - if ( lowerBound != null ) - { - buffer.append( lowerBound.isInclusive() ? '[' : '(' ); - buffer.append( lowerBound.getVersion() ); - } - else - { - buffer.append( '(' ); - } - buffer.append( ',' ); - if ( upperBound != null ) - { - buffer.append( upperBound.getVersion() ); - buffer.append( upperBound.isInclusive() ? ']' : ')' ); - } - else - { - buffer.append( ')' ); + public String toString() { + StringBuilder buffer = new StringBuilder(64); + if (lowerBound != null) { + buffer.append(lowerBound.isInclusive() ? '[' : '('); + buffer.append(lowerBound.getVersion()); + } else { + buffer.append('('); + } + buffer.append(','); + if (upperBound != null) { + buffer.append(upperBound.getVersion()); + buffer.append(upperBound.isInclusive() ? ']' : ')'); + } else { + buffer.append(')'); } return buffer.toString(); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionScheme.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionScheme.java index 3f6e13b57..3c9f6d93d 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionScheme.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/GenericVersionScheme.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.version; import java.util.ArrayList; import java.util.Collection; @@ -52,99 +51,79 @@ * respectively, until the kind mismatch is resolved, e.g. "1-alpha" = "1.0.0-alpha" < "1.0.1-ga" = "1.0.1". *

    */ -public final class GenericVersionScheme - implements VersionScheme -{ +public final class GenericVersionScheme implements VersionScheme { /** * Creates a new instance of the version scheme for parsing versions. */ - public GenericVersionScheme() - { - } + public GenericVersionScheme() {} @Override - public GenericVersion parseVersion( final String version ) - throws InvalidVersionSpecificationException - { - return new GenericVersion( version ); + public GenericVersion parseVersion(final String version) throws InvalidVersionSpecificationException { + return new GenericVersion(version); } @Override - public GenericVersionRange parseVersionRange( final String range ) - throws InvalidVersionSpecificationException - { - return new GenericVersionRange( range ); + public GenericVersionRange parseVersionRange(final String range) throws InvalidVersionSpecificationException { + return new GenericVersionRange(range); } @Override - public GenericVersionConstraint parseVersionConstraint( final String constraint ) - throws InvalidVersionSpecificationException - { - String process = requireNonNull( constraint, "constraint cannot be null" ); + public GenericVersionConstraint parseVersionConstraint(final String constraint) + throws InvalidVersionSpecificationException { + String process = requireNonNull(constraint, "constraint cannot be null"); Collection ranges = new ArrayList<>(); - while ( process.startsWith( "[" ) || process.startsWith( "(" ) ) - { - int index1 = process.indexOf( ')' ); - int index2 = process.indexOf( ']' ); + while (process.startsWith("[") || process.startsWith("(")) { + int index1 = process.indexOf(')'); + int index2 = process.indexOf(']'); int index = index2; - if ( index2 < 0 || ( index1 >= 0 && index1 < index2 ) ) - { + if (index2 < 0 || (index1 >= 0 && index1 < index2)) { index = index1; } - if ( index < 0 ) - { - throw new InvalidVersionSpecificationException( constraint, "Unbounded version range " + constraint ); + if (index < 0) { + throw new InvalidVersionSpecificationException(constraint, "Unbounded version range " + constraint); } - GenericVersionRange range = parseVersionRange( process.substring( 0, index + 1 ) ); - ranges.add( range ); + GenericVersionRange range = parseVersionRange(process.substring(0, index + 1)); + ranges.add(range); - process = process.substring( index + 1 ).trim(); + process = process.substring(index + 1).trim(); - if ( process.startsWith( "," ) ) - { - process = process.substring( 1 ).trim(); + if (process.startsWith(",")) { + process = process.substring(1).trim(); } } - if ( process.length() > 0 && !ranges.isEmpty() ) - { - throw new InvalidVersionSpecificationException( constraint, "Invalid version range " + constraint - + ", expected [ or ( but got " + process ); + if (process.length() > 0 && !ranges.isEmpty()) { + throw new InvalidVersionSpecificationException( + constraint, "Invalid version range " + constraint + ", expected [ or ( but got " + process); } GenericVersionConstraint result; - if ( ranges.isEmpty() ) - { - result = new GenericVersionConstraint( parseVersion( constraint ) ); - } - else - { - result = new GenericVersionConstraint( UnionVersionRange.from( ranges ) ); + if (ranges.isEmpty()) { + result = new GenericVersionConstraint(parseVersion(constraint)); + } else { + result = new GenericVersionConstraint(UnionVersionRange.from(ranges)); } return result; } @Override - public boolean equals( final Object obj ) - { - if ( this == obj ) - { + public boolean equals(final Object obj) { + if (this == obj) { return true; } - return obj != null && getClass().equals( obj.getClass() ); + return obj != null && getClass().equals(obj.getClass()); } @Override - public int hashCode() - { + public int hashCode() { return getClass().hashCode(); } @@ -158,32 +137,27 @@ public int hashCode() * command to command line, output is very similar to that of ComparableVersion on purpose. */ // CHECKSTYLE_ON: LineLength - public static void main( String... args ) - { - System.out.println( "Display parameters as parsed by Maven Resolver (in canonical form and as a list of tokens)" - + " and comparison result:" ); - if ( args.length == 0 ) - { + public static void main(String... args) { + System.out.println("Display parameters as parsed by Maven Resolver (in canonical form and as a list of tokens)" + + " and comparison result:"); + if (args.length == 0) { return; } GenericVersion prev = null; int i = 1; - for ( String version : args ) - { - GenericVersion c = new GenericVersion( version ); - - if ( prev != null ) - { - int compare = prev.compareTo( c ); - System.out.println( " " + prev + ' ' + ( ( compare == 0 ) ? "==" : ( ( compare < 0 ) ? "<" : ">" ) ) - + ' ' + version ); + for (String version : args) { + GenericVersion c = new GenericVersion(version); + + if (prev != null) { + int compare = prev.compareTo(c); + System.out.println( + " " + prev + ' ' + ((compare == 0) ? "==" : ((compare < 0) ? "<" : ">")) + ' ' + version); } - System.out.println( ( i++ ) + ". " + version + " -> " + c.asString() + "; tokens: " + c.asItems() ); + System.out.println((i++) + ". " + version + " -> " + c.asString() + "; tokens: " + c.asItems()); prev = c; } } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/UnionVersionRange.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/UnionVersionRange.java index 45ed90a8e..27356d7df 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/UnionVersionRange.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/UnionVersionRange.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.version; import java.util.Arrays; import java.util.Collection; @@ -32,9 +31,7 @@ /** * A union of version ranges. */ -public final class UnionVersionRange - implements VersionRange -{ +public final class UnionVersionRange implements VersionRange { private final Set ranges; @@ -47,13 +44,11 @@ public final class UnionVersionRange * * @param ranges The ranges, may be empty array or even {@code null}. */ - public static VersionRange from( VersionRange... ranges ) - { - if ( ranges == null || ranges.length == 0 ) - { - return from( Collections.emptySet() ); + public static VersionRange from(VersionRange... ranges) { + if (ranges == null || ranges.length == 0) { + return from(Collections.emptySet()); } - return from( Arrays.asList( ranges ) ); + return from(Arrays.asList(ranges)); } /** @@ -61,65 +56,45 @@ public static VersionRange from( VersionRange... ranges ) * * @param ranges The ranges, may be empty collection or even {@code null}. */ - public static VersionRange from( Collection ranges ) - { - if ( ranges != null && ranges.size() == 1 ) - { + public static VersionRange from(Collection ranges) { + if (ranges != null && ranges.size() == 1) { return ranges.iterator().next(); } - return new UnionVersionRange( ranges ); + return new UnionVersionRange(ranges); } - private UnionVersionRange( Collection ranges ) - { - if ( ranges == null || ranges.isEmpty() ) - { + private UnionVersionRange(Collection ranges) { + if (ranges == null || ranges.isEmpty()) { this.ranges = Collections.emptySet(); lowerBound = null; upperBound = null; - } - else - { - this.ranges = new HashSet<>( ranges ); + } else { + this.ranges = new HashSet<>(ranges); Bound lowerBound = null, upperBound = null; - for ( VersionRange range : this.ranges ) - { + for (VersionRange range : this.ranges) { Bound lb = range.getLowerBound(); - if ( lb == null ) - { + if (lb == null) { lowerBound = null; break; - } - else if ( lowerBound == null ) - { + } else if (lowerBound == null) { lowerBound = lb; - } - else - { - int c = lb.getVersion().compareTo( lowerBound.getVersion() ); - if ( c < 0 || ( c == 0 && !lowerBound.isInclusive() ) ) - { + } else { + int c = lb.getVersion().compareTo(lowerBound.getVersion()); + if (c < 0 || (c == 0 && !lowerBound.isInclusive())) { lowerBound = lb; } } } - for ( VersionRange range : this.ranges ) - { + for (VersionRange range : this.ranges) { Bound ub = range.getUpperBound(); - if ( ub == null ) - { + if (ub == null) { upperBound = null; break; - } - else if ( upperBound == null ) - { + } else if (upperBound == null) { upperBound = ub; - } - else - { - int c = ub.getVersion().compareTo( upperBound.getVersion() ); - if ( c > 0 || ( c == 0 && !upperBound.isInclusive() ) ) - { + } else { + int c = ub.getVersion().compareTo(upperBound.getVersion()); + if (c > 0 || (c == 0 && !upperBound.isInclusive())) { upperBound = ub; } } @@ -130,12 +105,9 @@ else if ( upperBound == null ) } @Override - public boolean containsVersion( Version version ) - { - for ( VersionRange range : ranges ) - { - if ( range.containsVersion( version ) ) - { + public boolean containsVersion(Version version) { + for (VersionRange range : ranges) { + if (range.containsVersion(version)) { return true; } } @@ -143,45 +115,36 @@ public boolean containsVersion( Version version ) } @Override - public Bound getLowerBound() - { + public Bound getLowerBound() { return lowerBound; } @Override - public Bound getUpperBound() - { + public Bound getUpperBound() { return upperBound; } @Override - public boolean equals( Object obj ) - { - if ( obj == this ) - { + public boolean equals(Object obj) { + if (obj == this) { return true; - } - else if ( obj == null || !getClass().equals( obj.getClass() ) ) - { + } else if (obj == null || !getClass().equals(obj.getClass())) { return false; } UnionVersionRange that = (UnionVersionRange) obj; - return ranges.equals( that.ranges ); + return ranges.equals(that.ranges); } - @SuppressWarnings( "checkstyle:magicnumber" ) + @SuppressWarnings("checkstyle:magicnumber") @Override - public int hashCode() - { + public int hashCode() { return 97 * ranges.hashCode(); } @Override - public String toString() - { - return ranges.stream().map( VersionRange::toString ).collect( Collectors.joining( ", " ) ); + public String toString() { + return ranges.stream().map(VersionRange::toString).collect(Collectors.joining(", ")); } - } diff --git a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/package-info.java b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/package-info.java index 9540aefca..8701bdef0 100644 --- a/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/package-info.java +++ b/maven-resolver-util/src/main/java/org/eclipse/aether/util/version/package-info.java @@ -7,9 +7,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -27,4 +27,3 @@ * "unions" of various {@link org.eclipse.aether.version.VersionRange} instances. */ package org.eclipse.aether.util.version; - diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/ChecksumUtilTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/ChecksumUtilTest.java index 1c5a6173c..748405554 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/ChecksumUtilTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/ChecksumUtilTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.eclipse.aether.internal.test.util.TestFileUtils.*; -import static org.junit.Assert.*; +package org.eclipse.aether.util; import java.io.File; import java.io.IOException; @@ -34,8 +30,10 @@ import org.junit.BeforeClass; import org.junit.Test; -public class ChecksumUtilTest -{ +import static org.eclipse.aether.internal.test.util.TestFileUtils.*; +import static org.junit.Assert.*; + +public class ChecksumUtilTest { private static final String EMPTY = "EMPTY"; private static final String PATTERN = "PATTERN"; private static final String TEXT = "TEXT"; @@ -53,204 +51,188 @@ public class ChecksumUtilTest private Map> sums = new HashMap<>(); @BeforeClass - public static void beforeClass() - { - emptyChecksums.put( "MD5", "d41d8cd98f00b204e9800998ecf8427e" ); - emptyChecksums.put( "SHA-1", "da39a3ee5e6b4b0d3255bfef95601890afd80709" ); - emptyChecksums.put( "SHA-256", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ); - emptyChecksums.put( "SHA-512", "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" ); - patternChecksums.put( "MD5", "14f01d6c7de7d4cf0a4887baa3528b5a" ); - patternChecksums.put( "SHA-1", "feeeda19f626f9b0ef6cbf5948c1ec9531694295" ); - patternChecksums.put( "SHA-256", "81d480a714840ab206dc8de62ca6119036f65499ad9e2e227c2465551bed684d" ); - patternChecksums.put( "SHA-512", "931aa34118d9a85b9514e0224046d736a5bd7e2b2f366505fe1ad07ed85e1a4ac0cbc18e9b9a7fe36ce835be2a18cb571202a4975d182553faff336970eb0b7e" ); - textChecksums.put( "MD5", "12582d1a662cefe3385f2113998e43ed" ); - textChecksums.put( "SHA-1", "a8ae272db549850eef2ff54376f8cac2770745ee" ); - textChecksums.put( "SHA-256", "35829adced2979761ba521dc2bb7d166e92ebed7342319d041398e509d481a46" ); - textChecksums.put( "SHA-512", "2d6d19570b26080fa88101af2256ce3dae63512b06864cd36a05371c81d6dbd0ec226dd75f22e8d46a9582e1fc40ee6e7a02d43c852f3c92255982b835db6e7c" ); + public static void beforeClass() { + emptyChecksums.put("MD5", "d41d8cd98f00b204e9800998ecf8427e"); + emptyChecksums.put("SHA-1", "da39a3ee5e6b4b0d3255bfef95601890afd80709"); + emptyChecksums.put("SHA-256", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + emptyChecksums.put( + "SHA-512", + "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"); + patternChecksums.put("MD5", "14f01d6c7de7d4cf0a4887baa3528b5a"); + patternChecksums.put("SHA-1", "feeeda19f626f9b0ef6cbf5948c1ec9531694295"); + patternChecksums.put("SHA-256", "81d480a714840ab206dc8de62ca6119036f65499ad9e2e227c2465551bed684d"); + patternChecksums.put( + "SHA-512", + "931aa34118d9a85b9514e0224046d736a5bd7e2b2f366505fe1ad07ed85e1a4ac0cbc18e9b9a7fe36ce835be2a18cb571202a4975d182553faff336970eb0b7e"); + textChecksums.put("MD5", "12582d1a662cefe3385f2113998e43ed"); + textChecksums.put("SHA-1", "a8ae272db549850eef2ff54376f8cac2770745ee"); + textChecksums.put("SHA-256", "35829adced2979761ba521dc2bb7d166e92ebed7342319d041398e509d481a46"); + textChecksums.put( + "SHA-512", + "2d6d19570b26080fa88101af2256ce3dae63512b06864cd36a05371c81d6dbd0ec226dd75f22e8d46a9582e1fc40ee6e7a02d43c852f3c92255982b835db6e7c"); } @Before - public void before() - throws IOException - { + public void before() throws IOException { sums.clear(); byte[] emptyBytes = new byte[0]; - bytes.put( EMPTY, emptyBytes ); - files.put( EMPTY, createTempFile( emptyBytes, 0 ) ); - sums.put( EMPTY, emptyChecksums ); - - byte[] patternBytes = writeBytes( new byte[] { 0, 1, 2, 4, 8, 16, 32, 64, 127, -1, -2, -4, -8, -16, -32, -64, -127 }, 1000 ); - bytes.put( PATTERN, patternBytes ); - files.put( PATTERN, createTempFile( patternBytes, 1 ) ); - sums.put( PATTERN, patternChecksums ); - - byte[] textBytes = writeBytes( "the quick brown fox jumps over the lazy dog\n".getBytes( StandardCharsets.UTF_8 ), 500 ); - bytes.put( TEXT, textBytes ); - files.put( TEXT, createTempFile( textBytes, 1 ) ); - sums.put( TEXT, textChecksums ); - + bytes.put(EMPTY, emptyBytes); + files.put(EMPTY, createTempFile(emptyBytes, 0)); + sums.put(EMPTY, emptyChecksums); + + byte[] patternBytes = + writeBytes(new byte[] {0, 1, 2, 4, 8, 16, 32, 64, 127, -1, -2, -4, -8, -16, -32, -64, -127}, 1000); + bytes.put(PATTERN, patternBytes); + files.put(PATTERN, createTempFile(patternBytes, 1)); + sums.put(PATTERN, patternChecksums); + + byte[] textBytes = + writeBytes("the quick brown fox jumps over the lazy dog\n".getBytes(StandardCharsets.UTF_8), 500); + bytes.put(TEXT, textBytes); + files.put(TEXT, createTempFile(textBytes, 1)); + sums.put(TEXT, textChecksums); } @Test - public void testEquality() - throws Throwable - { + public void testEquality() throws Throwable { Map checksums = null; - for ( Map.Entry fileEntry : files.entrySet() ) - { + for (Map.Entry fileEntry : files.entrySet()) { - checksums = ChecksumUtils.calc( fileEntry.getValue(), Arrays.asList( "SHA-512", "SHA-256", "SHA-1", "MD5" ) ); + checksums = ChecksumUtils.calc(fileEntry.getValue(), Arrays.asList("SHA-512", "SHA-256", "SHA-1", "MD5")); - for ( Entry entry : checksums.entrySet() ) - { - if ( entry.getValue() instanceof Throwable ) - { + for (Entry entry : checksums.entrySet()) { + if (entry.getValue() instanceof Throwable) { throw (Throwable) entry.getValue(); } String actual = entry.getValue().toString(); - String expected = sums.get( fileEntry.getKey() ).get( entry.getKey() ); - assertEquals( String.format( "checksums do not match for '%s', algorithm '%s'", fileEntry.getValue().getName(), - entry.getKey() ), expected, actual ); + String expected = sums.get(fileEntry.getKey()).get(entry.getKey()); + assertEquals( + String.format( + "checksums do not match for '%s', algorithm '%s'", + fileEntry.getValue().getName(), entry.getKey()), + expected, + actual); } - assertTrue( "Could not delete file", fileEntry.getValue().delete() ); + assertTrue("Could not delete file", fileEntry.getValue().delete()); } } @Test - public void testFileHandleLeakage() - throws IOException - { - for ( File file : files.values() ) - { - for ( int i = 0; i < 150; i++ ) - { - ChecksumUtils.calc( file, Arrays.asList( "SHA-512", "SHA-256", "SHA-1", "MD5" ) ); + public void testFileHandleLeakage() throws IOException { + for (File file : files.values()) { + for (int i = 0; i < 150; i++) { + ChecksumUtils.calc(file, Arrays.asList("SHA-512", "SHA-256", "SHA-1", "MD5")); } - assertTrue( "Could not delete file", file.delete() ); + assertTrue("Could not delete file", file.delete()); } - } @Test - public void testRead() - throws IOException - { - for ( Map checksums : sums.values() ) - { - String sha512 = checksums.get( "SHA-512" ); - String sha256 = checksums.get( "SHA-256" ); - String sha1 = checksums.get( "SHA-1" ); - String md5 = checksums.get( "MD5" ); - - File sha512File = createTempFile( sha512 ); - File sha256File = createTempFile( sha256 ); - File sha1File = createTempFile( sha1 ); - File md5File = createTempFile( md5 ); - - assertEquals( sha512, ChecksumUtils.read( sha512File ) ); - assertEquals( sha256, ChecksumUtils.read( sha256File ) ); - assertEquals( sha1, ChecksumUtils.read( sha1File ) ); - assertEquals( md5, ChecksumUtils.read( md5File ) ); - - assertTrue( "ChecksumUtils leaks file handles (cannot delete checksums.sha512)", sha512File.delete() ); - assertTrue( "ChecksumUtils leaks file handles (cannot delete checksums.sha256)", sha256File.delete() ); - assertTrue( "ChecksumUtils leaks file handles (cannot delete checksums.sha1)", sha1File.delete() ); - assertTrue( "ChecksumUtils leaks file handles (cannot delete checksums.md5)", md5File.delete() ); + public void testRead() throws IOException { + for (Map checksums : sums.values()) { + String sha512 = checksums.get("SHA-512"); + String sha256 = checksums.get("SHA-256"); + String sha1 = checksums.get("SHA-1"); + String md5 = checksums.get("MD5"); + + File sha512File = createTempFile(sha512); + File sha256File = createTempFile(sha256); + File sha1File = createTempFile(sha1); + File md5File = createTempFile(md5); + + assertEquals(sha512, ChecksumUtils.read(sha512File)); + assertEquals(sha256, ChecksumUtils.read(sha256File)); + assertEquals(sha1, ChecksumUtils.read(sha1File)); + assertEquals(md5, ChecksumUtils.read(md5File)); + + assertTrue("ChecksumUtils leaks file handles (cannot delete checksums.sha512)", sha512File.delete()); + assertTrue("ChecksumUtils leaks file handles (cannot delete checksums.sha256)", sha256File.delete()); + assertTrue("ChecksumUtils leaks file handles (cannot delete checksums.sha1)", sha1File.delete()); + assertTrue("ChecksumUtils leaks file handles (cannot delete checksums.md5)", md5File.delete()); } } @Test - public void testReadSpaces() - throws IOException - { - for ( Map checksums : sums.values() ) - { - String sha512 = checksums.get( "SHA-512" ); - String sha256 = checksums.get( "SHA-256" ); - String sha1 = checksums.get( "SHA-1" ); - String md5 = checksums.get( "MD5" ); - - File sha512File = createTempFile( "sha512-checksum = " + sha512 ); - File sha256File = createTempFile( "sha256-checksum = " + sha256 ); - File sha1File = createTempFile( "sha1-checksum = " + sha1 ); - File md5File = createTempFile( md5 + " test" ); - - assertEquals( sha512, ChecksumUtils.read( sha512File ) ); - assertEquals( sha256, ChecksumUtils.read( sha256File ) ); - assertEquals( sha1, ChecksumUtils.read( sha1File ) ); - assertEquals( md5, ChecksumUtils.read( md5File ) ); - - assertTrue( "ChecksumUtils leaks file handles (cannot delete checksums.sha512)", sha512File.delete() ); - assertTrue( "ChecksumUtils leaks file handles (cannot delete checksums.sha256)", sha256File.delete() ); - assertTrue( "ChecksumUtils leaks file handles (cannot delete checksums.sha1)", sha1File.delete() ); - assertTrue( "ChecksumUtils leaks file handles (cannot delete checksums.md5)", md5File.delete() ); + public void testReadSpaces() throws IOException { + for (Map checksums : sums.values()) { + String sha512 = checksums.get("SHA-512"); + String sha256 = checksums.get("SHA-256"); + String sha1 = checksums.get("SHA-1"); + String md5 = checksums.get("MD5"); + + File sha512File = createTempFile("sha512-checksum = " + sha512); + File sha256File = createTempFile("sha256-checksum = " + sha256); + File sha1File = createTempFile("sha1-checksum = " + sha1); + File md5File = createTempFile(md5 + " test"); + + assertEquals(sha512, ChecksumUtils.read(sha512File)); + assertEquals(sha256, ChecksumUtils.read(sha256File)); + assertEquals(sha1, ChecksumUtils.read(sha1File)); + assertEquals(md5, ChecksumUtils.read(md5File)); + + assertTrue("ChecksumUtils leaks file handles (cannot delete checksums.sha512)", sha512File.delete()); + assertTrue("ChecksumUtils leaks file handles (cannot delete checksums.sha256)", sha256File.delete()); + assertTrue("ChecksumUtils leaks file handles (cannot delete checksums.sha1)", sha1File.delete()); + assertTrue("ChecksumUtils leaks file handles (cannot delete checksums.md5)", md5File.delete()); } } @Test - public void testReadEmptyFile() - throws IOException - { - File file = createTempFile( "" ); + public void testReadEmptyFile() throws IOException { + File file = createTempFile(""); - assertEquals( "", ChecksumUtils.read( file ) ); + assertEquals("", ChecksumUtils.read(file)); - assertTrue( "ChecksumUtils leaks file handles (cannot delete checksum.empty)", file.delete() ); + assertTrue("ChecksumUtils leaks file handles (cannot delete checksum.empty)", file.delete()); } @Test - public void testToHexString() - { - assertNull( ChecksumUtils.toHexString( null ) ); - assertEquals( "", ChecksumUtils.toHexString( new byte[] {} ) ); - assertEquals( "00", ChecksumUtils.toHexString( new byte[] { 0 } ) ); - assertEquals( "ff", ChecksumUtils.toHexString( new byte[] { -1 } ) ); - assertEquals( "00017f", ChecksumUtils.toHexString( new byte[] { 0, 1, 127 } ) ); + public void testToHexString() { + assertNull(ChecksumUtils.toHexString(null)); + assertEquals("", ChecksumUtils.toHexString(new byte[] {})); + assertEquals("00", ChecksumUtils.toHexString(new byte[] {0})); + assertEquals("ff", ChecksumUtils.toHexString(new byte[] {-1})); + assertEquals("00017f", ChecksumUtils.toHexString(new byte[] {0, 1, 127})); } @Test - public void testFromHexString() - { - assertNull( ChecksumUtils.toHexString( null ) ); - assertArrayEquals( new byte[] {}, ChecksumUtils.fromHexString( "" ) ); - assertArrayEquals( new byte[] { 0 }, ChecksumUtils.fromHexString( "00" ) ); - assertArrayEquals( new byte[] { -1 } , ChecksumUtils.fromHexString( "ff" ) ); - assertArrayEquals( new byte[] { 0, 1, 127 }, ChecksumUtils.fromHexString( "00017f" ) ); + public void testFromHexString() { + assertNull(ChecksumUtils.toHexString(null)); + assertArrayEquals(new byte[] {}, ChecksumUtils.fromHexString("")); + assertArrayEquals(new byte[] {0}, ChecksumUtils.fromHexString("00")); + assertArrayEquals(new byte[] {-1}, ChecksumUtils.fromHexString("ff")); + assertArrayEquals(new byte[] {0, 1, 127}, ChecksumUtils.fromHexString("00017f")); } @Test - public void testCalcWithByteArray() throws Throwable - { + public void testCalcWithByteArray() throws Throwable { Map checksums = null; - for ( Map.Entry bytesEntry : bytes.entrySet() ) - { - checksums = ChecksumUtils.calc( bytesEntry.getValue(), Arrays.asList( "SHA-512", "SHA-256", "SHA-1", "MD5" ) ); + for (Map.Entry bytesEntry : bytes.entrySet()) { + checksums = ChecksumUtils.calc(bytesEntry.getValue(), Arrays.asList("SHA-512", "SHA-256", "SHA-1", "MD5")); - for ( Entry entry : checksums.entrySet() ) - { - if ( entry.getValue() instanceof Throwable ) - { + for (Entry entry : checksums.entrySet()) { + if (entry.getValue() instanceof Throwable) { throw (Throwable) entry.getValue(); } String actual = entry.getValue().toString(); - String expected = sums.get( bytesEntry.getKey() ).get( entry.getKey() ); - assertEquals( String.format( "checksums do not match for '%s', algorithm '%s'", bytesEntry.getKey(), - entry.getKey() ), expected, actual ); + String expected = sums.get(bytesEntry.getKey()).get(entry.getKey()); + assertEquals( + String.format( + "checksums do not match for '%s', algorithm '%s'", bytesEntry.getKey(), entry.getKey()), + expected, + actual); } } } - private byte[] writeBytes( byte[] pattern, int repeat ) - { + private byte[] writeBytes(byte[] pattern, int repeat) { byte[] result = new byte[pattern.length * repeat]; - for ( int i = 0; i < repeat; i++ ) - { - System.arraycopy( pattern, 0, result, i * pattern.length, pattern.length ); + for (int i = 0; i < repeat; i++) { + System.arraycopy(pattern, 0, result, i * pattern.length, pattern.length); } return result; } } - diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/ConfigUtilsTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/ConfigUtilsTest.java index 0c498121d..55a84595a 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/ConfigUtilsTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/ConfigUtilsTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util; import java.util.ArrayList; import java.util.Arrays; @@ -31,199 +28,175 @@ import org.junit.Test; -public class ConfigUtilsTest -{ +import static org.junit.Assert.*; + +public class ConfigUtilsTest { Map config = new HashMap<>(); @Test - public void testGetObject_Default() - { + public void testGetObject_Default() { Object val = new Object(); - assertSame( val, ConfigUtils.getObject( config, val, "no-value" ) ); + assertSame(val, ConfigUtils.getObject(config, val, "no-value")); } @Test - public void testGetObject_AlternativeKeys() - { + public void testGetObject_AlternativeKeys() { Object val = new Object(); - config.put( "some-object", val ); - assertSame( val, ConfigUtils.getObject( config, null, "no-object", "some-object" ) ); + config.put("some-object", val); + assertSame(val, ConfigUtils.getObject(config, null, "no-object", "some-object")); } @Test - public void testGetMap_Default() - { + public void testGetMap_Default() { Map val = new HashMap(); - assertSame( val, ConfigUtils.getMap( config, val, "no-value" ) ); + assertSame(val, ConfigUtils.getMap(config, val, "no-value")); } @Test - public void testGetMap_AlternativeKeys() - { + public void testGetMap_AlternativeKeys() { Map val = new HashMap(); - config.put( "some-map", val ); - assertSame( val, ConfigUtils.getMap( config, null, "no-object", "some-map" ) ); + config.put("some-map", val); + assertSame(val, ConfigUtils.getMap(config, null, "no-object", "some-map")); } @Test - public void testGetList_Default() - { + public void testGetList_Default() { List val = new ArrayList(); - assertSame( val, ConfigUtils.getList( config, val, "no-value" ) ); + assertSame(val, ConfigUtils.getList(config, val, "no-value")); } @Test - public void testGetList_AlternativeKeys() - { + public void testGetList_AlternativeKeys() { List val = new ArrayList(); - config.put( "some-list", val ); - assertSame( val, ConfigUtils.getList( config, null, "no-object", "some-list" ) ); + config.put("some-list", val); + assertSame(val, ConfigUtils.getList(config, null, "no-object", "some-list")); } @Test - public void testGetList_CollectionConversion() - { - Collection val = Collections.singleton( "item" ); - config.put( "some-collection", val ); - assertEquals( Arrays.asList( "item" ), ConfigUtils.getList( config, null, "some-collection" ) ); + public void testGetList_CollectionConversion() { + Collection val = Collections.singleton("item"); + config.put("some-collection", val); + assertEquals(Arrays.asList("item"), ConfigUtils.getList(config, null, "some-collection")); } @Test - public void testGetString_Default() - { - config.put( "no-string", new Object() ); - assertEquals( "default", ConfigUtils.getString( config, "default", "no-value" ) ); - assertEquals( "default", ConfigUtils.getString( config, "default", "no-string" ) ); + public void testGetString_Default() { + config.put("no-string", new Object()); + assertEquals("default", ConfigUtils.getString(config, "default", "no-value")); + assertEquals("default", ConfigUtils.getString(config, "default", "no-string")); } @Test - public void testGetString_AlternativeKeys() - { - config.put( "no-string", new Object() ); - config.put( "some-string", "passed" ); - assertEquals( "passed", ConfigUtils.getString( config, "default", "no-string", "some-string" ) ); + public void testGetString_AlternativeKeys() { + config.put("no-string", new Object()); + config.put("some-string", "passed"); + assertEquals("passed", ConfigUtils.getString(config, "default", "no-string", "some-string")); } @Test - public void testGetBoolean_Default() - { - config.put( "no-boolean", new Object() ); - assertTrue( ConfigUtils.getBoolean( config, true, "no-value" ) ); - assertFalse( ConfigUtils.getBoolean( config, false, "no-value" ) ); - assertTrue( ConfigUtils.getBoolean( config, true, "no-boolean" ) ); - assertFalse( ConfigUtils.getBoolean( config, false, "no-boolean" ) ); + public void testGetBoolean_Default() { + config.put("no-boolean", new Object()); + assertTrue(ConfigUtils.getBoolean(config, true, "no-value")); + assertFalse(ConfigUtils.getBoolean(config, false, "no-value")); + assertTrue(ConfigUtils.getBoolean(config, true, "no-boolean")); + assertFalse(ConfigUtils.getBoolean(config, false, "no-boolean")); } @Test - public void testGetBoolean_AlternativeKeys() - { - config.put( "no-boolean", new Object() ); - config.put( "some-boolean", true ); - assertTrue( ConfigUtils.getBoolean( config, false, "no-boolean", "some-boolean" ) ); - config.put( "some-boolean", false ); - assertFalse( ConfigUtils.getBoolean( config, true, "no-boolean", "some-boolean" ) ); + public void testGetBoolean_AlternativeKeys() { + config.put("no-boolean", new Object()); + config.put("some-boolean", true); + assertTrue(ConfigUtils.getBoolean(config, false, "no-boolean", "some-boolean")); + config.put("some-boolean", false); + assertFalse(ConfigUtils.getBoolean(config, true, "no-boolean", "some-boolean")); } @Test - public void testGetBoolean_StringConversion() - { - config.put( "some-boolean", "true" ); - assertTrue( ConfigUtils.getBoolean( config, false, "some-boolean" ) ); - config.put( "some-boolean", "false" ); - assertFalse( ConfigUtils.getBoolean( config, true, "some-boolean" ) ); + public void testGetBoolean_StringConversion() { + config.put("some-boolean", "true"); + assertTrue(ConfigUtils.getBoolean(config, false, "some-boolean")); + config.put("some-boolean", "false"); + assertFalse(ConfigUtils.getBoolean(config, true, "some-boolean")); } @Test - public void testGetInteger_Default() - { - config.put( "no-integer", new Object() ); - assertEquals( -17, ConfigUtils.getInteger( config, -17, "no-value" ) ); - assertEquals( 43, ConfigUtils.getInteger( config, 43, "no-integer" ) ); + public void testGetInteger_Default() { + config.put("no-integer", new Object()); + assertEquals(-17, ConfigUtils.getInteger(config, -17, "no-value")); + assertEquals(43, ConfigUtils.getInteger(config, 43, "no-integer")); } @Test - public void testGetInteger_AlternativeKeys() - { - config.put( "no-integer", "text" ); - config.put( "some-integer", 23 ); - assertEquals( 23, ConfigUtils.getInteger( config, 0, "no-integer", "some-integer" ) ); + public void testGetInteger_AlternativeKeys() { + config.put("no-integer", "text"); + config.put("some-integer", 23); + assertEquals(23, ConfigUtils.getInteger(config, 0, "no-integer", "some-integer")); } @Test - public void testGetInteger_StringConversion() - { - config.put( "some-integer", "-123456" ); - assertEquals( -123456, ConfigUtils.getInteger( config, 0, "some-integer" ) ); + public void testGetInteger_StringConversion() { + config.put("some-integer", "-123456"); + assertEquals(-123456, ConfigUtils.getInteger(config, 0, "some-integer")); } @Test - public void testGetInteger_NumberConversion() - { - config.put( "some-number", -123456.789 ); - assertEquals( -123456, ConfigUtils.getInteger( config, 0, "some-number" ) ); + public void testGetInteger_NumberConversion() { + config.put("some-number", -123456.789); + assertEquals(-123456, ConfigUtils.getInteger(config, 0, "some-number")); } @Test - public void testGetLong_Default() - { - config.put( "no-long", new Object() ); - assertEquals( -17L, ConfigUtils.getLong( config, -17L, "no-value" ) ); - assertEquals( 43L, ConfigUtils.getLong( config, 43L, "no-long" ) ); + public void testGetLong_Default() { + config.put("no-long", new Object()); + assertEquals(-17L, ConfigUtils.getLong(config, -17L, "no-value")); + assertEquals(43L, ConfigUtils.getLong(config, 43L, "no-long")); } @Test - public void testGetLong_AlternativeKeys() - { - config.put( "no-long", "text" ); - config.put( "some-long", 23L ); - assertEquals( 23L, ConfigUtils.getLong( config, 0, "no-long", "some-long" ) ); + public void testGetLong_AlternativeKeys() { + config.put("no-long", "text"); + config.put("some-long", 23L); + assertEquals(23L, ConfigUtils.getLong(config, 0, "no-long", "some-long")); } @Test - public void testGetLong_StringConversion() - { - config.put( "some-long", "-123456789012" ); - assertEquals( -123456789012L, ConfigUtils.getLong( config, 0, "some-long" ) ); + public void testGetLong_StringConversion() { + config.put("some-long", "-123456789012"); + assertEquals(-123456789012L, ConfigUtils.getLong(config, 0, "some-long")); } @Test - public void testGetLong_NumberConversion() - { - config.put( "some-number", -123456789012.789 ); - assertEquals( -123456789012L, ConfigUtils.getLong( config, 0, "some-number" ) ); + public void testGetLong_NumberConversion() { + config.put("some-number", -123456789012.789); + assertEquals(-123456789012L, ConfigUtils.getLong(config, 0, "some-number")); } @Test - public void testGetFloat_Default() - { - config.put( "no-float", new Object() ); - assertEquals( -17.1f, ConfigUtils.getFloat( config, -17.1f, "no-value" ), 0.01f ); - assertEquals( 43.2f, ConfigUtils.getFloat( config, 43.2f, "no-float" ), 0.01f ); + public void testGetFloat_Default() { + config.put("no-float", new Object()); + assertEquals(-17.1f, ConfigUtils.getFloat(config, -17.1f, "no-value"), 0.01f); + assertEquals(43.2f, ConfigUtils.getFloat(config, 43.2f, "no-float"), 0.01f); } @Test - public void testGetFloat_AlternativeKeys() - { - config.put( "no-float", "text" ); - config.put( "some-float", 12.3f ); - assertEquals( 12.3f, ConfigUtils.getFloat( config, 0, "no-float", "some-float" ), 0.01f ); + public void testGetFloat_AlternativeKeys() { + config.put("no-float", "text"); + config.put("some-float", 12.3f); + assertEquals(12.3f, ConfigUtils.getFloat(config, 0, "no-float", "some-float"), 0.01f); } @Test - public void testGetFloat_StringConversion() - { - config.put( "some-float", "-12.3" ); - assertEquals( -12.3f, ConfigUtils.getFloat( config, 0, "some-float" ), 0.01f ); - config.put( "some-float", "NaN" ); - assertTrue( Float.isNaN( ConfigUtils.getFloat( config, 0, "some-float" ) ) ); + public void testGetFloat_StringConversion() { + config.put("some-float", "-12.3"); + assertEquals(-12.3f, ConfigUtils.getFloat(config, 0, "some-float"), 0.01f); + config.put("some-float", "NaN"); + assertTrue(Float.isNaN(ConfigUtils.getFloat(config, 0, "some-float"))); } @Test - public void testGetFloat_NumberConversion() - { - config.put( "some-number", -1234f ); - assertEquals( -1234f, ConfigUtils.getFloat( config, 0, "some-number" ), 0.1f ); + public void testGetFloat_NumberConversion() { + config.put("some-number", -1234f); + assertEquals(-1234f, ConfigUtils.getFloat(config, 0, "some-number"), 0.1f); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/DirectoryUtilsTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/DirectoryUtilsTest.java index f47c69a74..e099c1348 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/DirectoryUtilsTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/DirectoryUtilsTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util; import java.io.IOException; import java.nio.file.FileSystems; @@ -34,95 +33,87 @@ import static org.hamcrest.Matchers.startsWith; import static org.junit.Assume.assumeTrue; -public class DirectoryUtilsTest -{ +public class DirectoryUtilsTest { @Rule public TestName testName = new TestName(); @Test - public void expectedCasesRelative() throws IOException - { + public void expectedCasesRelative() throws IOException { // hack for surefire: sets the property but directory may not exist - Files.createDirectories( Paths.get ( System.getProperty( "java.io.tmpdir" ) ) ); + Files.createDirectories(Paths.get(System.getProperty("java.io.tmpdir"))); - Path tmpDir = Files.createTempDirectory( testName.getMethodName() ); + Path tmpDir = Files.createTempDirectory(testName.getMethodName()); Path result; - result = DirectoryUtils.resolveDirectory( "foo", tmpDir, false ); - assertThat( result, equalTo( tmpDir.resolve( "foo" ) ) ); + result = DirectoryUtils.resolveDirectory("foo", tmpDir, false); + assertThat(result, equalTo(tmpDir.resolve("foo"))); - result = DirectoryUtils.resolveDirectory( "foo/bar", tmpDir, false ); - assertThat( result, equalTo( tmpDir.resolve( "foo/bar" ) ) ); + result = DirectoryUtils.resolveDirectory("foo/bar", tmpDir, false); + assertThat(result, equalTo(tmpDir.resolve("foo/bar"))); - result = DirectoryUtils.resolveDirectory( "foo/./bar/..", tmpDir, false ); - assertThat( result, equalTo( tmpDir.resolve( "foo" ) ) ); + result = DirectoryUtils.resolveDirectory("foo/./bar/..", tmpDir, false); + assertThat(result, equalTo(tmpDir.resolve("foo"))); } @Test - public void expectedCasesAbsolute() throws IOException - { + public void expectedCasesAbsolute() throws IOException { // TODO: this test is skipped on Windows, as it is not clear which drive letter will `new File("/foo")` // path get. According to Windows (and assuming Java Path does separator change OK), "\foo" file should // get resolved to CWD drive + "\foo" path, but seems Java 17 is different from 11 and 8 in this respect. // This below WORKS on win + Java8 abd win + Java11 but FAILS on win + Java17 - assumeTrue( !"WindowsFileSystem".equals( FileSystems.getDefault().getClass().getSimpleName() ) ); + assumeTrue( + !"WindowsFileSystem".equals(FileSystems.getDefault().getClass().getSimpleName())); // hack for surefire: sets the property but directory may not exist - Files.createDirectories( Paths.get ( System.getProperty( "java.io.tmpdir" ) ) ); + Files.createDirectories(Paths.get(System.getProperty("java.io.tmpdir"))); - Path tmpDir = Files.createTempDirectory( testName.getMethodName() ); + Path tmpDir = Files.createTempDirectory(testName.getMethodName()); Path result; - result = DirectoryUtils.resolveDirectory( "/foo", tmpDir, false ); - assertThat( result, equalTo( FileSystems.getDefault().getPath( "/foo" ).toAbsolutePath() ) ); + result = DirectoryUtils.resolveDirectory("/foo", tmpDir, false); + assertThat(result, equalTo(FileSystems.getDefault().getPath("/foo").toAbsolutePath())); - result = DirectoryUtils.resolveDirectory( "/foo/bar", tmpDir, false ); - assertThat( result, equalTo( FileSystems.getDefault().getPath( "/foo/bar" ).toAbsolutePath() ) ); + result = DirectoryUtils.resolveDirectory("/foo/bar", tmpDir, false); + assertThat(result, equalTo(FileSystems.getDefault().getPath("/foo/bar").toAbsolutePath())); - result = DirectoryUtils.resolveDirectory( "/foo/./bar/..", tmpDir, false ); - assertThat( result, equalTo( FileSystems.getDefault().getPath( "/foo" ).toAbsolutePath() ) ); + result = DirectoryUtils.resolveDirectory("/foo/./bar/..", tmpDir, false); + assertThat(result, equalTo(FileSystems.getDefault().getPath("/foo").toAbsolutePath())); } @Test - public void existsButIsADirectory() throws IOException - { + public void existsButIsADirectory() throws IOException { // hack for surefire: sets the property but directory may not exist - Files.createDirectories( Paths.get ( System.getProperty( "java.io.tmpdir" ) ) ); + Files.createDirectories(Paths.get(System.getProperty("java.io.tmpdir"))); - Path tmpDir = Files.createTempDirectory( testName.getMethodName() ); - Files.createDirectories( tmpDir.resolve( "foo" ) ); - Path result = DirectoryUtils.resolveDirectory( "foo", tmpDir, false ); - assertThat( result, equalTo( tmpDir.resolve( "foo" ) ) ); + Path tmpDir = Files.createTempDirectory(testName.getMethodName()); + Files.createDirectories(tmpDir.resolve("foo")); + Path result = DirectoryUtils.resolveDirectory("foo", tmpDir, false); + assertThat(result, equalTo(tmpDir.resolve("foo"))); } @Test - public void existsButNotADirectory() throws IOException - { + public void existsButNotADirectory() throws IOException { // hack for surefire: sets the property but directory may not exist - Files.createDirectories( Paths.get ( System.getProperty( "java.io.tmpdir" ) ) ); - - Path tmpDir = Files.createTempDirectory( testName.getMethodName() ); - Files.createFile( tmpDir.resolve( "foo" ) ); - try - { - DirectoryUtils.resolveDirectory( "foo", tmpDir, false ); - } - catch ( IOException e ) - { - assertThat( e.getMessage(), startsWith( "Path exists, but is not a directory:" ) ); + Files.createDirectories(Paths.get(System.getProperty("java.io.tmpdir"))); + + Path tmpDir = Files.createTempDirectory(testName.getMethodName()); + Files.createFile(tmpDir.resolve("foo")); + try { + DirectoryUtils.resolveDirectory("foo", tmpDir, false); + } catch (IOException e) { + assertThat(e.getMessage(), startsWith("Path exists, but is not a directory:")); } } @Test - public void notExistsAndIsCreated() throws IOException - { + public void notExistsAndIsCreated() throws IOException { // hack for surefire: sets the property but directory may not exist - Files.createDirectories( Paths.get ( System.getProperty( "java.io.tmpdir" ) ) ); + Files.createDirectories(Paths.get(System.getProperty("java.io.tmpdir"))); - Path tmpDir = Files.createTempDirectory( testName.getMethodName() ); - Files.createDirectories( tmpDir.resolve( "foo" ) ); - Path result = DirectoryUtils.resolveDirectory( "foo", tmpDir, true ); - assertThat( result, equalTo( tmpDir.resolve( "foo" ) ) ); - assertThat( Files.isDirectory( tmpDir.resolve( "foo" ) ), equalTo( true ) ); + Path tmpDir = Files.createTempDirectory(testName.getMethodName()); + Files.createDirectories(tmpDir.resolve("foo")); + Path result = DirectoryUtils.resolveDirectory("foo", tmpDir, true); + assertThat(result, equalTo(tmpDir.resolve("foo"))); + assertThat(Files.isDirectory(tmpDir.resolve("foo")), equalTo(true)); } } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/StringDigestUtilTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/StringDigestUtilTest.java index 23d9839ff..c12658445 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/StringDigestUtilTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/StringDigestUtilTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util; import org.junit.Test; @@ -25,77 +24,58 @@ import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail; -public class StringDigestUtilTest -{ +public class StringDigestUtilTest { @Test - public void sha1Simple() - { - assertThat( StringDigestUtil.sha1( null ), - is( "da39a3ee5e6b4b0d3255bfef95601890afd80709" ) ); - assertThat( StringDigestUtil.sha1( "" ), - is( "da39a3ee5e6b4b0d3255bfef95601890afd80709" ) ); - assertThat( StringDigestUtil.sha1( "something" ), - is( "1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29" ) ); - assertThat( StringDigestUtil.sha1().update( null ).digest(), - is( "da39a3ee5e6b4b0d3255bfef95601890afd80709" ) ); - assertThat( StringDigestUtil.sha1().update( "" ).digest(), - is( "da39a3ee5e6b4b0d3255bfef95601890afd80709" ) ); - assertThat( StringDigestUtil.sha1().update( "something" ).digest(), - is( "1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29" ) ); - assertThat( StringDigestUtil.sha1().update( "some" ).update( "thing" ).digest(), - is( "1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29" ) ); + public void sha1Simple() { + assertThat(StringDigestUtil.sha1(null), is("da39a3ee5e6b4b0d3255bfef95601890afd80709")); + assertThat(StringDigestUtil.sha1(""), is("da39a3ee5e6b4b0d3255bfef95601890afd80709")); + assertThat(StringDigestUtil.sha1("something"), is("1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29")); + assertThat(StringDigestUtil.sha1().update(null).digest(), is("da39a3ee5e6b4b0d3255bfef95601890afd80709")); + assertThat(StringDigestUtil.sha1().update("").digest(), is("da39a3ee5e6b4b0d3255bfef95601890afd80709")); + assertThat( + StringDigestUtil.sha1().update("something").digest(), is("1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29")); + assertThat( + StringDigestUtil.sha1().update("some").update("thing").digest(), + is("1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29")); } @Test - public void sha1Manual() - { - assertThat( new StringDigestUtil( "SHA-1" ).digest(), - is( "da39a3ee5e6b4b0d3255bfef95601890afd80709" ) ); - assertThat( new StringDigestUtil( "SHA-1" ).update( "" ).digest(), - is( "da39a3ee5e6b4b0d3255bfef95601890afd80709" ) ); - assertThat( new StringDigestUtil( "SHA-1" ).update( "something" ).digest(), - is( "1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29" ) ); - assertThat( new StringDigestUtil( "SHA-1" ).update( null ).digest(), - is( "da39a3ee5e6b4b0d3255bfef95601890afd80709" ) ); - assertThat( new StringDigestUtil( "SHA-1" ).update( "" ).digest(), - is( "da39a3ee5e6b4b0d3255bfef95601890afd80709" ) ); - assertThat( new StringDigestUtil( "SHA-1" ).update( "something" ).digest(), - is( "1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29" ) ); - assertThat( new StringDigestUtil( "SHA-1" ).update( "some" ).update( "thing" ).digest(), - is( "1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29" ) ); + public void sha1Manual() { + assertThat(new StringDigestUtil("SHA-1").digest(), is("da39a3ee5e6b4b0d3255bfef95601890afd80709")); + assertThat(new StringDigestUtil("SHA-1").update("").digest(), is("da39a3ee5e6b4b0d3255bfef95601890afd80709")); + assertThat( + new StringDigestUtil("SHA-1").update("something").digest(), + is("1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29")); + assertThat(new StringDigestUtil("SHA-1").update(null).digest(), is("da39a3ee5e6b4b0d3255bfef95601890afd80709")); + assertThat(new StringDigestUtil("SHA-1").update("").digest(), is("da39a3ee5e6b4b0d3255bfef95601890afd80709")); + assertThat( + new StringDigestUtil("SHA-1").update("something").digest(), + is("1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29")); + assertThat( + new StringDigestUtil("SHA-1").update("some").update("thing").digest(), + is("1af17e73721dbe0c40011b82ed4bb1a7dbe3ce29")); } @Test - public void md5Manual() - { - assertThat( new StringDigestUtil( "MD5" ).digest(), - is( "d41d8cd98f00b204e9800998ecf8427e" ) ); - assertThat( new StringDigestUtil( "MD5" ).update( "" ).digest(), - is( "d41d8cd98f00b204e9800998ecf8427e" ) ); - assertThat( new StringDigestUtil( "MD5" ).update( "something" ).digest(), - is( "437b930db84b8079c2dd804a71936b5f" ) ); - assertThat( new StringDigestUtil( "MD5" ).update( null ).digest(), - is( "d41d8cd98f00b204e9800998ecf8427e" ) ); - assertThat( new StringDigestUtil( "MD5" ).update( "" ).digest(), - is( "d41d8cd98f00b204e9800998ecf8427e" ) ); - assertThat( new StringDigestUtil( "MD5" ).update( "something" ).digest(), - is( "437b930db84b8079c2dd804a71936b5f" ) ); - assertThat( new StringDigestUtil( "MD5" ).update( "some" ).update( "thing" ).digest(), - is( "437b930db84b8079c2dd804a71936b5f" ) ); + public void md5Manual() { + assertThat(new StringDigestUtil("MD5").digest(), is("d41d8cd98f00b204e9800998ecf8427e")); + assertThat(new StringDigestUtil("MD5").update("").digest(), is("d41d8cd98f00b204e9800998ecf8427e")); + assertThat(new StringDigestUtil("MD5").update("something").digest(), is("437b930db84b8079c2dd804a71936b5f")); + assertThat(new StringDigestUtil("MD5").update(null).digest(), is("d41d8cd98f00b204e9800998ecf8427e")); + assertThat(new StringDigestUtil("MD5").update("").digest(), is("d41d8cd98f00b204e9800998ecf8427e")); + assertThat(new StringDigestUtil("MD5").update("something").digest(), is("437b930db84b8079c2dd804a71936b5f")); + assertThat( + new StringDigestUtil("MD5").update("some").update("thing").digest(), + is("437b930db84b8079c2dd804a71936b5f")); } @Test - public void unsupportedAlg() - { - try - { - new StringDigestUtil( "FOO-BAR" ); - fail( "StringDigestUtil should throw" ); - } - catch ( IllegalStateException e ) - { + public void unsupportedAlg() { + try { + new StringDigestUtil("FOO-BAR"); + fail("StringDigestUtil should throw"); + } catch (IllegalStateException e) { // good } } } - diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/StringUtilsTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/StringUtilsTest.java index d0a373b0b..8bfb0f7b5 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/StringUtilsTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/StringUtilsTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,23 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util; -import static org.junit.Assert.*; - -import org.eclipse.aether.util.StringUtils; import org.junit.Test; -@SuppressWarnings( "deprecation" ) -public class StringUtilsTest -{ +import static org.junit.Assert.*; + +@SuppressWarnings("deprecation") +public class StringUtilsTest { @Test - public void testIsEmpty() - { - assertTrue( StringUtils.isEmpty( null ) ); - assertTrue( StringUtils.isEmpty( "" ) ); - assertFalse( StringUtils.isEmpty( " " ) ); - assertFalse( StringUtils.isEmpty( "test" ) ); + public void testIsEmpty() { + assertTrue(StringUtils.isEmpty(null)); + assertTrue(StringUtils.isEmpty("")); + assertFalse(StringUtils.isEmpty(" ")); + assertFalse(StringUtils.isEmpty("test")); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/artifact/ArtifactIdUtilsTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/artifact/ArtifactIdUtilsTest.java index 6b382b72f..26f755001 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/artifact/ArtifactIdUtilsTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/artifact/ArtifactIdUtilsTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,184 +16,175 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.artifact; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class ArtifactIdUtilsTest -{ +public class ArtifactIdUtilsTest { @Test - public void testToIdArtifact() - { + public void testToIdArtifact() { Artifact artifact = null; - assertSame( null, ArtifactIdUtils.toId( artifact ) ); + assertSame(null, ArtifactIdUtils.toId(artifact)); - artifact = new DefaultArtifact( "gid", "aid", "ext", "1.0-20110205.132618-23" ); - assertEquals( "gid:aid:ext:1.0-20110205.132618-23", ArtifactIdUtils.toId( artifact ) ); + artifact = new DefaultArtifact("gid", "aid", "ext", "1.0-20110205.132618-23"); + assertEquals("gid:aid:ext:1.0-20110205.132618-23", ArtifactIdUtils.toId(artifact)); - artifact = new DefaultArtifact( "gid", "aid", "cls", "ext", "1.0-20110205.132618-23" ); - assertEquals( "gid:aid:ext:cls:1.0-20110205.132618-23", ArtifactIdUtils.toId( artifact ) ); + artifact = new DefaultArtifact("gid", "aid", "cls", "ext", "1.0-20110205.132618-23"); + assertEquals("gid:aid:ext:cls:1.0-20110205.132618-23", ArtifactIdUtils.toId(artifact)); } @Test - public void testToIdStrings() - { - assertEquals( ":::", ArtifactIdUtils.toId( null, null, null, null, null ) ); + public void testToIdStrings() { + assertEquals(":::", ArtifactIdUtils.toId(null, null, null, null, null)); - assertEquals( "gid:aid:ext:1", ArtifactIdUtils.toId( "gid", "aid", "ext", "", "1" ) ); + assertEquals("gid:aid:ext:1", ArtifactIdUtils.toId("gid", "aid", "ext", "", "1")); - assertEquals( "gid:aid:ext:cls:1", ArtifactIdUtils.toId( "gid", "aid", "ext", "cls", "1" ) ); + assertEquals("gid:aid:ext:cls:1", ArtifactIdUtils.toId("gid", "aid", "ext", "cls", "1")); } @Test - public void testToBaseIdArtifact() - { + public void testToBaseIdArtifact() { Artifact artifact = null; - assertSame( null, ArtifactIdUtils.toBaseId( artifact ) ); + assertSame(null, ArtifactIdUtils.toBaseId(artifact)); - artifact = new DefaultArtifact( "gid", "aid", "ext", "1.0-20110205.132618-23" ); - assertEquals( "gid:aid:ext:1.0-SNAPSHOT", ArtifactIdUtils.toBaseId( artifact ) ); + artifact = new DefaultArtifact("gid", "aid", "ext", "1.0-20110205.132618-23"); + assertEquals("gid:aid:ext:1.0-SNAPSHOT", ArtifactIdUtils.toBaseId(artifact)); - artifact = new DefaultArtifact( "gid", "aid", "cls", "ext", "1.0-20110205.132618-23" ); - assertEquals( "gid:aid:ext:cls:1.0-SNAPSHOT", ArtifactIdUtils.toBaseId( artifact ) ); + artifact = new DefaultArtifact("gid", "aid", "cls", "ext", "1.0-20110205.132618-23"); + assertEquals("gid:aid:ext:cls:1.0-SNAPSHOT", ArtifactIdUtils.toBaseId(artifact)); } @Test - public void testToVersionlessIdArtifact() - { + public void testToVersionlessIdArtifact() { Artifact artifact = null; - assertSame( null, ArtifactIdUtils.toId( artifact ) ); + assertSame(null, ArtifactIdUtils.toId(artifact)); - artifact = new DefaultArtifact( "gid", "aid", "ext", "1" ); - assertEquals( "gid:aid:ext", ArtifactIdUtils.toVersionlessId( artifact ) ); + artifact = new DefaultArtifact("gid", "aid", "ext", "1"); + assertEquals("gid:aid:ext", ArtifactIdUtils.toVersionlessId(artifact)); - artifact = new DefaultArtifact( "gid", "aid", "cls", "ext", "1" ); - assertEquals( "gid:aid:ext:cls", ArtifactIdUtils.toVersionlessId( artifact ) ); + artifact = new DefaultArtifact("gid", "aid", "cls", "ext", "1"); + assertEquals("gid:aid:ext:cls", ArtifactIdUtils.toVersionlessId(artifact)); } @Test - public void testToVersionlessIdStrings() - { - assertEquals( "::", ArtifactIdUtils.toVersionlessId( null, null, null, null ) ); + public void testToVersionlessIdStrings() { + assertEquals("::", ArtifactIdUtils.toVersionlessId(null, null, null, null)); - assertEquals( "gid:aid:ext", ArtifactIdUtils.toVersionlessId( "gid", "aid", "ext", "" ) ); + assertEquals("gid:aid:ext", ArtifactIdUtils.toVersionlessId("gid", "aid", "ext", "")); - assertEquals( "gid:aid:ext:cls", ArtifactIdUtils.toVersionlessId( "gid", "aid", "ext", "cls" ) ); + assertEquals("gid:aid:ext:cls", ArtifactIdUtils.toVersionlessId("gid", "aid", "ext", "cls")); } @Test - public void testEqualsId() - { + public void testEqualsId() { Artifact artifact1 = null; Artifact artifact2 = null; - assertFalse( ArtifactIdUtils.equalsId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsId( artifact2, artifact1 ) ); + assertFalse(ArtifactIdUtils.equalsId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsId(artifact2, artifact1)); - artifact1 = new DefaultArtifact( "gid", "aid", "ext", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsId( artifact2, artifact1 ) ); + artifact1 = new DefaultArtifact("gid", "aid", "ext", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gidX", "aid", "ext", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gidX", "aid", "ext", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aidX", "ext", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aidX", "ext", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aid", "extX", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aid", "extX", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aid", "ext", "1.0-20110205.132618-24" ); - assertFalse( ArtifactIdUtils.equalsId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aid", "ext", "1.0-20110205.132618-24"); + assertFalse(ArtifactIdUtils.equalsId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aid", "ext", "1.0-20110205.132618-23" ); - assertTrue( ArtifactIdUtils.equalsId( artifact1, artifact2 ) ); - assertTrue( ArtifactIdUtils.equalsId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aid", "ext", "1.0-20110205.132618-23"); + assertTrue(ArtifactIdUtils.equalsId(artifact1, artifact2)); + assertTrue(ArtifactIdUtils.equalsId(artifact2, artifact1)); - assertTrue( ArtifactIdUtils.equalsId( artifact1, artifact1 ) ); + assertTrue(ArtifactIdUtils.equalsId(artifact1, artifact1)); } @Test - public void testEqualsBaseId() - { + public void testEqualsBaseId() { Artifact artifact1 = null; Artifact artifact2 = null; - assertFalse( ArtifactIdUtils.equalsBaseId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsBaseId( artifact2, artifact1 ) ); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact2, artifact1)); - artifact1 = new DefaultArtifact( "gid", "aid", "ext", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsBaseId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsBaseId( artifact2, artifact1 ) ); + artifact1 = new DefaultArtifact("gid", "aid", "ext", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gidX", "aid", "ext", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsBaseId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsBaseId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gidX", "aid", "ext", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aidX", "ext", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsBaseId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsBaseId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aidX", "ext", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aid", "extX", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsBaseId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsBaseId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aid", "extX", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aid", "ext", "X.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsBaseId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsBaseId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aid", "ext", "X.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsBaseId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aid", "ext", "1.0-20110205.132618-24" ); - assertTrue( ArtifactIdUtils.equalsBaseId( artifact1, artifact2 ) ); - assertTrue( ArtifactIdUtils.equalsBaseId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aid", "ext", "1.0-20110205.132618-24"); + assertTrue(ArtifactIdUtils.equalsBaseId(artifact1, artifact2)); + assertTrue(ArtifactIdUtils.equalsBaseId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aid", "ext", "1.0-20110205.132618-23" ); - assertTrue( ArtifactIdUtils.equalsBaseId( artifact1, artifact2 ) ); - assertTrue( ArtifactIdUtils.equalsBaseId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aid", "ext", "1.0-20110205.132618-23"); + assertTrue(ArtifactIdUtils.equalsBaseId(artifact1, artifact2)); + assertTrue(ArtifactIdUtils.equalsBaseId(artifact2, artifact1)); - assertTrue( ArtifactIdUtils.equalsBaseId( artifact1, artifact1 ) ); + assertTrue(ArtifactIdUtils.equalsBaseId(artifact1, artifact1)); } @Test - public void testEqualsVersionlessId() - { + public void testEqualsVersionlessId() { Artifact artifact1 = null; Artifact artifact2 = null; - assertFalse( ArtifactIdUtils.equalsVersionlessId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsVersionlessId( artifact2, artifact1 ) ); + assertFalse(ArtifactIdUtils.equalsVersionlessId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsVersionlessId(artifact2, artifact1)); - artifact1 = new DefaultArtifact( "gid", "aid", "ext", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsVersionlessId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsVersionlessId( artifact2, artifact1 ) ); + artifact1 = new DefaultArtifact("gid", "aid", "ext", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsVersionlessId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsVersionlessId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gidX", "aid", "ext", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsVersionlessId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsVersionlessId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gidX", "aid", "ext", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsVersionlessId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsVersionlessId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aidX", "ext", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsVersionlessId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsVersionlessId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aidX", "ext", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsVersionlessId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsVersionlessId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aid", "extX", "1.0-20110205.132618-23" ); - assertFalse( ArtifactIdUtils.equalsVersionlessId( artifact1, artifact2 ) ); - assertFalse( ArtifactIdUtils.equalsVersionlessId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aid", "extX", "1.0-20110205.132618-23"); + assertFalse(ArtifactIdUtils.equalsVersionlessId(artifact1, artifact2)); + assertFalse(ArtifactIdUtils.equalsVersionlessId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aid", "ext", "1.0-20110205.132618-24" ); - assertTrue( ArtifactIdUtils.equalsVersionlessId( artifact1, artifact2 ) ); - assertTrue( ArtifactIdUtils.equalsVersionlessId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aid", "ext", "1.0-20110205.132618-24"); + assertTrue(ArtifactIdUtils.equalsVersionlessId(artifact1, artifact2)); + assertTrue(ArtifactIdUtils.equalsVersionlessId(artifact2, artifact1)); - artifact2 = new DefaultArtifact( "gid", "aid", "ext", "1.0-20110205.132618-23" ); - assertTrue( ArtifactIdUtils.equalsVersionlessId( artifact1, artifact2 ) ); - assertTrue( ArtifactIdUtils.equalsVersionlessId( artifact2, artifact1 ) ); + artifact2 = new DefaultArtifact("gid", "aid", "ext", "1.0-20110205.132618-23"); + assertTrue(ArtifactIdUtils.equalsVersionlessId(artifact1, artifact2)); + assertTrue(ArtifactIdUtils.equalsVersionlessId(artifact2, artifact1)); - assertTrue( ArtifactIdUtils.equalsVersionlessId( artifact1, artifact1 ) ); + assertTrue(ArtifactIdUtils.equalsVersionlessId(artifact1, artifact1)); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/artifact/SubArtifactTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/artifact/SubArtifactTest.java index b03194fed..2a6473afa 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/artifact/SubArtifactTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/artifact/SubArtifactTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.artifact; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.artifact; import java.io.File; import java.util.Collections; @@ -28,131 +25,118 @@ import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; -import org.eclipse.aether.util.artifact.SubArtifact; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class SubArtifactTest -{ +public class SubArtifactTest { - private Artifact newMainArtifact( String coords ) - { - return new DefaultArtifact( coords ); + private Artifact newMainArtifact(String coords) { + return new DefaultArtifact(coords); } @Test - public void testMainArtifactFileNotRetained() - { - Artifact a = newMainArtifact( "gid:aid:ver" ).setFile( new File( "" ) ); - assertNotNull( a.getFile() ); - a = new SubArtifact( a, "", "pom" ); - assertNull( a.getFile() ); + public void testMainArtifactFileNotRetained() { + Artifact a = newMainArtifact("gid:aid:ver").setFile(new File("")); + assertNotNull(a.getFile()); + a = new SubArtifact(a, "", "pom"); + assertNull(a.getFile()); } @Test - public void testMainArtifactPropertiesNotRetained() - { - Artifact a = newMainArtifact( "gid:aid:ver" ).setProperties( Collections.singletonMap( "key", "value" ) ); - assertEquals( 1, a.getProperties().size() ); - a = new SubArtifact( a, "", "pom" ); - assertEquals( 0, a.getProperties().size() ); - assertSame( null, a.getProperty( "key", null ) ); + public void testMainArtifactPropertiesNotRetained() { + Artifact a = newMainArtifact("gid:aid:ver").setProperties(Collections.singletonMap("key", "value")); + assertEquals(1, a.getProperties().size()); + a = new SubArtifact(a, "", "pom"); + assertEquals(0, a.getProperties().size()); + assertSame(null, a.getProperty("key", null)); } - @Test( expected = NullPointerException.class ) - public void testMainArtifactMissing() - { - new SubArtifact( null, "", "pom" ); + @Test(expected = NullPointerException.class) + public void testMainArtifactMissing() { + new SubArtifact(null, "", "pom"); } @Test - public void testEmptyClassifier() - { - Artifact main = newMainArtifact( "gid:aid:ext:cls:ver" ); - Artifact sub = new SubArtifact( main, "", "pom" ); - assertEquals( "", sub.getClassifier() ); - sub = new SubArtifact( main, null, "pom" ); - assertEquals( "", sub.getClassifier() ); + public void testEmptyClassifier() { + Artifact main = newMainArtifact("gid:aid:ext:cls:ver"); + Artifact sub = new SubArtifact(main, "", "pom"); + assertEquals("", sub.getClassifier()); + sub = new SubArtifact(main, null, "pom"); + assertEquals("", sub.getClassifier()); } @Test - public void testEmptyExtension() - { - Artifact main = newMainArtifact( "gid:aid:ext:cls:ver" ); - Artifact sub = new SubArtifact( main, "tests", "" ); - assertEquals( "", sub.getExtension() ); - sub = new SubArtifact( main, "tests", null ); - assertEquals( "", sub.getExtension() ); + public void testEmptyExtension() { + Artifact main = newMainArtifact("gid:aid:ext:cls:ver"); + Artifact sub = new SubArtifact(main, "tests", ""); + assertEquals("", sub.getExtension()); + sub = new SubArtifact(main, "tests", null); + assertEquals("", sub.getExtension()); } @Test - public void testSameClassifier() - { - Artifact main = newMainArtifact( "gid:aid:ext:cls:ver" ); - Artifact sub = new SubArtifact( main, "*", "pom" ); - assertEquals( "cls", sub.getClassifier() ); + public void testSameClassifier() { + Artifact main = newMainArtifact("gid:aid:ext:cls:ver"); + Artifact sub = new SubArtifact(main, "*", "pom"); + assertEquals("cls", sub.getClassifier()); } @Test - public void testSameExtension() - { - Artifact main = newMainArtifact( "gid:aid:ext:cls:ver" ); - Artifact sub = new SubArtifact( main, "tests", "*" ); - assertEquals( "ext", sub.getExtension() ); + public void testSameExtension() { + Artifact main = newMainArtifact("gid:aid:ext:cls:ver"); + Artifact sub = new SubArtifact(main, "tests", "*"); + assertEquals("ext", sub.getExtension()); } @Test - public void testDerivedClassifier() - { - Artifact main = newMainArtifact( "gid:aid:ext:cls:ver" ); - Artifact sub = new SubArtifact( main, "*-tests", "pom" ); - assertEquals( "cls-tests", sub.getClassifier() ); - sub = new SubArtifact( main, "tests-*", "pom" ); - assertEquals( "tests-cls", sub.getClassifier() ); - - main = newMainArtifact( "gid:aid:ext:ver" ); - sub = new SubArtifact( main, "*-tests", "pom" ); - assertEquals( "tests", sub.getClassifier() ); - sub = new SubArtifact( main, "tests-*", "pom" ); - assertEquals( "tests", sub.getClassifier() ); + public void testDerivedClassifier() { + Artifact main = newMainArtifact("gid:aid:ext:cls:ver"); + Artifact sub = new SubArtifact(main, "*-tests", "pom"); + assertEquals("cls-tests", sub.getClassifier()); + sub = new SubArtifact(main, "tests-*", "pom"); + assertEquals("tests-cls", sub.getClassifier()); + + main = newMainArtifact("gid:aid:ext:ver"); + sub = new SubArtifact(main, "*-tests", "pom"); + assertEquals("tests", sub.getClassifier()); + sub = new SubArtifact(main, "tests-*", "pom"); + assertEquals("tests", sub.getClassifier()); } @Test - public void testDerivedExtension() - { - Artifact main = newMainArtifact( "gid:aid:ext:cls:ver" ); - Artifact sub = new SubArtifact( main, "", "*.asc" ); - assertEquals( "ext.asc", sub.getExtension() ); - sub = new SubArtifact( main, "", "asc.*" ); - assertEquals( "asc.ext", sub.getExtension() ); + public void testDerivedExtension() { + Artifact main = newMainArtifact("gid:aid:ext:cls:ver"); + Artifact sub = new SubArtifact(main, "", "*.asc"); + assertEquals("ext.asc", sub.getExtension()); + sub = new SubArtifact(main, "", "asc.*"); + assertEquals("asc.ext", sub.getExtension()); } @Test - public void testImmutability() - { - Artifact a = new SubArtifact( newMainArtifact( "gid:aid:ver" ), "", "pom" ); - assertNotSame( a, a.setFile( new File( "file" ) ) ); - assertNotSame( a, a.setVersion( "otherVersion" ) ); - assertNotSame( a, a.setProperties( Collections.singletonMap( "key", "value" ) ) ); + public void testImmutability() { + Artifact a = new SubArtifact(newMainArtifact("gid:aid:ver"), "", "pom"); + assertNotSame(a, a.setFile(new File("file"))); + assertNotSame(a, a.setVersion("otherVersion")); + assertNotSame(a, a.setProperties(Collections.singletonMap("key", "value"))); } @Test - public void testPropertiesCopied() - { + public void testPropertiesCopied() { Map props = new HashMap<>(); - props.put( "key", "value1" ); + props.put("key", "value1"); - Artifact a = new SubArtifact( newMainArtifact( "gid:aid:ver" ), "", "pom", props, null ); - assertEquals( "value1", a.getProperty( "key", null ) ); + Artifact a = new SubArtifact(newMainArtifact("gid:aid:ver"), "", "pom", props, null); + assertEquals("value1", a.getProperty("key", null)); props.clear(); - assertEquals( "value1", a.getProperty( "key", null ) ); + assertEquals("value1", a.getProperty("key", null)); - props.put( "key", "value2" ); - a = a.setProperties( props ); - assertEquals( "value2", a.getProperty( "key", null ) ); + props.put("key", "value2"); + a = a.setProperties(props); + assertEquals("value2", a.getProperty("key", null)); props.clear(); - assertEquals( "value2", a.getProperty( "key", null ) ); + assertEquals("value2", a.getProperty("key", null)); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/AbstractDependencyFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/AbstractDependencyFilterTest.java index f8bc5f4a2..d62b295e8 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/AbstractDependencyFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/AbstractDependencyFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.filter; import java.util.List; @@ -26,34 +25,25 @@ import static java.util.Objects.requireNonNull; -public abstract class AbstractDependencyFilterTest -{ +public abstract class AbstractDependencyFilterTest { - protected DependencyFilter getAcceptFilter() - { - return new DependencyFilter() - { + protected DependencyFilter getAcceptFilter() { + return new DependencyFilter() { - public boolean accept( DependencyNode node, List parents ) - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( parents, "parents cannot be null" ); + public boolean accept(DependencyNode node, List parents) { + requireNonNull(node, "node cannot be null"); + requireNonNull(parents, "parents cannot be null"); return true; } - }; } - protected DependencyFilter getDenyFilter() - { - return new DependencyFilter() - { + protected DependencyFilter getDenyFilter() { + return new DependencyFilter() { - public boolean accept( DependencyNode node, List parents ) - { + public boolean accept(DependencyNode node, List parents) { return false; } }; } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/AndDependencyFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/AndDependencyFilterTest.java index 7ddc666fe..2c01c8f44 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/AndDependencyFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/AndDependencyFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.filter; import java.util.Collection; import java.util.LinkedList; @@ -28,65 +25,62 @@ import org.eclipse.aether.graph.DependencyFilter; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.internal.test.util.NodeBuilder; -import org.eclipse.aether.util.filter.AndDependencyFilter; import org.junit.Test; -public class AndDependencyFilterTest - extends AbstractDependencyFilterTest -{ +import static org.junit.Assert.*; + +public class AndDependencyFilterTest extends AbstractDependencyFilterTest { @Test - public void acceptTest() - { + public void acceptTest() { NodeBuilder builder = new NodeBuilder(); - builder.artifactId( "test" ); + builder.artifactId("test"); List parents = new LinkedList<>(); // Empty AND - assertTrue( new AndDependencyFilter().accept( builder.build(), parents ) ); + assertTrue(new AndDependencyFilter().accept(builder.build(), parents)); // Basic Boolean Input - assertTrue( new AndDependencyFilter( getAcceptFilter() ).accept( builder.build(), parents ) ); - assertFalse( new AndDependencyFilter( getDenyFilter() ).accept( builder.build(), parents ) ); + assertTrue(new AndDependencyFilter(getAcceptFilter()).accept(builder.build(), parents)); + assertFalse(new AndDependencyFilter(getDenyFilter()).accept(builder.build(), parents)); - assertFalse( new AndDependencyFilter( getDenyFilter(), getDenyFilter() ).accept( builder.build(), parents ) ); - assertFalse( new AndDependencyFilter( getDenyFilter(), getAcceptFilter() ).accept( builder.build(), parents ) ); - assertFalse( new AndDependencyFilter( getAcceptFilter(), getDenyFilter() ).accept( builder.build(), parents ) ); - assertTrue( new AndDependencyFilter( getAcceptFilter(), getAcceptFilter() ).accept( builder.build(), parents ) ); + assertFalse(new AndDependencyFilter(getDenyFilter(), getDenyFilter()).accept(builder.build(), parents)); + assertFalse(new AndDependencyFilter(getDenyFilter(), getAcceptFilter()).accept(builder.build(), parents)); + assertFalse(new AndDependencyFilter(getAcceptFilter(), getDenyFilter()).accept(builder.build(), parents)); + assertTrue(new AndDependencyFilter(getAcceptFilter(), getAcceptFilter()).accept(builder.build(), parents)); - assertFalse( new AndDependencyFilter( getDenyFilter(), getDenyFilter(), getDenyFilter() ).accept( builder.build(), - parents ) ); - assertFalse( new AndDependencyFilter( getAcceptFilter(), getDenyFilter(), getDenyFilter() ).accept( builder.build(), - parents ) ); - assertFalse( new AndDependencyFilter( getAcceptFilter(), getAcceptFilter(), getDenyFilter() ).accept( builder.build(), - parents ) ); - assertTrue( new AndDependencyFilter( getAcceptFilter(), getAcceptFilter(), getAcceptFilter() ).accept( builder.build(), - parents ) ); + assertFalse(new AndDependencyFilter(getDenyFilter(), getDenyFilter(), getDenyFilter()) + .accept(builder.build(), parents)); + assertFalse(new AndDependencyFilter(getAcceptFilter(), getDenyFilter(), getDenyFilter()) + .accept(builder.build(), parents)); + assertFalse(new AndDependencyFilter(getAcceptFilter(), getAcceptFilter(), getDenyFilter()) + .accept(builder.build(), parents)); + assertTrue(new AndDependencyFilter(getAcceptFilter(), getAcceptFilter(), getAcceptFilter()) + .accept(builder.build(), parents)); // User another constructor Collection filters = new LinkedList<>(); - filters.add( getDenyFilter() ); - filters.add( getAcceptFilter() ); - assertFalse( new AndDependencyFilter( filters ).accept( builder.build(), parents ) ); + filters.add(getDenyFilter()); + filters.add(getAcceptFilter()); + assertFalse(new AndDependencyFilter(filters).accept(builder.build(), parents)); filters = new LinkedList<>(); - filters.add( getDenyFilter() ); - filters.add( getDenyFilter() ); - assertFalse( new AndDependencyFilter( filters ).accept( builder.build(), parents ) ); + filters.add(getDenyFilter()); + filters.add(getDenyFilter()); + assertFalse(new AndDependencyFilter(filters).accept(builder.build(), parents)); filters = new LinkedList<>(); - filters.add( getAcceptFilter() ); - filters.add( getAcceptFilter() ); - assertTrue( new AndDependencyFilter( filters ).accept( builder.build(), parents ) ); + filters.add(getAcceptFilter()); + filters.add(getAcceptFilter()); + assertTrue(new AndDependencyFilter(filters).accept(builder.build(), parents)); // newInstance - assertTrue( AndDependencyFilter.newInstance( getAcceptFilter(), getAcceptFilter() ).accept( builder.build(), - parents ) ); - assertFalse( AndDependencyFilter.newInstance( getAcceptFilter(), getDenyFilter() ).accept( builder.build(), - parents ) ); + assertTrue(AndDependencyFilter.newInstance(getAcceptFilter(), getAcceptFilter()) + .accept(builder.build(), parents)); + assertFalse(AndDependencyFilter.newInstance(getAcceptFilter(), getDenyFilter()) + .accept(builder.build(), parents)); - assertFalse( AndDependencyFilter.newInstance( getDenyFilter(), null ).accept( builder.build(), parents ) ); - assertTrue( AndDependencyFilter.newInstance( getAcceptFilter(), null ).accept( builder.build(), parents ) ); - assertNull( AndDependencyFilter.newInstance( null, null ) ); + assertFalse(AndDependencyFilter.newInstance(getDenyFilter(), null).accept(builder.build(), parents)); + assertTrue(AndDependencyFilter.newInstance(getAcceptFilter(), null).accept(builder.build(), parents)); + assertNull(AndDependencyFilter.newInstance(null, null)); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/DependencyFilterUtilsTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/DependencyFilterUtilsTest.java index 28bde572f..7b6d78e10 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/DependencyFilterUtilsTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/DependencyFilterUtilsTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.filter; import java.util.Collections; import java.util.List; @@ -27,115 +24,106 @@ import org.eclipse.aether.graph.DependencyFilter; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.internal.test.util.NodeBuilder; -import org.eclipse.aether.util.filter.DependencyFilterUtils; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DependencyFilterUtilsTest -{ +public class DependencyFilterUtilsTest { private static List PARENTS = Collections.emptyList(); @Test - public void testClasspathFilterCompile() - { - NodeBuilder builder = new NodeBuilder().artifactId( "aid" ); - DependencyFilter filter = DependencyFilterUtils.classpathFilter( "compile" ); - - assertTrue( filter.accept( builder.scope( "compile" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "system" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "provided" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "runtime" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "test" ).build(), PARENTS ) ); + public void testClasspathFilterCompile() { + NodeBuilder builder = new NodeBuilder().artifactId("aid"); + DependencyFilter filter = DependencyFilterUtils.classpathFilter("compile"); + + assertTrue(filter.accept(builder.scope("compile").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("system").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("provided").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("runtime").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("test").build(), PARENTS)); } @Test - public void testClasspathFilterRuntime() - { - NodeBuilder builder = new NodeBuilder().artifactId( "aid" ); - DependencyFilter filter = DependencyFilterUtils.classpathFilter( "runtime" ); - - assertTrue( filter.accept( builder.scope( "compile" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "system" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "provided" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "runtime" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "test" ).build(), PARENTS ) ); + public void testClasspathFilterRuntime() { + NodeBuilder builder = new NodeBuilder().artifactId("aid"); + DependencyFilter filter = DependencyFilterUtils.classpathFilter("runtime"); + + assertTrue(filter.accept(builder.scope("compile").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("system").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("provided").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("runtime").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("test").build(), PARENTS)); } @Test - public void testClasspathFilterTest() - { - NodeBuilder builder = new NodeBuilder().artifactId( "aid" ); - DependencyFilter filter = DependencyFilterUtils.classpathFilter( "test" ); - - assertTrue( filter.accept( builder.scope( "compile" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "system" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "provided" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "runtime" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "test" ).build(), PARENTS ) ); + public void testClasspathFilterTest() { + NodeBuilder builder = new NodeBuilder().artifactId("aid"); + DependencyFilter filter = DependencyFilterUtils.classpathFilter("test"); + + assertTrue(filter.accept(builder.scope("compile").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("system").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("provided").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("runtime").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("test").build(), PARENTS)); } @Test - public void testClasspathFilterCompileRuntime() - { - NodeBuilder builder = new NodeBuilder().artifactId( "aid" ); - DependencyFilter filter = DependencyFilterUtils.classpathFilter( "compile", "runtime" ); - - assertTrue( filter.accept( builder.scope( "compile" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "system" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "provided" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "runtime" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "test" ).build(), PARENTS ) ); + public void testClasspathFilterCompileRuntime() { + NodeBuilder builder = new NodeBuilder().artifactId("aid"); + DependencyFilter filter = DependencyFilterUtils.classpathFilter("compile", "runtime"); + + assertTrue(filter.accept(builder.scope("compile").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("system").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("provided").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("runtime").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("test").build(), PARENTS)); } @Test - public void testClasspathFilterCompilePlusRuntime() - { - NodeBuilder builder = new NodeBuilder().artifactId( "aid" ); - DependencyFilter filter = DependencyFilterUtils.classpathFilter( "compile+runtime" ); - - assertTrue( filter.accept( builder.scope( "compile" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "system" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "provided" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "runtime" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "test" ).build(), PARENTS ) ); + public void testClasspathFilterCompilePlusRuntime() { + NodeBuilder builder = new NodeBuilder().artifactId("aid"); + DependencyFilter filter = DependencyFilterUtils.classpathFilter("compile+runtime"); + + assertTrue(filter.accept(builder.scope("compile").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("system").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("provided").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("runtime").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("test").build(), PARENTS)); } @Test - public void testClasspathFilterRuntimeCommaSystem() - { - NodeBuilder builder = new NodeBuilder().artifactId( "aid" ); - DependencyFilter filter = DependencyFilterUtils.classpathFilter( "runtime,system" ); - - assertTrue( filter.accept( builder.scope( "compile" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "system" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "provided" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "runtime" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "test" ).build(), PARENTS ) ); + public void testClasspathFilterRuntimeCommaSystem() { + NodeBuilder builder = new NodeBuilder().artifactId("aid"); + DependencyFilter filter = DependencyFilterUtils.classpathFilter("runtime,system"); + + assertTrue(filter.accept(builder.scope("compile").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("system").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("provided").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("runtime").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("test").build(), PARENTS)); } @Test - public void testClasspathFilterNull() - { - NodeBuilder builder = new NodeBuilder().artifactId( "aid" ); - DependencyFilter filter = DependencyFilterUtils.classpathFilter( (String[]) null ); - - assertFalse( filter.accept( builder.scope( "compile" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "system" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "provided" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "runtime" ).build(), PARENTS ) ); - assertFalse( filter.accept( builder.scope( "test" ).build(), PARENTS ) ); + public void testClasspathFilterNull() { + NodeBuilder builder = new NodeBuilder().artifactId("aid"); + DependencyFilter filter = DependencyFilterUtils.classpathFilter((String[]) null); + + assertFalse(filter.accept(builder.scope("compile").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("system").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("provided").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("runtime").build(), PARENTS)); + assertFalse(filter.accept(builder.scope("test").build(), PARENTS)); } @Test - public void testClasspathFilterUnknownScope() - { - NodeBuilder builder = new NodeBuilder().artifactId( "aid" ); - DependencyFilter filter = DependencyFilterUtils.classpathFilter( "compile" ); + public void testClasspathFilterUnknownScope() { + NodeBuilder builder = new NodeBuilder().artifactId("aid"); + DependencyFilter filter = DependencyFilterUtils.classpathFilter("compile"); - assertTrue( filter.accept( builder.scope( "" ).build(), PARENTS ) ); - assertTrue( filter.accept( builder.scope( "unknown" ).build(), PARENTS ) ); + assertTrue(filter.accept(builder.scope("").build(), PARENTS)); + assertTrue(filter.accept(builder.scope("unknown").build(), PARENTS)); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/ExclusionDependencyFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/ExclusionDependencyFilterTest.java index 37fca1069..d2bc3b6d4 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/ExclusionDependencyFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/ExclusionDependencyFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.filter; import java.util.Arrays; import java.util.LinkedList; @@ -27,33 +24,32 @@ import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.internal.test.util.NodeBuilder; -import org.eclipse.aether.util.filter.ExclusionsDependencyFilter; import org.junit.Test; -public class ExclusionDependencyFilterTest -{ +import static org.junit.Assert.*; + +public class ExclusionDependencyFilterTest { @Test - public void acceptTest() - { + public void acceptTest() { NodeBuilder builder = new NodeBuilder(); - builder.groupId( "com.example.test" ).artifactId( "testArtifact" ); + builder.groupId("com.example.test").artifactId("testArtifact"); List parents = new LinkedList<>(); String[] excludes; - excludes = new String[] { "com.example.test:testArtifact" }; - assertFalse( new ExclusionsDependencyFilter( Arrays.asList( excludes ) ).accept( builder.build(), parents ) ); + excludes = new String[] {"com.example.test:testArtifact"}; + assertFalse(new ExclusionsDependencyFilter(Arrays.asList(excludes)).accept(builder.build(), parents)); - excludes = new String[] { "com.example.test:testArtifact", "com.foo:otherArtifact" }; - assertFalse( new ExclusionsDependencyFilter( Arrays.asList( excludes ) ).accept( builder.build(), parents ) ); + excludes = new String[] {"com.example.test:testArtifact", "com.foo:otherArtifact"}; + assertFalse(new ExclusionsDependencyFilter(Arrays.asList(excludes)).accept(builder.build(), parents)); - excludes = new String[] { "testArtifact" }; - assertFalse( new ExclusionsDependencyFilter( Arrays.asList( excludes ) ).accept( builder.build(), parents ) ); + excludes = new String[] {"testArtifact"}; + assertFalse(new ExclusionsDependencyFilter(Arrays.asList(excludes)).accept(builder.build(), parents)); - excludes = new String[] { "otherArtifact" }; - assertTrue( new ExclusionsDependencyFilter( Arrays.asList( excludes ) ).accept( builder.build(), parents ) ); + excludes = new String[] {"otherArtifact"}; + assertTrue(new ExclusionsDependencyFilter(Arrays.asList(excludes)).accept(builder.build(), parents)); - assertTrue( new ExclusionsDependencyFilter( null ).accept( builder.build(), parents ) ); + assertTrue(new ExclusionsDependencyFilter(null).accept(builder.build(), parents)); } } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/OrDependencyFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/OrDependencyFilterTest.java index a9f0774e3..9a93b7452 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/OrDependencyFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/OrDependencyFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.filter; import java.util.Collection; import java.util.LinkedList; @@ -28,60 +25,56 @@ import org.eclipse.aether.graph.DependencyFilter; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.internal.test.util.NodeBuilder; -import org.eclipse.aether.util.filter.AndDependencyFilter; -import org.eclipse.aether.util.filter.OrDependencyFilter; import org.junit.Test; -public class OrDependencyFilterTest - extends AbstractDependencyFilterTest -{ +import static org.junit.Assert.*; + +public class OrDependencyFilterTest extends AbstractDependencyFilterTest { @Test - public void acceptTest() - { + public void acceptTest() { NodeBuilder builder = new NodeBuilder(); - builder.artifactId( "test" ); + builder.artifactId("test"); List parents = new LinkedList<>(); // Empty OR - assertFalse( new OrDependencyFilter().accept( builder.build(), parents ) ); + assertFalse(new OrDependencyFilter().accept(builder.build(), parents)); // Basic Boolean Input - assertTrue( new OrDependencyFilter( getAcceptFilter() ).accept( builder.build(), parents ) ); - assertFalse( new OrDependencyFilter( getDenyFilter() ).accept( builder.build(), parents ) ); + assertTrue(new OrDependencyFilter(getAcceptFilter()).accept(builder.build(), parents)); + assertFalse(new OrDependencyFilter(getDenyFilter()).accept(builder.build(), parents)); - assertFalse( new OrDependencyFilter( getDenyFilter(), getDenyFilter() ).accept( builder.build(), parents ) ); - assertTrue( new OrDependencyFilter( getDenyFilter(), getAcceptFilter() ).accept( builder.build(), parents ) ); - assertTrue( new OrDependencyFilter( getAcceptFilter(), getDenyFilter() ).accept( builder.build(), parents ) ); - assertTrue( new OrDependencyFilter( getAcceptFilter(), getAcceptFilter() ).accept( builder.build(), parents ) ); + assertFalse(new OrDependencyFilter(getDenyFilter(), getDenyFilter()).accept(builder.build(), parents)); + assertTrue(new OrDependencyFilter(getDenyFilter(), getAcceptFilter()).accept(builder.build(), parents)); + assertTrue(new OrDependencyFilter(getAcceptFilter(), getDenyFilter()).accept(builder.build(), parents)); + assertTrue(new OrDependencyFilter(getAcceptFilter(), getAcceptFilter()).accept(builder.build(), parents)); - assertFalse( new OrDependencyFilter( getDenyFilter(), getDenyFilter(), getDenyFilter() ).accept( builder.build(), - parents ) ); - assertTrue( new OrDependencyFilter( getAcceptFilter(), getDenyFilter(), getDenyFilter() ).accept( builder.build(), - parents ) ); - assertTrue( new OrDependencyFilter( getAcceptFilter(), getAcceptFilter(), getDenyFilter() ).accept( builder.build(), - parents ) ); - assertTrue( new OrDependencyFilter( getAcceptFilter(), getAcceptFilter(), getAcceptFilter() ).accept( builder.build(), - parents ) ); + assertFalse(new OrDependencyFilter(getDenyFilter(), getDenyFilter(), getDenyFilter()) + .accept(builder.build(), parents)); + assertTrue(new OrDependencyFilter(getAcceptFilter(), getDenyFilter(), getDenyFilter()) + .accept(builder.build(), parents)); + assertTrue(new OrDependencyFilter(getAcceptFilter(), getAcceptFilter(), getDenyFilter()) + .accept(builder.build(), parents)); + assertTrue(new OrDependencyFilter(getAcceptFilter(), getAcceptFilter(), getAcceptFilter()) + .accept(builder.build(), parents)); // User another constructor Collection filters = new LinkedList<>(); - filters.add( getDenyFilter() ); - filters.add( getAcceptFilter() ); - assertTrue( new OrDependencyFilter( filters ).accept( builder.build(), parents ) ); + filters.add(getDenyFilter()); + filters.add(getAcceptFilter()); + assertTrue(new OrDependencyFilter(filters).accept(builder.build(), parents)); filters = new LinkedList<>(); - filters.add( getDenyFilter() ); - filters.add( getDenyFilter() ); - assertFalse( new OrDependencyFilter( filters ).accept( builder.build(), parents ) ); + filters.add(getDenyFilter()); + filters.add(getDenyFilter()); + assertFalse(new OrDependencyFilter(filters).accept(builder.build(), parents)); // newInstance - assertTrue( AndDependencyFilter.newInstance( getAcceptFilter(), getAcceptFilter() ).accept( builder.build(), - parents ) ); - assertFalse( AndDependencyFilter.newInstance( getAcceptFilter(), getDenyFilter() ).accept( builder.build(), - parents ) ); - assertTrue( AndDependencyFilter.newInstance( getAcceptFilter(), null ).accept( builder.build(), parents ) ); - assertFalse( AndDependencyFilter.newInstance( getDenyFilter(), null ).accept( builder.build(), parents ) ); - assertNull( AndDependencyFilter.newInstance( null, null ) ); + assertTrue(AndDependencyFilter.newInstance(getAcceptFilter(), getAcceptFilter()) + .accept(builder.build(), parents)); + assertFalse(AndDependencyFilter.newInstance(getAcceptFilter(), getDenyFilter()) + .accept(builder.build(), parents)); + assertTrue(AndDependencyFilter.newInstance(getAcceptFilter(), null).accept(builder.build(), parents)); + assertFalse(AndDependencyFilter.newInstance(getDenyFilter(), null).accept(builder.build(), parents)); + assertNull(AndDependencyFilter.newInstance(null, null)); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/PatternExclusionsDependencyFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/PatternExclusionsDependencyFilterTest.java index 429668258..3a716b390 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/PatternExclusionsDependencyFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/PatternExclusionsDependencyFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,154 +16,172 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.filter; import java.util.LinkedList; import java.util.List; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.internal.test.util.NodeBuilder; -import org.eclipse.aether.util.filter.PatternExclusionsDependencyFilter; import org.eclipse.aether.util.version.GenericVersionScheme; import org.eclipse.aether.version.VersionScheme; import org.junit.Test; -public class PatternExclusionsDependencyFilterTest -{ +import static org.junit.Assert.*; + +public class PatternExclusionsDependencyFilterTest { @Test - public void acceptTestCornerCases() - { + public void acceptTestCornerCases() { NodeBuilder builder = new NodeBuilder(); - builder.artifactId( "testArtifact" ); + builder.artifactId("testArtifact"); DependencyNode node = builder.build(); List parents = new LinkedList<>(); // Empty String, Empty List - assertTrue( dontAccept( node, "" ) ); - assertTrue( new PatternExclusionsDependencyFilter( new LinkedList() ).accept( node, parents ) ); - assertTrue( new PatternExclusionsDependencyFilter( (String[]) null ).accept( node, parents ) ); - assertTrue( new PatternExclusionsDependencyFilter( (VersionScheme) null, "[1,10]" ).accept( node, parents ) ); + assertTrue(dontAccept(node, "")); + assertTrue(new PatternExclusionsDependencyFilter(new LinkedList()).accept(node, parents)); + assertTrue(new PatternExclusionsDependencyFilter((String[]) null).accept(node, parents)); + assertTrue(new PatternExclusionsDependencyFilter((VersionScheme) null, "[1,10]").accept(node, parents)); } @Test - public void acceptTestMatches() - { + public void acceptTestMatches() { NodeBuilder builder = new NodeBuilder(); - builder.groupId( "com.example.test" ).artifactId( "testArtifact" ).ext( "jar" ).version( "1.0.3" ); + builder.groupId("com.example.test") + .artifactId("testArtifact") + .ext("jar") + .version("1.0.3"); DependencyNode node = builder.build(); // full match - assertTrue( "com.example.test:testArtifact:jar:1.0.3", dontAccept( node, "com.example.test:testArtifact:jar:1.0.3" ) ); + assertTrue( + "com.example.test:testArtifact:jar:1.0.3", dontAccept(node, "com.example.test:testArtifact:jar:1.0.3")); // single wildcard - assertTrue( "*:testArtifact:jar:1.0.3", dontAccept( node, "*:testArtifact:jar:1.0.3" ) ); - assertTrue( "com.example.test:*:jar:1.0.3", dontAccept( node, "com.example.test:*:jar:1.0.3" ) ); - assertTrue( "com.example.test:testArtifact:*:1.0.3", dontAccept( node, "com.example.test:testArtifact:*:1.0.3" ) ); - assertTrue( "com.example.test:testArtifact:*:1.0.3", dontAccept( node, "com.example.test:testArtifact:*:1.0.3" ) ); + assertTrue("*:testArtifact:jar:1.0.3", dontAccept(node, "*:testArtifact:jar:1.0.3")); + assertTrue("com.example.test:*:jar:1.0.3", dontAccept(node, "com.example.test:*:jar:1.0.3")); + assertTrue("com.example.test:testArtifact:*:1.0.3", dontAccept(node, "com.example.test:testArtifact:*:1.0.3")); + assertTrue("com.example.test:testArtifact:*:1.0.3", dontAccept(node, "com.example.test:testArtifact:*:1.0.3")); // implicit wildcard - assertTrue( ":testArtifact:jar:1.0.3", dontAccept( node, ":testArtifact:jar:1.0.3" ) ); - assertTrue( "com.example.test::jar:1.0.3", dontAccept( node, "com.example.test::jar:1.0.3" ) ); - assertTrue( "com.example.test:testArtifact::1.0.3", dontAccept( node, "com.example.test:testArtifact::1.0.3" ) ); - assertTrue( "com.example.test:testArtifact:jar:", dontAccept( node, "com.example.test:testArtifact:jar:" ) ); + assertTrue(":testArtifact:jar:1.0.3", dontAccept(node, ":testArtifact:jar:1.0.3")); + assertTrue("com.example.test::jar:1.0.3", dontAccept(node, "com.example.test::jar:1.0.3")); + assertTrue("com.example.test:testArtifact::1.0.3", dontAccept(node, "com.example.test:testArtifact::1.0.3")); + assertTrue("com.example.test:testArtifact:jar:", dontAccept(node, "com.example.test:testArtifact:jar:")); // multi wildcards - assertTrue( "*:*:jar:1.0.3", dontAccept( node, "*:*:jar:1.0.3" ) ); - assertTrue( "com.example.test:*:*:1.0.3", dontAccept( node, "com.example.test:*:*:1.0.3" ) ); - assertTrue( "com.example.test:testArtifact:*:*", dontAccept( node, "com.example.test:testArtifact:*:*" ) ); - assertTrue( "*:testArtifact:jar:*", dontAccept( node, "*:testArtifact:jar:*" ) ); - assertTrue( "*:*:jar:*", dontAccept( node, "*:*:jar:*" ) ); - assertTrue( ":*:jar:", dontAccept( node, ":*:jar:" ) ); + assertTrue("*:*:jar:1.0.3", dontAccept(node, "*:*:jar:1.0.3")); + assertTrue("com.example.test:*:*:1.0.3", dontAccept(node, "com.example.test:*:*:1.0.3")); + assertTrue("com.example.test:testArtifact:*:*", dontAccept(node, "com.example.test:testArtifact:*:*")); + assertTrue("*:testArtifact:jar:*", dontAccept(node, "*:testArtifact:jar:*")); + assertTrue("*:*:jar:*", dontAccept(node, "*:*:jar:*")); + assertTrue(":*:jar:", dontAccept(node, ":*:jar:")); // partial wildcards - assertTrue( "*.example.test:testArtifact:jar:1.0.3", dontAccept( node, "*.example.test:testArtifact:jar:1.0.3" ) ); - assertTrue( "com.example.test:testArtifact:*ar:1.0.*", dontAccept( node, "com.example.test:testArtifact:*ar:1.0.*" ) ); - assertTrue( "com.example.test:testArtifact:jar:1.0.*", dontAccept( node, "com.example.test:testArtifact:jar:1.0.*" ) ); - assertTrue( "*.example.*:testArtifact:jar:1.0.3", dontAccept( node, "*.example.*:testArtifact:jar:1.0.3" ) ); + assertTrue("*.example.test:testArtifact:jar:1.0.3", dontAccept(node, "*.example.test:testArtifact:jar:1.0.3")); + assertTrue( + "com.example.test:testArtifact:*ar:1.0.*", dontAccept(node, "com.example.test:testArtifact:*ar:1.0.*")); + assertTrue( + "com.example.test:testArtifact:jar:1.0.*", dontAccept(node, "com.example.test:testArtifact:jar:1.0.*")); + assertTrue("*.example.*:testArtifact:jar:1.0.3", dontAccept(node, "*.example.*:testArtifact:jar:1.0.3")); // wildcard as empty string - assertTrue( "com.example.test*:testArtifact:jar:1.0.3", dontAccept( node, "com.example.test*:testArtifact:jar:1.0.3" ) ); + assertTrue( + "com.example.test*:testArtifact:jar:1.0.3", + dontAccept(node, "com.example.test*:testArtifact:jar:1.0.3")); } @Test - public void acceptTestLessToken() - { + public void acceptTestLessToken() { NodeBuilder builder = new NodeBuilder(); - builder.groupId( "com.example.test" ).artifactId( "testArtifact" ).ext( "jar" ).version( "1.0.3" ); + builder.groupId("com.example.test") + .artifactId("testArtifact") + .ext("jar") + .version("1.0.3"); DependencyNode node = builder.build(); - assertTrue( "com.example.test:testArtifact:jar", dontAccept( node, "com.example.test:testArtifact:jar" ) ); - assertTrue( "com.example.test:testArtifact", dontAccept( node, "com.example.test:testArtifact" ) ); - assertTrue( "com.example.test", dontAccept( node, "com.example.test" ) ); + assertTrue("com.example.test:testArtifact:jar", dontAccept(node, "com.example.test:testArtifact:jar")); + assertTrue("com.example.test:testArtifact", dontAccept(node, "com.example.test:testArtifact")); + assertTrue("com.example.test", dontAccept(node, "com.example.test")); - assertFalse( "com.example.foo", dontAccept( node, "com.example.foo" ) ); + assertFalse("com.example.foo", dontAccept(node, "com.example.foo")); } @Test - public void acceptTestMissmatch() - { + public void acceptTestMissmatch() { NodeBuilder builder = new NodeBuilder(); - builder.groupId( "com.example.test" ).artifactId( "testArtifact" ).ext( "jar" ).version( "1.0.3" ); + builder.groupId("com.example.test") + .artifactId("testArtifact") + .ext("jar") + .version("1.0.3"); DependencyNode node = builder.build(); - assertFalse( "OTHER.GROUP.ID:testArtifact:jar:1.0.3", dontAccept( node, "OTHER.GROUP.ID:testArtifact:jar:1.0.3" ) ); - assertFalse( "com.example.test:OTHER_ARTIFACT:jar:1.0.3", dontAccept( node, "com.example.test:OTHER_ARTIFACT:jar:1.0.3" ) ); - assertFalse( "com.example.test:OTHER_ARTIFACT:jar:1.0.3", dontAccept( node, "com.example.test:OTHER_ARTIFACT:jar:1.0.3" ) ); - assertFalse( "com.example.test:testArtifact:WAR:1.0.3", dontAccept( node, "com.example.test:testArtifact:WAR:1.0.3" ) ); - assertFalse( "com.example.test:testArtifact:jar:SNAPSHOT", dontAccept( node, "com.example.test:testArtifact:jar:SNAPSHOT" ) ); - - assertFalse( "*:*:war:*", dontAccept( node, "*:*:war:*" ) ); - assertFalse( "OTHER.GROUP.ID", dontAccept( node, "OTHER.GROUP.ID" ) ); + assertFalse("OTHER.GROUP.ID:testArtifact:jar:1.0.3", dontAccept(node, "OTHER.GROUP.ID:testArtifact:jar:1.0.3")); + assertFalse( + "com.example.test:OTHER_ARTIFACT:jar:1.0.3", + dontAccept(node, "com.example.test:OTHER_ARTIFACT:jar:1.0.3")); + assertFalse( + "com.example.test:OTHER_ARTIFACT:jar:1.0.3", + dontAccept(node, "com.example.test:OTHER_ARTIFACT:jar:1.0.3")); + assertFalse( + "com.example.test:testArtifact:WAR:1.0.3", dontAccept(node, "com.example.test:testArtifact:WAR:1.0.3")); + assertFalse( + "com.example.test:testArtifact:jar:SNAPSHOT", + dontAccept(node, "com.example.test:testArtifact:jar:SNAPSHOT")); + + assertFalse("*:*:war:*", dontAccept(node, "*:*:war:*")); + assertFalse("OTHER.GROUP.ID", dontAccept(node, "OTHER.GROUP.ID")); } @Test - public void acceptTestMoreToken() - { + public void acceptTestMoreToken() { NodeBuilder builder = new NodeBuilder(); - builder.groupId( "com.example.test" ).artifactId( "testArtifact" ).ext( "jar" ).version( "1.0.3" ); + builder.groupId("com.example.test") + .artifactId("testArtifact") + .ext("jar") + .version("1.0.3"); DependencyNode node = builder.build(); - assertFalse( "com.example.test:testArtifact:jar:1.0.3:foo", dontAccept( node, "com.example.test:testArtifact:jar:1.0.3:foo" ) ); + assertFalse( + "com.example.test:testArtifact:jar:1.0.3:foo", + dontAccept(node, "com.example.test:testArtifact:jar:1.0.3:foo")); } @Test - public void acceptTestRange() - { + public void acceptTestRange() { NodeBuilder builder = new NodeBuilder(); - builder.groupId( "com.example.test" ).artifactId( "testArtifact" ).ext( "jar" ).version( "1.0.3" ); + builder.groupId("com.example.test") + .artifactId("testArtifact") + .ext("jar") + .version("1.0.3"); DependencyNode node = builder.build(); String prefix = "com.example.test:testArtifact:jar:"; - assertTrue( prefix + "[1.0.3,1.0.4)", dontAcceptVersionRange( node, prefix + "[1.0.3,1.0.4)" ) ); - assertTrue( prefix + "[1.0.3,)", dontAcceptVersionRange( node, prefix + "[1.0.3,)" ) ); - assertTrue( prefix + "[1.0.3,]", dontAcceptVersionRange( node, prefix + "[1.0.3,]" ) ); - assertTrue( prefix + "(,1.0.3]", dontAcceptVersionRange( node, prefix + "(,1.0.3]" ) ); - assertTrue( prefix + "[1.0,]", dontAcceptVersionRange( node, prefix + "[1.0,]" ) ); - assertTrue( prefix + "[1,4]", dontAcceptVersionRange( node, prefix + "[1,4]" ) ); - assertTrue( prefix + "(1,4)", dontAcceptVersionRange( node, prefix + "(1,4)" ) ); + assertTrue(prefix + "[1.0.3,1.0.4)", dontAcceptVersionRange(node, prefix + "[1.0.3,1.0.4)")); + assertTrue(prefix + "[1.0.3,)", dontAcceptVersionRange(node, prefix + "[1.0.3,)")); + assertTrue(prefix + "[1.0.3,]", dontAcceptVersionRange(node, prefix + "[1.0.3,]")); + assertTrue(prefix + "(,1.0.3]", dontAcceptVersionRange(node, prefix + "(,1.0.3]")); + assertTrue(prefix + "[1.0,]", dontAcceptVersionRange(node, prefix + "[1.0,]")); + assertTrue(prefix + "[1,4]", dontAcceptVersionRange(node, prefix + "[1,4]")); + assertTrue(prefix + "(1,4)", dontAcceptVersionRange(node, prefix + "(1,4)")); - assertTrue( prefix + "(1.0.2,1.0.3]", - dontAcceptVersionRange( node, prefix + "(1.0.2,1.0.3]", prefix + "(1.1,)" ) ); + assertTrue(prefix + "(1.0.2,1.0.3]", dontAcceptVersionRange(node, prefix + "(1.0.2,1.0.3]", prefix + "(1.1,)")); - assertFalse( prefix + "(1.0.3,2.0]", dontAcceptVersionRange( node, prefix + "(1.0.3,2.0]" ) ); - assertFalse( prefix + "(1,1.0.2]", dontAcceptVersionRange( node, prefix + "(1,1.0.2]" ) ); + assertFalse(prefix + "(1.0.3,2.0]", dontAcceptVersionRange(node, prefix + "(1.0.3,2.0]")); + assertFalse(prefix + "(1,1.0.2]", dontAcceptVersionRange(node, prefix + "(1,1.0.2]")); - assertFalse( prefix + "(1.0.2,1.0.3)", - dontAcceptVersionRange( node, prefix + "(1.0.2,1.0.3)", prefix + "(1.0.3,)" ) ); + assertFalse( + prefix + "(1.0.2,1.0.3)", dontAcceptVersionRange(node, prefix + "(1.0.2,1.0.3)", prefix + "(1.0.3,)")); } - private boolean dontAccept( DependencyNode node, String expression ) - { - return !new PatternExclusionsDependencyFilter( expression ).accept( node, new LinkedList() ); + private boolean dontAccept(DependencyNode node, String expression) { + return !new PatternExclusionsDependencyFilter(expression).accept(node, new LinkedList()); } - private boolean dontAcceptVersionRange( DependencyNode node, String... expression ) - { - return !new PatternExclusionsDependencyFilter( new GenericVersionScheme(), expression ).accept( node, - new LinkedList() ); + private boolean dontAcceptVersionRange(DependencyNode node, String... expression) { + return !new PatternExclusionsDependencyFilter(new GenericVersionScheme(), expression) + .accept(node, new LinkedList()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/PatternInclusionsDependencyFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/PatternInclusionsDependencyFilterTest.java index 50c8b8a5b..3117a24ad 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/PatternInclusionsDependencyFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/PatternInclusionsDependencyFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,153 +16,164 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.filter; import java.util.LinkedList; import java.util.List; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.internal.test.util.NodeBuilder; -import org.eclipse.aether.util.filter.PatternInclusionsDependencyFilter; import org.eclipse.aether.util.version.GenericVersionScheme; import org.eclipse.aether.version.VersionScheme; import org.junit.Test; -public class PatternInclusionsDependencyFilterTest - extends AbstractDependencyFilterTest -{ +import static org.junit.Assert.*; + +public class PatternInclusionsDependencyFilterTest extends AbstractDependencyFilterTest { @Test - public void acceptTestCornerCases() - { + public void acceptTestCornerCases() { NodeBuilder builder = new NodeBuilder(); - builder.artifactId( "testArtifact" ); + builder.artifactId("testArtifact"); DependencyNode node = builder.build(); List parents = new LinkedList<>(); // Empty String, Empty List - assertTrue( accept( node, "" ) ); - assertFalse( new PatternInclusionsDependencyFilter( new LinkedList() ).accept( node, parents ) ); - assertFalse( new PatternInclusionsDependencyFilter( (String[]) null ).accept( node, parents ) ); - assertFalse( new PatternInclusionsDependencyFilter( (VersionScheme) null, "[1,10]" ).accept( node, parents ) ); + assertTrue(accept(node, "")); + assertFalse(new PatternInclusionsDependencyFilter(new LinkedList()).accept(node, parents)); + assertFalse(new PatternInclusionsDependencyFilter((String[]) null).accept(node, parents)); + assertFalse(new PatternInclusionsDependencyFilter((VersionScheme) null, "[1,10]").accept(node, parents)); } @Test - public void acceptTestMatches() - { + public void acceptTestMatches() { NodeBuilder builder = new NodeBuilder(); - builder.groupId( "com.example.test" ).artifactId( "testArtifact" ).ext( "jar" ).version( "1.0.3" ); + builder.groupId("com.example.test") + .artifactId("testArtifact") + .ext("jar") + .version("1.0.3"); DependencyNode node = builder.build(); // full match - assertTrue( "com.example.test:testArtifact:jar:1.0.3", accept( node, "com.example.test:testArtifact:jar:1.0.3" ) ); + assertTrue("com.example.test:testArtifact:jar:1.0.3", accept(node, "com.example.test:testArtifact:jar:1.0.3")); // single wildcard - assertTrue( "*:testArtifact:jar:1.0.3", accept( node, "*:testArtifact:jar:1.0.3" ) ); - assertTrue( "com.example.test:*:jar:1.0.3", accept( node, "com.example.test:*:jar:1.0.3" ) ); - assertTrue( "com.example.test:testArtifact:*:1.0.3", accept( node, "com.example.test:testArtifact:*:1.0.3" ) ); - assertTrue( "com.example.test:testArtifact:*:1.0.3", accept( node, "com.example.test:testArtifact:*:1.0.3" ) ); + assertTrue("*:testArtifact:jar:1.0.3", accept(node, "*:testArtifact:jar:1.0.3")); + assertTrue("com.example.test:*:jar:1.0.3", accept(node, "com.example.test:*:jar:1.0.3")); + assertTrue("com.example.test:testArtifact:*:1.0.3", accept(node, "com.example.test:testArtifact:*:1.0.3")); + assertTrue("com.example.test:testArtifact:*:1.0.3", accept(node, "com.example.test:testArtifact:*:1.0.3")); // implicit wildcard - assertTrue( ":testArtifact:jar:1.0.3", accept( node, ":testArtifact:jar:1.0.3" ) ); - assertTrue( "com.example.test::jar:1.0.3", accept( node, "com.example.test::jar:1.0.3" ) ); - assertTrue( "com.example.test:testArtifact::1.0.3", accept( node, "com.example.test:testArtifact::1.0.3" ) ); - assertTrue( "com.example.test:testArtifact:jar:", accept( node, "com.example.test:testArtifact:jar:" ) ); + assertTrue(":testArtifact:jar:1.0.3", accept(node, ":testArtifact:jar:1.0.3")); + assertTrue("com.example.test::jar:1.0.3", accept(node, "com.example.test::jar:1.0.3")); + assertTrue("com.example.test:testArtifact::1.0.3", accept(node, "com.example.test:testArtifact::1.0.3")); + assertTrue("com.example.test:testArtifact:jar:", accept(node, "com.example.test:testArtifact:jar:")); // multi wildcards - assertTrue( "*:*:jar:1.0.3", accept( node, "*:*:jar:1.0.3" ) ); - assertTrue( "com.example.test:*:*:1.0.3", accept( node, "com.example.test:*:*:1.0.3" ) ); - assertTrue( "com.example.test:testArtifact:*:*", accept( node, "com.example.test:testArtifact:*:*" ) ); - assertTrue( "*:testArtifact:jar:*", accept( node, "*:testArtifact:jar:*" ) ); - assertTrue( "*:*:jar:*", accept( node, "*:*:jar:*" ) ); - assertTrue( ":*:jar:", accept( node, ":*:jar:" ) ); + assertTrue("*:*:jar:1.0.3", accept(node, "*:*:jar:1.0.3")); + assertTrue("com.example.test:*:*:1.0.3", accept(node, "com.example.test:*:*:1.0.3")); + assertTrue("com.example.test:testArtifact:*:*", accept(node, "com.example.test:testArtifact:*:*")); + assertTrue("*:testArtifact:jar:*", accept(node, "*:testArtifact:jar:*")); + assertTrue("*:*:jar:*", accept(node, "*:*:jar:*")); + assertTrue(":*:jar:", accept(node, ":*:jar:")); // partial wildcards - assertTrue( "*.example.test:testArtifact:jar:1.0.3", accept( node, "*.example.test:testArtifact:jar:1.0.3" ) ); - assertTrue( "com.example.test:testArtifact:*ar:1.0.*", accept( node, "com.example.test:testArtifact:*ar:1.0.*" ) ); - assertTrue( "com.example.test:testArtifact:jar:1.0.*", accept( node, "com.example.test:testArtifact:jar:1.0.*" ) ); - assertTrue( "*.example.*:testArtifact:jar:1.0.3", accept( node, "*.example.*:testArtifact:jar:1.0.3" ) ); + assertTrue("*.example.test:testArtifact:jar:1.0.3", accept(node, "*.example.test:testArtifact:jar:1.0.3")); + assertTrue("com.example.test:testArtifact:*ar:1.0.*", accept(node, "com.example.test:testArtifact:*ar:1.0.*")); + assertTrue("com.example.test:testArtifact:jar:1.0.*", accept(node, "com.example.test:testArtifact:jar:1.0.*")); + assertTrue("*.example.*:testArtifact:jar:1.0.3", accept(node, "*.example.*:testArtifact:jar:1.0.3")); // wildcard as empty string - assertTrue( "com.example.test*:testArtifact:jar:1.0.3", accept( node, "com.example.test*:testArtifact:jar:1.0.3" ) ); + assertTrue( + "com.example.test*:testArtifact:jar:1.0.3", accept(node, "com.example.test*:testArtifact:jar:1.0.3")); } @Test - public void acceptTestLessToken() - { + public void acceptTestLessToken() { NodeBuilder builder = new NodeBuilder(); - builder.groupId( "com.example.test" ).artifactId( "testArtifact" ).ext( "jar" ).version( "1.0.3" ); + builder.groupId("com.example.test") + .artifactId("testArtifact") + .ext("jar") + .version("1.0.3"); DependencyNode node = builder.build(); - assertTrue( "com.example.test:testArtifact:jar", accept( node, "com.example.test:testArtifact:jar" ) ); - assertTrue( "com.example.test:testArtifact", accept( node, "com.example.test:testArtifact" ) ); - assertTrue( "com.example.test", accept( node, "com.example.test" ) ); + assertTrue("com.example.test:testArtifact:jar", accept(node, "com.example.test:testArtifact:jar")); + assertTrue("com.example.test:testArtifact", accept(node, "com.example.test:testArtifact")); + assertTrue("com.example.test", accept(node, "com.example.test")); - assertFalse( "com.example.foo", accept( node, "com.example.foo" ) ); + assertFalse("com.example.foo", accept(node, "com.example.foo")); } @Test - public void acceptTestMissmatch() - { + public void acceptTestMissmatch() { NodeBuilder builder = new NodeBuilder(); - builder.groupId( "com.example.test" ).artifactId( "testArtifact" ).ext( "jar" ).version( "1.0.3" ); + builder.groupId("com.example.test") + .artifactId("testArtifact") + .ext("jar") + .version("1.0.3"); DependencyNode node = builder.build(); - assertFalse( "OTHER.GROUP.ID:testArtifact:jar:1.0.3", accept( node, "OTHER.GROUP.ID:testArtifact:jar:1.0.3" ) ); - assertFalse( "com.example.test:OTHER_ARTIFACT:jar:1.0.3", accept( node, "com.example.test:OTHER_ARTIFACT:jar:1.0.3" ) ); - assertFalse( "com.example.test:OTHER_ARTIFACT:jar:1.0.3", accept( node, "com.example.test:OTHER_ARTIFACT:jar:1.0.3" ) ); - assertFalse( "com.example.test:testArtifact:WAR:1.0.3", accept( node, "com.example.test:testArtifact:WAR:1.0.3" ) ); - assertFalse( "com.example.test:testArtifact:jar:SNAPSHOT", accept( node, "com.example.test:testArtifact:jar:SNAPSHOT" ) ); - - assertFalse( "*:*:war:*", accept( node, "*:*:war:*" ) ); - assertFalse( "OTHER.GROUP.ID", accept( node, "OTHER.GROUP.ID" ) ); + assertFalse("OTHER.GROUP.ID:testArtifact:jar:1.0.3", accept(node, "OTHER.GROUP.ID:testArtifact:jar:1.0.3")); + assertFalse( + "com.example.test:OTHER_ARTIFACT:jar:1.0.3", accept(node, "com.example.test:OTHER_ARTIFACT:jar:1.0.3")); + assertFalse( + "com.example.test:OTHER_ARTIFACT:jar:1.0.3", accept(node, "com.example.test:OTHER_ARTIFACT:jar:1.0.3")); + assertFalse("com.example.test:testArtifact:WAR:1.0.3", accept(node, "com.example.test:testArtifact:WAR:1.0.3")); + assertFalse( + "com.example.test:testArtifact:jar:SNAPSHOT", + accept(node, "com.example.test:testArtifact:jar:SNAPSHOT")); + + assertFalse("*:*:war:*", accept(node, "*:*:war:*")); + assertFalse("OTHER.GROUP.ID", accept(node, "OTHER.GROUP.ID")); } @Test - public void acceptTestMoreToken() - { + public void acceptTestMoreToken() { NodeBuilder builder = new NodeBuilder(); - builder.groupId( "com.example.test" ).artifactId( "testArtifact" ).ext( "jar" ).version( "1.0.3" ); + builder.groupId("com.example.test") + .artifactId("testArtifact") + .ext("jar") + .version("1.0.3"); DependencyNode node = builder.build(); - assertFalse( "com.example.test:testArtifact:jar:1.0.3:foo", accept( node, "com.example.test:testArtifact:jar:1.0.3:foo" ) ); + assertFalse( + "com.example.test:testArtifact:jar:1.0.3:foo", + accept(node, "com.example.test:testArtifact:jar:1.0.3:foo")); } @Test - public void acceptTestRange() - { + public void acceptTestRange() { NodeBuilder builder = new NodeBuilder(); - builder.groupId( "com.example.test" ).artifactId( "testArtifact" ).ext( "jar" ).version( "1.0.3" ); + builder.groupId("com.example.test") + .artifactId("testArtifact") + .ext("jar") + .version("1.0.3"); DependencyNode node = builder.build(); String prefix = "com.example.test:testArtifact:jar:"; - assertTrue( prefix + "[1.0.3,1.0.4)", acceptVersionRange( node, prefix + "[1.0.3,1.0.4)" ) ); - assertTrue( prefix + "[1.0.3,)", acceptVersionRange( node, prefix + "[1.0.3,)" ) ); - assertTrue( prefix + "[1.0.3,]", acceptVersionRange( node, prefix + "[1.0.3,]" ) ); - assertTrue( prefix + "(,1.0.3]", acceptVersionRange( node, prefix + "(,1.0.3]" ) ); - assertTrue( prefix + "[1.0,]", acceptVersionRange( node, prefix + "[1.0,]" ) ); - assertTrue( prefix + "[1,4]", acceptVersionRange( node, prefix + "[1,4]" ) ); - assertTrue( prefix + "(1,4)", acceptVersionRange( node, prefix + "(1,4)" ) ); + assertTrue(prefix + "[1.0.3,1.0.4)", acceptVersionRange(node, prefix + "[1.0.3,1.0.4)")); + assertTrue(prefix + "[1.0.3,)", acceptVersionRange(node, prefix + "[1.0.3,)")); + assertTrue(prefix + "[1.0.3,]", acceptVersionRange(node, prefix + "[1.0.3,]")); + assertTrue(prefix + "(,1.0.3]", acceptVersionRange(node, prefix + "(,1.0.3]")); + assertTrue(prefix + "[1.0,]", acceptVersionRange(node, prefix + "[1.0,]")); + assertTrue(prefix + "[1,4]", acceptVersionRange(node, prefix + "[1,4]")); + assertTrue(prefix + "(1,4)", acceptVersionRange(node, prefix + "(1,4)")); - assertTrue( prefix + "(1.0.2,1.0.3]", acceptVersionRange( node, prefix + "(1.0.2,1.0.3]", prefix + "(1.1,)" ) ); + assertTrue(prefix + "(1.0.2,1.0.3]", acceptVersionRange(node, prefix + "(1.0.2,1.0.3]", prefix + "(1.1,)")); - assertFalse( prefix + "(1.0.3,2.0]", acceptVersionRange( node, prefix + "(1.0.3,2.0]" ) ); - assertFalse( prefix + "(1,1.0.2]", acceptVersionRange( node, prefix + "(1,1.0.2]" ) ); + assertFalse(prefix + "(1.0.3,2.0]", acceptVersionRange(node, prefix + "(1.0.3,2.0]")); + assertFalse(prefix + "(1,1.0.2]", acceptVersionRange(node, prefix + "(1,1.0.2]")); - assertFalse( prefix + "(1.0.2,1.0.3)", acceptVersionRange( node, prefix + "(1.0.2,1.0.3)", prefix + "(1.0.3,)" ) ); + assertFalse(prefix + "(1.0.2,1.0.3)", acceptVersionRange(node, prefix + "(1.0.2,1.0.3)", prefix + "(1.0.3,)")); } - public boolean accept( DependencyNode node, String expression ) - { - return new PatternInclusionsDependencyFilter( expression ).accept( node, new LinkedList() ); + public boolean accept(DependencyNode node, String expression) { + return new PatternInclusionsDependencyFilter(expression).accept(node, new LinkedList()); } - public boolean acceptVersionRange( DependencyNode node, String... expression ) - { - return new PatternInclusionsDependencyFilter( new GenericVersionScheme(), expression ).accept( node, - new LinkedList() ); + public boolean acceptVersionRange(DependencyNode node, String... expression) { + return new PatternInclusionsDependencyFilter(new GenericVersionScheme(), expression) + .accept(node, new LinkedList()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/ScopeDependencyFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/ScopeDependencyFilterTest.java index 50b2c5486..573277918 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/ScopeDependencyFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/filter/ScopeDependencyFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.filter; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.filter; import java.util.Arrays; import java.util.LinkedList; @@ -27,45 +24,41 @@ import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.internal.test.util.NodeBuilder; -import org.eclipse.aether.util.filter.ScopeDependencyFilter; import org.junit.Test; -public class ScopeDependencyFilterTest - extends AbstractDependencyFilterTest -{ +import static org.junit.Assert.*; + +public class ScopeDependencyFilterTest extends AbstractDependencyFilterTest { @Test - public void acceptTest() - { + public void acceptTest() { NodeBuilder builder = new NodeBuilder(); - builder.scope( "compile" ).artifactId( "test" ); + builder.scope("compile").artifactId("test"); List parents = new LinkedList<>(); // null or empty - assertTrue( new ScopeDependencyFilter( null, null ).accept( builder.build(), parents ) ); - assertTrue( new ScopeDependencyFilter( new LinkedList(), new LinkedList() ).accept( builder.build(), - parents ) ); - assertTrue( new ScopeDependencyFilter( (String[]) null ).accept( builder.build(), parents ) ); + assertTrue(new ScopeDependencyFilter(null, null).accept(builder.build(), parents)); + assertTrue(new ScopeDependencyFilter(new LinkedList(), new LinkedList()) + .accept(builder.build(), parents)); + assertTrue(new ScopeDependencyFilter((String[]) null).accept(builder.build(), parents)); // only excludes - assertTrue( new ScopeDependencyFilter( "test" ).accept( builder.build(), parents ) ); - assertFalse( new ScopeDependencyFilter( "compile" ).accept( builder.build(), parents ) ); - assertFalse( new ScopeDependencyFilter( "compile", "test" ).accept( builder.build(), parents ) ); + assertTrue(new ScopeDependencyFilter("test").accept(builder.build(), parents)); + assertFalse(new ScopeDependencyFilter("compile").accept(builder.build(), parents)); + assertFalse(new ScopeDependencyFilter("compile", "test").accept(builder.build(), parents)); // Both - String[] excludes1 = { "provided" }; - String[] includes1 = { "compile", "test" }; - assertTrue( new ScopeDependencyFilter( Arrays.asList( includes1 ), Arrays.asList( excludes1 ) ).accept( builder.build(), - parents ) ); - assertTrue( new ScopeDependencyFilter( Arrays.asList( includes1 ), null ).accept( builder.build(), parents ) ); + String[] excludes1 = {"provided"}; + String[] includes1 = {"compile", "test"}; + assertTrue(new ScopeDependencyFilter(Arrays.asList(includes1), Arrays.asList(excludes1)) + .accept(builder.build(), parents)); + assertTrue(new ScopeDependencyFilter(Arrays.asList(includes1), null).accept(builder.build(), parents)); // exclude wins - String[] excludes2 = { "compile" }; - String[] includes2 = { "compile" }; - assertFalse( new ScopeDependencyFilter( Arrays.asList( includes2 ), Arrays.asList( excludes2 ) ).accept( builder.build(), - parents ) ); - + String[] excludes2 = {"compile"}; + String[] includes2 = {"compile"}; + assertFalse(new ScopeDependencyFilter(Arrays.asList(includes2), Arrays.asList(excludes2)) + .accept(builder.build(), parents)); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/manager/ClassicDependencyManagerTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/manager/ClassicDependencyManagerTest.java index 25935858f..00f3d5f3c 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/manager/ClassicDependencyManagerTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/manager/ClassicDependencyManagerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.manager; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.manager; import java.util.Arrays; @@ -34,49 +31,45 @@ import org.junit.Before; import org.junit.Test; -public class ClassicDependencyManagerTest -{ +import static org.junit.Assert.*; + +public class ClassicDependencyManagerTest { - private final Artifact A = new DefaultArtifact( "test", "a", "", "" ); + private final Artifact A = new DefaultArtifact("test", "a", "", ""); - private final Artifact A1 = new DefaultArtifact( "test", "a", "", "1" ); + private final Artifact A1 = new DefaultArtifact("test", "a", "", "1"); - private final Artifact B = new DefaultArtifact( "test", "b", "", "" ); + private final Artifact B = new DefaultArtifact("test", "b", "", ""); - private final Artifact B1 = new DefaultArtifact( "test", "b", "", "1" ); + private final Artifact B1 = new DefaultArtifact("test", "b", "", "1"); private RepositorySystemSession session; - private DependencyCollectionContext newContext( Dependency... managedDependencies ) - { - return TestUtils.newCollectionContext( session, null, Arrays.asList( managedDependencies ) ); + private DependencyCollectionContext newContext(Dependency... managedDependencies) { + return TestUtils.newCollectionContext(session, null, Arrays.asList(managedDependencies)); } @Before - public void setUp() - { + public void setUp() { session = TestUtils.newSession(); } @Test - public void testManageOptional() - { + public void testManageOptional() { DependencyManager manager = new ClassicDependencyManager(); - manager = - manager.deriveChildManager( newContext( new Dependency( A, null, null ), new Dependency( B, null, true ) ) ); + manager = manager.deriveChildManager(newContext(new Dependency(A, null, null), new Dependency(B, null, true))); DependencyManagement mngt; - mngt = manager.manageDependency( new Dependency( A1, null ) ); - assertNull( mngt ); - mngt = manager.manageDependency( new Dependency( B1, null ) ); - assertNull( mngt ); - - manager = manager.deriveChildManager( newContext() ); - mngt = manager.manageDependency( new Dependency( A1, null ) ); - assertNull( mngt ); - mngt = manager.manageDependency( new Dependency( B1, null ) ); - assertNotNull( mngt ); - assertEquals( Boolean.TRUE, mngt.getOptional() ); + mngt = manager.manageDependency(new Dependency(A1, null)); + assertNull(mngt); + mngt = manager.manageDependency(new Dependency(B1, null)); + assertNull(mngt); + + manager = manager.deriveChildManager(newContext()); + mngt = manager.manageDependency(new Dependency(A1, null)); + assertNull(mngt); + mngt = manager.manageDependency(new Dependency(B1, null)); + assertNotNull(mngt); + assertEquals(Boolean.TRUE, mngt.getOptional()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/AndDependencySelectorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/AndDependencySelectorTest.java index f49456b34..24c541b32 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/AndDependencySelectorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/AndDependencySelectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.selector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,9 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.selector; -import static java.util.Objects.requireNonNull; -import static org.junit.Assert.*; +import java.util.Collections; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.DefaultArtifact; @@ -30,158 +28,131 @@ import org.eclipse.aether.internal.test.util.TestUtils; import org.junit.Test; -import java.util.Collections; +import static java.util.Objects.requireNonNull; +import static org.junit.Assert.*; -public class AndDependencySelectorTest -{ +public class AndDependencySelectorTest { - static class DummyDependencySelector - implements DependencySelector - { + static class DummyDependencySelector implements DependencySelector { private final boolean select; private final DependencySelector child; - public DummyDependencySelector() - { - this( true ); + public DummyDependencySelector() { + this(true); } - public DummyDependencySelector( boolean select ) - { + public DummyDependencySelector(boolean select) { this.select = select; this.child = this; } - public DummyDependencySelector( boolean select, DependencySelector child ) - { + public DummyDependencySelector(boolean select, DependencySelector child) { this.select = select; this.child = child; } - public boolean selectDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); + public boolean selectDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); return select; } - public DependencySelector deriveChildSelector( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencySelector deriveChildSelector(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); return child; } @Override - public String toString() - { + public String toString() { return "Dummy(" + select + ')'; } } @Test - public void testNewInstance() - { - assertNull( AndDependencySelector.newInstance( null, null ) ); + public void testNewInstance() { + assertNull(AndDependencySelector.newInstance(null, null)); DependencySelector selector = new DummyDependencySelector(); - assertSame( selector, AndDependencySelector.newInstance( selector, null ) ); - assertSame( selector, AndDependencySelector.newInstance( null, selector ) ); - assertSame( selector, AndDependencySelector.newInstance( selector, selector ) ); - assertNotNull( AndDependencySelector.newInstance( selector, new DummyDependencySelector() ) ); + assertSame(selector, AndDependencySelector.newInstance(selector, null)); + assertSame(selector, AndDependencySelector.newInstance(null, selector)); + assertSame(selector, AndDependencySelector.newInstance(selector, selector)); + assertNotNull(AndDependencySelector.newInstance(selector, new DummyDependencySelector())); } @Test - public void testTraverseDependency() - { - Dependency dependency = new Dependency( new DefaultArtifact( "g:a:v:1" ), "runtime" ); + public void testTraverseDependency() { + Dependency dependency = new Dependency(new DefaultArtifact("g:a:v:1"), "runtime"); DependencySelector selector = new AndDependencySelector(); - assertTrue( selector.selectDependency( dependency ) ); + assertTrue(selector.selectDependency(dependency)); - selector = - new AndDependencySelector( new DummyDependencySelector( false ), new DummyDependencySelector( false ) ); - assertFalse( selector.selectDependency( dependency ) ); + selector = new AndDependencySelector(new DummyDependencySelector(false), new DummyDependencySelector(false)); + assertFalse(selector.selectDependency(dependency)); - selector = - new AndDependencySelector( new DummyDependencySelector( true ), new DummyDependencySelector( false ) ); - assertFalse( selector.selectDependency( dependency ) ); + selector = new AndDependencySelector(new DummyDependencySelector(true), new DummyDependencySelector(false)); + assertFalse(selector.selectDependency(dependency)); - selector = new AndDependencySelector( new DummyDependencySelector( true ), new DummyDependencySelector( true ) ); - assertTrue( selector.selectDependency( dependency ) ); + selector = new AndDependencySelector(new DummyDependencySelector(true), new DummyDependencySelector(true)); + assertTrue(selector.selectDependency(dependency)); } @Test - public void testDeriveChildSelector_Unchanged() - { - DependencySelector other1 = new DummyDependencySelector( true ); - DependencySelector other2 = new DummyDependencySelector( false ); - DependencySelector selector = new AndDependencySelector( other1, other2 ); + public void testDeriveChildSelector_Unchanged() { + DependencySelector other1 = new DummyDependencySelector(true); + DependencySelector other2 = new DummyDependencySelector(false); + DependencySelector selector = new AndDependencySelector(other1, other2); RepositorySystemSession session = TestUtils.newSession(); - DependencyCollectionContext context = TestUtils.newCollectionContext( session, - null, - Collections.emptyList() ); - assertSame( selector, selector.deriveChildSelector( context ) ); + DependencyCollectionContext context = TestUtils.newCollectionContext(session, null, Collections.emptyList()); + assertSame(selector, selector.deriveChildSelector(context)); } @Test - public void testDeriveChildSelector_OneRemaining() - { - DependencySelector other1 = new DummyDependencySelector( true ); - DependencySelector other2 = new DummyDependencySelector( false, null ); - DependencySelector selector = new AndDependencySelector( other1, other2 ); + public void testDeriveChildSelector_OneRemaining() { + DependencySelector other1 = new DummyDependencySelector(true); + DependencySelector other2 = new DummyDependencySelector(false, null); + DependencySelector selector = new AndDependencySelector(other1, other2); RepositorySystemSession session = TestUtils.newSession(); - DependencyCollectionContext context = TestUtils.newCollectionContext( session, - null, - Collections.emptyList() ); - assertSame( other1, selector.deriveChildSelector( context ) ); + DependencyCollectionContext context = TestUtils.newCollectionContext(session, null, Collections.emptyList()); + assertSame(other1, selector.deriveChildSelector(context)); } @Test - public void testDeriveChildSelector_ZeroRemaining() - { - DependencySelector other1 = new DummyDependencySelector( true, null ); - DependencySelector other2 = new DummyDependencySelector( false, null ); - DependencySelector selector = new AndDependencySelector( other1, other2 ); + public void testDeriveChildSelector_ZeroRemaining() { + DependencySelector other1 = new DummyDependencySelector(true, null); + DependencySelector other2 = new DummyDependencySelector(false, null); + DependencySelector selector = new AndDependencySelector(other1, other2); RepositorySystemSession session = TestUtils.newSession(); - DependencyCollectionContext context = TestUtils.newCollectionContext( session, - null, - Collections.emptyList() ); - assertNull( selector.deriveChildSelector( context ) ); + DependencyCollectionContext context = TestUtils.newCollectionContext(session, null, Collections.emptyList()); + assertNull(selector.deriveChildSelector(context)); } @Test - public void testEquals() - { - DependencySelector other1 = new DummyDependencySelector( true ); - DependencySelector other2 = new DummyDependencySelector( false ); - DependencySelector selector1 = new AndDependencySelector( other1, other2 ); - DependencySelector selector2 = new AndDependencySelector( other2, other1 ); - DependencySelector selector3 = new AndDependencySelector( other1 ); - assertEquals( selector1, selector1 ); - assertEquals( selector1, selector2 ); - assertNotEquals( selector1, selector3 ); - assertNotEquals( selector1, this ); - assertNotEquals( selector1, null ); + public void testEquals() { + DependencySelector other1 = new DummyDependencySelector(true); + DependencySelector other2 = new DummyDependencySelector(false); + DependencySelector selector1 = new AndDependencySelector(other1, other2); + DependencySelector selector2 = new AndDependencySelector(other2, other1); + DependencySelector selector3 = new AndDependencySelector(other1); + assertEquals(selector1, selector1); + assertEquals(selector1, selector2); + assertNotEquals(selector1, selector3); + assertNotEquals(selector1, this); + assertNotEquals(selector1, null); } @Test - public void testHashCode() - { - DependencySelector other1 = new DummyDependencySelector( true ); - DependencySelector other2 = new DummyDependencySelector( false ); - DependencySelector selector1 = new AndDependencySelector( other1, other2 ); - DependencySelector selector2 = new AndDependencySelector( other2, other1 ); - assertEquals( selector1.hashCode(), selector2.hashCode() ); + public void testHashCode() { + DependencySelector other1 = new DummyDependencySelector(true); + DependencySelector other2 = new DummyDependencySelector(false); + DependencySelector selector1 = new AndDependencySelector(other1, other2); + DependencySelector selector2 = new AndDependencySelector(other2, other1); + assertEquals(selector1.hashCode(), selector2.hashCode()); } @Test - public void testToString() - { - DependencySelector andSelector = new AndDependencySelector( - new DummyDependencySelector( true ), - new DummyDependencySelector( false ) - ); + public void testToString() { + DependencySelector andSelector = + new AndDependencySelector(new DummyDependencySelector(true), new DummyDependencySelector(false)); assertEquals("AndDependencySelector(Dummy(true) && Dummy(false))", andSelector.toString()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/ExclusionDependencySelectorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/ExclusionDependencySelectorTest.java index 67081ba9a..d6adf98c0 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/ExclusionDependencySelectorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/ExclusionDependencySelectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.selector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,22 +16,21 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.selector; -import static org.junit.Assert.*; +import java.util.Collections; import org.eclipse.aether.graph.Exclusion; import org.junit.Test; -import java.util.Collections; +import static org.junit.Assert.*; -public class ExclusionDependencySelectorTest -{ +public class ExclusionDependencySelectorTest { @Test - public void testToString() - { + public void testToString() { assertEquals( - "ExclusionDependencySelector(a:b:d:c)", - new ExclusionDependencySelector( Collections.singletonList( new Exclusion("a", "b", "c", "d") ) ).toString() - ); + "ExclusionDependencySelector(a:b:d:c)", + new ExclusionDependencySelector(Collections.singletonList(new Exclusion("a", "b", "c", "d"))) + .toString()); } } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/OptionalDependencySelectorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/OptionalDependencySelectorTest.java index b2c370826..19e5bd865 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/OptionalDependencySelectorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/OptionalDependencySelectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.selector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,15 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.selector; import org.junit.Test; -public class OptionalDependencySelectorTest -{ +import static org.junit.Assert.*; + +public class OptionalDependencySelectorTest { @Test - public void testToString() - { - assertEquals( - "OptionalDependencySelector(depth: 0)", - new OptionalDependencySelector().toString() - ); + public void testToString() { + assertEquals("OptionalDependencySelector(depth: 0)", new OptionalDependencySelector().toString()); } -} \ No newline at end of file +} diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/ScopeDependencySelectorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/ScopeDependencySelectorTest.java index 7d842586b..f16f49be8 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/ScopeDependencySelectorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/ScopeDependencySelectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.selector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,21 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.selector; -import static org.junit.Assert.*; +import java.util.Collections; import org.junit.Test; -import java.util.Collections; +import static org.junit.Assert.*; -public class ScopeDependencySelectorTest -{ +public class ScopeDependencySelectorTest { @Test - public void testToString() - { + public void testToString() { assertEquals( - "ScopeDependencySelector(included: [foo], excluded: [bar], transitive: false)", - new ScopeDependencySelector(Collections.singleton( "foo" ), Collections.singleton( "bar" ) ).toString() - ); + "ScopeDependencySelector(included: [foo], excluded: [bar], transitive: false)", + new ScopeDependencySelector(Collections.singleton("foo"), Collections.singleton("bar")).toString()); } -} \ No newline at end of file +} diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/StaticDependencySelectorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/StaticDependencySelectorTest.java index 79ccce63e..55344bbff 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/StaticDependencySelectorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/selector/StaticDependencySelectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.selector; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,19 +16,15 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.selector; import org.junit.Test; -public class StaticDependencySelectorTest -{ +import static org.junit.Assert.*; + +public class StaticDependencySelectorTest { @Test - public void testToString() - { - assertEquals( - "StaticDependencySelector(Select all)", - new StaticDependencySelector( true ).toString() - ); + public void testToString() { + assertEquals("StaticDependencySelector(Select all)", new StaticDependencySelector(true).toString()); } -} \ No newline at end of file +} diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/AbstractDependencyGraphTransformerTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/AbstractDependencyGraphTransformerTest.java index 372be11c4..43b797331 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/AbstractDependencyGraphTransformerTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/AbstractDependencyGraphTransformerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.transformer; import java.util.LinkedList; import java.util.List; @@ -33,10 +30,11 @@ import org.junit.After; import org.junit.Before; +import static org.junit.Assert.*; + /** */ -public abstract class AbstractDependencyGraphTransformerTest -{ +public abstract class AbstractDependencyGraphTransformerTest { protected DependencyGraphTransformer transformer; @@ -50,49 +48,38 @@ public abstract class AbstractDependencyGraphTransformerTest protected abstract DependencyGraphParser newParser(); - protected DependencyNode transform( DependencyNode root ) - throws Exception - { - context = TestUtils.newTransformationContext( session ); - root = transformer.transformGraph( root, context ); - assertNotNull( root ); + protected DependencyNode transform(DependencyNode root) throws Exception { + context = TestUtils.newTransformationContext(session); + root = transformer.transformGraph(root, context); + assertNotNull(root); return root; } - protected DependencyNode parseResource( String resource, String... substitutions ) - throws Exception - { - parser.setSubstitutions( substitutions ); - return parser.parseResource( resource ); + protected DependencyNode parseResource(String resource, String... substitutions) throws Exception { + parser.setSubstitutions(substitutions); + return parser.parseResource(resource); } - protected DependencyNode parseLiteral( String literal, String... substitutions ) - throws Exception - { - parser.setSubstitutions( substitutions ); - return parser.parseLiteral( literal ); + protected DependencyNode parseLiteral(String literal, String... substitutions) throws Exception { + parser.setSubstitutions(substitutions); + return parser.parseLiteral(literal); } - protected List find( DependencyNode node, String id ) - { + protected List find(DependencyNode node, String id) { LinkedList trail = new LinkedList<>(); - find( trail, node, id ); + find(trail, node, id); return trail; } - private boolean find( LinkedList trail, DependencyNode node, String id ) - { - trail.addFirst( node ); + private boolean find(LinkedList trail, DependencyNode node, String id) { + trail.addFirst(node); - if ( isMatch( node, id ) ) - { + if (isMatch(node, id)) { return true; } - for ( DependencyNode child : node.getChildren() ) - { - if ( find( trail, child, id ) ) - { + for (DependencyNode child : node.getChildren()) { + if (find(trail, child, id)) { return true; } } @@ -102,30 +89,25 @@ private boolean find( LinkedList trail, DependencyNode node, Str return false; } - private boolean isMatch( DependencyNode node, String id ) - { - if ( node.getDependency() == null ) - { + private boolean isMatch(DependencyNode node, String id) { + if (node.getDependency() == null) { return false; } - return id.equals( node.getDependency().getArtifact().getArtifactId() ); + return id.equals(node.getDependency().getArtifact().getArtifactId()); } @Before - public void setUp() - { + public void setUp() { transformer = newTransformer(); parser = newParser(); session = new DefaultRepositorySystemSession(); } @After - public void tearDown() - { + public void tearDown() { transformer = null; parser = null; session = null; context = null; } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictIdSorterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictIdSorterTest.java index 4f4e03196..1e01033ca 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictIdSorterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictIdSorterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.transformer; import java.util.Collection; import java.util.LinkedList; @@ -29,101 +26,83 @@ import org.eclipse.aether.collection.DependencyGraphTransformer; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.internal.test.util.DependencyGraphParser; -import org.eclipse.aether.util.graph.transformer.ConflictIdSorter; -import org.eclipse.aether.util.graph.transformer.TransformationContextKeys; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class ConflictIdSorterTest - extends AbstractDependencyGraphTransformerTest -{ +public class ConflictIdSorterTest extends AbstractDependencyGraphTransformerTest { @Override - protected DependencyGraphTransformer newTransformer() - { - return new ChainedDependencyGraphTransformer( new SimpleConflictMarker(), new ConflictIdSorter() ); + protected DependencyGraphTransformer newTransformer() { + return new ChainedDependencyGraphTransformer(new SimpleConflictMarker(), new ConflictIdSorter()); } @Override - protected DependencyGraphParser newParser() - { - return new DependencyGraphParser( "transformer/conflict-id-sorter/" ); + protected DependencyGraphParser newParser() { + return new DependencyGraphParser("transformer/conflict-id-sorter/"); } - private void expectOrder( List sorted, String... ids ) - { - Queue queue = new LinkedList<>( sorted ); + private void expectOrder(List sorted, String... ids) { + Queue queue = new LinkedList<>(sorted); - for ( String id : ids ) - { + for (String id : ids) { String item = queue.poll(); - assertNotNull( String.format( "not enough conflict groups (no match for '%s'", id ), item ); + assertNotNull(String.format("not enough conflict groups (no match for '%s'", id), item); - if ( !"*".equals( id ) ) - { - assertEquals( id, item ); + if (!"*".equals(id)) { + assertEquals(id, item); } } - assertTrue( String.format( "leftover conflict groups (remaining: '%s')", queue ), queue.isEmpty() ); + assertTrue(String.format("leftover conflict groups (remaining: '%s')", queue), queue.isEmpty()); } - private void expectOrder( String... id ) - { - @SuppressWarnings( "unchecked" ) - List sorted = (List) context.get( TransformationContextKeys.SORTED_CONFLICT_IDS ); - expectOrder( sorted, id ); + private void expectOrder(String... id) { + @SuppressWarnings("unchecked") + List sorted = (List) context.get(TransformationContextKeys.SORTED_CONFLICT_IDS); + expectOrder(sorted, id); } - private void expectCycle( boolean cycle ) - { - Collection cycles = (Collection) context.get( TransformationContextKeys.CYCLIC_CONFLICT_IDS ); - assertEquals( cycle, !cycles.isEmpty() ); + private void expectCycle(boolean cycle) { + Collection cycles = (Collection) context.get(TransformationContextKeys.CYCLIC_CONFLICT_IDS); + assertEquals(cycle, !cycles.isEmpty()); } @Test - public void testSimple() - throws Exception - { - DependencyNode node = parseResource( "simple.txt" ); - assertSame( node, transform( node ) ); - - expectOrder( "gid2:aid::jar", "gid:aid::jar", "gid:aid2::jar" ); - expectCycle( false ); + public void testSimple() throws Exception { + DependencyNode node = parseResource("simple.txt"); + assertSame(node, transform(node)); + + expectOrder("gid2:aid::jar", "gid:aid::jar", "gid:aid2::jar"); + expectCycle(false); } @Test - public void testCycle() - throws Exception - { - DependencyNode node = parseResource( "cycle.txt" ); - assertSame( node, transform( node ) ); - - expectOrder( "gid:aid::jar", "gid2:aid::jar" ); - expectCycle( true ); + public void testCycle() throws Exception { + DependencyNode node = parseResource("cycle.txt"); + assertSame(node, transform(node)); + + expectOrder("gid:aid::jar", "gid2:aid::jar"); + expectCycle(true); } @Test - public void testCycles() - throws Exception - { - DependencyNode node = parseResource( "cycles.txt" ); - assertSame( node, transform( node ) ); - - expectOrder( "*", "*", "*", "gid:aid::jar" ); - expectCycle( true ); + public void testCycles() throws Exception { + DependencyNode node = parseResource("cycles.txt"); + assertSame(node, transform(node)); + + expectOrder("*", "*", "*", "gid:aid::jar"); + expectCycle(true); } @Test - public void testNoConflicts() - throws Exception - { - DependencyNode node = parseResource( "no-conflicts.txt" ); - assertSame( node, transform( node ) ); - - expectOrder( "gid:aid::jar", "gid3:aid::jar", "gid2:aid::jar", "gid4:aid::jar" ); - expectCycle( false ); - } + public void testNoConflicts() throws Exception { + DependencyNode node = parseResource("no-conflicts.txt"); + assertSame(node, transform(node)); + expectOrder("gid:aid::jar", "gid3:aid::jar", "gid2:aid::jar", "gid4:aid::jar"); + expectCycle(false); + } } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictMarkerTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictMarkerTest.java index 6a81d5176..878f72c0f 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictMarkerTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictMarkerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,105 +16,97 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.transformer; import java.util.Map; import org.eclipse.aether.collection.DependencyGraphTransformer; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.internal.test.util.DependencyGraphParser; -import org.eclipse.aether.util.graph.transformer.ConflictMarker; -import org.eclipse.aether.util.graph.transformer.TransformationContextKeys; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class ConflictMarkerTest - extends AbstractDependencyGraphTransformerTest -{ +public class ConflictMarkerTest extends AbstractDependencyGraphTransformerTest { @Override - protected DependencyGraphTransformer newTransformer() - { + protected DependencyGraphTransformer newTransformer() { return new ConflictMarker(); } @Override - protected DependencyGraphParser newParser() - { - return new DependencyGraphParser( "transformer/conflict-marker/" ); + protected DependencyGraphParser newParser() { + return new DependencyGraphParser("transformer/conflict-marker/"); } @Test - public void testSimple() - throws Exception - { - DependencyNode root = parseResource( "simple.txt" ); + public void testSimple() throws Exception { + DependencyNode root = parseResource("simple.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - Map ids = (Map) context.get( TransformationContextKeys.CONFLICT_IDS ); - assertNotNull( ids ); + Map ids = (Map) context.get(TransformationContextKeys.CONFLICT_IDS); + assertNotNull(ids); - assertNull( ids.get( root ) ); - assertNotNull( ids.get( root.getChildren().get( 0 ) ) ); - assertNotNull( ids.get( root.getChildren().get( 1 ) ) ); - assertNotSame( ids.get( root.getChildren().get( 0 ) ), ids.get( root.getChildren().get( 1 ) ) ); - assertNotEquals( ids.get( root.getChildren().get( 0 ) ), ids.get( root.getChildren().get( 1 ) ) ); + assertNull(ids.get(root)); + assertNotNull(ids.get(root.getChildren().get(0))); + assertNotNull(ids.get(root.getChildren().get(1))); + assertNotSame( + ids.get(root.getChildren().get(0)), ids.get(root.getChildren().get(1))); + assertNotEquals( + ids.get(root.getChildren().get(0)), ids.get(root.getChildren().get(1))); } @Test - public void testRelocation1() - throws Exception - { - DependencyNode root = parseResource( "relocation1.txt" ); + public void testRelocation1() throws Exception { + DependencyNode root = parseResource("relocation1.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - Map ids = (Map) context.get( TransformationContextKeys.CONFLICT_IDS ); - assertNotNull( ids ); + Map ids = (Map) context.get(TransformationContextKeys.CONFLICT_IDS); + assertNotNull(ids); - assertNull( ids.get( root ) ); - assertNotNull( ids.get( root.getChildren().get( 0 ) ) ); - assertNotNull( ids.get( root.getChildren().get( 1 ) ) ); - assertSame( ids.get( root.getChildren().get( 0 ) ), ids.get( root.getChildren().get( 1 ) ) ); + assertNull(ids.get(root)); + assertNotNull(ids.get(root.getChildren().get(0))); + assertNotNull(ids.get(root.getChildren().get(1))); + assertSame( + ids.get(root.getChildren().get(0)), ids.get(root.getChildren().get(1))); } @Test - public void testRelocation2() - throws Exception - { - DependencyNode root = parseResource( "relocation2.txt" ); + public void testRelocation2() throws Exception { + DependencyNode root = parseResource("relocation2.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - Map ids = (Map) context.get( TransformationContextKeys.CONFLICT_IDS ); - assertNotNull( ids ); + Map ids = (Map) context.get(TransformationContextKeys.CONFLICT_IDS); + assertNotNull(ids); - assertNull( ids.get( root ) ); - assertNotNull( ids.get( root.getChildren().get( 0 ) ) ); - assertNotNull( ids.get( root.getChildren().get( 1 ) ) ); - assertSame( ids.get( root.getChildren().get( 0 ) ), ids.get( root.getChildren().get( 1 ) ) ); + assertNull(ids.get(root)); + assertNotNull(ids.get(root.getChildren().get(0))); + assertNotNull(ids.get(root.getChildren().get(1))); + assertSame( + ids.get(root.getChildren().get(0)), ids.get(root.getChildren().get(1))); } @Test - public void testRelocation3() - throws Exception - { - DependencyNode root = parseResource( "relocation3.txt" ); - - assertSame( root, transform( root ) ); - - Map ids = (Map) context.get( TransformationContextKeys.CONFLICT_IDS ); - assertNotNull( ids ); - - assertNull( ids.get( root ) ); - assertNotNull( ids.get( root.getChildren().get( 0 ) ) ); - assertNotNull( ids.get( root.getChildren().get( 1 ) ) ); - assertNotNull( ids.get( root.getChildren().get( 2 ) ) ); - assertSame( ids.get( root.getChildren().get( 0 ) ), ids.get( root.getChildren().get( 1 ) ) ); - assertSame( ids.get( root.getChildren().get( 1 ) ), ids.get( root.getChildren().get( 2 ) ) ); + public void testRelocation3() throws Exception { + DependencyNode root = parseResource("relocation3.txt"); + + assertSame(root, transform(root)); + + Map ids = (Map) context.get(TransformationContextKeys.CONFLICT_IDS); + assertNotNull(ids); + + assertNull(ids.get(root)); + assertNotNull(ids.get(root.getChildren().get(0))); + assertNotNull(ids.get(root.getChildren().get(1))); + assertNotNull(ids.get(root.getChildren().get(2))); + assertSame( + ids.get(root.getChildren().get(0)), ids.get(root.getChildren().get(1))); + assertSame( + ids.get(root.getChildren().get(1)), ids.get(root.getChildren().get(2))); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictResolverTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictResolverTest.java index 40410a357..01b288000 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictResolverTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/ConflictResolverTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.artifact.DefaultArtifact; @@ -29,147 +32,131 @@ import org.eclipse.aether.internal.test.util.TestVersionConstraint; import org.junit.Test; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -public class ConflictResolverTest -{ +public class ConflictResolverTest { @Test - public void noTransformationRequired() throws RepositoryException - { + public void noTransformationRequired() throws RepositoryException { ConflictResolver resolver = makeDefaultResolver(); // Foo -> Bar - DependencyNode fooNode = makeDependencyNode( "group-id", "foo", "1.0" ); - DependencyNode barNode = makeDependencyNode( "group-id", "bar", "1.0" ); - fooNode.setChildren( mutableList( barNode ) ); + DependencyNode fooNode = makeDependencyNode("group-id", "foo", "1.0"); + DependencyNode barNode = makeDependencyNode("group-id", "bar", "1.0"); + fooNode.setChildren(mutableList(barNode)); - DependencyNode transformedNode = resolver.transformGraph( - fooNode, TestUtils.newTransformationContext( TestUtils.newSession() ) - ); + DependencyNode transformedNode = + resolver.transformGraph(fooNode, TestUtils.newTransformationContext(TestUtils.newSession())); - assertSame( fooNode, transformedNode ); - assertEquals( 1, transformedNode.getChildren().size() ); - assertSame( barNode, transformedNode.getChildren().get( 0 ) ); + assertSame(fooNode, transformedNode); + assertEquals(1, transformedNode.getChildren().size()); + assertSame(barNode, transformedNode.getChildren().get(0)); } @Test - public void versionClash() throws RepositoryException - { + public void versionClash() throws RepositoryException { ConflictResolver resolver = makeDefaultResolver(); // Foo -> Bar -> Baz 2.0 // |---> Baz 1.0 - DependencyNode fooNode = makeDependencyNode( "some-group", "foo", "1.0" ); - DependencyNode barNode = makeDependencyNode( "some-group", "bar", "1.0" ); - DependencyNode baz1Node = makeDependencyNode( "some-group", "baz", "1.0" ); - DependencyNode baz2Node = makeDependencyNode( "some-group", "baz", "2.0" ); - fooNode.setChildren( mutableList( barNode, baz1Node ) ); - barNode.setChildren( mutableList( baz2Node ) ); - - DependencyNode transformedNode = resolver.transformGraph( - fooNode, TestUtils.newTransformationContext( TestUtils.newSession() ) - ); - - assertSame( fooNode, transformedNode ); - assertEquals( 2, fooNode.getChildren().size() ); - assertSame( barNode, fooNode.getChildren().get( 0 ) ); - assertTrue( barNode.getChildren().isEmpty() ); - assertSame( baz1Node, fooNode.getChildren().get( 1 ) ); + DependencyNode fooNode = makeDependencyNode("some-group", "foo", "1.0"); + DependencyNode barNode = makeDependencyNode("some-group", "bar", "1.0"); + DependencyNode baz1Node = makeDependencyNode("some-group", "baz", "1.0"); + DependencyNode baz2Node = makeDependencyNode("some-group", "baz", "2.0"); + fooNode.setChildren(mutableList(barNode, baz1Node)); + barNode.setChildren(mutableList(baz2Node)); + + DependencyNode transformedNode = + resolver.transformGraph(fooNode, TestUtils.newTransformationContext(TestUtils.newSession())); + + assertSame(fooNode, transformedNode); + assertEquals(2, fooNode.getChildren().size()); + assertSame(barNode, fooNode.getChildren().get(0)); + assertTrue(barNode.getChildren().isEmpty()); + assertSame(baz1Node, fooNode.getChildren().get(1)); } @Test - public void derivedScopeChange() throws RepositoryException - { + public void derivedScopeChange() throws RepositoryException { ConflictResolver resolver = makeDefaultResolver(); // Foo -> Bar (test) -> Jaz // |---> Baz -> Jaz - DependencyNode fooNode = makeDependencyNode( "some-group", "foo", "1.0" ); - DependencyNode barNode = makeDependencyNode( "some-group", "bar", "1.0", "test" ); - DependencyNode bazNode = makeDependencyNode( "some-group", "baz", "1.0" ); - DependencyNode jazNode = makeDependencyNode( "some-group", "jaz", "1.0" ); - fooNode.setChildren( mutableList( barNode, bazNode ) ); - - List jazList = mutableList( jazNode ); - barNode.setChildren( jazList ); - bazNode.setChildren( jazList ); - - DependencyNode transformedNode = resolver.transformGraph( - fooNode, TestUtils.newTransformationContext( TestUtils.newSession() ) - ); - - assertSame( fooNode, transformedNode ); - assertEquals( 2, fooNode.getChildren().size() ); - assertSame( barNode, fooNode.getChildren().get( 0 ) ); - assertEquals( 1, barNode.getChildren().size() ); - assertSame( jazNode, barNode.getChildren().get( 0 ) ); - assertSame( bazNode, fooNode.getChildren().get( 1 ) ); - assertEquals( 1, barNode.getChildren().size() ); - assertSame( jazNode, barNode.getChildren().get( 0 ) ); + DependencyNode fooNode = makeDependencyNode("some-group", "foo", "1.0"); + DependencyNode barNode = makeDependencyNode("some-group", "bar", "1.0", "test"); + DependencyNode bazNode = makeDependencyNode("some-group", "baz", "1.0"); + DependencyNode jazNode = makeDependencyNode("some-group", "jaz", "1.0"); + fooNode.setChildren(mutableList(barNode, bazNode)); + + List jazList = mutableList(jazNode); + barNode.setChildren(jazList); + bazNode.setChildren(jazList); + + DependencyNode transformedNode = + resolver.transformGraph(fooNode, TestUtils.newTransformationContext(TestUtils.newSession())); + + assertSame(fooNode, transformedNode); + assertEquals(2, fooNode.getChildren().size()); + assertSame(barNode, fooNode.getChildren().get(0)); + assertEquals(1, barNode.getChildren().size()); + assertSame(jazNode, barNode.getChildren().get(0)); + assertSame(bazNode, fooNode.getChildren().get(1)); + assertEquals(1, barNode.getChildren().size()); + assertSame(jazNode, barNode.getChildren().get(0)); } @Test - public void derivedOptionalStatusChange() throws RepositoryException - { + public void derivedOptionalStatusChange() throws RepositoryException { ConflictResolver resolver = makeDefaultResolver(); // Foo -> Bar (optional) -> Jaz // |---> Baz -> Jaz - DependencyNode fooNode = makeDependencyNode( "some-group", "foo", "1.0" ); - DependencyNode barNode = makeDependencyNode( "some-group", "bar", "1.0" ); + DependencyNode fooNode = makeDependencyNode("some-group", "foo", "1.0"); + DependencyNode barNode = makeDependencyNode("some-group", "bar", "1.0"); barNode.setOptional(true); - DependencyNode bazNode = makeDependencyNode( "some-group", "baz", "1.0" ); - DependencyNode jazNode = makeDependencyNode( "some-group", "jaz", "1.0" ); - fooNode.setChildren( mutableList( barNode, bazNode ) ); - - List jazList = mutableList( jazNode ); - barNode.setChildren( jazList ); - bazNode.setChildren( jazList ); - - DependencyNode transformedNode = resolver.transformGraph( - fooNode, TestUtils.newTransformationContext( TestUtils.newSession() ) - ); - - assertSame( fooNode, transformedNode ); - assertEquals( 2, fooNode.getChildren().size() ); - assertSame( barNode, fooNode.getChildren().get( 0 ) ); - assertEquals( 1, barNode.getChildren().size() ); - assertSame( jazNode, barNode.getChildren().get( 0 ) ); - assertSame( bazNode, fooNode.getChildren().get( 1 ) ); - assertEquals( 1, barNode.getChildren().size() ); - assertSame( jazNode, barNode.getChildren().get( 0 ) ); + DependencyNode bazNode = makeDependencyNode("some-group", "baz", "1.0"); + DependencyNode jazNode = makeDependencyNode("some-group", "jaz", "1.0"); + fooNode.setChildren(mutableList(barNode, bazNode)); + + List jazList = mutableList(jazNode); + barNode.setChildren(jazList); + bazNode.setChildren(jazList); + + DependencyNode transformedNode = + resolver.transformGraph(fooNode, TestUtils.newTransformationContext(TestUtils.newSession())); + + assertSame(fooNode, transformedNode); + assertEquals(2, fooNode.getChildren().size()); + assertSame(barNode, fooNode.getChildren().get(0)); + assertEquals(1, barNode.getChildren().size()); + assertSame(jazNode, barNode.getChildren().get(0)); + assertSame(bazNode, fooNode.getChildren().get(1)); + assertEquals(1, barNode.getChildren().size()); + assertSame(jazNode, barNode.getChildren().get(0)); } - private static ConflictResolver makeDefaultResolver() - { + private static ConflictResolver makeDefaultResolver() { return new ConflictResolver( - new NearestVersionSelector(), new JavaScopeSelector(), new SimpleOptionalitySelector(), new JavaScopeDeriver() - ); + new NearestVersionSelector(), + new JavaScopeSelector(), + new SimpleOptionalitySelector(), + new JavaScopeDeriver()); } - private static DependencyNode makeDependencyNode( String groupId, String artifactId, String version ) - { - return makeDependencyNode( groupId, artifactId, version, "compile" ); + private static DependencyNode makeDependencyNode(String groupId, String artifactId, String version) { + return makeDependencyNode(groupId, artifactId, version, "compile"); } - private static DependencyNode makeDependencyNode( String groupId, String artifactId, String version, String scope ) - { + private static DependencyNode makeDependencyNode(String groupId, String artifactId, String version, String scope) { DefaultDependencyNode node = new DefaultDependencyNode( - new Dependency( new DefaultArtifact( groupId + ':' + artifactId + ':' + version ), scope ) - ); - node.setVersion( new TestVersion( version ) ); - node.setVersionConstraint( new TestVersionConstraint( node.getVersion() ) ); + new Dependency(new DefaultArtifact(groupId + ':' + artifactId + ':' + version), scope)); + node.setVersion(new TestVersion(version)); + node.setVersionConstraint(new TestVersionConstraint(node.getVersion())); return node; } - private static List mutableList(DependencyNode... nodes) - { - return new ArrayList<>( Arrays.asList( nodes ) ); + private static List mutableList(DependencyNode... nodes) { + return new ArrayList<>(Arrays.asList(nodes)); } -} \ No newline at end of file +} diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/JavaDependencyContextRefinerTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/JavaDependencyContextRefinerTest.java index bb0d65a36..8a5309133 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/JavaDependencyContextRefinerTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/JavaDependencyContextRefinerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,100 +16,85 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.transformer; import org.eclipse.aether.collection.DependencyGraphTransformer; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.internal.test.util.DependencyGraphParser; -import org.eclipse.aether.util.graph.transformer.JavaDependencyContextRefiner; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class JavaDependencyContextRefinerTest - extends AbstractDependencyGraphTransformerTest -{ +public class JavaDependencyContextRefinerTest extends AbstractDependencyGraphTransformerTest { @Override - protected DependencyGraphTransformer newTransformer() - { + protected DependencyGraphTransformer newTransformer() { return new JavaDependencyContextRefiner(); } @Override - protected DependencyGraphParser newParser() - { - return new DependencyGraphParser( "transformer/context-refiner/" ); + protected DependencyGraphParser newParser() { + return new DependencyGraphParser("transformer/context-refiner/"); } @Test - public void testDoNotRefineOtherContext() - throws Exception - { - DependencyNode node = parseLiteral( "gid:aid:cls:ver" ); - node.setRequestContext( "otherContext" ); - - DependencyNode refinedNode = transform( node ); - assertEquals( node, refinedNode ); + public void testDoNotRefineOtherContext() throws Exception { + DependencyNode node = parseLiteral("gid:aid:cls:ver"); + node.setRequestContext("otherContext"); + + DependencyNode refinedNode = transform(node); + assertEquals(node, refinedNode); } @Test - public void testRefineToCompile() - throws Exception - { + public void testRefineToCompile() throws Exception { String expected = "project/compile"; - DependencyNode node = parseLiteral( "gid:aid:ver compile" ); - node.setRequestContext( "project" ); - DependencyNode refinedNode = transform( node ); - assertEquals( expected, refinedNode.getRequestContext() ); + DependencyNode node = parseLiteral("gid:aid:ver compile"); + node.setRequestContext("project"); + DependencyNode refinedNode = transform(node); + assertEquals(expected, refinedNode.getRequestContext()); - node = parseLiteral( "gid:aid:ver system" ); - node.setRequestContext( "project" ); - refinedNode = transform( node ); - assertEquals( expected, refinedNode.getRequestContext() ); + node = parseLiteral("gid:aid:ver system"); + node.setRequestContext("project"); + refinedNode = transform(node); + assertEquals(expected, refinedNode.getRequestContext()); - node = parseLiteral( "gid:aid:ver provided" ); - node.setRequestContext( "project" ); - refinedNode = transform( node ); - assertEquals( expected, refinedNode.getRequestContext() ); + node = parseLiteral("gid:aid:ver provided"); + node.setRequestContext("project"); + refinedNode = transform(node); + assertEquals(expected, refinedNode.getRequestContext()); } @Test - public void testRefineToTest() - throws Exception - { + public void testRefineToTest() throws Exception { String expected = "project/test"; - DependencyNode node = parseLiteral( "gid:aid:ver test" ); - node.setRequestContext( "project" ); - DependencyNode refinedNode = transform( node ); - assertEquals( expected, refinedNode.getRequestContext() ); + DependencyNode node = parseLiteral("gid:aid:ver test"); + node.setRequestContext("project"); + DependencyNode refinedNode = transform(node); + assertEquals(expected, refinedNode.getRequestContext()); } @Test - public void testRefineToRuntime() - throws Exception - { + public void testRefineToRuntime() throws Exception { String expected = "project/runtime"; - DependencyNode node = parseLiteral( "gid:aid:ver runtime" ); - node.setRequestContext( "project" ); - DependencyNode refinedNode = transform( node ); - assertEquals( expected, refinedNode.getRequestContext() ); + DependencyNode node = parseLiteral("gid:aid:ver runtime"); + node.setRequestContext("project"); + DependencyNode refinedNode = transform(node); + assertEquals(expected, refinedNode.getRequestContext()); } @Test - public void testDoNotRefineUnknownScopes() - throws Exception - { + public void testDoNotRefineUnknownScopes() throws Exception { String expected = "project"; - DependencyNode node = parseLiteral( "gid:aid:ver unknownScope" ); - node.setRequestContext( "project" ); - DependencyNode refinedNode = transform( node ); - assertEquals( expected, refinedNode.getRequestContext() ); + DependencyNode node = parseLiteral("gid:aid:ver unknownScope"); + node.setRequestContext("project"); + DependencyNode refinedNode = transform(node); + assertEquals(expected, refinedNode.getRequestContext()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/JavaScopeSelectorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/JavaScopeSelectorTest.java index 3098910d8..62b1b71b4 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/JavaScopeSelectorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/JavaScopeSelectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.transformer; import java.util.Locale; @@ -28,204 +25,174 @@ import org.eclipse.aether.internal.test.util.DependencyGraphParser; import org.junit.Test; -public class JavaScopeSelectorTest - extends AbstractDependencyGraphTransformerTest -{ +import static org.junit.Assert.*; - private enum Scope - { - TEST, PROVIDED, RUNTIME, COMPILE; +public class JavaScopeSelectorTest extends AbstractDependencyGraphTransformerTest { + + private enum Scope { + TEST, + PROVIDED, + RUNTIME, + COMPILE; @Override - public String toString() - { - return super.name().toLowerCase( Locale.ENGLISH ); + public String toString() { + return super.name().toLowerCase(Locale.ENGLISH); } } @Override - protected DependencyGraphTransformer newTransformer() - { - return new ConflictResolver( new NearestVersionSelector(), new JavaScopeSelector(), - new SimpleOptionalitySelector(), new JavaScopeDeriver() ); + protected DependencyGraphTransformer newTransformer() { + return new ConflictResolver( + new NearestVersionSelector(), new JavaScopeSelector(), + new SimpleOptionalitySelector(), new JavaScopeDeriver()); } @Override - protected DependencyGraphParser newParser() - { - return new DependencyGraphParser( "transformer/scope-calculator/" ); + protected DependencyGraphParser newParser() { + return new DependencyGraphParser("transformer/scope-calculator/"); } - private void expectScope( String expected, DependencyNode root, int... coords ) - { - expectScope( null, expected, root, coords ); + private void expectScope(String expected, DependencyNode root, int... coords) { + expectScope(null, expected, root, coords); } - private void expectScope( String msg, String expected, DependencyNode root, int... coords ) - { - if ( msg == null ) - { + private void expectScope(String msg, String expected, DependencyNode root, int... coords) { + if (msg == null) { msg = ""; } - try - { + try { DependencyNode node = root; - node = path( node, coords ); - - assertEquals( msg + "\nculprit: " + node.toString() + "\n", expected, node.getDependency().getScope() ); - } - catch ( IndexOutOfBoundsException | NullPointerException e ) - { - throw new IllegalArgumentException( "illegal coordinates for child", e ); + node = path(node, coords); + + assertEquals( + msg + "\nculprit: " + node.toString() + "\n", + expected, + node.getDependency().getScope()); + } catch (IndexOutOfBoundsException | NullPointerException e) { + throw new IllegalArgumentException("illegal coordinates for child", e); } } - private DependencyNode path( DependencyNode node, int... coords ) - { - for ( int coord : coords ) - { - node = node.getChildren().get( coord ); + private DependencyNode path(DependencyNode node, int... coords) { + for (int coord : coords) { + node = node.getChildren().get(coord); } return node; } @Test - public void testScopeInheritanceProvided() - throws Exception - { + public void testScopeInheritanceProvided() throws Exception { String resource = "inheritance.txt"; String expected = "test"; - DependencyNode root = transform( parseResource( resource, "provided", "test" ) ); - expectScope( parser.dump( root ), expected, root, 0, 0 ); + DependencyNode root = transform(parseResource(resource, "provided", "test")); + expectScope(parser.dump(root), expected, root, 0, 0); } @Test - public void testConflictWinningScopeGetsUsedForInheritance() - throws Exception - { - DependencyNode root = parseResource( "conflict-and-inheritance.txt" ); - assertSame( root, transform( root ) ); - - expectScope( "compile", root, 0, 0 ); - expectScope( "compile", root, 0, 0, 0 ); + public void testConflictWinningScopeGetsUsedForInheritance() throws Exception { + DependencyNode root = parseResource("conflict-and-inheritance.txt"); + assertSame(root, transform(root)); + + expectScope("compile", root, 0, 0); + expectScope("compile", root, 0, 0, 0); } @Test public void testScopeOfDirectDependencyWinsConflictAndGetsUsedForInheritanceToChildrenEverywhereInGraph() - throws Exception - { - DependencyNode root = parseResource( "direct-with-conflict-and-inheritance.txt" ); - assertSame( root, transform( root ) ); + throws Exception { + DependencyNode root = parseResource("direct-with-conflict-and-inheritance.txt"); + assertSame(root, transform(root)); - expectScope( "test", root, 0, 0 ); + expectScope("test", root, 0, 0); } @Test - public void testCycleA() - throws Exception - { - DependencyNode root = parseResource( "cycle-a.txt" ); - assertSame( root, transform( root ) ); - - expectScope( "compile", root, 0 ); - expectScope( "runtime", root, 1 ); + public void testCycleA() throws Exception { + DependencyNode root = parseResource("cycle-a.txt"); + assertSame(root, transform(root)); + + expectScope("compile", root, 0); + expectScope("runtime", root, 1); } @Test - public void testCycleB() - throws Exception - { - DependencyNode root = parseResource( "cycle-b.txt" ); - assertSame( root, transform( root ) ); - - expectScope( "runtime", root, 0 ); - expectScope( "compile", root, 1 ); + public void testCycleB() throws Exception { + DependencyNode root = parseResource("cycle-b.txt"); + assertSame(root, transform(root)); + + expectScope("runtime", root, 0); + expectScope("compile", root, 1); } @Test - public void testCycleC() - throws Exception - { - DependencyNode root = parseResource( "cycle-c.txt" ); - assertSame( root, transform( root ) ); - - expectScope( "runtime", root, 0 ); - expectScope( "runtime", root, 0, 0 ); - expectScope( "runtime", root, 1 ); - expectScope( "runtime", root, 1, 0 ); + public void testCycleC() throws Exception { + DependencyNode root = parseResource("cycle-c.txt"); + assertSame(root, transform(root)); + + expectScope("runtime", root, 0); + expectScope("runtime", root, 0, 0); + expectScope("runtime", root, 1); + expectScope("runtime", root, 1, 0); } @Test - public void testCycleD() - throws Exception - { - DependencyNode root = parseResource( "cycle-d.txt" ); - assertSame( root, transform( root ) ); - - expectScope( "compile", root, 0 ); - expectScope( "compile", root, 0, 0 ); + public void testCycleD() throws Exception { + DependencyNode root = parseResource("cycle-d.txt"); + assertSame(root, transform(root)); + + expectScope("compile", root, 0); + expectScope("compile", root, 0, 0); } @Test - public void testDirectNodesAlwaysWin() - throws Exception - { + public void testDirectNodesAlwaysWin() throws Exception { - for ( Scope directScope : Scope.values() ) - { + for (Scope directScope : Scope.values()) { String direct = directScope.toString(); - DependencyNode root = parseResource( "direct-nodes-winning.txt", direct ); + DependencyNode root = parseResource("direct-nodes-winning.txt", direct); - String msg = - String.format( "direct node should be setting scope ('%s') for all nodes.\n" + parser.dump( root ), - direct ); - assertSame( root, transform( root ) ); - msg += "\ntransformed:\n" + parser.dump( root ); + String msg = String.format( + "direct node should be setting scope ('%s') for all nodes.\n" + parser.dump(root), direct); + assertSame(root, transform(root)); + msg += "\ntransformed:\n" + parser.dump(root); - expectScope( msg, direct, root, 0 ); + expectScope(msg, direct, root, 0); } } @Test - public void testNonDirectMultipleInheritance() - throws Exception - { - for ( Scope scope1 : Scope.values() ) - { - for ( Scope scope2 : Scope.values() ) - { - DependencyNode root = parseResource( "multiple-inheritance.txt", scope1.toString(), scope2.toString() ); - - String expected = scope1.compareTo( scope2 ) >= 0 ? scope1.toString() : scope2.toString(); - String msg = String.format( "expected '%s' to win\n" + parser.dump( root ), expected ); - - assertSame( root, transform( root ) ); - msg += "\ntransformed:\n" + parser.dump( root ); - - expectScope( msg, expected, root, 0, 0 ); + public void testNonDirectMultipleInheritance() throws Exception { + for (Scope scope1 : Scope.values()) { + for (Scope scope2 : Scope.values()) { + DependencyNode root = parseResource("multiple-inheritance.txt", scope1.toString(), scope2.toString()); + + String expected = scope1.compareTo(scope2) >= 0 ? scope1.toString() : scope2.toString(); + String msg = String.format("expected '%s' to win\n" + parser.dump(root), expected); + + assertSame(root, transform(root)); + msg += "\ntransformed:\n" + parser.dump(root); + + expectScope(msg, expected, root, 0, 0); } } } @Test - public void testConflictScopeOrdering() - throws Exception - { - for ( Scope scope1 : Scope.values() ) - { - for ( Scope scope2 : Scope.values() ) - { - DependencyNode root = parseResource( "dueling-scopes.txt", scope1.toString(), scope2.toString() ); - - String expected = scope1.compareTo( scope2 ) >= 0 ? scope1.toString() : scope2.toString(); - String msg = String.format( "expected '%s' to win\n" + parser.dump( root ), expected ); - - assertSame( root, transform( root ) ); - msg += "\ntransformed:\n" + parser.dump( root ); - - expectScope( msg, expected, root, 0, 0 ); + public void testConflictScopeOrdering() throws Exception { + for (Scope scope1 : Scope.values()) { + for (Scope scope2 : Scope.values()) { + DependencyNode root = parseResource("dueling-scopes.txt", scope1.toString(), scope2.toString()); + + String expected = scope1.compareTo(scope2) >= 0 ? scope1.toString() : scope2.toString(); + String msg = String.format("expected '%s' to win\n" + parser.dump(root), expected); + + assertSame(root, transform(root)); + msg += "\ntransformed:\n" + parser.dump(root); + + expectScope(msg, expected, root, 0, 0); } } } @@ -234,24 +201,20 @@ public void testConflictScopeOrdering() * obscure case (illegal maven POM). */ @Test - public void testConflictingDirectNodes() - throws Exception - { - for ( Scope scope1 : Scope.values() ) - { - for ( Scope scope2 : Scope.values() ) - { - DependencyNode root = parseResource( "conflicting-direct-nodes.txt", scope1.toString(), scope2.toString() ); + public void testConflictingDirectNodes() throws Exception { + for (Scope scope1 : Scope.values()) { + for (Scope scope2 : Scope.values()) { + DependencyNode root = + parseResource("conflicting-direct-nodes.txt", scope1.toString(), scope2.toString()); String expected = scope1.toString(); - String msg = String.format( "expected '%s' to win\n" + parser.dump( root ), expected ); + String msg = String.format("expected '%s' to win\n" + parser.dump(root), expected); - assertSame( root, transform( root ) ); - msg += "\ntransformed:\n" + parser.dump( root ); + assertSame(root, transform(root)); + msg += "\ntransformed:\n" + parser.dump(root); - expectScope( msg, expected, root, 0 ); + expectScope(msg, expected, root, 0); } } } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/NearestVersionSelectorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/NearestVersionSelectorTest.java index b71adab2b..a5cf77c2a 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/NearestVersionSelectorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/NearestVersionSelectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.transformer; import java.util.List; @@ -28,217 +25,186 @@ import org.eclipse.aether.internal.test.util.DependencyGraphParser; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class NearestVersionSelectorTest - extends AbstractDependencyGraphTransformerTest -{ +public class NearestVersionSelectorTest extends AbstractDependencyGraphTransformerTest { @Override - protected ConflictResolver newTransformer() - { - return new ConflictResolver( new NearestVersionSelector(), new JavaScopeSelector(), - new SimpleOptionalitySelector(), new JavaScopeDeriver() ); + protected ConflictResolver newTransformer() { + return new ConflictResolver( + new NearestVersionSelector(), new JavaScopeSelector(), + new SimpleOptionalitySelector(), new JavaScopeDeriver()); } @Override - protected DependencyGraphParser newParser() - { - return new DependencyGraphParser( "transformer/version-resolver/" ); + protected DependencyGraphParser newParser() { + return new DependencyGraphParser("transformer/version-resolver/"); } @Test - public void testSelectHighestVersionFromMultipleVersionsAtSameLevel() - throws Exception - { - DependencyNode root = parseResource( "sibling-versions.txt" ); - assertSame( root, transform( root ) ); + public void testSelectHighestVersionFromMultipleVersionsAtSameLevel() throws Exception { + DependencyNode root = parseResource("sibling-versions.txt"); + assertSame(root, transform(root)); - assertEquals( 1, root.getChildren().size() ); - assertEquals( "3", root.getChildren().get( 0 ).getArtifact().getVersion() ); + assertEquals(1, root.getChildren().size()); + assertEquals("3", root.getChildren().get(0).getArtifact().getVersion()); } @Test - public void testSelectedVersionAtDeeperLevelThanOriginallySeen() - throws Exception - { - DependencyNode root = parseResource( "nearest-underneath-loser-a.txt" ); + public void testSelectedVersionAtDeeperLevelThanOriginallySeen() throws Exception { + DependencyNode root = parseResource("nearest-underneath-loser-a.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - List trail = find( root, "j" ); - assertEquals( 5, trail.size() ); + List trail = find(root, "j"); + assertEquals(5, trail.size()); } @Test - public void testNearestDirtyVersionUnderneathRemovedNode() - throws Exception - { - DependencyNode root = parseResource( "nearest-underneath-loser-b.txt" ); + public void testNearestDirtyVersionUnderneathRemovedNode() throws Exception { + DependencyNode root = parseResource("nearest-underneath-loser-b.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - List trail = find( root, "j" ); - assertEquals( 5, trail.size() ); + List trail = find(root, "j"); + assertEquals(5, trail.size()); } @Test - public void testViolationOfHardConstraintFallsBackToNearestSeenNotFirstSeen() - throws Exception - { - DependencyNode root = parseResource( "range-backtracking.txt" ); + public void testViolationOfHardConstraintFallsBackToNearestSeenNotFirstSeen() throws Exception { + DependencyNode root = parseResource("range-backtracking.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - List trail = find( root, "x" ); - assertEquals( 3, trail.size() ); - assertEquals( "2", trail.get( 0 ).getArtifact().getVersion() ); + List trail = find(root, "x"); + assertEquals(3, trail.size()); + assertEquals("2", trail.get(0).getArtifact().getVersion()); } @Test - public void testCyclicConflictIdGraph() - throws Exception - { - DependencyNode root = parseResource( "conflict-id-cycle.txt" ); + public void testCyclicConflictIdGraph() throws Exception { + DependencyNode root = parseResource("conflict-id-cycle.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - assertEquals( 2, root.getChildren().size() ); - assertEquals( "a", root.getChildren().get( 0 ).getArtifact().getArtifactId() ); - assertEquals( "b", root.getChildren().get( 1 ).getArtifact().getArtifactId() ); - assertTrue( root.getChildren().get( 0 ).getChildren().isEmpty() ); - assertTrue( root.getChildren().get( 1 ).getChildren().isEmpty() ); + assertEquals(2, root.getChildren().size()); + assertEquals("a", root.getChildren().get(0).getArtifact().getArtifactId()); + assertEquals("b", root.getChildren().get(1).getArtifact().getArtifactId()); + assertTrue(root.getChildren().get(0).getChildren().isEmpty()); + assertTrue(root.getChildren().get(1).getChildren().isEmpty()); } - @Test( expected = UnsolvableVersionConflictException.class ) - public void testUnsolvableRangeConflictBetweenHardConstraints() - throws Exception - { - DependencyNode root = parseResource( "unsolvable.txt" ); + @Test(expected = UnsolvableVersionConflictException.class) + public void testUnsolvableRangeConflictBetweenHardConstraints() throws Exception { + DependencyNode root = parseResource("unsolvable.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); } - @Test( expected = UnsolvableVersionConflictException.class ) - public void testUnsolvableRangeConflictWithUnrelatedCycle() - throws Exception - { - DependencyNode root = parseResource( "unsolvable-with-cycle.txt" ); + @Test(expected = UnsolvableVersionConflictException.class) + public void testUnsolvableRangeConflictWithUnrelatedCycle() throws Exception { + DependencyNode root = parseResource("unsolvable-with-cycle.txt"); - transform( root ); + transform(root); } @Test - public void testSolvableConflictBetweenHardConstraints() - throws Exception - { - DependencyNode root = parseResource( "ranges.txt" ); + public void testSolvableConflictBetweenHardConstraints() throws Exception { + DependencyNode root = parseResource("ranges.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); } @Test - public void testConflictGroupCompletelyDroppedFromResolvedTree() - throws Exception - { - DependencyNode root = parseResource( "dead-conflict-group.txt" ); + public void testConflictGroupCompletelyDroppedFromResolvedTree() throws Exception { + DependencyNode root = parseResource("dead-conflict-group.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - assertEquals( 2, root.getChildren().size() ); - assertEquals( "a", root.getChildren().get( 0 ).getArtifact().getArtifactId() ); - assertEquals( "b", root.getChildren().get( 1 ).getArtifact().getArtifactId() ); - assertTrue( root.getChildren().get( 0 ).getChildren().isEmpty() ); - assertTrue( root.getChildren().get( 1 ).getChildren().isEmpty() ); + assertEquals(2, root.getChildren().size()); + assertEquals("a", root.getChildren().get(0).getArtifact().getArtifactId()); + assertEquals("b", root.getChildren().get(1).getArtifact().getArtifactId()); + assertTrue(root.getChildren().get(0).getChildren().isEmpty()); + assertTrue(root.getChildren().get(1).getChildren().isEmpty()); } @Test - public void testNearestSoftVersionPrunedByFartherRange() - throws Exception - { - DependencyNode root = parseResource( "soft-vs-range.txt" ); + public void testNearestSoftVersionPrunedByFartherRange() throws Exception { + DependencyNode root = parseResource("soft-vs-range.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - assertEquals( 2, root.getChildren().size() ); - assertEquals( "a", root.getChildren().get( 0 ).getArtifact().getArtifactId() ); - assertEquals( 0, root.getChildren().get( 0 ).getChildren().size() ); - assertEquals( "b", root.getChildren().get( 1 ).getArtifact().getArtifactId() ); - assertEquals( 1, root.getChildren().get( 1 ).getChildren().size() ); + assertEquals(2, root.getChildren().size()); + assertEquals("a", root.getChildren().get(0).getArtifact().getArtifactId()); + assertEquals(0, root.getChildren().get(0).getChildren().size()); + assertEquals("b", root.getChildren().get(1).getArtifact().getArtifactId()); + assertEquals(1, root.getChildren().get(1).getChildren().size()); } @Test - public void testCyclicGraph() - throws Exception - { - DependencyNode root = parseResource( "cycle.txt" ); + public void testCyclicGraph() throws Exception { + DependencyNode root = parseResource("cycle.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - assertEquals( 2, root.getChildren().size() ); - assertEquals( 1, root.getChildren().get( 0 ).getChildren().size() ); - assertEquals( 0, root.getChildren().get( 0 ).getChildren().get( 0 ).getChildren().size() ); - assertEquals( 0, root.getChildren().get( 1 ).getChildren().size() ); + assertEquals(2, root.getChildren().size()); + assertEquals(1, root.getChildren().get(0).getChildren().size()); + assertEquals( + 0, root.getChildren().get(0).getChildren().get(0).getChildren().size()); + assertEquals(0, root.getChildren().get(1).getChildren().size()); } @Test - public void testLoop() - throws Exception - { - DependencyNode root = parseResource( "loop.txt" ); + public void testLoop() throws Exception { + DependencyNode root = parseResource("loop.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - assertEquals( 0, root.getChildren().size() ); + assertEquals(0, root.getChildren().size()); } @Test - public void testOverlappingCycles() - throws Exception - { - DependencyNode root = parseResource( "overlapping-cycles.txt" ); + public void testOverlappingCycles() throws Exception { + DependencyNode root = parseResource("overlapping-cycles.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - assertEquals( 2, root.getChildren().size() ); + assertEquals(2, root.getChildren().size()); } @Test - public void testScopeDerivationAndConflictResolutionCantHappenForAllNodesBeforeVersionSelection() - throws Exception - { - DependencyNode root = parseResource( "scope-vs-version.txt" ); + public void testScopeDerivationAndConflictResolutionCantHappenForAllNodesBeforeVersionSelection() throws Exception { + DependencyNode root = parseResource("scope-vs-version.txt"); - assertSame( root, transform( root ) ); + assertSame(root, transform(root)); - DependencyNode[] nodes = find( root, "y" ).toArray( new DependencyNode[0] ); - assertEquals( 3, nodes.length ); - assertEquals( "test", nodes[1].getDependency().getScope() ); - assertEquals( "test", nodes[0].getDependency().getScope() ); + DependencyNode[] nodes = find(root, "y").toArray(new DependencyNode[0]); + assertEquals(3, nodes.length); + assertEquals("test", nodes[1].getDependency().getScope()); + assertEquals("test", nodes[0].getDependency().getScope()); } @Test - public void testVerboseMode() - throws Exception - { - DependencyNode root = parseResource( "verbose.txt" ); - - session.setConfigProperty( ConflictResolver.CONFIG_PROP_VERBOSE, Boolean.TRUE ); - assertSame( root, transform( root ) ); - - assertEquals( 2, root.getChildren().size() ); - assertEquals( 1, root.getChildren().get( 0 ).getChildren().size() ); - DependencyNode winner = root.getChildren().get( 0 ).getChildren().get( 0 ); - assertEquals( "test", winner.getDependency().getScope() ); - assertEquals( "compile", winner.getData().get( ConflictResolver.NODE_DATA_ORIGINAL_SCOPE ) ); - assertEquals( false, winner.getData().get( ConflictResolver.NODE_DATA_ORIGINAL_OPTIONALITY) ); - assertEquals( 1, root.getChildren().get( 1 ).getChildren().size() ); - DependencyNode loser = root.getChildren().get( 1 ).getChildren().get( 0 ); - assertEquals( "test", loser.getDependency().getScope() ); - assertEquals( 0, loser.getChildren().size() ); - assertSame( winner, loser.getData().get( ConflictResolver.NODE_DATA_WINNER ) ); - assertEquals( "compile", loser.getData().get( ConflictResolver.NODE_DATA_ORIGINAL_SCOPE ) ); - assertEquals( false, loser.getData().get( ConflictResolver.NODE_DATA_ORIGINAL_OPTIONALITY ) ); + public void testVerboseMode() throws Exception { + DependencyNode root = parseResource("verbose.txt"); + + session.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, Boolean.TRUE); + assertSame(root, transform(root)); + + assertEquals(2, root.getChildren().size()); + assertEquals(1, root.getChildren().get(0).getChildren().size()); + DependencyNode winner = root.getChildren().get(0).getChildren().get(0); + assertEquals("test", winner.getDependency().getScope()); + assertEquals("compile", winner.getData().get(ConflictResolver.NODE_DATA_ORIGINAL_SCOPE)); + assertEquals(false, winner.getData().get(ConflictResolver.NODE_DATA_ORIGINAL_OPTIONALITY)); + assertEquals(1, root.getChildren().get(1).getChildren().size()); + DependencyNode loser = root.getChildren().get(1).getChildren().get(0); + assertEquals("test", loser.getDependency().getScope()); + assertEquals(0, loser.getChildren().size()); + assertSame(winner, loser.getData().get(ConflictResolver.NODE_DATA_WINNER)); + assertEquals("compile", loser.getData().get(ConflictResolver.NODE_DATA_ORIGINAL_SCOPE)); + assertEquals(false, loser.getData().get(ConflictResolver.NODE_DATA_ORIGINAL_OPTIONALITY)); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/RootQueueTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/RootQueueTest.java index f609ed726..04d22b351 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/RootQueueTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/RootQueueTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,89 +16,84 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.transformer; import org.eclipse.aether.util.graph.transformer.ConflictIdSorter.ConflictId; import org.eclipse.aether.util.graph.transformer.ConflictIdSorter.RootQueue; import org.junit.Test; -public class RootQueueTest -{ +import static org.junit.Assert.*; + +public class RootQueueTest { @Test - public void testIsEmpty() - { - ConflictId id = new ConflictId( "a", 0 ); - RootQueue queue = new RootQueue( 10 ); - assertTrue( queue.isEmpty() ); - queue.add( id ); - assertFalse( queue.isEmpty() ); - assertSame( id, queue.remove() ); - assertTrue( queue.isEmpty() ); + public void testIsEmpty() { + ConflictId id = new ConflictId("a", 0); + RootQueue queue = new RootQueue(10); + assertTrue(queue.isEmpty()); + queue.add(id); + assertFalse(queue.isEmpty()); + assertSame(id, queue.remove()); + assertTrue(queue.isEmpty()); } @Test - public void testAddSortsByDepth() - { - ConflictId id1 = new ConflictId( "a", 0 ); - ConflictId id2 = new ConflictId( "b", 1 ); - ConflictId id3 = new ConflictId( "c", 2 ); - ConflictId id4 = new ConflictId( "d", 3 ); + public void testAddSortsByDepth() { + ConflictId id1 = new ConflictId("a", 0); + ConflictId id2 = new ConflictId("b", 1); + ConflictId id3 = new ConflictId("c", 2); + ConflictId id4 = new ConflictId("d", 3); - RootQueue queue = new RootQueue( 10 ); - queue.add( id1 ); - queue.add( id2 ); - queue.add( id3 ); - queue.add( id4 ); - assertSame( id1, queue.remove() ); - assertSame( id2, queue.remove() ); - assertSame( id3, queue.remove() ); - assertSame( id4, queue.remove() ); + RootQueue queue = new RootQueue(10); + queue.add(id1); + queue.add(id2); + queue.add(id3); + queue.add(id4); + assertSame(id1, queue.remove()); + assertSame(id2, queue.remove()); + assertSame(id3, queue.remove()); + assertSame(id4, queue.remove()); - queue = new RootQueue( 10 ); - queue.add( id4 ); - queue.add( id3 ); - queue.add( id2 ); - queue.add( id1 ); - assertSame( id1, queue.remove() ); - assertSame( id2, queue.remove() ); - assertSame( id3, queue.remove() ); - assertSame( id4, queue.remove() ); + queue = new RootQueue(10); + queue.add(id4); + queue.add(id3); + queue.add(id2); + queue.add(id1); + assertSame(id1, queue.remove()); + assertSame(id2, queue.remove()); + assertSame(id3, queue.remove()); + assertSame(id4, queue.remove()); } @Test - public void testAddWithArrayCompact() - { - ConflictId id = new ConflictId( "a", 0 ); + public void testAddWithArrayCompact() { + ConflictId id = new ConflictId("a", 0); - RootQueue queue = new RootQueue( 10 ); - assertTrue( queue.isEmpty() ); - queue.add( id ); - assertFalse( queue.isEmpty() ); - assertSame( id, queue.remove() ); - assertTrue( queue.isEmpty() ); - queue.add( id ); - assertFalse( queue.isEmpty() ); - assertSame( id, queue.remove() ); - assertTrue( queue.isEmpty() ); + RootQueue queue = new RootQueue(10); + assertTrue(queue.isEmpty()); + queue.add(id); + assertFalse(queue.isEmpty()); + assertSame(id, queue.remove()); + assertTrue(queue.isEmpty()); + queue.add(id); + assertFalse(queue.isEmpty()); + assertSame(id, queue.remove()); + assertTrue(queue.isEmpty()); } @Test - public void testAddMinimumAfterSomeRemoves() - { - ConflictId id1 = new ConflictId( "a", 0 ); - ConflictId id2 = new ConflictId( "b", 1 ); - ConflictId id3 = new ConflictId( "c", 2 ); + public void testAddMinimumAfterSomeRemoves() { + ConflictId id1 = new ConflictId("a", 0); + ConflictId id2 = new ConflictId("b", 1); + ConflictId id3 = new ConflictId("c", 2); - RootQueue queue = new RootQueue( 10 ); - queue.add( id2 ); - queue.add( id3 ); - assertSame( id2, queue.remove() ); - queue.add( id1 ); - assertSame( id1, queue.remove() ); - assertSame( id3, queue.remove() ); - assertTrue( queue.isEmpty() ); + RootQueue queue = new RootQueue(10); + queue.add(id2); + queue.add(id3); + assertSame(id2, queue.remove()); + queue.add(id1); + assertSame(id1, queue.remove()); + assertSame(id3, queue.remove()); + assertTrue(queue.isEmpty()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/SimpleConflictMarker.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/SimpleConflictMarker.java index 4a02f6f92..3df73a068 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/SimpleConflictMarker.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/SimpleConflictMarker.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,10 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.transformer; import java.util.IdentityHashMap; import java.util.Map; -import static java.util.Objects.requireNonNull; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.artifact.Artifact; @@ -30,53 +28,46 @@ import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.DependencyNode; +import static java.util.Objects.requireNonNull; + /** * Set "groupId:artId:classifier:extension" as conflict marker for every node. */ -class SimpleConflictMarker - implements DependencyGraphTransformer -{ +class SimpleConflictMarker implements DependencyGraphTransformer { - public DependencyNode transformGraph( DependencyNode node, DependencyGraphTransformationContext context ) - throws RepositoryException - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( context, "context cannot be null" ); - @SuppressWarnings( "unchecked" ) + public DependencyNode transformGraph(DependencyNode node, DependencyGraphTransformationContext context) + throws RepositoryException { + requireNonNull(node, "node cannot be null"); + requireNonNull(context, "context cannot be null"); + @SuppressWarnings("unchecked") Map conflictIds = - (Map) context.get( TransformationContextKeys.CONFLICT_IDS ); - if ( conflictIds == null ) - { + (Map) context.get(TransformationContextKeys.CONFLICT_IDS); + if (conflictIds == null) { conflictIds = new IdentityHashMap<>(); - context.put( TransformationContextKeys.CONFLICT_IDS, conflictIds ); + context.put(TransformationContextKeys.CONFLICT_IDS, conflictIds); } - mark( node, conflictIds ); + mark(node, conflictIds); return node; } - private void mark( DependencyNode node, Map conflictIds ) - { + private void mark(DependencyNode node, Map conflictIds) { Dependency dependency = node.getDependency(); - if ( dependency != null ) - { + if (dependency != null) { Artifact artifact = dependency.getArtifact(); - String key = - String.format( "%s:%s:%s:%s", artifact.getGroupId(), artifact.getArtifactId(), - artifact.getClassifier(), artifact.getExtension() ); + String key = String.format( + "%s:%s:%s:%s", + artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier(), artifact.getExtension()); - if ( conflictIds.put( node, key ) != null ) - { + if (conflictIds.put(node, key) != null) { return; } } - for ( DependencyNode child : node.getChildren() ) - { - mark( child, conflictIds ); + for (DependencyNode child : node.getChildren()) { + mark(child, conflictIds); } } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/SimpleOptionalitySelectorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/SimpleOptionalitySelectorTest.java index c2b810237..8fd5733b3 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/SimpleOptionalitySelectorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/transformer/SimpleOptionalitySelectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.transformer; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,66 +16,60 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.transformer; import org.eclipse.aether.collection.DependencyGraphTransformer; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.internal.test.util.DependencyGraphParser; import org.junit.Test; -public class SimpleOptionalitySelectorTest - extends AbstractDependencyGraphTransformerTest -{ +import static org.junit.Assert.*; + +public class SimpleOptionalitySelectorTest extends AbstractDependencyGraphTransformerTest { @Override - protected DependencyGraphTransformer newTransformer() - { - return new ConflictResolver( new NearestVersionSelector(), new JavaScopeSelector(), - new SimpleOptionalitySelector(), new JavaScopeDeriver() ); + protected DependencyGraphTransformer newTransformer() { + return new ConflictResolver( + new NearestVersionSelector(), new JavaScopeSelector(), + new SimpleOptionalitySelector(), new JavaScopeDeriver()); } @Override - protected DependencyGraphParser newParser() - { - return new DependencyGraphParser( "transformer/optionality-selector/" ); + protected DependencyGraphParser newParser() { + return new DependencyGraphParser("transformer/optionality-selector/"); } @Test - public void testDeriveOptionality() - throws Exception - { - DependencyNode root = parseResource( "derive.txt" ); - assertSame( root, transform( root ) ); + public void testDeriveOptionality() throws Exception { + DependencyNode root = parseResource("derive.txt"); + assertSame(root, transform(root)); - assertEquals( 2, root.getChildren().size() ); - assertTrue( root.getChildren().get( 0 ).getDependency().isOptional() ); - assertTrue( root.getChildren().get( 0 ).getChildren().get( 0 ).getDependency().isOptional() ); - assertFalse( root.getChildren().get( 1 ).getDependency().isOptional() ); - assertFalse( root.getChildren().get( 1 ).getChildren().get( 0 ).getDependency().isOptional() ); + assertEquals(2, root.getChildren().size()); + assertTrue(root.getChildren().get(0).getDependency().isOptional()); + assertTrue( + root.getChildren().get(0).getChildren().get(0).getDependency().isOptional()); + assertFalse(root.getChildren().get(1).getDependency().isOptional()); + assertFalse( + root.getChildren().get(1).getChildren().get(0).getDependency().isOptional()); } @Test - public void testResolveOptionalityConflict_NonOptionalWins() - throws Exception - { - DependencyNode root = parseResource( "conflict.txt" ); - assertSame( root, transform( root ) ); + public void testResolveOptionalityConflict_NonOptionalWins() throws Exception { + DependencyNode root = parseResource("conflict.txt"); + assertSame(root, transform(root)); - assertEquals( 2, root.getChildren().size() ); - assertTrue( root.getChildren().get( 0 ).getDependency().isOptional() ); - assertFalse( root.getChildren().get( 0 ).getChildren().get( 0 ).getDependency().isOptional() ); + assertEquals(2, root.getChildren().size()); + assertTrue(root.getChildren().get(0).getDependency().isOptional()); + assertFalse( + root.getChildren().get(0).getChildren().get(0).getDependency().isOptional()); } @Test - public void testResolveOptionalityConflict_DirectDeclarationWins() - throws Exception - { - DependencyNode root = parseResource( "conflict-direct-dep.txt" ); - assertSame( root, transform( root ) ); + public void testResolveOptionalityConflict_DirectDeclarationWins() throws Exception { + DependencyNode root = parseResource("conflict-direct-dep.txt"); + assertSame(root, transform(root)); - assertEquals( 2, root.getChildren().size() ); - assertTrue( root.getChildren().get( 1 ).getDependency().isOptional() ); + assertEquals(2, root.getChildren().size()); + assertTrue(root.getChildren().get(1).getDependency().isOptional()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/AndDependencyTraverserTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/AndDependencyTraverserTest.java index 991807c94..3fdb5867f 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/AndDependencyTraverserTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/AndDependencyTraverserTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.traverser; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,9 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.traverser; -import static java.util.Objects.requireNonNull; -import static org.junit.Assert.*; +import java.util.Collections; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.DefaultArtifact; @@ -33,153 +31,132 @@ import org.junit.Before; import org.junit.Test; -import java.util.Collections; +import static java.util.Objects.requireNonNull; +import static org.junit.Assert.*; -public class AndDependencyTraverserTest -{ +public class AndDependencyTraverserTest { - static class DummyDependencyTraverser - implements DependencyTraverser - { + static class DummyDependencyTraverser implements DependencyTraverser { private final boolean traverse; private final DependencyTraverser child; - public DummyDependencyTraverser() - { - this( true ); + public DummyDependencyTraverser() { + this(true); } - public DummyDependencyTraverser( boolean traverse ) - { + public DummyDependencyTraverser(boolean traverse) { this.traverse = traverse; this.child = this; } - public DummyDependencyTraverser( boolean traverse, DependencyTraverser child ) - { + public DummyDependencyTraverser(boolean traverse, DependencyTraverser child) { this.traverse = traverse; this.child = child; } - public boolean traverseDependency( Dependency dependency ) - { - requireNonNull( dependency, "dependency cannot be null" ); + public boolean traverseDependency(Dependency dependency) { + requireNonNull(dependency, "dependency cannot be null"); return traverse; } - public DependencyTraverser deriveChildTraverser( DependencyCollectionContext context ) - { - requireNonNull( context, "context cannot be null" ); + public DependencyTraverser deriveChildTraverser(DependencyCollectionContext context) { + requireNonNull(context, "context cannot be null"); return child; } - } private RepositorySystemSession session; private DependencyCollectionContext context; @Before - public void setup() - { + public void setup() { session = TestUtils.newSession(); - context = TestUtils.newCollectionContext( session, null, Collections.emptyList() ); + context = TestUtils.newCollectionContext(session, null, Collections.emptyList()); } @After - public void teardown() throws Exception - { - if ( session.getLocalRepository() != null ) - { - TestFileUtils.deleteFile( session.getLocalRepository().getBasedir() ); + public void teardown() throws Exception { + if (session.getLocalRepository() != null) { + TestFileUtils.deleteFile(session.getLocalRepository().getBasedir()); } session = null; context = null; } @Test - public void testNewInstance() - { - assertNull( AndDependencyTraverser.newInstance( null, null ) ); + public void testNewInstance() { + assertNull(AndDependencyTraverser.newInstance(null, null)); DependencyTraverser traverser = new DummyDependencyTraverser(); - assertSame( traverser, AndDependencyTraverser.newInstance( traverser, null ) ); - assertSame( traverser, AndDependencyTraverser.newInstance( null, traverser ) ); - assertSame( traverser, AndDependencyTraverser.newInstance( traverser, traverser ) ); - assertNotNull( AndDependencyTraverser.newInstance( traverser, new DummyDependencyTraverser() ) ); + assertSame(traverser, AndDependencyTraverser.newInstance(traverser, null)); + assertSame(traverser, AndDependencyTraverser.newInstance(null, traverser)); + assertSame(traverser, AndDependencyTraverser.newInstance(traverser, traverser)); + assertNotNull(AndDependencyTraverser.newInstance(traverser, new DummyDependencyTraverser())); } @Test - public void testTraverseDependency() - { - Dependency dependency = new Dependency( new DefaultArtifact( "g:a:v:1" ), "runtime" ); + public void testTraverseDependency() { + Dependency dependency = new Dependency(new DefaultArtifact("g:a:v:1"), "runtime"); DependencyTraverser traverser = new AndDependencyTraverser(); - assertTrue( traverser.traverseDependency( dependency ) ); + assertTrue(traverser.traverseDependency(dependency)); traverser = - new AndDependencyTraverser( new DummyDependencyTraverser( false ), new DummyDependencyTraverser( false ) ); - assertFalse( traverser.traverseDependency( dependency ) ); + new AndDependencyTraverser(new DummyDependencyTraverser(false), new DummyDependencyTraverser(false)); + assertFalse(traverser.traverseDependency(dependency)); - traverser = - new AndDependencyTraverser( new DummyDependencyTraverser( true ), new DummyDependencyTraverser( false ) ); - assertFalse( traverser.traverseDependency( dependency ) ); + traverser = new AndDependencyTraverser(new DummyDependencyTraverser(true), new DummyDependencyTraverser(false)); + assertFalse(traverser.traverseDependency(dependency)); - traverser = - new AndDependencyTraverser( new DummyDependencyTraverser( true ), new DummyDependencyTraverser( true ) ); - assertTrue( traverser.traverseDependency( dependency ) ); + traverser = new AndDependencyTraverser(new DummyDependencyTraverser(true), new DummyDependencyTraverser(true)); + assertTrue(traverser.traverseDependency(dependency)); } @Test - public void testDeriveChildTraverser_Unchanged() - { - DependencyTraverser other1 = new DummyDependencyTraverser( true ); - DependencyTraverser other2 = new DummyDependencyTraverser( false ); - DependencyTraverser traverser = new AndDependencyTraverser( other1, other2 ); - assertSame( traverser, traverser.deriveChildTraverser( context ) ); + public void testDeriveChildTraverser_Unchanged() { + DependencyTraverser other1 = new DummyDependencyTraverser(true); + DependencyTraverser other2 = new DummyDependencyTraverser(false); + DependencyTraverser traverser = new AndDependencyTraverser(other1, other2); + assertSame(traverser, traverser.deriveChildTraverser(context)); } @Test - public void testDeriveChildTraverser_OneRemaining() - { - DependencyTraverser other1 = new DummyDependencyTraverser( true ); - DependencyTraverser other2 = new DummyDependencyTraverser( false, null ); - DependencyTraverser traverser = new AndDependencyTraverser( other1, other2 ); - assertSame( other1, traverser.deriveChildTraverser( context ) ); + public void testDeriveChildTraverser_OneRemaining() { + DependencyTraverser other1 = new DummyDependencyTraverser(true); + DependencyTraverser other2 = new DummyDependencyTraverser(false, null); + DependencyTraverser traverser = new AndDependencyTraverser(other1, other2); + assertSame(other1, traverser.deriveChildTraverser(context)); } @Test - public void testDeriveChildTraverser_ZeroRemaining() - { - DependencyTraverser other1 = new DummyDependencyTraverser( true, null ); - DependencyTraverser other2 = new DummyDependencyTraverser( false, null ); - DependencyTraverser traverser = new AndDependencyTraverser( other1, other2 ); - assertNull( traverser.deriveChildTraverser( context ) ); + public void testDeriveChildTraverser_ZeroRemaining() { + DependencyTraverser other1 = new DummyDependencyTraverser(true, null); + DependencyTraverser other2 = new DummyDependencyTraverser(false, null); + DependencyTraverser traverser = new AndDependencyTraverser(other1, other2); + assertNull(traverser.deriveChildTraverser(context)); } @Test - public void testEquals() - { - DependencyTraverser other1 = new DummyDependencyTraverser( true ); - DependencyTraverser other2 = new DummyDependencyTraverser( false ); - DependencyTraverser traverser1 = new AndDependencyTraverser( other1, other2 ); - DependencyTraverser traverser2 = new AndDependencyTraverser( other2, other1 ); - DependencyTraverser traverser3 = new AndDependencyTraverser( other1 ); - assertEquals( traverser1, traverser1 ); - assertEquals( traverser1, traverser2 ); - assertNotEquals( traverser1, traverser3 ); - assertNotEquals( traverser1, this ); - assertNotEquals( traverser1, null ); + public void testEquals() { + DependencyTraverser other1 = new DummyDependencyTraverser(true); + DependencyTraverser other2 = new DummyDependencyTraverser(false); + DependencyTraverser traverser1 = new AndDependencyTraverser(other1, other2); + DependencyTraverser traverser2 = new AndDependencyTraverser(other2, other1); + DependencyTraverser traverser3 = new AndDependencyTraverser(other1); + assertEquals(traverser1, traverser1); + assertEquals(traverser1, traverser2); + assertNotEquals(traverser1, traverser3); + assertNotEquals(traverser1, this); + assertNotEquals(traverser1, null); } @Test - public void testHashCode() - { - DependencyTraverser other1 = new DummyDependencyTraverser( true ); - DependencyTraverser other2 = new DummyDependencyTraverser( false ); - DependencyTraverser traverser1 = new AndDependencyTraverser( other1, other2 ); - DependencyTraverser traverser2 = new AndDependencyTraverser( other2, other1 ); - assertEquals( traverser1.hashCode(), traverser2.hashCode() ); + public void testHashCode() { + DependencyTraverser other1 = new DummyDependencyTraverser(true); + DependencyTraverser other2 = new DummyDependencyTraverser(false); + DependencyTraverser traverser1 = new AndDependencyTraverser(other1, other2); + DependencyTraverser traverser2 = new AndDependencyTraverser(other2, other1); + assertEquals(traverser1.hashCode(), traverser2.hashCode()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/FatArtifactTraverserTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/FatArtifactTraverserTest.java index a7982e340..a23ba82d2 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/FatArtifactTraverserTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/FatArtifactTraverserTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.traverser; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.traverser; import java.util.Collections; import java.util.Map; @@ -36,68 +33,61 @@ import org.junit.Before; import org.junit.Test; -public class FatArtifactTraverserTest -{ +import static org.junit.Assert.*; + +public class FatArtifactTraverserTest { private RepositorySystemSession session; private DependencyCollectionContext context; @Before - public void setup() - { + public void setup() { session = TestUtils.newSession(); - context = TestUtils.newCollectionContext( session, null, Collections.emptyList() ); + context = TestUtils.newCollectionContext(session, null, Collections.emptyList()); } @After - public void teardown() throws Exception - { - if ( session.getLocalRepository() != null ) - { - TestFileUtils.deleteFile( session.getLocalRepository().getBasedir() ); + public void teardown() throws Exception { + if (session.getLocalRepository() != null) { + TestFileUtils.deleteFile(session.getLocalRepository().getBasedir()); } session = null; context = null; } @Test - public void testTraverseDependency() - { + public void testTraverseDependency() { DependencyTraverser traverser = new FatArtifactTraverser(); Map props = null; - assertTrue( traverser.traverseDependency( new Dependency( new DefaultArtifact( "g:a:v:1", props ), "test" ) ) ); - props = Collections.singletonMap( ArtifactProperties.INCLUDES_DEPENDENCIES, "false" ); - assertTrue( traverser.traverseDependency( new Dependency( new DefaultArtifact( "g:a:v:1", props ), "test" ) ) ); - props = Collections.singletonMap( ArtifactProperties.INCLUDES_DEPENDENCIES, "unrecognized" ); - assertTrue( traverser.traverseDependency( new Dependency( new DefaultArtifact( "g:a:v:1", props ), "test" ) ) ); - props = Collections.singletonMap( ArtifactProperties.INCLUDES_DEPENDENCIES, "true" ); - assertFalse( traverser.traverseDependency( new Dependency( new DefaultArtifact( "g:a:v:1", props ), "test" ) ) ); + assertTrue(traverser.traverseDependency(new Dependency(new DefaultArtifact("g:a:v:1", props), "test"))); + props = Collections.singletonMap(ArtifactProperties.INCLUDES_DEPENDENCIES, "false"); + assertTrue(traverser.traverseDependency(new Dependency(new DefaultArtifact("g:a:v:1", props), "test"))); + props = Collections.singletonMap(ArtifactProperties.INCLUDES_DEPENDENCIES, "unrecognized"); + assertTrue(traverser.traverseDependency(new Dependency(new DefaultArtifact("g:a:v:1", props), "test"))); + props = Collections.singletonMap(ArtifactProperties.INCLUDES_DEPENDENCIES, "true"); + assertFalse(traverser.traverseDependency(new Dependency(new DefaultArtifact("g:a:v:1", props), "test"))); } @Test - public void testDeriveChildTraverser() - { + public void testDeriveChildTraverser() { DependencyTraverser traverser = new FatArtifactTraverser(); - assertSame( traverser, traverser.deriveChildTraverser( context ) ); + assertSame(traverser, traverser.deriveChildTraverser(context)); } @Test - public void testEquals() - { + public void testEquals() { DependencyTraverser traverser1 = new FatArtifactTraverser(); DependencyTraverser traverser2 = new FatArtifactTraverser(); - assertEquals( traverser1, traverser1 ); - assertEquals( traverser1, traverser2 ); - assertNotEquals( traverser1, this ); - assertNotEquals( traverser1, null ); + assertEquals(traverser1, traverser1); + assertEquals(traverser1, traverser2); + assertNotEquals(traverser1, this); + assertNotEquals(traverser1, null); } @Test - public void testHashCode() - { + public void testHashCode() { DependencyTraverser traverser1 = new FatArtifactTraverser(); DependencyTraverser traverser2 = new FatArtifactTraverser(); - assertEquals( traverser1.hashCode(), traverser2.hashCode() ); + assertEquals(traverser1.hashCode(), traverser2.hashCode()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/StaticDependencyTraverserTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/StaticDependencyTraverserTest.java index d47041c62..a2e6aaaa8 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/StaticDependencyTraverserTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/traverser/StaticDependencyTraverserTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.traverser; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.graph.traverser; -import static org.junit.Assert.*; +import java.util.Collections; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.DefaultArtifact; @@ -32,68 +31,59 @@ import org.junit.Before; import org.junit.Test; -import java.util.Collections; +import static org.junit.Assert.*; -public class StaticDependencyTraverserTest -{ +public class StaticDependencyTraverserTest { private RepositorySystemSession session; private DependencyCollectionContext context; @Before - public void setup() - { + public void setup() { session = TestUtils.newSession(); - context = TestUtils.newCollectionContext( session, null, Collections.emptyList() ); + context = TestUtils.newCollectionContext(session, null, Collections.emptyList()); } @After - public void teardown() throws Exception - { - if ( session.getLocalRepository() != null ) - { - TestFileUtils.deleteFile( session.getLocalRepository().getBasedir() ); + public void teardown() throws Exception { + if (session.getLocalRepository() != null) { + TestFileUtils.deleteFile(session.getLocalRepository().getBasedir()); } session = null; context = null; } @Test - public void testTraverseDependency() - { - Dependency dependency = new Dependency( new DefaultArtifact( "g:a:v:1" ), "runtime" ); - DependencyTraverser traverser = new StaticDependencyTraverser( true ); - assertTrue( traverser.traverseDependency( dependency ) ); - traverser = new StaticDependencyTraverser( false ); - assertFalse( traverser.traverseDependency( dependency ) ); + public void testTraverseDependency() { + Dependency dependency = new Dependency(new DefaultArtifact("g:a:v:1"), "runtime"); + DependencyTraverser traverser = new StaticDependencyTraverser(true); + assertTrue(traverser.traverseDependency(dependency)); + traverser = new StaticDependencyTraverser(false); + assertFalse(traverser.traverseDependency(dependency)); } @Test - public void testDeriveChildTraverser() - { - DependencyTraverser traverser = new StaticDependencyTraverser( true ); - assertSame( traverser, traverser.deriveChildTraverser( context ) ); + public void testDeriveChildTraverser() { + DependencyTraverser traverser = new StaticDependencyTraverser(true); + assertSame(traverser, traverser.deriveChildTraverser(context)); } @Test - public void testEquals() - { - DependencyTraverser traverser1 = new StaticDependencyTraverser( true ); - DependencyTraverser traverser2 = new StaticDependencyTraverser( true ); - DependencyTraverser traverser3 = new StaticDependencyTraverser( false ); - assertEquals( traverser1, traverser1 ); - assertEquals( traverser1, traverser2 ); - assertNotEquals( traverser1, traverser3 ); - assertNotEquals( traverser1, this ); - assertNotEquals( traverser1, null ); + public void testEquals() { + DependencyTraverser traverser1 = new StaticDependencyTraverser(true); + DependencyTraverser traverser2 = new StaticDependencyTraverser(true); + DependencyTraverser traverser3 = new StaticDependencyTraverser(false); + assertEquals(traverser1, traverser1); + assertEquals(traverser1, traverser2); + assertNotEquals(traverser1, traverser3); + assertNotEquals(traverser1, this); + assertNotEquals(traverser1, null); } @Test - public void testHashCode() - { - DependencyTraverser traverser1 = new StaticDependencyTraverser( true ); - DependencyTraverser traverser2 = new StaticDependencyTraverser( true ); - assertEquals( traverser1.hashCode(), traverser2.hashCode() ); + public void testHashCode() { + DependencyTraverser traverser1 = new StaticDependencyTraverser(true); + DependencyTraverser traverser2 = new StaticDependencyTraverser(true); + assertEquals(traverser1.hashCode(), traverser2.hashCode()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/AbstractVersionFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/AbstractVersionFilterTest.java index 13fd4b01b..0645babd9 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/AbstractVersionFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/AbstractVersionFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.versions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.versions; import java.util.Iterator; @@ -37,60 +34,50 @@ import org.junit.After; import org.junit.Before; -public abstract class AbstractVersionFilterTest -{ +import static org.junit.Assert.*; + +public abstract class AbstractVersionFilterTest { protected DefaultRepositorySystemSession session; @Before - public void setUp() - { + public void setUp() { session = TestUtils.newSession(); } @After - public void tearDown() - { + public void tearDown() { session = null; } - protected VersionFilter.VersionFilterContext newContext( String gav, String... versions ) - { + protected VersionFilter.VersionFilterContext newContext(String gav, String... versions) { VersionRangeRequest request = new VersionRangeRequest(); - request.setArtifact( new DefaultArtifact( gav ) ); - VersionRangeResult result = new VersionRangeResult( request ); + request.setArtifact(new DefaultArtifact(gav)); + VersionRangeResult result = new VersionRangeResult(request); VersionScheme scheme = new GenericVersionScheme(); - try - { - result.setVersionConstraint( scheme.parseVersionConstraint( request.getArtifact().getVersion() ) ); - for ( String version : versions ) - { - result.addVersion( scheme.parseVersion( version ) ); + try { + result.setVersionConstraint( + scheme.parseVersionConstraint(request.getArtifact().getVersion())); + for (String version : versions) { + result.addVersion(scheme.parseVersion(version)); } + } catch (InvalidVersionSpecificationException e) { + throw new IllegalArgumentException(e); } - catch ( InvalidVersionSpecificationException e ) - { - throw new IllegalArgumentException( e ); - } - return TestUtils.newVersionFilterContext( session, result ); + return TestUtils.newVersionFilterContext(session, result); } - protected VersionFilter derive( VersionFilter filter, String gav ) - { - return filter.deriveChildFilter( TestUtils.newCollectionContext( session, - new Dependency( new DefaultArtifact( gav ), "" ), - null ) ); + protected VersionFilter derive(VersionFilter filter, String gav) { + return filter.deriveChildFilter( + TestUtils.newCollectionContext(session, new Dependency(new DefaultArtifact(gav), ""), null)); } - protected void assertVersions( VersionFilter.VersionFilterContext context, String... versions ) - { - assertEquals( versions.length, context.getCount() ); + protected void assertVersions(VersionFilter.VersionFilterContext context, String... versions) { + assertEquals(versions.length, context.getCount()); Iterator it = context.iterator(); - for ( String version : versions ) - { - assertTrue( it.hasNext() ); - assertEquals( version, it.next().toString() ); + for (String version : versions) { + assertTrue(it.hasNext()); + assertEquals(version, it.next().toString()); } } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/ChainedVersionFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/ChainedVersionFilterTest.java index 6c0c75015..4a7f35b47 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/ChainedVersionFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/ChainedVersionFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.versions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.versions; import org.eclipse.aether.collection.DependencyCollectionContext; import org.eclipse.aether.collection.VersionFilter; @@ -29,58 +26,49 @@ import org.eclipse.aether.util.graph.version.SnapshotVersionFilter; import org.junit.Test; -public class ChainedVersionFilterTest - extends AbstractVersionFilterTest -{ +import static org.junit.Assert.*; + +public class ChainedVersionFilterTest extends AbstractVersionFilterTest { @Test - public void testFilterVersions() - throws Exception - { + public void testFilterVersions() throws Exception { VersionFilter filter = - ChainedVersionFilter.newInstance( new SnapshotVersionFilter(), new HighestVersionFilter() ); - VersionFilterContext ctx = newContext( "g:a:[1,9]", "1", "2", "3-SNAPSHOT" ); - filter.filterVersions( ctx ); - assertVersions( ctx, "2" ); + ChainedVersionFilter.newInstance(new SnapshotVersionFilter(), new HighestVersionFilter()); + VersionFilterContext ctx = newContext("g:a:[1,9]", "1", "2", "3-SNAPSHOT"); + filter.filterVersions(ctx); + assertVersions(ctx, "2"); } @Test - public void testDeriveChildFilter() - { + public void testDeriveChildFilter() { VersionFilter filter1 = new HighestVersionFilter(); - VersionFilter filter2 = new VersionFilter() - { - public void filterVersions( VersionFilterContext context ) - { - } + VersionFilter filter2 = new VersionFilter() { + public void filterVersions(VersionFilterContext context) {} - public VersionFilter deriveChildFilter( DependencyCollectionContext context ) - { + public VersionFilter deriveChildFilter(DependencyCollectionContext context) { return null; } }; - VersionFilter filter = ChainedVersionFilter.newInstance( filter1 ); - assertSame( filter, derive( filter, "g:a:1" ) ); + VersionFilter filter = ChainedVersionFilter.newInstance(filter1); + assertSame(filter, derive(filter, "g:a:1")); - filter = ChainedVersionFilter.newInstance( filter2 ); - assertSame( null, derive( filter, "g:a:1" ) ); + filter = ChainedVersionFilter.newInstance(filter2); + assertSame(null, derive(filter, "g:a:1")); - filter = ChainedVersionFilter.newInstance( filter1, filter2 ); - assertSame( filter1, derive( filter, "g:a:1" ) ); + filter = ChainedVersionFilter.newInstance(filter1, filter2); + assertSame(filter1, derive(filter, "g:a:1")); - filter = ChainedVersionFilter.newInstance( filter2, filter1 ); - assertSame( filter1, derive( filter, "g:a:1" ) ); + filter = ChainedVersionFilter.newInstance(filter2, filter1); + assertSame(filter1, derive(filter, "g:a:1")); } - @SuppressWarnings( "EqualsWithItself" ) + @SuppressWarnings("EqualsWithItself") @Test - public void testEquals() - { - VersionFilter filter = ChainedVersionFilter.newInstance( new HighestVersionFilter() ); - assertNotEquals( null, filter ); - assertEquals( filter, filter ); - assertEquals( filter, ChainedVersionFilter.newInstance( new HighestVersionFilter() ) ); + public void testEquals() { + VersionFilter filter = ChainedVersionFilter.newInstance(new HighestVersionFilter()); + assertNotEquals(null, filter); + assertEquals(filter, filter); + assertEquals(filter, ChainedVersionFilter.newInstance(new HighestVersionFilter())); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/ContextualSnapshotVersionFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/ContextualSnapshotVersionFilterTest.java index a9cb1a886..99d712f6e 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/ContextualSnapshotVersionFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/ContextualSnapshotVersionFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.versions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.versions; import org.eclipse.aether.collection.VersionFilter; import org.eclipse.aether.collection.VersionFilter.VersionFilterContext; @@ -27,47 +24,42 @@ import org.eclipse.aether.util.graph.version.SnapshotVersionFilter; import org.junit.Test; -public class ContextualSnapshotVersionFilterTest - extends AbstractVersionFilterTest -{ +import static org.junit.Assert.*; + +public class ContextualSnapshotVersionFilterTest extends AbstractVersionFilterTest { @Test - public void testFilterVersions() - throws Exception - { + public void testFilterVersions() throws Exception { VersionFilter filter = new ContextualSnapshotVersionFilter(); - VersionFilterContext ctx = newContext( "g:a:[1,9]", "1", "2-SNAPSHOT" ); - filter.filterVersions( ctx ); - assertVersions( ctx, "1", "2-SNAPSHOT" ); + VersionFilterContext ctx = newContext("g:a:[1,9]", "1", "2-SNAPSHOT"); + filter.filterVersions(ctx); + assertVersions(ctx, "1", "2-SNAPSHOT"); - ctx = newContext( "g:a:[1,9]", "1", "2-SNAPSHOT" ); - derive( filter, "g:a:1" ).filterVersions( ctx ); - assertVersions( ctx, "1" ); + ctx = newContext("g:a:[1,9]", "1", "2-SNAPSHOT"); + derive(filter, "g:a:1").filterVersions(ctx); + assertVersions(ctx, "1"); - ctx = newContext( "g:a:[1,9]", "1", "2-SNAPSHOT" ); - session.setConfigProperty( ContextualSnapshotVersionFilter.CONFIG_PROP_ENABLE, "true" ); - derive( filter, "g:a:1-SNAPSHOT" ).filterVersions( ctx ); - assertVersions( ctx, "1" ); + ctx = newContext("g:a:[1,9]", "1", "2-SNAPSHOT"); + session.setConfigProperty(ContextualSnapshotVersionFilter.CONFIG_PROP_ENABLE, "true"); + derive(filter, "g:a:1-SNAPSHOT").filterVersions(ctx); + assertVersions(ctx, "1"); } @Test - public void testDeriveChildFilter() - { + public void testDeriveChildFilter() { ContextualSnapshotVersionFilter filter = new ContextualSnapshotVersionFilter(); - assertTrue( derive( filter, "g:a:1" ) instanceof SnapshotVersionFilter ); - assertSame( null, derive( filter, "g:a:1-SNAPSHOT" ) ); - session.setConfigProperty( ContextualSnapshotVersionFilter.CONFIG_PROP_ENABLE, "true" ); - assertTrue( derive( filter, "g:a:1-SNAPSHOT" ) instanceof SnapshotVersionFilter ); + assertTrue(derive(filter, "g:a:1") instanceof SnapshotVersionFilter); + assertSame(null, derive(filter, "g:a:1-SNAPSHOT")); + session.setConfigProperty(ContextualSnapshotVersionFilter.CONFIG_PROP_ENABLE, "true"); + assertTrue(derive(filter, "g:a:1-SNAPSHOT") instanceof SnapshotVersionFilter); } - @SuppressWarnings( "EqualsWithItself" ) + @SuppressWarnings("EqualsWithItself") @Test - public void testEquals() - { + public void testEquals() { ContextualSnapshotVersionFilter filter = new ContextualSnapshotVersionFilter(); - assertNotEquals( null, filter ); - assertEquals( filter, filter ); - assertEquals( filter, new ContextualSnapshotVersionFilter() ); + assertNotEquals(null, filter); + assertEquals(filter, filter); + assertEquals(filter, new ContextualSnapshotVersionFilter()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/HighestVersionFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/HighestVersionFilterTest.java index 35a034a24..8d3ee4326 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/HighestVersionFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/HighestVersionFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.versions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,41 +16,36 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.versions; import org.eclipse.aether.collection.VersionFilter.VersionFilterContext; import org.eclipse.aether.util.graph.version.HighestVersionFilter; import org.junit.Test; -public class HighestVersionFilterTest - extends AbstractVersionFilterTest -{ +import static org.junit.Assert.*; + +public class HighestVersionFilterTest extends AbstractVersionFilterTest { @Test - public void testFilterVersions() - { + public void testFilterVersions() { HighestVersionFilter filter = new HighestVersionFilter(); - VersionFilterContext ctx = newContext( "g:a:[1,9]", "1", "2", "3", "4", "5", "6", "7", "8", "9" ); - filter.filterVersions( ctx ); - assertVersions( ctx, "9" ); + VersionFilterContext ctx = newContext("g:a:[1,9]", "1", "2", "3", "4", "5", "6", "7", "8", "9"); + filter.filterVersions(ctx); + assertVersions(ctx, "9"); } @Test - public void testDeriveChildFilter() - { + public void testDeriveChildFilter() { HighestVersionFilter filter = new HighestVersionFilter(); - assertSame( filter, derive( filter, "g:a:1" ) ); + assertSame(filter, derive(filter, "g:a:1")); } - @SuppressWarnings( "EqualsWithItself" ) + @SuppressWarnings("EqualsWithItself") @Test - public void testEquals() - { + public void testEquals() { HighestVersionFilter filter = new HighestVersionFilter(); - assertNotEquals( null, filter ); - assertEquals( filter, filter ); - assertEquals( filter, new HighestVersionFilter() ); + assertNotEquals(null, filter); + assertEquals(filter, filter); + assertEquals(filter, new HighestVersionFilter()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/SnapshotVersionFilterTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/SnapshotVersionFilterTest.java index d7d27fcf7..cfc0daa87 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/SnapshotVersionFilterTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/versions/SnapshotVersionFilterTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.versions; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,41 +16,36 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.versions; import org.eclipse.aether.collection.VersionFilter.VersionFilterContext; import org.eclipse.aether.util.graph.version.SnapshotVersionFilter; import org.junit.Test; -public class SnapshotVersionFilterTest - extends AbstractVersionFilterTest -{ +import static org.junit.Assert.*; + +public class SnapshotVersionFilterTest extends AbstractVersionFilterTest { @Test - public void testFilterVersions() - { + public void testFilterVersions() { SnapshotVersionFilter filter = new SnapshotVersionFilter(); - VersionFilterContext ctx = newContext( "g:a:[1,9]", "1", "2-SNAPSHOT", "3.1", "4.0-SNAPSHOT", "5.0.0" ); - filter.filterVersions( ctx ); - assertVersions( ctx, "1", "3.1", "5.0.0" ); + VersionFilterContext ctx = newContext("g:a:[1,9]", "1", "2-SNAPSHOT", "3.1", "4.0-SNAPSHOT", "5.0.0"); + filter.filterVersions(ctx); + assertVersions(ctx, "1", "3.1", "5.0.0"); } @Test - public void testDeriveChildFilter() - { + public void testDeriveChildFilter() { SnapshotVersionFilter filter = new SnapshotVersionFilter(); - assertSame( filter, derive( filter, "g:a:1" ) ); + assertSame(filter, derive(filter, "g:a:1")); } - @SuppressWarnings( "EqualsWithItself" ) + @SuppressWarnings("EqualsWithItself") @Test - public void testEquals() - { + public void testEquals() { SnapshotVersionFilter filter = new SnapshotVersionFilter(); - assertNotEquals( null, filter ); - assertEquals( filter, filter ); - assertEquals( filter, new SnapshotVersionFilter() ); + assertNotEquals(null, filter); + assertEquals(filter, filter); + assertEquals(filter, new SnapshotVersionFilter()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/FilteringDependencyVisitorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/FilteringDependencyVisitorTest.java index 4e6a54376..015638e51 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/FilteringDependencyVisitorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/FilteringDependencyVisitorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Objects.requireNonNull; -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.visitor; import java.util.List; @@ -29,41 +25,35 @@ import org.eclipse.aether.internal.test.util.DependencyGraphParser; import org.junit.Test; -public class FilteringDependencyVisitorTest -{ +import static java.util.Objects.requireNonNull; +import static org.junit.Assert.*; + +public class FilteringDependencyVisitorTest { - private DependencyNode parse( String resource ) - throws Exception - { - return new DependencyGraphParser( "visitor/filtering/" ).parseResource( resource ); + private DependencyNode parse(String resource) throws Exception { + return new DependencyGraphParser("visitor/filtering/").parseResource(resource); } @Test - public void testFilterCalledWithProperParentStack() - throws Exception - { - DependencyNode root = parse( "parents.txt" ); - - final StringBuilder buffer = new StringBuilder( 256 ); - DependencyFilter filter = new DependencyFilter() - { - public boolean accept( DependencyNode node, List parents ) - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( parents, "parents cannot be null" ); - for ( DependencyNode parent : parents ) - { - buffer.append( parent.getDependency().getArtifact().getArtifactId() ); + public void testFilterCalledWithProperParentStack() throws Exception { + DependencyNode root = parse("parents.txt"); + + final StringBuilder buffer = new StringBuilder(256); + DependencyFilter filter = new DependencyFilter() { + public boolean accept(DependencyNode node, List parents) { + requireNonNull(node, "node cannot be null"); + requireNonNull(parents, "parents cannot be null"); + for (DependencyNode parent : parents) { + buffer.append(parent.getDependency().getArtifact().getArtifactId()); } - buffer.append( "," ); + buffer.append(","); return false; } }; - FilteringDependencyVisitor visitor = new FilteringDependencyVisitor( new PreorderNodeListGenerator(), filter ); - root.accept( visitor ); + FilteringDependencyVisitor visitor = new FilteringDependencyVisitor(new PreorderNodeListGenerator(), filter); + root.accept(visitor); - assertEquals( ",a,ba,cba,a,ea,", buffer.toString() ); + assertEquals(",a,ba,cba,a,ea,", buffer.toString()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PathRecordingDependencyVisitorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PathRecordingDependencyVisitorTest.java index efd4f6c50..998f43f81 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PathRecordingDependencyVisitorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PathRecordingDependencyVisitorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,9 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static java.util.Objects.requireNonNull; -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.visitor; import java.util.List; @@ -29,136 +25,119 @@ import org.eclipse.aether.internal.test.util.DependencyGraphParser; import org.junit.Test; -public class PathRecordingDependencyVisitorTest -{ +import static java.util.Objects.requireNonNull; +import static org.junit.Assert.*; - private DependencyNode parse( String resource ) - throws Exception - { - return new DependencyGraphParser( "visitor/path-recorder/" ).parseResource( resource ); +public class PathRecordingDependencyVisitorTest { + + private DependencyNode parse(String resource) throws Exception { + return new DependencyGraphParser("visitor/path-recorder/").parseResource(resource); } - private void assertPath( List actual, String... expected ) - { - assertEquals( actual.toString(), expected.length, actual.size() ); - for ( int i = 0; i < expected.length; i++ ) - { - DependencyNode node = actual.get( i ); - assertEquals( actual.toString(), expected[i], node.getDependency().getArtifact().getArtifactId() ); + private void assertPath(List actual, String... expected) { + assertEquals(actual.toString(), expected.length, actual.size()); + for (int i = 0; i < expected.length; i++) { + DependencyNode node = actual.get(i); + assertEquals( + actual.toString(), + expected[i], + node.getDependency().getArtifact().getArtifactId()); } } @Test - public void testGetPaths_RecordsMatchesBeneathUnmatchedParents() - throws Exception - { - DependencyNode root = parse( "simple.txt" ); + public void testGetPaths_RecordsMatchesBeneathUnmatchedParents() throws Exception { + DependencyNode root = parse("simple.txt"); - PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor( new ArtifactMatcher() ); - root.accept( visitor ); + PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor(new ArtifactMatcher()); + root.accept(visitor); List> paths = visitor.getPaths(); - assertEquals( paths.toString(), 2, paths.size() ); - assertPath( paths.get( 0 ), "a", "b", "x" ); - assertPath( paths.get( 1 ), "a", "x" ); + assertEquals(paths.toString(), 2, paths.size()); + assertPath(paths.get(0), "a", "b", "x"); + assertPath(paths.get(1), "a", "x"); } @Test - public void testGetPaths_DoesNotRecordMatchesBeneathMatchedParents() - throws Exception - { - DependencyNode root = parse( "nested.txt" ); + public void testGetPaths_DoesNotRecordMatchesBeneathMatchedParents() throws Exception { + DependencyNode root = parse("nested.txt"); - PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor( new ArtifactMatcher() ); - root.accept( visitor ); + PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor(new ArtifactMatcher()); + root.accept(visitor); List> paths = visitor.getPaths(); - assertEquals( paths.toString(), 1, paths.size() ); - assertPath( paths.get( 0 ), "x" ); + assertEquals(paths.toString(), 1, paths.size()); + assertPath(paths.get(0), "x"); } @Test - public void testGetPaths_RecordsMatchesBeneathMatchedParentsIfRequested() - throws Exception - { - DependencyNode root = parse( "nested.txt" ); + public void testGetPaths_RecordsMatchesBeneathMatchedParentsIfRequested() throws Exception { + DependencyNode root = parse("nested.txt"); - PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor( new ArtifactMatcher(), false ); - root.accept( visitor ); + PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor(new ArtifactMatcher(), false); + root.accept(visitor); List> paths = visitor.getPaths(); - assertEquals( paths.toString(), 3, paths.size() ); - assertPath( paths.get( 0 ), "x" ); - assertPath( paths.get( 1 ), "x", "a", "y" ); - assertPath( paths.get( 2 ), "x", "y" ); + assertEquals(paths.toString(), 3, paths.size()); + assertPath(paths.get(0), "x"); + assertPath(paths.get(1), "x", "a", "y"); + assertPath(paths.get(2), "x", "y"); } @Test - public void testFilterCalledWithProperParentStack() - throws Exception - { - DependencyNode root = parse( "parents.txt" ); - - final StringBuilder buffer = new StringBuilder( 256 ); - DependencyFilter filter = new DependencyFilter() - { - public boolean accept( DependencyNode node, List parents ) - { - requireNonNull( node, "node cannot be null" ); - requireNonNull( parents, "parents cannot be null" ); - for ( DependencyNode parent : parents ) - { - buffer.append( parent.getDependency().getArtifact().getArtifactId() ); + public void testFilterCalledWithProperParentStack() throws Exception { + DependencyNode root = parse("parents.txt"); + + final StringBuilder buffer = new StringBuilder(256); + DependencyFilter filter = new DependencyFilter() { + public boolean accept(DependencyNode node, List parents) { + requireNonNull(node, "node cannot be null"); + requireNonNull(parents, "parents cannot be null"); + for (DependencyNode parent : parents) { + buffer.append(parent.getDependency().getArtifact().getArtifactId()); } - buffer.append( "," ); + buffer.append(","); return false; } }; - PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor( filter ); - root.accept( visitor ); + PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor(filter); + root.accept(visitor); - assertEquals( ",a,ba,cba,a,ea,", buffer.toString() ); + assertEquals(",a,ba,cba,a,ea,", buffer.toString()); } @Test - public void testGetPaths_HandlesCycles() - throws Exception - { - DependencyNode root = parse( "cycle.txt" ); + public void testGetPaths_HandlesCycles() throws Exception { + DependencyNode root = parse("cycle.txt"); - PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor( new ArtifactMatcher(), false ); - root.accept( visitor ); + PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor(new ArtifactMatcher(), false); + root.accept(visitor); List> paths = visitor.getPaths(); - assertEquals( paths.toString(), 4, paths.size() ); - assertPath( paths.get( 0 ), "a", "b", "x" ); - assertPath( paths.get( 1 ), "a", "x" ); - assertPath( paths.get( 2 ), "a", "x", "b", "x" ); - assertPath( paths.get( 3 ), "a", "x", "x" ); + assertEquals(paths.toString(), 4, paths.size()); + assertPath(paths.get(0), "a", "b", "x"); + assertPath(paths.get(1), "a", "x"); + assertPath(paths.get(2), "a", "x", "b", "x"); + assertPath(paths.get(3), "a", "x", "x"); } @Test - public void testGetPaths_HandlesCycles_threePaths() - throws Exception - { - DependencyNode root = parse( "cycle-3paths.txt" ); + public void testGetPaths_HandlesCycles_threePaths() throws Exception { + DependencyNode root = parse("cycle-3paths.txt"); - PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor( new ArtifactMatcher() ); - root.accept( visitor ); + PathRecordingDependencyVisitor visitor = new PathRecordingDependencyVisitor(new ArtifactMatcher()); + root.accept(visitor); List> paths = visitor.getPaths(); - assertEquals( paths.toString(), 1, paths.size() ); - assertPath( paths.get( 0 ), "a", "b"); + assertEquals(paths.toString(), 1, paths.size()); + assertPath(paths.get(0), "a", "b"); } - private static class ArtifactMatcher - implements DependencyFilter - { - public boolean accept( DependencyNode node, List parents ) - { - return node.getDependency() != null && node.getDependency().getArtifact().getGroupId().equals( "match" ); + private static class ArtifactMatcher implements DependencyFilter { + public boolean accept(DependencyNode node, List parents) { + return node.getDependency() != null + && node.getDependency().getArtifact().getGroupId().equals("match"); } } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PostorderNodeListGeneratorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PostorderNodeListGeneratorTest.java index 8d6f525f9..116c08b10 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PostorderNodeListGeneratorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PostorderNodeListGeneratorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.visitor; import java.util.List; @@ -27,47 +24,42 @@ import org.eclipse.aether.internal.test.util.DependencyGraphParser; import org.junit.Test; -public class PostorderNodeListGeneratorTest -{ +import static org.junit.Assert.*; + +public class PostorderNodeListGeneratorTest { - private DependencyNode parse( String resource ) - throws Exception - { - return new DependencyGraphParser( "visitor/ordered-list/" ).parseResource( resource ); + private DependencyNode parse(String resource) throws Exception { + return new DependencyGraphParser("visitor/ordered-list/").parseResource(resource); } - private void assertSequence( List actual, String... expected ) - { - assertEquals( actual.toString(), expected.length, actual.size() ); - for ( int i = 0; i < expected.length; i++ ) - { - DependencyNode node = actual.get( i ); - assertEquals( actual.toString(), expected[i], node.getDependency().getArtifact().getArtifactId() ); + private void assertSequence(List actual, String... expected) { + assertEquals(actual.toString(), expected.length, actual.size()); + for (int i = 0; i < expected.length; i++) { + DependencyNode node = actual.get(i); + assertEquals( + actual.toString(), + expected[i], + node.getDependency().getArtifact().getArtifactId()); } } @Test - public void testOrdering() - throws Exception - { - DependencyNode root = parse( "simple.txt" ); + public void testOrdering() throws Exception { + DependencyNode root = parse("simple.txt"); PostorderNodeListGenerator visitor = new PostorderNodeListGenerator(); - root.accept( visitor ); + root.accept(visitor); - assertSequence( visitor.getNodes(), "c", "b", "e", "d", "a" ); + assertSequence(visitor.getNodes(), "c", "b", "e", "d", "a"); } @Test - public void testDuplicateSuppression() - throws Exception - { - DependencyNode root = parse( "cycles.txt" ); + public void testDuplicateSuppression() throws Exception { + DependencyNode root = parse("cycles.txt"); PostorderNodeListGenerator visitor = new PostorderNodeListGenerator(); - root.accept( visitor ); + root.accept(visitor); - assertSequence( visitor.getNodes(), "c", "b", "e", "d", "a" ); + assertSequence(visitor.getNodes(), "c", "b", "e", "d", "a"); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PreorderNodeListGeneratorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PreorderNodeListGeneratorTest.java index 200dd3bad..c169d522d 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PreorderNodeListGeneratorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/PreorderNodeListGeneratorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.visitor; import java.util.List; @@ -27,47 +24,42 @@ import org.eclipse.aether.internal.test.util.DependencyGraphParser; import org.junit.Test; -public class PreorderNodeListGeneratorTest -{ +import static org.junit.Assert.*; + +public class PreorderNodeListGeneratorTest { - private DependencyNode parse( String resource ) - throws Exception - { - return new DependencyGraphParser( "visitor/ordered-list/" ).parseResource( resource ); + private DependencyNode parse(String resource) throws Exception { + return new DependencyGraphParser("visitor/ordered-list/").parseResource(resource); } - private void assertSequence( List actual, String... expected ) - { - assertEquals( actual.toString(), expected.length, actual.size() ); - for ( int i = 0; i < expected.length; i++ ) - { - DependencyNode node = actual.get( i ); - assertEquals( actual.toString(), expected[i], node.getDependency().getArtifact().getArtifactId() ); + private void assertSequence(List actual, String... expected) { + assertEquals(actual.toString(), expected.length, actual.size()); + for (int i = 0; i < expected.length; i++) { + DependencyNode node = actual.get(i); + assertEquals( + actual.toString(), + expected[i], + node.getDependency().getArtifact().getArtifactId()); } } @Test - public void testOrdering() - throws Exception - { - DependencyNode root = parse( "simple.txt" ); + public void testOrdering() throws Exception { + DependencyNode root = parse("simple.txt"); PreorderNodeListGenerator visitor = new PreorderNodeListGenerator(); - root.accept( visitor ); + root.accept(visitor); - assertSequence( visitor.getNodes(), "a", "b", "c", "d", "e" ); + assertSequence(visitor.getNodes(), "a", "b", "c", "d", "e"); } @Test - public void testDuplicateSuppression() - throws Exception - { - DependencyNode root = parse( "cycles.txt" ); + public void testDuplicateSuppression() throws Exception { + DependencyNode root = parse("cycles.txt"); PreorderNodeListGenerator visitor = new PreorderNodeListGenerator(); - root.accept( visitor ); + root.accept(visitor); - assertSequence( visitor.getNodes(), "a", "b", "c", "d", "e" ); + assertSequence(visitor.getNodes(), "a", "b", "c", "d", "e"); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/TreeDependencyVisitorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/TreeDependencyVisitorTest.java index 36cb6ace4..1c8608c78 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/TreeDependencyVisitorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/graph/visitor/TreeDependencyVisitorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.graph.visitor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,54 +16,48 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.graph.visitor; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.graph.DependencyVisitor; import org.eclipse.aether.internal.test.util.DependencyGraphParser; import org.junit.Test; -public class TreeDependencyVisitorTest -{ +import static org.junit.Assert.*; + +public class TreeDependencyVisitorTest { - private DependencyNode parse( String resource ) - throws Exception - { - return new DependencyGraphParser( "visitor/tree/" ).parseResource( resource ); + private DependencyNode parse(String resource) throws Exception { + return new DependencyGraphParser("visitor/tree/").parseResource(resource); } @Test - public void testDuplicateSuppression() - throws Exception - { - DependencyNode root = parse( "cycles.txt" ); + public void testDuplicateSuppression() throws Exception { + DependencyNode root = parse("cycles.txt"); RecordingVisitor rec = new RecordingVisitor(); - TreeDependencyVisitor visitor = new TreeDependencyVisitor( rec ); - root.accept( visitor ); + TreeDependencyVisitor visitor = new TreeDependencyVisitor(rec); + root.accept(visitor); - assertEquals( ">a >b >c d a >b >c d ' ).append( node.getDependency().getArtifact().getArtifactId() ).append( ' ' ); + public boolean visitEnter(DependencyNode node) { + buffer.append('>') + .append(node.getDependency().getArtifact().getArtifactId()) + .append(' '); return true; } - public boolean visitLeave( DependencyNode node ) - { - buffer.append( '<' ).append( node.getDependency().getArtifact().getArtifactId() ).append( ' ' ); + public boolean visitLeave(DependencyNode node) { + buffer.append('<') + .append(node.getDependency().getArtifact().getArtifactId()) + .append(' '); return true; } - } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/listener/ChainedRepositoryListenerTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/listener/ChainedRepositoryListenerTest.java index 6eaa25b8c..3b9ae0cb5 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/listener/ChainedRepositoryListenerTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/listener/ChainedRepositoryListenerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.listener; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,29 +16,24 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.listener; import java.lang.reflect.Method; import org.eclipse.aether.RepositoryListener; -import org.eclipse.aether.util.listener.ChainedRepositoryListener; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class ChainedRepositoryListenerTest -{ +public class ChainedRepositoryListenerTest { @Test - public void testAllEventTypesHandled() - throws Exception - { - for ( Method method : RepositoryListener.class.getMethods() ) - { - assertNotNull( ChainedRepositoryListener.class.getDeclaredMethod( method.getName(), - method.getParameterTypes() ) ); + public void testAllEventTypesHandled() throws Exception { + for (Method method : RepositoryListener.class.getMethods()) { + assertNotNull( + ChainedRepositoryListener.class.getDeclaredMethod(method.getName(), method.getParameterTypes())); } } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/listener/ChainedTransferListenerTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/listener/ChainedTransferListenerTest.java index 7e7e96947..b19054eb4 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/listener/ChainedTransferListenerTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/listener/ChainedTransferListenerTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.listener; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,29 +16,24 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.listener; import java.lang.reflect.Method; import org.eclipse.aether.transfer.TransferListener; -import org.eclipse.aether.util.listener.ChainedTransferListener; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class ChainedTransferListenerTest -{ +public class ChainedTransferListenerTest { @Test - public void testAllEventTypesHandled() - throws Exception - { - for ( Method method : TransferListener.class.getMethods() ) - { - assertNotNull( ChainedTransferListener.class.getDeclaredMethod( method.getName(), - method.getParameterTypes() ) ); + public void testAllEventTypesHandled() throws Exception { + for (Method method : TransferListener.class.getMethods()) { + assertNotNull( + ChainedTransferListener.class.getDeclaredMethod(method.getName(), method.getParameterTypes())); } } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/ComponentAuthenticationTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/ComponentAuthenticationTest.java index 17386daa3..cef972cd2 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/ComponentAuthenticationTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/ComponentAuthenticationTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.repository; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystemSession; @@ -29,78 +26,70 @@ import org.eclipse.aether.repository.RemoteRepository; import org.junit.Test; -public class ComponentAuthenticationTest -{ +import static org.junit.Assert.*; - private static class Component - { - } +public class ComponentAuthenticationTest { + + private static class Component {} - private RepositorySystemSession newSession() - { + private RepositorySystemSession newSession() { return new DefaultRepositorySystemSession(); } - private RemoteRepository newRepo( Authentication auth ) - { - return new RemoteRepository.Builder( "test", "default", "http://localhost" ).setAuthentication( auth ).build(); + private RemoteRepository newRepo(Authentication auth) { + return new RemoteRepository.Builder("test", "default", "http://localhost") + .setAuthentication(auth) + .build(); } - private AuthenticationContext newContext( Authentication auth ) - { - return AuthenticationContext.forRepository( newSession(), newRepo( auth ) ); + private AuthenticationContext newContext(Authentication auth) { + return AuthenticationContext.forRepository(newSession(), newRepo(auth)); } - private String newDigest( Authentication auth ) - { - return AuthenticationDigest.forRepository( newSession(), newRepo( auth ) ); + private String newDigest(Authentication auth) { + return AuthenticationDigest.forRepository(newSession(), newRepo(auth)); } @Test - public void testFill() - { + public void testFill() { Component comp = new Component(); - Authentication auth = new ComponentAuthentication( "key", comp ); - AuthenticationContext context = newContext( auth ); - assertNull( context.get( "another-key" ) ); - assertSame( comp, context.get( "key", Component.class ) ); + Authentication auth = new ComponentAuthentication("key", comp); + AuthenticationContext context = newContext(auth); + assertNull(context.get("another-key")); + assertSame(comp, context.get("key", Component.class)); } @Test - public void testDigest() - { - Authentication auth1 = new ComponentAuthentication( "key", new Component() ); - Authentication auth2 = new ComponentAuthentication( "key", new Component() ); - String digest1 = newDigest( auth1 ); - String digest2 = newDigest( auth2 ); - assertEquals( digest1, digest2 ); - - Authentication auth3 = new ComponentAuthentication( "key", new Object() ); - String digest3 = newDigest( auth3 ); - assertNotEquals( digest3, digest1 ); - - Authentication auth4 = new ComponentAuthentication( "Key", new Component() ); - String digest4 = newDigest( auth4 ); - assertNotEquals( digest4, digest1 ); + public void testDigest() { + Authentication auth1 = new ComponentAuthentication("key", new Component()); + Authentication auth2 = new ComponentAuthentication("key", new Component()); + String digest1 = newDigest(auth1); + String digest2 = newDigest(auth2); + assertEquals(digest1, digest2); + + Authentication auth3 = new ComponentAuthentication("key", new Object()); + String digest3 = newDigest(auth3); + assertNotEquals(digest3, digest1); + + Authentication auth4 = new ComponentAuthentication("Key", new Component()); + String digest4 = newDigest(auth4); + assertNotEquals(digest4, digest1); } @Test - public void testEquals() - { - Authentication auth1 = new ComponentAuthentication( "key", new Component() ); - Authentication auth2 = new ComponentAuthentication( "key", new Component() ); - Authentication auth3 = new ComponentAuthentication( "key", new Object() ); - assertEquals( auth1, auth2 ); - assertNotEquals( auth1, auth3 ); - assertNotEquals( null, auth1 ); + public void testEquals() { + Authentication auth1 = new ComponentAuthentication("key", new Component()); + Authentication auth2 = new ComponentAuthentication("key", new Component()); + Authentication auth3 = new ComponentAuthentication("key", new Object()); + assertEquals(auth1, auth2); + assertNotEquals(auth1, auth3); + assertNotEquals(null, auth1); } @Test - public void testHashCode() - { - Authentication auth1 = new ComponentAuthentication( "key", new Component() ); - Authentication auth2 = new ComponentAuthentication( "key", new Component() ); - assertEquals( auth1.hashCode(), auth2.hashCode() ); + public void testHashCode() { + Authentication auth1 = new ComponentAuthentication("key", new Component()); + Authentication auth2 = new ComponentAuthentication("key", new Component()); + assertEquals(auth1.hashCode(), auth2.hashCode()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/DefaultProxySelectorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/DefaultProxySelectorTest.java index 3eacbd5c7..a09ddb08b 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/DefaultProxySelectorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/DefaultProxySelectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,59 +16,51 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.repository; -import static org.junit.Assert.*; - -import org.eclipse.aether.util.repository.DefaultProxySelector; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class DefaultProxySelectorTest -{ +public class DefaultProxySelectorTest { - private boolean isNonProxyHost( String host, String nonProxyHosts ) - { - return new DefaultProxySelector.NonProxyHosts( nonProxyHosts ).isNonProxyHost( host ); + private boolean isNonProxyHost(String host, String nonProxyHosts) { + return new DefaultProxySelector.NonProxyHosts(nonProxyHosts).isNonProxyHost(host); } @Test - public void testIsNonProxyHost_Blank() - { - assertFalse( isNonProxyHost( "www.eclipse.org", null ) ); - assertFalse( isNonProxyHost( "www.eclipse.org", "" ) ); + public void testIsNonProxyHost_Blank() { + assertFalse(isNonProxyHost("www.eclipse.org", null)); + assertFalse(isNonProxyHost("www.eclipse.org", "")); } @Test - public void testIsNonProxyHost_Wildcard() - { - assertTrue( isNonProxyHost( "www.eclipse.org", "*" ) ); - assertTrue( isNonProxyHost( "www.eclipse.org", "*.org" ) ); - assertFalse( isNonProxyHost( "www.eclipse.org", "*.com" ) ); - assertTrue( isNonProxyHost( "www.eclipse.org", "www.*" ) ); - assertTrue( isNonProxyHost( "www.eclipse.org", "www.*.org" ) ); + public void testIsNonProxyHost_Wildcard() { + assertTrue(isNonProxyHost("www.eclipse.org", "*")); + assertTrue(isNonProxyHost("www.eclipse.org", "*.org")); + assertFalse(isNonProxyHost("www.eclipse.org", "*.com")); + assertTrue(isNonProxyHost("www.eclipse.org", "www.*")); + assertTrue(isNonProxyHost("www.eclipse.org", "www.*.org")); } @Test - public void testIsNonProxyHost_Multiple() - { - assertTrue( isNonProxyHost( "eclipse.org", "eclipse.org|host2" ) ); - assertTrue( isNonProxyHost( "eclipse.org", "host1|eclipse.org" ) ); - assertTrue( isNonProxyHost( "eclipse.org", "host1|eclipse.org|host2" ) ); + public void testIsNonProxyHost_Multiple() { + assertTrue(isNonProxyHost("eclipse.org", "eclipse.org|host2")); + assertTrue(isNonProxyHost("eclipse.org", "host1|eclipse.org")); + assertTrue(isNonProxyHost("eclipse.org", "host1|eclipse.org|host2")); } @Test - public void testIsNonProxyHost_Misc() - { - assertFalse( isNonProxyHost( "www.eclipse.org", "www.eclipse.com" ) ); - assertFalse( isNonProxyHost( "www.eclipse.org", "eclipse.org" ) ); + public void testIsNonProxyHost_Misc() { + assertFalse(isNonProxyHost("www.eclipse.org", "www.eclipse.com")); + assertFalse(isNonProxyHost("www.eclipse.org", "eclipse.org")); } @Test - public void testIsNonProxyHost_CaseInsensitivity() - { - assertTrue( isNonProxyHost( "www.eclipse.org", "www.ECLIPSE.org" ) ); - assertTrue( isNonProxyHost( "www.ECLIPSE.org", "www.eclipse.org" ) ); + public void testIsNonProxyHost_CaseInsensitivity() { + assertTrue(isNonProxyHost("www.eclipse.org", "www.ECLIPSE.org")); + assertTrue(isNonProxyHost("www.ECLIPSE.org", "www.eclipse.org")); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/JreProxySelectorTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/JreProxySelectorTest.java index 5e8d2740b..eb609f063 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/JreProxySelectorTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/JreProxySelectorTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.repository; import java.io.IOException; import java.net.Authenticator; @@ -42,16 +39,13 @@ import org.junit.Before; import org.junit.Test; -public class JreProxySelectorTest -{ +import static org.junit.Assert.*; - private abstract class AbstractProxySelector - extends java.net.ProxySelector - { +public class JreProxySelectorTest { + + private abstract class AbstractProxySelector extends java.net.ProxySelector { @Override - public void connectFailed( URI uri, SocketAddress sa, IOException ioe ) - { - } + public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {} } private ProxySelector selector = new JreProxySelector(); @@ -59,121 +53,100 @@ public void connectFailed( URI uri, SocketAddress sa, IOException ioe ) private java.net.ProxySelector original; @Before - public void init() - { + public void init() { original = java.net.ProxySelector.getDefault(); } @After - public void exit() - { - java.net.ProxySelector.setDefault( original ); - Authenticator.setDefault( null ); + public void exit() { + java.net.ProxySelector.setDefault(original); + Authenticator.setDefault(null); } @Test - public void testGetProxy_InvalidUrl() - { - RemoteRepository repo = new RemoteRepository.Builder( "test", "default", "http://host:invalid" ).build(); - assertNull( selector.getProxy( repo ) ); + public void testGetProxy_InvalidUrl() { + RemoteRepository repo = new RemoteRepository.Builder("test", "default", "http://host:invalid").build(); + assertNull(selector.getProxy(repo)); } @Test - public void testGetProxy_OpaqueUrl() - { - RemoteRepository repo = new RemoteRepository.Builder( "test", "default", "classpath:base" ).build(); - assertNull( selector.getProxy( repo ) ); + public void testGetProxy_OpaqueUrl() { + RemoteRepository repo = new RemoteRepository.Builder("test", "default", "classpath:base").build(); + assertNull(selector.getProxy(repo)); } @Test - public void testGetProxy_NullSelector() - { - RemoteRepository repo = new RemoteRepository.Builder( "test", "default", "http://repo.eclipse.org/" ).build(); - java.net.ProxySelector.setDefault( null ); - assertNull( selector.getProxy( repo ) ); + public void testGetProxy_NullSelector() { + RemoteRepository repo = new RemoteRepository.Builder("test", "default", "http://repo.eclipse.org/").build(); + java.net.ProxySelector.setDefault(null); + assertNull(selector.getProxy(repo)); } @Test - public void testGetProxy_NoProxies() - { - RemoteRepository repo = new RemoteRepository.Builder( "test", "default", "http://repo.eclipse.org/" ).build(); - java.net.ProxySelector.setDefault( new AbstractProxySelector() - { + public void testGetProxy_NoProxies() { + RemoteRepository repo = new RemoteRepository.Builder("test", "default", "http://repo.eclipse.org/").build(); + java.net.ProxySelector.setDefault(new AbstractProxySelector() { @Override - public List select( URI uri ) - { + public List select(URI uri) { return Collections.emptyList(); } - - } ); - assertNull( selector.getProxy( repo ) ); + }); + assertNull(selector.getProxy(repo)); } @Test - public void testGetProxy_DirectProxy() - { - RemoteRepository repo = new RemoteRepository.Builder( "test", "default", "http://repo.eclipse.org/" ).build(); - final InetSocketAddress addr = InetSocketAddress.createUnresolved( "proxy", 8080 ); - java.net.ProxySelector.setDefault( new AbstractProxySelector() - { + public void testGetProxy_DirectProxy() { + RemoteRepository repo = new RemoteRepository.Builder("test", "default", "http://repo.eclipse.org/").build(); + final InetSocketAddress addr = InetSocketAddress.createUnresolved("proxy", 8080); + java.net.ProxySelector.setDefault(new AbstractProxySelector() { @Override - public List select( URI uri ) - { - return Arrays.asList( java.net.Proxy.NO_PROXY, new java.net.Proxy( java.net.Proxy.Type.HTTP, addr ) ); + public List select(URI uri) { + return Arrays.asList(java.net.Proxy.NO_PROXY, new java.net.Proxy(java.net.Proxy.Type.HTTP, addr)); } - - } ); - assertNull( selector.getProxy( repo ) ); + }); + assertNull(selector.getProxy(repo)); } @Test - public void testGetProxy_HttpProxy() - throws Exception - { + public void testGetProxy_HttpProxy() throws Exception { final RemoteRepository repo = - new RemoteRepository.Builder( "test", "default", "http://repo.eclipse.org/" ).build(); - final URL url = new URL( repo.getUrl() ); - final InetSocketAddress addr = InetSocketAddress.createUnresolved( "proxy", 8080 ); - java.net.ProxySelector.setDefault( new AbstractProxySelector() - { + new RemoteRepository.Builder("test", "default", "http://repo.eclipse.org/").build(); + final URL url = new URL(repo.getUrl()); + final InetSocketAddress addr = InetSocketAddress.createUnresolved("proxy", 8080); + java.net.ProxySelector.setDefault(new AbstractProxySelector() { @Override - public List select( URI uri ) - { - if ( repo.getHost().equalsIgnoreCase( uri.getHost() ) ) - { - return Arrays.asList( new java.net.Proxy( java.net.Proxy.Type.HTTP, addr ) ); + public List select(URI uri) { + if (repo.getHost().equalsIgnoreCase(uri.getHost())) { + return Arrays.asList(new java.net.Proxy(java.net.Proxy.Type.HTTP, addr)); } return Collections.emptyList(); } - - } ); - Authenticator.setDefault( new Authenticator() - { + }); + Authenticator.setDefault(new Authenticator() { @Override - protected PasswordAuthentication getPasswordAuthentication() - { - if ( Authenticator.RequestorType.PROXY.equals( getRequestorType() ) - && addr.getHostName().equals( getRequestingHost() ) && addr.getPort() == getRequestingPort() - && url.equals( getRequestingURL() ) ) - { - return new PasswordAuthentication( "proxyuser", "proxypass".toCharArray() ); + protected PasswordAuthentication getPasswordAuthentication() { + if (Authenticator.RequestorType.PROXY.equals(getRequestorType()) + && addr.getHostName().equals(getRequestingHost()) + && addr.getPort() == getRequestingPort() + && url.equals(getRequestingURL())) { + return new PasswordAuthentication("proxyuser", "proxypass".toCharArray()); } return super.getPasswordAuthentication(); } - } ); + }); - Proxy proxy = selector.getProxy( repo ); - assertNotNull( proxy ); - assertEquals( addr.getHostName(), proxy.getHost() ); - assertEquals( addr.getPort(), proxy.getPort() ); - assertEquals( Proxy.TYPE_HTTP, proxy.getType() ); + Proxy proxy = selector.getProxy(repo); + assertNotNull(proxy); + assertEquals(addr.getHostName(), proxy.getHost()); + assertEquals(addr.getPort(), proxy.getPort()); + assertEquals(Proxy.TYPE_HTTP, proxy.getType()); - RemoteRepository repo2 = new RemoteRepository.Builder( repo ).setProxy( proxy ).build(); + RemoteRepository repo2 = + new RemoteRepository.Builder(repo).setProxy(proxy).build(); Authentication auth = proxy.getAuthentication(); - assertNotNull( auth ); - AuthenticationContext authCtx = AuthenticationContext.forProxy( new DefaultRepositorySystemSession(), repo2 ); - assertEquals( "proxyuser", authCtx.get( AuthenticationContext.USERNAME ) ); - assertEquals( "proxypass", authCtx.get( AuthenticationContext.PASSWORD ) ); + assertNotNull(auth); + AuthenticationContext authCtx = AuthenticationContext.forProxy(new DefaultRepositorySystemSession(), repo2); + assertEquals("proxyuser", authCtx.get(AuthenticationContext.USERNAME)); + assertEquals("proxypass", authCtx.get(AuthenticationContext.PASSWORD)); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/SecretAuthenticationTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/SecretAuthenticationTest.java index f7045ac4e..4da926165 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/SecretAuthenticationTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/SecretAuthenticationTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.repository; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystemSession; @@ -29,81 +26,74 @@ import org.eclipse.aether.repository.RemoteRepository; import org.junit.Test; -public class SecretAuthenticationTest -{ +import static org.junit.Assert.*; + +public class SecretAuthenticationTest { - private RepositorySystemSession newSession() - { + private RepositorySystemSession newSession() { return new DefaultRepositorySystemSession(); } - private RemoteRepository newRepo( Authentication auth ) - { - return new RemoteRepository.Builder( "test", "default", "http://localhost" ).setAuthentication( auth ).build(); + private RemoteRepository newRepo(Authentication auth) { + return new RemoteRepository.Builder("test", "default", "http://localhost") + .setAuthentication(auth) + .build(); } - private AuthenticationContext newContext( Authentication auth ) - { - return AuthenticationContext.forRepository( newSession(), newRepo( auth ) ); + private AuthenticationContext newContext(Authentication auth) { + return AuthenticationContext.forRepository(newSession(), newRepo(auth)); } - private String newDigest( Authentication auth ) - { - return AuthenticationDigest.forRepository( newSession(), newRepo( auth ) ); + private String newDigest(Authentication auth) { + return AuthenticationDigest.forRepository(newSession(), newRepo(auth)); } @Test - public void testConstructor_CopyChars() - { - char[] value = { 'v', 'a', 'l' }; - new SecretAuthentication( "key", value ); - assertArrayEquals( new char[] { 'v', 'a', 'l' }, value ); + public void testConstructor_CopyChars() { + char[] value = {'v', 'a', 'l'}; + new SecretAuthentication("key", value); + assertArrayEquals(new char[] {'v', 'a', 'l'}, value); } @Test - public void testFill() - { - Authentication auth = new SecretAuthentication( "key", "value" ); - AuthenticationContext context = newContext( auth ); - assertNull( context.get( "another-key" ) ); - assertEquals( "value", context.get( "key" ) ); + public void testFill() { + Authentication auth = new SecretAuthentication("key", "value"); + AuthenticationContext context = newContext(auth); + assertNull(context.get("another-key")); + assertEquals("value", context.get("key")); } @Test - public void testDigest() - { - Authentication auth1 = new SecretAuthentication( "key", "value" ); - Authentication auth2 = new SecretAuthentication( "key", "value" ); - String digest1 = newDigest( auth1 ); - String digest2 = newDigest( auth2 ); - assertEquals( digest1, digest2 ); - - Authentication auth3 = new SecretAuthentication( "key", "Value" ); - String digest3 = newDigest( auth3 ); - assertNotEquals( digest3, digest1 ); - - Authentication auth4 = new SecretAuthentication( "Key", "value" ); - String digest4 = newDigest( auth4 ); - assertNotEquals( digest4, digest1 ); + public void testDigest() { + Authentication auth1 = new SecretAuthentication("key", "value"); + Authentication auth2 = new SecretAuthentication("key", "value"); + String digest1 = newDigest(auth1); + String digest2 = newDigest(auth2); + assertEquals(digest1, digest2); + + Authentication auth3 = new SecretAuthentication("key", "Value"); + String digest3 = newDigest(auth3); + assertNotEquals(digest3, digest1); + + Authentication auth4 = new SecretAuthentication("Key", "value"); + String digest4 = newDigest(auth4); + assertNotEquals(digest4, digest1); } @Test - public void testEquals() - { - Authentication auth1 = new SecretAuthentication( "key", "value" ); - Authentication auth2 = new SecretAuthentication( "key", "value" ); - Authentication auth3 = new SecretAuthentication( "key", "Value" ); - assertEquals( auth1, auth2 ); - assertNotEquals( auth1, auth3 ); - assertNotEquals( null, auth1 ); + public void testEquals() { + Authentication auth1 = new SecretAuthentication("key", "value"); + Authentication auth2 = new SecretAuthentication("key", "value"); + Authentication auth3 = new SecretAuthentication("key", "Value"); + assertEquals(auth1, auth2); + assertNotEquals(auth1, auth3); + assertNotEquals(null, auth1); } @Test - public void testHashCode() - { - Authentication auth1 = new SecretAuthentication( "key", "value" ); - Authentication auth2 = new SecretAuthentication( "key", "value" ); - assertEquals( auth1.hashCode(), auth2.hashCode() ); + public void testHashCode() { + Authentication auth1 = new SecretAuthentication("key", "value"); + Authentication auth2 = new SecretAuthentication("key", "value"); + assertEquals(auth1.hashCode(), auth2.hashCode()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/StringAuthenticationTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/StringAuthenticationTest.java index 6f3c52492..ba75713eb 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/StringAuthenticationTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/repository/StringAuthenticationTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.repository; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.repository; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystemSession; @@ -29,73 +26,67 @@ import org.eclipse.aether.repository.RemoteRepository; import org.junit.Test; -public class StringAuthenticationTest -{ +import static org.junit.Assert.*; + +public class StringAuthenticationTest { - private RepositorySystemSession newSession() - { + private RepositorySystemSession newSession() { return new DefaultRepositorySystemSession(); } - private RemoteRepository newRepo( Authentication auth ) - { - return new RemoteRepository.Builder( "test", "default", "http://localhost" ).setAuthentication( auth ).build(); + private RemoteRepository newRepo(Authentication auth) { + return new RemoteRepository.Builder("test", "default", "http://localhost") + .setAuthentication(auth) + .build(); } - private AuthenticationContext newContext( Authentication auth ) - { - return AuthenticationContext.forRepository( newSession(), newRepo( auth ) ); + private AuthenticationContext newContext(Authentication auth) { + return AuthenticationContext.forRepository(newSession(), newRepo(auth)); } - private String newDigest( Authentication auth ) - { - return AuthenticationDigest.forRepository( newSession(), newRepo( auth ) ); + private String newDigest(Authentication auth) { + return AuthenticationDigest.forRepository(newSession(), newRepo(auth)); } @Test - public void testFill() - { - Authentication auth = new StringAuthentication( "key", "value" ); - AuthenticationContext context = newContext( auth ); - assertNull( context.get( "another-key" ) ); - assertEquals( "value", context.get( "key" ) ); + public void testFill() { + Authentication auth = new StringAuthentication("key", "value"); + AuthenticationContext context = newContext(auth); + assertNull(context.get("another-key")); + assertEquals("value", context.get("key")); } @Test - public void testDigest() - { - Authentication auth1 = new StringAuthentication( "key", "value" ); - Authentication auth2 = new StringAuthentication( "key", "value" ); - String digest1 = newDigest( auth1 ); - String digest2 = newDigest( auth2 ); - assertEquals( digest1, digest2 ); + public void testDigest() { + Authentication auth1 = new StringAuthentication("key", "value"); + Authentication auth2 = new StringAuthentication("key", "value"); + String digest1 = newDigest(auth1); + String digest2 = newDigest(auth2); + assertEquals(digest1, digest2); - Authentication auth3 = new StringAuthentication( "key", "Value" ); - String digest3 = newDigest( auth3 ); - assertNotEquals( digest3, digest1 ); + Authentication auth3 = new StringAuthentication("key", "Value"); + String digest3 = newDigest(auth3); + assertNotEquals(digest3, digest1); - Authentication auth4 = new StringAuthentication( "Key", "value" ); - String digest4 = newDigest( auth4 ); - assertNotEquals( digest4, digest1 ); + Authentication auth4 = new StringAuthentication("Key", "value"); + String digest4 = newDigest(auth4); + assertNotEquals(digest4, digest1); } @Test - public void testEquals() - { - Authentication auth1 = new StringAuthentication( "key", "value" ); - Authentication auth2 = new StringAuthentication( "key", "value" ); - Authentication auth3 = new StringAuthentication( "key", "Value" ); - assertEquals( auth1, auth2 ); - assertNotEquals( auth1, auth3 ); - assertNotEquals( null, auth1 ); + public void testEquals() { + Authentication auth1 = new StringAuthentication("key", "value"); + Authentication auth2 = new StringAuthentication("key", "value"); + Authentication auth3 = new StringAuthentication("key", "Value"); + assertEquals(auth1, auth2); + assertNotEquals(auth1, auth3); + assertNotEquals(null, auth1); } @Test - public void testHashCode() - { - Authentication auth1 = new StringAuthentication( "key", "value" ); - Authentication auth2 = new StringAuthentication( "key", "value" ); - assertEquals( auth1.hashCode(), auth2.hashCode() ); + public void testHashCode() { + Authentication auth1 = new StringAuthentication("key", "value"); + Authentication auth2 = new StringAuthentication("key", "value"); + assertEquals(auth1.hashCode(), auth2.hashCode()); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/AbstractVersionTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/AbstractVersionTest.java index 32f19f284..3ddb04373 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/AbstractVersionTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/AbstractVersionTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,17 +16,17 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.version; + +import org.eclipse.aether.version.Version; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.eclipse.aether.version.Version; - /** */ -abstract class AbstractVersionTest -{ +abstract class AbstractVersionTest { protected static final int X_LT_Y = -1; @@ -36,46 +34,36 @@ abstract class AbstractVersionTest protected static final int X_GT_Y = 1; - protected abstract Version newVersion( String version ); + protected abstract Version newVersion(String version); - protected void assertOrder( int expected, String version1, String version2 ) - { - Version v1 = newVersion( version1 ); - Version v2 = newVersion( version2 ); + protected void assertOrder(int expected, String version1, String version2) { + Version v1 = newVersion(version1); + Version v2 = newVersion(version2); - if ( expected > 0 ) - { - assertEquals( "expected " + v1 + " > " + v2, 1, Integer.signum( v1.compareTo( v2 ) ) ); - assertEquals( "expected " + v2 + " < " + v1, -1, Integer.signum( v2.compareTo( v1 ) ) ); - assertFalse( "expected " + v1 + " != " + v2, v1.equals( v2 ) ); - assertFalse( "expected " + v2 + " != " + v1, v2.equals( v1 ) ); - } - else if ( expected < 0 ) - { - assertEquals( "expected " + v1 + " < " + v2, -1, Integer.signum( v1.compareTo( v2 ) ) ); - assertEquals( "expected " + v2 + " > " + v1, 1, Integer.signum( v2.compareTo( v1 ) ) ); - assertFalse( "expected " + v1 + " != " + v2, v1.equals( v2 ) ); - assertFalse( "expected " + v2 + " != " + v1, v2.equals( v1 ) ); - } - else - { - assertEquals( "expected " + v1 + " == " + v2, 0, v1.compareTo( v2 ) ); - assertEquals( "expected " + v2 + " == " + v1, 0, v2.compareTo( v1 ) ); - assertTrue( "expected " + v1 + " == " + v2, v1.equals( v2 ) ); - assertTrue( "expected " + v2 + " == " + v1, v2.equals( v1 ) ); - assertEquals( "expected #(" + v1 + ") == #(" + v1 + ")", v1.hashCode(), v2.hashCode() ); + if (expected > 0) { + assertEquals("expected " + v1 + " > " + v2, 1, Integer.signum(v1.compareTo(v2))); + assertEquals("expected " + v2 + " < " + v1, -1, Integer.signum(v2.compareTo(v1))); + assertFalse("expected " + v1 + " != " + v2, v1.equals(v2)); + assertFalse("expected " + v2 + " != " + v1, v2.equals(v1)); + } else if (expected < 0) { + assertEquals("expected " + v1 + " < " + v2, -1, Integer.signum(v1.compareTo(v2))); + assertEquals("expected " + v2 + " > " + v1, 1, Integer.signum(v2.compareTo(v1))); + assertFalse("expected " + v1 + " != " + v2, v1.equals(v2)); + assertFalse("expected " + v2 + " != " + v1, v2.equals(v1)); + } else { + assertEquals("expected " + v1 + " == " + v2, 0, v1.compareTo(v2)); + assertEquals("expected " + v2 + " == " + v1, 0, v2.compareTo(v1)); + assertTrue("expected " + v1 + " == " + v2, v1.equals(v2)); + assertTrue("expected " + v2 + " == " + v1, v2.equals(v1)); + assertEquals("expected #(" + v1 + ") == #(" + v1 + ")", v1.hashCode(), v2.hashCode()); } } - protected void assertSequence( String... versions ) - { - for ( int i = 0; i < versions.length - 1; i++ ) - { - for ( int j = i + 1; j < versions.length; j++ ) - { - assertOrder( X_LT_Y, versions[i], versions[j] ); + protected void assertSequence(String... versions) { + for (int i = 0; i < versions.length - 1; i++) { + for (int j = i + 1; j < versions.length; j++) { + assertOrder(X_LT_Y, versions[i], versions[j]); } } } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionRangeTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionRangeTest.java index 08e9bce53..1ff13a260 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionRangeTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionRangeTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,147 +16,123 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.version; -import static org.junit.Assert.*; - -import org.eclipse.aether.util.version.GenericVersion; -import org.eclipse.aether.util.version.GenericVersionRange; import org.eclipse.aether.version.InvalidVersionSpecificationException; import org.eclipse.aether.version.Version; import org.eclipse.aether.version.VersionRange; import org.junit.Test; -public class GenericVersionRangeTest -{ +import static org.junit.Assert.*; + +public class GenericVersionRangeTest { - private Version newVersion( String version ) - { - return new GenericVersion( version ); + private Version newVersion(String version) { + return new GenericVersion(version); } - private VersionRange parseValid( String range ) - { - try - { - return new GenericVersionRange( range ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new AssertionError( range + " should be valid but failed to parse due to: " + e.getMessage(), e ); + private VersionRange parseValid(String range) { + try { + return new GenericVersionRange(range); + } catch (InvalidVersionSpecificationException e) { + throw new AssertionError(range + " should be valid but failed to parse due to: " + e.getMessage(), e); } } - private void parseInvalid( String range ) - { - try - { - new GenericVersionRange( range ); - fail( range + " should be invalid" ); - } - catch ( InvalidVersionSpecificationException e ) - { - assertTrue( true ); + private void parseInvalid(String range) { + try { + new GenericVersionRange(range); + fail(range + " should be invalid"); + } catch (InvalidVersionSpecificationException e) { + assertTrue(true); } } - private void assertContains( VersionRange range, String version ) - { - assertTrue( range + " should contain " + version, range.containsVersion( newVersion( version ) ) ); + private void assertContains(VersionRange range, String version) { + assertTrue(range + " should contain " + version, range.containsVersion(newVersion(version))); } - private void assertNotContains( VersionRange range, String version ) - { - assertFalse( range + " should not contain " + version, range.containsVersion( newVersion( version ) ) ); + private void assertNotContains(VersionRange range, String version) { + assertFalse(range + " should not contain " + version, range.containsVersion(newVersion(version))); } @Test - public void testLowerBoundInclusiveUpperBoundInclusive() - { - VersionRange range = parseValid( "[1,2]" ); - assertContains( range, "1" ); - assertContains( range, "1.1-SNAPSHOT" ); - assertContains( range, "2" ); - assertEquals( range, parseValid( range.toString() ) ); + public void testLowerBoundInclusiveUpperBoundInclusive() { + VersionRange range = parseValid("[1,2]"); + assertContains(range, "1"); + assertContains(range, "1.1-SNAPSHOT"); + assertContains(range, "2"); + assertEquals(range, parseValid(range.toString())); } @Test - public void testLowerBoundInclusiveUpperBoundExclusive() - { - VersionRange range = parseValid( "[1.2.3.4.5,1.2.3.4.6)" ); - assertContains( range, "1.2.3.4.5" ); - assertNotContains( range, "1.2.3.4.6" ); - assertEquals( range, parseValid( range.toString() ) ); + public void testLowerBoundInclusiveUpperBoundExclusive() { + VersionRange range = parseValid("[1.2.3.4.5,1.2.3.4.6)"); + assertContains(range, "1.2.3.4.5"); + assertNotContains(range, "1.2.3.4.6"); + assertEquals(range, parseValid(range.toString())); } @Test - public void testLowerBoundExclusiveUpperBoundInclusive() - { - VersionRange range = parseValid( "(1a,1b]" ); - assertNotContains( range, "1a" ); - assertContains( range, "1b" ); - assertEquals( range, parseValid( range.toString() ) ); + public void testLowerBoundExclusiveUpperBoundInclusive() { + VersionRange range = parseValid("(1a,1b]"); + assertNotContains(range, "1a"); + assertContains(range, "1b"); + assertEquals(range, parseValid(range.toString())); } @Test - public void testLowerBoundExclusiveUpperBoundExclusive() - { - VersionRange range = parseValid( "(1,3)" ); - assertNotContains( range, "1" ); - assertContains( range, "2-SNAPSHOT" ); - assertNotContains( range, "3" ); - assertEquals( range, parseValid( range.toString() ) ); + public void testLowerBoundExclusiveUpperBoundExclusive() { + VersionRange range = parseValid("(1,3)"); + assertNotContains(range, "1"); + assertContains(range, "2-SNAPSHOT"); + assertNotContains(range, "3"); + assertEquals(range, parseValid(range.toString())); } @Test - public void testSingleVersion() - { - VersionRange range = parseValid( "[1]" ); - assertContains( range, "1" ); - assertEquals( range, parseValid( range.toString() ) ); - - range = parseValid( "[1,1]" ); - assertContains( range, "1" ); - assertEquals( range, parseValid( range.toString() ) ); + public void testSingleVersion() { + VersionRange range = parseValid("[1]"); + assertContains(range, "1"); + assertEquals(range, parseValid(range.toString())); + + range = parseValid("[1,1]"); + assertContains(range, "1"); + assertEquals(range, parseValid(range.toString())); } @Test - public void testSingleWildcardVersion() - { - VersionRange range = parseValid( "[1.2.*]" ); - assertContains( range, "1.2-alpha-1" ); - assertContains( range, "1.2-SNAPSHOT" ); - assertContains( range, "1.2" ); - assertContains( range, "1.2.9999999" ); - assertNotContains( range, "1.3-rc-1" ); - assertEquals( range, parseValid( range.toString() ) ); + public void testSingleWildcardVersion() { + VersionRange range = parseValid("[1.2.*]"); + assertContains(range, "1.2-alpha-1"); + assertContains(range, "1.2-SNAPSHOT"); + assertContains(range, "1.2"); + assertContains(range, "1.2.9999999"); + assertNotContains(range, "1.3-rc-1"); + assertEquals(range, parseValid(range.toString())); } @Test - public void testMissingOpenCloseDelimiter() - { - parseInvalid( "1.0" ); + public void testMissingOpenCloseDelimiter() { + parseInvalid("1.0"); } @Test - public void testMissingOpenDelimiter() - { - parseInvalid( "1.0]" ); - parseInvalid( "1.0)" ); + public void testMissingOpenDelimiter() { + parseInvalid("1.0]"); + parseInvalid("1.0)"); } @Test - public void testMissingCloseDelimiter() - { - parseInvalid( "[1.0" ); - parseInvalid( "(1.0" ); + public void testMissingCloseDelimiter() { + parseInvalid("[1.0"); + parseInvalid("(1.0"); } @Test - public void testTooManyVersions() - { - parseInvalid( "[1,2,3]" ); - parseInvalid( "(1,2,3)" ); - parseInvalid( "[1,2,3)" ); + public void testTooManyVersions() { + parseInvalid("[1,2,3]"); + parseInvalid("(1,2,3)"); + parseInvalid("[1,2,3)"); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionSchemeTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionSchemeTest.java index f161a035f..907178d6c 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionSchemeTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionSchemeTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,103 +16,90 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.version; import org.eclipse.aether.version.InvalidVersionSpecificationException; import org.eclipse.aether.version.VersionConstraint; import org.junit.Before; import org.junit.Test; +import static org.junit.Assert.*; + /** */ -public class GenericVersionSchemeTest -{ +public class GenericVersionSchemeTest { private GenericVersionScheme scheme; @Before - public void setUp() - { + public void setUp() { scheme = new GenericVersionScheme(); } - private InvalidVersionSpecificationException parseInvalid( String constraint ) - { - try - { - scheme.parseVersionConstraint( constraint ); - fail( "expected exception for constraint " + constraint ); + private InvalidVersionSpecificationException parseInvalid(String constraint) { + try { + scheme.parseVersionConstraint(constraint); + fail("expected exception for constraint " + constraint); return null; - } - catch ( InvalidVersionSpecificationException e ) - { + } catch (InvalidVersionSpecificationException e) { return e; } } @Test - public void testEnumeratedVersions() - throws InvalidVersionSpecificationException - { - VersionConstraint c = scheme.parseVersionConstraint( "1.0" ); - assertEquals( "1.0", c.getVersion().toString() ); - assertTrue( c.containsVersion( new GenericVersion( "1.0" ) ) ); - - c = scheme.parseVersionConstraint( "[1.0]" ); - assertNull( c.getVersion() ); - assertTrue( c.containsVersion( new GenericVersion( "1.0" ) ) ); - - c = scheme.parseVersionConstraint( "[1.0],[2.0]" ); - assertTrue( c.containsVersion( new GenericVersion( "1.0" ) ) ); - assertTrue( c.containsVersion( new GenericVersion( "2.0" ) ) ); - - c = scheme.parseVersionConstraint( "[1.0],[2.0],[3.0]" ); - assertContains( c, "1.0", "2.0", "3.0" ); - assertNotContains( c, "1.5" ); - - c = scheme.parseVersionConstraint( "[1,3),(3,5)" ); - assertContains( c, "1", "2", "4" ); - assertNotContains( c, "3", "5" ); - - c = scheme.parseVersionConstraint( "[1,3),(3,)" ); - assertContains( c, "1", "2", "4" ); - assertNotContains( c, "3" ); + public void testEnumeratedVersions() throws InvalidVersionSpecificationException { + VersionConstraint c = scheme.parseVersionConstraint("1.0"); + assertEquals("1.0", c.getVersion().toString()); + assertTrue(c.containsVersion(new GenericVersion("1.0"))); + + c = scheme.parseVersionConstraint("[1.0]"); + assertNull(c.getVersion()); + assertTrue(c.containsVersion(new GenericVersion("1.0"))); + + c = scheme.parseVersionConstraint("[1.0],[2.0]"); + assertTrue(c.containsVersion(new GenericVersion("1.0"))); + assertTrue(c.containsVersion(new GenericVersion("2.0"))); + + c = scheme.parseVersionConstraint("[1.0],[2.0],[3.0]"); + assertContains(c, "1.0", "2.0", "3.0"); + assertNotContains(c, "1.5"); + + c = scheme.parseVersionConstraint("[1,3),(3,5)"); + assertContains(c, "1", "2", "4"); + assertNotContains(c, "3", "5"); + + c = scheme.parseVersionConstraint("[1,3),(3,)"); + assertContains(c, "1", "2", "4"); + assertNotContains(c, "3"); } - private void assertNotContains( VersionConstraint c, String... versions ) - { - assertContains( String.format( "%s: %%s should not be contained\n", c.toString() ), c, false, versions ); + private void assertNotContains(VersionConstraint c, String... versions) { + assertContains(String.format("%s: %%s should not be contained\n", c.toString()), c, false, versions); } - private void assertContains( String msg, VersionConstraint c, boolean b, String... versions ) - { - for ( String v : versions ) - { - assertEquals( String.format( msg, v ), b, c.containsVersion( new GenericVersion( v ) ) ); + private void assertContains(String msg, VersionConstraint c, boolean b, String... versions) { + for (String v : versions) { + assertEquals(String.format(msg, v), b, c.containsVersion(new GenericVersion(v))); } } - private void assertContains( VersionConstraint c, String... versions ) - { - assertContains( String.format( "%s: %%s should be contained\n", c.toString() ), c, true, versions ); + private void assertContains(VersionConstraint c, String... versions) { + assertContains(String.format("%s: %%s should be contained\n", c.toString()), c, true, versions); } @Test - public void testInvalid() - { - parseInvalid( "[1," ); - parseInvalid( "[1,2],(3," ); - parseInvalid( "[1,2],3" ); + public void testInvalid() { + parseInvalid("[1,"); + parseInvalid("[1,2],(3,"); + parseInvalid("[1,2],3"); } @Test public void testSameUpperAndLowerBound() throws InvalidVersionSpecificationException { - VersionConstraint c = scheme.parseVersionConstraint( "[1.0]" ); - assertEquals( "[1.0,1.0]", c.toString() ); - VersionConstraint c2 = scheme.parseVersionConstraint( c.toString() ); - assertEquals( c, c2 ); - assertTrue( c.containsVersion( new GenericVersion( "1.0" ) ) ); + VersionConstraint c = scheme.parseVersionConstraint("[1.0]"); + assertEquals("[1.0,1.0]", c.toString()); + VersionConstraint c2 = scheme.parseVersionConstraint(c.toString()); + assertEquals(c, c2); + assertTrue(c.containsVersion(new GenericVersion("1.0"))); } - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionTest.java index 55fbc8c3b..79543547d 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/GenericVersionTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.eclipse.aether.util.version; import java.util.ArrayList; import java.util.Collections; @@ -34,322 +33,315 @@ /** */ -public class GenericVersionTest - extends AbstractVersionTest -{ +public class GenericVersionTest extends AbstractVersionTest { - protected Version newVersion( String version ) - { - return new GenericVersion( version ); + protected Version newVersion(String version) { + return new GenericVersion(version); } @Test - public void testEmptyVersion() - { - assertOrder( X_EQ_Y, "0", "" ); + public void testEmptyVersion() { + assertOrder(X_EQ_Y, "0", ""); } @Test - public void testNumericOrdering() - { - assertOrder( X_LT_Y, "2", "10" ); - assertOrder( X_LT_Y, "1.2", "1.10" ); - assertOrder( X_LT_Y, "1.0.2", "1.0.10" ); - assertOrder( X_LT_Y, "1.0.0.2", "1.0.0.10" ); - assertOrder( X_LT_Y, "1.0.20101206.111434.1", "1.0.20101206.111435.1" ); - assertOrder( X_LT_Y, "1.0.20101206.111434.2", "1.0.20101206.111434.10" ); + public void testNumericOrdering() { + assertOrder(X_LT_Y, "2", "10"); + assertOrder(X_LT_Y, "1.2", "1.10"); + assertOrder(X_LT_Y, "1.0.2", "1.0.10"); + assertOrder(X_LT_Y, "1.0.0.2", "1.0.0.10"); + assertOrder(X_LT_Y, "1.0.20101206.111434.1", "1.0.20101206.111435.1"); + assertOrder(X_LT_Y, "1.0.20101206.111434.2", "1.0.20101206.111434.10"); } @Test - public void testDelimiters() - { - assertOrder( X_EQ_Y, "1.0", "1-0" ); - assertOrder( X_EQ_Y, "1.0", "1_0" ); - assertOrder( X_EQ_Y, "1.a", "1a" ); + public void testDelimiters() { + assertOrder(X_EQ_Y, "1.0", "1-0"); + assertOrder(X_EQ_Y, "1.0", "1_0"); + assertOrder(X_EQ_Y, "1.a", "1a"); } @Test - public void testLeadingZerosAreSemanticallyIrrelevant() - { - assertOrder( X_EQ_Y, "1", "01" ); - assertOrder( X_EQ_Y, "1.2", "1.002" ); - assertOrder( X_EQ_Y, "1.2.3", "1.2.0003" ); - assertOrder( X_EQ_Y, "1.2.3.4", "1.2.3.00004" ); + public void testLeadingZerosAreSemanticallyIrrelevant() { + assertOrder(X_EQ_Y, "1", "01"); + assertOrder(X_EQ_Y, "1.2", "1.002"); + assertOrder(X_EQ_Y, "1.2.3", "1.2.0003"); + assertOrder(X_EQ_Y, "1.2.3.4", "1.2.3.00004"); } @Test - public void testTrailingZerosAreSemanticallyIrrelevant() - { - assertOrder( X_EQ_Y, "1", "1.0.0.0.0.0.0.0.0.0.0.0.0.0" ); - assertOrder( X_EQ_Y, "1", "1-0-0-0-0-0-0-0-0-0-0-0-0-0" ); - assertOrder( X_EQ_Y, "1", "1.0-0.0-0.0-0.0-0.0-0.0-0.0" ); - assertOrder( X_EQ_Y, "1", "1.0000000000000" ); - assertOrder( X_EQ_Y, "1.0", "1.0.0" ); + public void testTrailingZerosAreSemanticallyIrrelevant() { + assertOrder(X_EQ_Y, "1", "1.0.0.0.0.0.0.0.0.0.0.0.0.0"); + assertOrder(X_EQ_Y, "1", "1-0-0-0-0-0-0-0-0-0-0-0-0-0"); + assertOrder(X_EQ_Y, "1", "1.0-0.0-0.0-0.0-0.0-0.0-0.0"); + assertOrder(X_EQ_Y, "1", "1.0000000000000"); + assertOrder(X_EQ_Y, "1.0", "1.0.0"); } @Test - public void testTrailingZerosBeforeQualifierAreSemanticallyIrrelevant() - { - assertOrder( X_EQ_Y, "1.0-ga", "1.0.0-ga" ); - assertOrder( X_EQ_Y, "1.0.ga", "1.0.0.ga" ); - assertOrder( X_EQ_Y, "1.0ga", "1.0.0ga" ); - - assertOrder( X_EQ_Y, "1.0-alpha", "1.0.0-alpha" ); - assertOrder( X_EQ_Y, "1.0.alpha", "1.0.0.alpha" ); - assertOrder( X_EQ_Y, "1.0alpha", "1.0.0alpha" ); - assertOrder( X_EQ_Y, "1.0-alpha-snapshot", "1.0.0-alpha-snapshot" ); - assertOrder( X_EQ_Y, "1.0.alpha.snapshot", "1.0.0.alpha.snapshot" ); - - assertOrder( X_EQ_Y, "1.x.0-alpha", "1.x.0.0-alpha" ); - assertOrder( X_EQ_Y, "1.x.0.alpha", "1.x.0.0.alpha" ); - assertOrder( X_EQ_Y, "1.x.0-alpha-snapshot", "1.x.0.0-alpha-snapshot" ); - assertOrder( X_EQ_Y, "1.x.0.alpha.snapshot", "1.x.0.0.alpha.snapshot" ); + public void testTrailingZerosBeforeQualifierAreSemanticallyIrrelevant() { + assertOrder(X_EQ_Y, "1.0-ga", "1.0.0-ga"); + assertOrder(X_EQ_Y, "1.0.ga", "1.0.0.ga"); + assertOrder(X_EQ_Y, "1.0ga", "1.0.0ga"); + + assertOrder(X_EQ_Y, "1.0-alpha", "1.0.0-alpha"); + assertOrder(X_EQ_Y, "1.0.alpha", "1.0.0.alpha"); + assertOrder(X_EQ_Y, "1.0alpha", "1.0.0alpha"); + assertOrder(X_EQ_Y, "1.0-alpha-snapshot", "1.0.0-alpha-snapshot"); + assertOrder(X_EQ_Y, "1.0.alpha.snapshot", "1.0.0.alpha.snapshot"); + + assertOrder(X_EQ_Y, "1.x.0-alpha", "1.x.0.0-alpha"); + assertOrder(X_EQ_Y, "1.x.0.alpha", "1.x.0.0.alpha"); + assertOrder(X_EQ_Y, "1.x.0-alpha-snapshot", "1.x.0.0-alpha-snapshot"); + assertOrder(X_EQ_Y, "1.x.0.alpha.snapshot", "1.x.0.0.alpha.snapshot"); } @Test - public void testTrailingDelimitersAreSemanticallyIrrelevant() - { - assertOrder( X_EQ_Y, "1", "1............." ); - assertOrder( X_EQ_Y, "1", "1-------------" ); - assertOrder( X_EQ_Y, "1.0", "1............." ); - assertOrder( X_EQ_Y, "1.0", "1-------------" ); + public void testTrailingDelimitersAreSemanticallyIrrelevant() { + assertOrder(X_EQ_Y, "1", "1............."); + assertOrder(X_EQ_Y, "1", "1-------------"); + assertOrder(X_EQ_Y, "1.0", "1............."); + assertOrder(X_EQ_Y, "1.0", "1-------------"); } @Test - public void testInitialDelimiters() - { - assertOrder( X_EQ_Y, "0.1", ".1" ); - assertOrder( X_EQ_Y, "0.0.1", "..1" ); - assertOrder( X_EQ_Y, "0.1", "-1" ); - assertOrder( X_EQ_Y, "0.0.1", "--1" ); + public void testInitialDelimiters() { + assertOrder(X_EQ_Y, "0.1", ".1"); + assertOrder(X_EQ_Y, "0.0.1", "..1"); + assertOrder(X_EQ_Y, "0.1", "-1"); + assertOrder(X_EQ_Y, "0.0.1", "--1"); } @Test - public void testConsecutiveDelimiters() - { - assertOrder( X_EQ_Y, "1.0.1", "1..1" ); - assertOrder( X_EQ_Y, "1.0.0.1", "1...1" ); - assertOrder( X_EQ_Y, "1.0.1", "1--1" ); - assertOrder( X_EQ_Y, "1.0.0.1", "1---1" ); + public void testConsecutiveDelimiters() { + assertOrder(X_EQ_Y, "1.0.1", "1..1"); + assertOrder(X_EQ_Y, "1.0.0.1", "1...1"); + assertOrder(X_EQ_Y, "1.0.1", "1--1"); + assertOrder(X_EQ_Y, "1.0.0.1", "1---1"); } @Test - public void testUnlimitedNumberOfVersionComponents() - { - assertOrder( X_GT_Y, "1.0.1.2.3.4.5.6.7.8.9.0.1.2.10", "1.0.1.2.3.4.5.6.7.8.9.0.1.2.3" ); + public void testUnlimitedNumberOfVersionComponents() { + assertOrder(X_GT_Y, "1.0.1.2.3.4.5.6.7.8.9.0.1.2.10", "1.0.1.2.3.4.5.6.7.8.9.0.1.2.3"); } @Test - public void testUnlimitedNumberOfDigitsInNumericComponent() - { - assertOrder( X_GT_Y, "1.1234567890123456789012345678901", "1.123456789012345678901234567891" ); + public void testUnlimitedNumberOfDigitsInNumericComponent() { + assertOrder(X_GT_Y, "1.1234567890123456789012345678901", "1.123456789012345678901234567891"); } @Test - public void testTransitionFromDigitToLetterAndViceVersaIsEqualivantToDelimiter() - { - assertOrder( X_EQ_Y, "1alpha10", "1.alpha.10" ); - assertOrder( X_EQ_Y, "1alpha10", "1-alpha-10" ); + public void testTransitionFromDigitToLetterAndViceVersaIsEqualivantToDelimiter() { + assertOrder(X_EQ_Y, "1alpha10", "1.alpha.10"); + assertOrder(X_EQ_Y, "1alpha10", "1-alpha-10"); - assertOrder( X_GT_Y, "1.alpha10", "1.alpha2" ); - assertOrder( X_GT_Y, "10alpha", "1alpha" ); + assertOrder(X_GT_Y, "1.alpha10", "1.alpha2"); + assertOrder(X_GT_Y, "10alpha", "1alpha"); } @Test - public void testWellKnownQualifierOrdering() - { - assertOrder( X_EQ_Y, "1-alpha1", "1-a1" ); - assertOrder( X_LT_Y, "1-alpha", "1-beta" ); - assertOrder( X_EQ_Y, "1-beta1", "1-b1" ); - assertOrder( X_LT_Y, "1-beta", "1-milestone" ); - assertOrder( X_EQ_Y, "1-milestone1", "1-m1" ); - assertOrder( X_LT_Y, "1-milestone", "1-rc" ); - assertOrder( X_EQ_Y, "1-rc", "1-cr" ); - assertOrder( X_LT_Y, "1-rc", "1-snapshot" ); - assertOrder( X_LT_Y, "1-snapshot", "1" ); - assertOrder( X_EQ_Y, "1", "1-ga" ); - assertOrder( X_EQ_Y, "1", "1.ga.0.ga" ); - assertOrder( X_EQ_Y, "1.0", "1-ga" ); - assertOrder( X_EQ_Y, "1", "1-ga.ga" ); - assertOrder( X_EQ_Y, "1", "1-ga-ga" ); - assertOrder( X_EQ_Y, "A", "A.ga.ga" ); - assertOrder( X_EQ_Y, "A", "A-ga-ga" ); - assertOrder( X_EQ_Y, "1", "1-final" ); - assertOrder( X_EQ_Y, "1", "1-release" ); - assertOrder( X_LT_Y, "1", "1-sp" ); - - assertOrder( X_LT_Y, "A.rc.1", "A.ga.1" ); - assertOrder( X_GT_Y, "A.sp.1", "A.ga.1" ); - assertOrder( X_LT_Y, "A.rc.x", "A.ga.x" ); - assertOrder( X_GT_Y, "A.sp.x", "A.ga.x" ); + public void testWellKnownQualifierOrdering() { + assertOrder(X_EQ_Y, "1-alpha1", "1-a1"); + assertOrder(X_LT_Y, "1-alpha", "1-beta"); + assertOrder(X_EQ_Y, "1-beta1", "1-b1"); + assertOrder(X_LT_Y, "1-beta", "1-milestone"); + assertOrder(X_EQ_Y, "1-milestone1", "1-m1"); + assertOrder(X_LT_Y, "1-milestone", "1-rc"); + assertOrder(X_EQ_Y, "1-rc", "1-cr"); + assertOrder(X_LT_Y, "1-rc", "1-snapshot"); + assertOrder(X_LT_Y, "1-snapshot", "1"); + assertOrder(X_EQ_Y, "1", "1-ga"); + assertOrder(X_EQ_Y, "1", "1.ga.0.ga"); + assertOrder(X_EQ_Y, "1.0", "1-ga"); + assertOrder(X_EQ_Y, "1", "1-ga.ga"); + assertOrder(X_EQ_Y, "1", "1-ga-ga"); + assertOrder(X_EQ_Y, "A", "A.ga.ga"); + assertOrder(X_EQ_Y, "A", "A-ga-ga"); + assertOrder(X_EQ_Y, "1", "1-final"); + assertOrder(X_EQ_Y, "1", "1-release"); + assertOrder(X_LT_Y, "1", "1-sp"); + + assertOrder(X_LT_Y, "A.rc.1", "A.ga.1"); + assertOrder(X_GT_Y, "A.sp.1", "A.ga.1"); + assertOrder(X_LT_Y, "A.rc.x", "A.ga.x"); + assertOrder(X_GT_Y, "A.sp.x", "A.ga.x"); } @Test - public void testWellKnownQualifierVersusUnknownQualifierOrdering() - { - assertOrder( X_GT_Y, "1-abc", "1-alpha" ); - assertOrder( X_GT_Y, "1-abc", "1-beta" ); - assertOrder( X_GT_Y, "1-abc", "1-milestone" ); - assertOrder( X_GT_Y, "1-abc", "1-rc" ); - assertOrder( X_GT_Y, "1-abc", "1-snapshot" ); - assertOrder( X_GT_Y, "1-abc", "1" ); - assertOrder( X_GT_Y, "1-abc", "1-sp" ); + public void testWellKnownQualifierVersusUnknownQualifierOrdering() { + assertOrder(X_GT_Y, "1-abc", "1-alpha"); + assertOrder(X_GT_Y, "1-abc", "1-beta"); + assertOrder(X_GT_Y, "1-abc", "1-milestone"); + assertOrder(X_GT_Y, "1-abc", "1-rc"); + assertOrder(X_GT_Y, "1-abc", "1-snapshot"); + assertOrder(X_GT_Y, "1-abc", "1"); + assertOrder(X_GT_Y, "1-abc", "1-sp"); } @Test - public void testWellKnownSingleCharQualifiersOnlyRecognizedIfImmediatelyFollowedByNumber() - { - assertOrder( X_GT_Y, "1.0a", "1.0" ); - assertOrder( X_GT_Y, "1.0-a", "1.0" ); - assertOrder( X_GT_Y, "1.0.a", "1.0" ); - assertOrder( X_GT_Y, "1.0b", "1.0" ); - assertOrder( X_GT_Y, "1.0-b", "1.0" ); - assertOrder( X_GT_Y, "1.0.b", "1.0" ); - assertOrder( X_GT_Y, "1.0m", "1.0" ); - assertOrder( X_GT_Y, "1.0-m", "1.0" ); - assertOrder( X_GT_Y, "1.0.m", "1.0" ); - - assertOrder( X_LT_Y, "1.0a1", "1.0" ); - assertOrder( X_LT_Y, "1.0-a1", "1.0" ); - assertOrder( X_LT_Y, "1.0.a1", "1.0" ); - assertOrder( X_LT_Y, "1.0b1", "1.0" ); - assertOrder( X_LT_Y, "1.0-b1", "1.0" ); - assertOrder( X_LT_Y, "1.0.b1", "1.0" ); - assertOrder( X_LT_Y, "1.0m1", "1.0" ); - assertOrder( X_LT_Y, "1.0-m1", "1.0" ); - assertOrder( X_LT_Y, "1.0.m1", "1.0" ); - - assertOrder( X_GT_Y, "1.0a.1", "1.0" ); - assertOrder( X_GT_Y, "1.0a-1", "1.0" ); - assertOrder( X_GT_Y, "1.0b.1", "1.0" ); - assertOrder( X_GT_Y, "1.0b-1", "1.0" ); - assertOrder( X_GT_Y, "1.0m.1", "1.0" ); - assertOrder( X_GT_Y, "1.0m-1", "1.0" ); + public void testWellKnownSingleCharQualifiersOnlyRecognizedIfImmediatelyFollowedByNumber() { + assertOrder(X_GT_Y, "1.0a", "1.0"); + assertOrder(X_GT_Y, "1.0-a", "1.0"); + assertOrder(X_GT_Y, "1.0.a", "1.0"); + assertOrder(X_GT_Y, "1.0b", "1.0"); + assertOrder(X_GT_Y, "1.0-b", "1.0"); + assertOrder(X_GT_Y, "1.0.b", "1.0"); + assertOrder(X_GT_Y, "1.0m", "1.0"); + assertOrder(X_GT_Y, "1.0-m", "1.0"); + assertOrder(X_GT_Y, "1.0.m", "1.0"); + + assertOrder(X_LT_Y, "1.0a1", "1.0"); + assertOrder(X_LT_Y, "1.0-a1", "1.0"); + assertOrder(X_LT_Y, "1.0.a1", "1.0"); + assertOrder(X_LT_Y, "1.0b1", "1.0"); + assertOrder(X_LT_Y, "1.0-b1", "1.0"); + assertOrder(X_LT_Y, "1.0.b1", "1.0"); + assertOrder(X_LT_Y, "1.0m1", "1.0"); + assertOrder(X_LT_Y, "1.0-m1", "1.0"); + assertOrder(X_LT_Y, "1.0.m1", "1.0"); + + assertOrder(X_GT_Y, "1.0a.1", "1.0"); + assertOrder(X_GT_Y, "1.0a-1", "1.0"); + assertOrder(X_GT_Y, "1.0b.1", "1.0"); + assertOrder(X_GT_Y, "1.0b-1", "1.0"); + assertOrder(X_GT_Y, "1.0m.1", "1.0"); + assertOrder(X_GT_Y, "1.0m-1", "1.0"); } @Test - public void testUnknownQualifierOrdering() - { - assertOrder( X_LT_Y, "1-abc", "1-abcd" ); - assertOrder( X_LT_Y, "1-abc", "1-bcd" ); - assertOrder( X_GT_Y, "1-abc", "1-aac" ); + public void testUnknownQualifierOrdering() { + assertOrder(X_LT_Y, "1-abc", "1-abcd"); + assertOrder(X_LT_Y, "1-abc", "1-bcd"); + assertOrder(X_GT_Y, "1-abc", "1-aac"); } @Test - public void testCaseInsensitiveOrderingOfQualifiers() - { - assertOrder( X_EQ_Y, "1.alpha", "1.ALPHA" ); - assertOrder( X_EQ_Y, "1.alpha", "1.Alpha" ); + public void testCaseInsensitiveOrderingOfQualifiers() { + assertOrder(X_EQ_Y, "1.alpha", "1.ALPHA"); + assertOrder(X_EQ_Y, "1.alpha", "1.Alpha"); - assertOrder( X_EQ_Y, "1.beta", "1.BETA" ); - assertOrder( X_EQ_Y, "1.beta", "1.Beta" ); + assertOrder(X_EQ_Y, "1.beta", "1.BETA"); + assertOrder(X_EQ_Y, "1.beta", "1.Beta"); - assertOrder( X_EQ_Y, "1.milestone", "1.MILESTONE" ); - assertOrder( X_EQ_Y, "1.milestone", "1.Milestone" ); + assertOrder(X_EQ_Y, "1.milestone", "1.MILESTONE"); + assertOrder(X_EQ_Y, "1.milestone", "1.Milestone"); - assertOrder( X_EQ_Y, "1.rc", "1.RC" ); - assertOrder( X_EQ_Y, "1.rc", "1.Rc" ); - assertOrder( X_EQ_Y, "1.cr", "1.CR" ); - assertOrder( X_EQ_Y, "1.cr", "1.Cr" ); + assertOrder(X_EQ_Y, "1.rc", "1.RC"); + assertOrder(X_EQ_Y, "1.rc", "1.Rc"); + assertOrder(X_EQ_Y, "1.cr", "1.CR"); + assertOrder(X_EQ_Y, "1.cr", "1.Cr"); - assertOrder( X_EQ_Y, "1.snapshot", "1.SNAPSHOT" ); - assertOrder( X_EQ_Y, "1.snapshot", "1.Snapshot" ); + assertOrder(X_EQ_Y, "1.snapshot", "1.SNAPSHOT"); + assertOrder(X_EQ_Y, "1.snapshot", "1.Snapshot"); - assertOrder( X_EQ_Y, "1.ga", "1.GA" ); - assertOrder( X_EQ_Y, "1.ga", "1.Ga" ); - assertOrder( X_EQ_Y, "1.final", "1.FINAL" ); - assertOrder( X_EQ_Y, "1.final", "1.Final" ); - assertOrder( X_EQ_Y, "1.release", "1.RELEASE" ); - assertOrder( X_EQ_Y, "1.release", "1.Release" ); + assertOrder(X_EQ_Y, "1.ga", "1.GA"); + assertOrder(X_EQ_Y, "1.ga", "1.Ga"); + assertOrder(X_EQ_Y, "1.final", "1.FINAL"); + assertOrder(X_EQ_Y, "1.final", "1.Final"); + assertOrder(X_EQ_Y, "1.release", "1.RELEASE"); + assertOrder(X_EQ_Y, "1.release", "1.Release"); - assertOrder( X_EQ_Y, "1.sp", "1.SP" ); - assertOrder( X_EQ_Y, "1.sp", "1.Sp" ); + assertOrder(X_EQ_Y, "1.sp", "1.SP"); + assertOrder(X_EQ_Y, "1.sp", "1.Sp"); - assertOrder( X_EQ_Y, "1.unknown", "1.UNKNOWN" ); - assertOrder( X_EQ_Y, "1.unknown", "1.Unknown" ); + assertOrder(X_EQ_Y, "1.unknown", "1.UNKNOWN"); + assertOrder(X_EQ_Y, "1.unknown", "1.Unknown"); } @Test - public void testCaseInsensitiveOrderingOfQualifiersIsLocaleIndependent() - { + public void testCaseInsensitiveOrderingOfQualifiersIsLocaleIndependent() { Locale orig = Locale.getDefault(); - try - { - Locale[] locales = { Locale.ENGLISH, new Locale( "tr" ) }; - for ( Locale locale : locales ) - { - Locale.setDefault( locale ); - assertOrder( X_EQ_Y, "1-abcdefghijklmnopqrstuvwxyz", "1-ABCDEFGHIJKLMNOPQRSTUVWXYZ" ); + try { + Locale[] locales = {Locale.ENGLISH, new Locale("tr")}; + for (Locale locale : locales) { + Locale.setDefault(locale); + assertOrder(X_EQ_Y, "1-abcdefghijklmnopqrstuvwxyz", "1-ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } - } - finally - { - Locale.setDefault( orig ); + } finally { + Locale.setDefault(orig); } } @Test - public void testQualifierVersusNumberOrdering() - { - assertOrder( X_LT_Y, "1-ga", "1-1" ); - assertOrder( X_LT_Y, "1.ga", "1.1" ); - assertOrder( X_EQ_Y, "1-ga", "1.0" ); - assertOrder( X_EQ_Y, "1.ga", "1.0" ); + public void testQualifierVersusNumberOrdering() { + assertOrder(X_LT_Y, "1-ga", "1-1"); + assertOrder(X_LT_Y, "1.ga", "1.1"); + assertOrder(X_EQ_Y, "1-ga", "1.0"); + assertOrder(X_EQ_Y, "1.ga", "1.0"); - assertOrder( X_LT_Y, "1-ga-1", "1-0-1" ); - assertOrder( X_LT_Y, "1.ga.1", "1.0.1" ); + assertOrder(X_LT_Y, "1-ga-1", "1-0-1"); + assertOrder(X_LT_Y, "1.ga.1", "1.0.1"); - assertOrder( X_GT_Y, "1.sp", "1.0" ); - assertOrder( X_LT_Y, "1.sp", "1.1" ); + assertOrder(X_GT_Y, "1.sp", "1.0"); + assertOrder(X_LT_Y, "1.sp", "1.1"); - assertOrder( X_LT_Y, "1-abc", "1-1" ); - assertOrder( X_LT_Y, "1.abc", "1.1" ); + assertOrder(X_LT_Y, "1-abc", "1-1"); + assertOrder(X_LT_Y, "1.abc", "1.1"); - assertOrder( X_LT_Y, "1-xyz", "1-1" ); - assertOrder( X_LT_Y, "1.xyz", "1.1" ); + assertOrder(X_LT_Y, "1-xyz", "1-1"); + assertOrder(X_LT_Y, "1.xyz", "1.1"); } @Test - public void testVersionEvolution() - { - assertSequence( "0.9.9-SNAPSHOT", "0.9.9", "0.9.10-SNAPSHOT", "0.9.10", "1.0-alpha-2-SNAPSHOT", "1.0-alpha-2", - "1.0-alpha-10-SNAPSHOT", "1.0-alpha-10", "1.0-beta-1-SNAPSHOT", "1.0-beta-1", - "1.0-rc-1-SNAPSHOT", "1.0-rc-1", "1.0-SNAPSHOT", "1.0", "1.0-sp-1-SNAPSHOT", "1.0-sp-1", - "1.0.1-alpha-1-SNAPSHOT", "1.0.1-alpha-1", "1.0.1-beta-1-SNAPSHOT", "1.0.1-beta-1", - "1.0.1-rc-1-SNAPSHOT", "1.0.1-rc-1", "1.0.1-SNAPSHOT", "1.0.1", "1.1-SNAPSHOT", "1.1" ); - - assertSequence( "1.0-alpha", "1.0", "1.0-1" ); - assertSequence( "1.0.alpha", "1.0", "1.0-1" ); - assertSequence( "1.0-alpha", "1.0", "1.0.1" ); - assertSequence( "1.0.alpha", "1.0", "1.0.1" ); + public void testVersionEvolution() { + assertSequence( + "0.9.9-SNAPSHOT", + "0.9.9", + "0.9.10-SNAPSHOT", + "0.9.10", + "1.0-alpha-2-SNAPSHOT", + "1.0-alpha-2", + "1.0-alpha-10-SNAPSHOT", + "1.0-alpha-10", + "1.0-beta-1-SNAPSHOT", + "1.0-beta-1", + "1.0-rc-1-SNAPSHOT", + "1.0-rc-1", + "1.0-SNAPSHOT", + "1.0", + "1.0-sp-1-SNAPSHOT", + "1.0-sp-1", + "1.0.1-alpha-1-SNAPSHOT", + "1.0.1-alpha-1", + "1.0.1-beta-1-SNAPSHOT", + "1.0.1-beta-1", + "1.0.1-rc-1-SNAPSHOT", + "1.0.1-rc-1", + "1.0.1-SNAPSHOT", + "1.0.1", + "1.1-SNAPSHOT", + "1.1"); + + assertSequence("1.0-alpha", "1.0", "1.0-1"); + assertSequence("1.0.alpha", "1.0", "1.0-1"); + assertSequence("1.0-alpha", "1.0", "1.0.1"); + assertSequence("1.0.alpha", "1.0", "1.0.1"); } @Test - public void testMinimumSegment() - { - assertOrder( X_LT_Y, "1.min", "1.0-alpha-1" ); - assertOrder( X_LT_Y, "1.min", "1.0-SNAPSHOT" ); - assertOrder( X_LT_Y, "1.min", "1.0" ); - assertOrder( X_LT_Y, "1.min", "1.9999999999" ); + public void testMinimumSegment() { + assertOrder(X_LT_Y, "1.min", "1.0-alpha-1"); + assertOrder(X_LT_Y, "1.min", "1.0-SNAPSHOT"); + assertOrder(X_LT_Y, "1.min", "1.0"); + assertOrder(X_LT_Y, "1.min", "1.9999999999"); - assertOrder( X_EQ_Y, "1.min", "1.MIN" ); + assertOrder(X_EQ_Y, "1.min", "1.MIN"); - assertOrder( X_GT_Y, "1.min", "0.99999" ); - assertOrder( X_GT_Y, "1.min", "0.max" ); + assertOrder(X_GT_Y, "1.min", "0.99999"); + assertOrder(X_GT_Y, "1.min", "0.max"); } @Test - public void testMaximumSegment() - { - assertOrder( X_GT_Y, "1.max", "1.0-alpha-1" ); - assertOrder( X_GT_Y, "1.max", "1.0-SNAPSHOT" ); - assertOrder( X_GT_Y, "1.max", "1.0" ); - assertOrder( X_GT_Y, "1.max", "1.9999999999" ); + public void testMaximumSegment() { + assertOrder(X_GT_Y, "1.max", "1.0-alpha-1"); + assertOrder(X_GT_Y, "1.max", "1.0-SNAPSHOT"); + assertOrder(X_GT_Y, "1.max", "1.0"); + assertOrder(X_GT_Y, "1.max", "1.9999999999"); - assertOrder( X_EQ_Y, "1.max", "1.MAX" ); + assertOrder(X_EQ_Y, "1.max", "1.MAX"); - assertOrder( X_LT_Y, "1.max", "2.0-alpha-1" ); - assertOrder( X_LT_Y, "1.max", "2.min" ); + assertOrder(X_LT_Y, "1.max", "2.0-alpha-1"); + assertOrder(X_LT_Y, "1.max", "2.min"); } /** @@ -361,26 +353,20 @@ public void testMaximumSegment() */ @Test public void testCompareUuidRandom() { - for ( int j = 0; j < 32; j++ ) - { - ArrayList versions = new ArrayList<>(); - for ( int i = 0; i < 64; i++ ) - { - versions.add( newVersion( UUID.randomUUID().toString() ) ); - } - try - { - Collections.sort( versions ); - } - catch ( Exception e ) - { - e.printStackTrace( System.err ); - System.err.println( "The UUIDs used" ); - System.err.println( - versions.stream().map( Version::toString ).collect( Collectors.joining( "\n" ) ) ); - fail( "unexpected exception" ); - } + for (int j = 0; j < 32; j++) { + ArrayList versions = new ArrayList<>(); + for (int i = 0; i < 64; i++) { + versions.add(newVersion(UUID.randomUUID().toString())); } + try { + Collections.sort(versions); + } catch (Exception e) { + e.printStackTrace(System.err); + System.err.println("The UUIDs used"); + System.err.println(versions.stream().map(Version::toString).collect(Collectors.joining("\n"))); + fail("unexpected exception"); + } + } } /** @@ -389,17 +375,12 @@ public void testCompareUuidRandom() { * Works on known set that failed before fix, provided by {@link #uuidVersionStringStream()}. */ @Test - public void testCompareUuidVersionStringStream() - { + public void testCompareUuidVersionStringStream() { // this operation below fails with IAEx if comparison is unstable - uuidVersionStringStream() - .map( this::newVersion ) - .sorted() - .collect( toList() ); + uuidVersionStringStream().map(this::newVersion).sorted().collect(toList()); } - private Stream uuidVersionStringStream() - { + private Stream uuidVersionStringStream() { return Stream.of( "e3f6b227-e09d-4461-a030-b8c1755834f7", "dfdf5e15-b047-4fee-94e5-3ddf6fe90a0c", @@ -466,6 +447,4 @@ private Stream uuidVersionStringStream() "f95e94f7-2443-4b2f-a10d-059d8d224dd9", "b558af80-78bc-43c7-b916-d635a23cc4b5"); } - - } diff --git a/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/UnionVersionRangeTest.java b/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/UnionVersionRangeTest.java index 570b6b778..a7b57ab8f 100644 --- a/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/UnionVersionRangeTest.java +++ b/maven-resolver-util/src/test/java/org/eclipse/aether/util/version/UnionVersionRangeTest.java @@ -1,5 +1,3 @@ -package org.eclipse.aether.util.version; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -8,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + * + * 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 @@ -18,8 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.junit.Assert.*; +package org.eclipse.aether.util.version; import java.util.Collections; @@ -27,79 +24,66 @@ import org.eclipse.aether.version.VersionRange; import org.junit.Test; -public class UnionVersionRangeTest -{ +import static org.junit.Assert.*; - private VersionRange newRange( String range ) - { - try - { - return new GenericVersionScheme().parseVersionRange( range ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new IllegalArgumentException( e ); +public class UnionVersionRangeTest { + + private VersionRange newRange(String range) { + try { + return new GenericVersionScheme().parseVersionRange(range); + } catch (InvalidVersionSpecificationException e) { + throw new IllegalArgumentException(e); } } - private void assertBound( String version, boolean inclusive, VersionRange.Bound bound ) - { - if ( version == null ) - { - assertNull( bound ); - } - else - { - assertNotNull( bound ); - assertNotNull( bound.getVersion() ); - assertEquals( inclusive, bound.isInclusive() ); - try - { - assertEquals( new GenericVersionScheme().parseVersion( version ), bound.getVersion() ); - } - catch ( InvalidVersionSpecificationException e ) - { - throw new IllegalArgumentException( e ); + private void assertBound(String version, boolean inclusive, VersionRange.Bound bound) { + if (version == null) { + assertNull(bound); + } else { + assertNotNull(bound); + assertNotNull(bound.getVersion()); + assertEquals(inclusive, bound.isInclusive()); + try { + assertEquals(new GenericVersionScheme().parseVersion(version), bound.getVersion()); + } catch (InvalidVersionSpecificationException e) { + throw new IllegalArgumentException(e); } } } @Test - public void testGetLowerBound() - { - VersionRange range = UnionVersionRange.from( Collections. emptySet() ); - assertBound( null, false, range.getLowerBound() ); + public void testGetLowerBound() { + VersionRange range = UnionVersionRange.from(Collections.emptySet()); + assertBound(null, false, range.getLowerBound()); - range = UnionVersionRange.from( newRange( "[1,2]" ), newRange( "[3,4]" ) ); - assertBound( "1", true, range.getLowerBound() ); + range = UnionVersionRange.from(newRange("[1,2]"), newRange("[3,4]")); + assertBound("1", true, range.getLowerBound()); - range = UnionVersionRange.from( newRange( "[1,2]" ), newRange( "(,4]" ) ); - assertBound( null, false, range.getLowerBound() ); + range = UnionVersionRange.from(newRange("[1,2]"), newRange("(,4]")); + assertBound(null, false, range.getLowerBound()); - range = UnionVersionRange.from( newRange( "[1,2]" ), newRange( "(1,4]" ) ); - assertBound( "1", true, range.getLowerBound() ); + range = UnionVersionRange.from(newRange("[1,2]"), newRange("(1,4]")); + assertBound("1", true, range.getLowerBound()); - range = UnionVersionRange.from( newRange( "[1,2]" ), newRange( "(0,4]" ) ); - assertBound( "0", false, range.getLowerBound() ); + range = UnionVersionRange.from(newRange("[1,2]"), newRange("(0,4]")); + assertBound("0", false, range.getLowerBound()); } @Test - public void testGetUpperBound() - { - VersionRange range = UnionVersionRange.from( Collections. emptySet() ); - assertBound( null, false, range.getUpperBound() ); + public void testGetUpperBound() { + VersionRange range = UnionVersionRange.from(Collections.emptySet()); + assertBound(null, false, range.getUpperBound()); - range = UnionVersionRange.from( newRange( "[1,2]" ), newRange( "[3,4]" ) ); - assertBound( "4", true, range.getUpperBound() ); + range = UnionVersionRange.from(newRange("[1,2]"), newRange("[3,4]")); + assertBound("4", true, range.getUpperBound()); - range = UnionVersionRange.from( newRange( "[1,2]" ), newRange( "[3,)" ) ); - assertBound( null, false, range.getUpperBound() ); + range = UnionVersionRange.from(newRange("[1,2]"), newRange("[3,)")); + assertBound(null, false, range.getUpperBound()); - range = UnionVersionRange.from( newRange( "[1,2]" ), newRange( "[1,2)" ) ); - assertBound( "2", true, range.getUpperBound() ); + range = UnionVersionRange.from(newRange("[1,2]"), newRange("[1,2)")); + assertBound("2", true, range.getUpperBound()); - range = UnionVersionRange.from( newRange( "[1,2]" ), newRange( "[1,3)" ) ); - assertBound( "3", false, range.getUpperBound() ); + range = UnionVersionRange.from(newRange("[1,2]"), newRange("[1,3)")); + assertBound("3", false, range.getUpperBound()); } - } diff --git a/pom.xml b/pom.xml index bf0e58c08..7b1130b34 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 org.apache.maven maven-parent - 37 + 39 @@ -35,9 +33,7 @@ pom Maven Artifact Resolver - - The parent and aggregator for the repository system. - + The parent and aggregator for the repository system. https://maven.apache.org/resolver/ 2010 @@ -47,11 +43,29 @@ + + + maven-resolver-api + maven-resolver-spi + maven-resolver-util + maven-resolver-named-locks + maven-resolver-named-locks-hazelcast + maven-resolver-named-locks-redisson + maven-resolver-impl + maven-resolver-test-util + maven-resolver-connector-basic + maven-resolver-transport-classpath + maven-resolver-transport-file + maven-resolver-transport-http + maven-resolver-transport-wagon + maven-resolver-demos + + scm:git:https://gitbox.apache.org/repos/asf/maven-resolver.git scm:git:https://gitbox.apache.org/repos/asf/maven-resolver.git - https://github.com/apache/maven-resolver/tree/${project.scm.tag} master + https://github.com/apache/maven-resolver/tree/${project.scm.tag} jira @@ -83,24 +97,6 @@ 2023-01-13T06:54:05Z - - - maven-resolver-api - maven-resolver-spi - maven-resolver-util - maven-resolver-named-locks - maven-resolver-named-locks-hazelcast - maven-resolver-named-locks-redisson - maven-resolver-impl - maven-resolver-test-util - maven-resolver-connector-basic - maven-resolver-transport-classpath - maven-resolver-transport-file - maven-resolver-transport-http - maven-resolver-transport-wagon - maven-resolver-demos - - @@ -288,15 +284,17 @@ - + + org.apache.maven.plugins - maven-deploy-plugin - 3.0.0 + maven-install-plugin + 3.1.0 - + + org.apache.maven.plugins - maven-install-plugin - 3.0.1 + maven-deploy-plugin + 3.1.0 com.github.siom79.japicmp @@ -316,10 +314,10 @@ default-source-cmp - verify cmp + verify @@ -350,10 +348,10 @@ default-binary-cmp - verify cmp + verify true @@ -494,10 +492,10 @@ generate-index - process-classes main-index + process-classes @@ -524,13 +522,11 @@ bnd-process - - Bundle-SymbolicName: ${Bundle-SymbolicName} + Bundle-SymbolicName: ${Bundle-SymbolicName} # Export packages not containing the substring 'internal' -exportcontents: ${removeall;${packages};${packages;NAMED;*internal*}} # Reproducible build - -noextraheaders: true - + -noextraheaders: true @@ -563,10 +559,10 @@ check-java-compat - process-classes check + process-classes @@ -584,10 +580,10 @@ aggregate - false aggregate + false @@ -597,10 +593,10 @@ aggregate - false aggregate + false