View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.artifact;
20  
21  import javax.inject.Inject;
22  import javax.inject.Named;
23  
24  import java.io.File;
25  import java.io.FileOutputStream;
26  import java.io.IOException;
27  import java.io.OutputStreamWriter;
28  import java.io.Writer;
29  import java.nio.charset.StandardCharsets;
30  import java.security.MessageDigest;
31  import java.util.ArrayList;
32  import java.util.Arrays;
33  import java.util.List;
34  
35  import org.apache.maven.api.DependencyScope;
36  import org.apache.maven.artifact.factory.ArtifactFactory;
37  import org.apache.maven.artifact.repository.ArtifactRepository;
38  import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
39  import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
40  import org.apache.maven.bridge.MavenRepositorySystem;
41  import org.apache.maven.execution.DefaultMavenExecutionRequest;
42  import org.apache.maven.execution.DefaultMavenExecutionResult;
43  import org.apache.maven.execution.MavenSession;
44  import org.apache.maven.internal.impl.DefaultLookup;
45  import org.apache.maven.internal.impl.DefaultSessionFactory;
46  import org.apache.maven.plugin.LegacySupport;
47  import org.apache.maven.repository.internal.artifact.FatArtifactTraverser;
48  import org.apache.maven.repository.internal.scopes.Maven4ScopeManagerConfiguration;
49  import org.apache.maven.repository.legacy.repository.ArtifactRepositoryFactory;
50  import org.apache.maven.rtinfo.RuntimeInformation;
51  import org.codehaus.plexus.PlexusContainer;
52  import org.codehaus.plexus.testing.PlexusTest;
53  import org.eclipse.aether.DefaultRepositorySystemSession;
54  import org.eclipse.aether.RepositorySystem;
55  import org.eclipse.aether.RepositorySystemSession;
56  import org.eclipse.aether.collection.DependencyGraphTransformer;
57  import org.eclipse.aether.collection.DependencyManager;
58  import org.eclipse.aether.collection.DependencySelector;
59  import org.eclipse.aether.collection.DependencyTraverser;
60  import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory;
61  import org.eclipse.aether.internal.impl.scope.ManagedDependencyContextRefiner;
62  import org.eclipse.aether.internal.impl.scope.ManagedScopeDeriver;
63  import org.eclipse.aether.internal.impl.scope.ManagedScopeSelector;
64  import org.eclipse.aether.internal.impl.scope.OptionalDependencySelector;
65  import org.eclipse.aether.internal.impl.scope.ScopeDependencySelector;
66  import org.eclipse.aether.internal.impl.scope.ScopeManagerImpl;
67  import org.eclipse.aether.repository.LocalRepository;
68  import org.eclipse.aether.util.graph.manager.ClassicDependencyManager;
69  import org.eclipse.aether.util.graph.selector.AndDependencySelector;
70  import org.eclipse.aether.util.graph.selector.ExclusionDependencySelector;
71  import org.eclipse.aether.util.graph.transformer.ChainedDependencyGraphTransformer;
72  import org.eclipse.aether.util.graph.transformer.ConflictResolver;
73  import org.eclipse.aether.util.graph.transformer.NearestVersionSelector;
74  import org.eclipse.aether.util.graph.transformer.SimpleOptionalitySelector;
75  import org.eclipse.aether.util.repository.SimpleArtifactDescriptorPolicy;
76  import org.junit.jupiter.api.BeforeEach;
77  
78  import static org.codehaus.plexus.testing.PlexusExtension.getBasedir;
79  import static org.junit.jupiter.api.Assertions.assertFalse;
80  import static org.junit.jupiter.api.Assertions.assertTrue;
81  
82  /**
83   */
84  @PlexusTest
85  @Deprecated
86  public abstract class AbstractArtifactComponentTestCase // extends PlexusTestCase
87   {
88      @Inject
89      protected ArtifactFactory artifactFactory;
90  
91      @Inject
92      protected ArtifactRepositoryFactory artifactRepositoryFactory;
93  
94      @Inject
95      LegacySupport legacySupport;
96  
97      @Inject
98      @Named("default")
99      ArtifactRepositoryLayout repoLayout;
100 
101     @Inject
102     PlexusContainer container;
103 
104     public PlexusContainer getContainer() {
105         return container;
106     }
107 
108     @BeforeEach
109     public void setUp() throws Exception {
110         RepositorySystemSession repoSession = initRepoSession();
111         MavenSession session = new MavenSession(
112                 getContainer(), repoSession, new DefaultMavenExecutionRequest(), new DefaultMavenExecutionResult());
113         session.setSession(new DefaultSessionFactory(
114                         getContainer().lookup(RepositorySystem.class),
115                         getContainer().lookup(MavenRepositorySystem.class),
116                         new DefaultLookup(getContainer()),
117                         getContainer().lookup(RuntimeInformation.class))
118                 .newSession(session));
119 
120         legacySupport.setSession(session);
121     }
122 
123     protected abstract String component();
124 
125     /**
126      * Return an existing file, not a directory - causes creation to fail.
127      *
128      * @throws Exception
129      */
130     protected ArtifactRepository badLocalRepository() throws Exception {
131         String path = "target/test-repositories/" + component() + "/bad-local-repository";
132 
133         File f = new File(getBasedir(), path);
134 
135         f.createNewFile();
136 
137         return artifactRepositoryFactory.createArtifactRepository(
138                 "test", "file://" + f.getPath(), repoLayout, null, null);
139     }
140 
141     protected String getRepositoryLayout() {
142         return "default";
143     }
144 
145     protected ArtifactRepository localRepository() throws Exception {
146         String path = "target/test-repositories/" + component() + "/local-repository";
147 
148         File f = new File(getBasedir(), path);
149 
150         return artifactRepositoryFactory.createArtifactRepository(
151                 "local", "file://" + f.getPath(), repoLayout, null, null);
152     }
153 
154     protected ArtifactRepository remoteRepository() throws Exception {
155         String path = "target/test-repositories/" + component() + "/remote-repository";
156 
157         File f = new File(getBasedir(), path);
158 
159         return artifactRepositoryFactory.createArtifactRepository(
160                 "test",
161                 "file://" + f.getPath(),
162                 repoLayout,
163                 new ArtifactRepositoryPolicy(),
164                 new ArtifactRepositoryPolicy());
165     }
166 
167     protected ArtifactRepository badRemoteRepository() throws Exception {
168         return artifactRepositoryFactory.createArtifactRepository(
169                 "test", "http://foo.bar/repository", repoLayout, null, null);
170     }
171 
172     protected void assertRemoteArtifactPresent(Artifact artifact) throws Exception {
173         ArtifactRepository remoteRepo = remoteRepository();
174 
175         String path = remoteRepo.pathOf(artifact);
176 
177         File file = new File(remoteRepo.getBasedir(), path);
178 
179         assertTrue(file.exists(), "Remote artifact " + file + " should be present.");
180     }
181 
182     protected void assertLocalArtifactPresent(Artifact artifact) throws Exception {
183         ArtifactRepository localRepo = localRepository();
184 
185         String path = localRepo.pathOf(artifact);
186 
187         File file = new File(localRepo.getBasedir(), path);
188 
189         assertTrue(file.exists(), "Local artifact " + file + " should be present.");
190     }
191 
192     protected void assertRemoteArtifactNotPresent(Artifact artifact) throws Exception {
193         ArtifactRepository remoteRepo = remoteRepository();
194 
195         String path = remoteRepo.pathOf(artifact);
196 
197         File file = new File(remoteRepo.getBasedir(), path);
198 
199         assertFalse(file.exists(), "Remote artifact " + file + " should not be present.");
200     }
201 
202     protected void assertLocalArtifactNotPresent(Artifact artifact) throws Exception {
203         ArtifactRepository localRepo = localRepository();
204 
205         String path = localRepo.pathOf(artifact);
206 
207         File file = new File(localRepo.getBasedir(), path);
208 
209         assertFalse(file.exists(), "Local artifact " + file + " should not be present.");
210     }
211 
212     // ----------------------------------------------------------------------
213     //
214     // ----------------------------------------------------------------------
215 
216     protected List<ArtifactRepository> remoteRepositories() throws Exception {
217         List<ArtifactRepository> remoteRepositories = new ArrayList<>();
218 
219         remoteRepositories.add(remoteRepository());
220 
221         return remoteRepositories;
222     }
223 
224     // ----------------------------------------------------------------------
225     // Test artifact generation for unit tests
226     // ----------------------------------------------------------------------
227 
228     protected Artifact createLocalArtifact(String artifactId, String version) throws Exception {
229         Artifact artifact = createArtifact(artifactId, version);
230 
231         createArtifact(artifact, localRepository());
232 
233         return artifact;
234     }
235 
236     protected Artifact createRemoteArtifact(String artifactId, String version) throws Exception {
237         Artifact artifact = createArtifact(artifactId, version);
238 
239         createArtifact(artifact, remoteRepository());
240 
241         return artifact;
242     }
243 
244     protected void createLocalArtifact(Artifact artifact) throws Exception {
245         createArtifact(artifact, localRepository());
246     }
247 
248     protected void createRemoteArtifact(Artifact artifact) throws Exception {
249         createArtifact(artifact, remoteRepository());
250     }
251 
252     protected void createArtifact(Artifact artifact, ArtifactRepository repository) throws Exception {
253         String path = repository.pathOf(artifact);
254 
255         File artifactFile = new File(repository.getBasedir(), path);
256 
257         if (!artifactFile.getParentFile().exists()) {
258             artifactFile.getParentFile().mkdirs();
259         }
260         try (Writer writer = new OutputStreamWriter(new FileOutputStream(artifactFile), StandardCharsets.ISO_8859_1)) {
261             writer.write(artifact.getId());
262         }
263 
264         MessageDigest md = MessageDigest.getInstance("MD5");
265         md.update(artifact.getId().getBytes());
266         byte[] digest = md.digest();
267 
268         String md5path = repository.pathOf(artifact) + ".md5";
269         File md5artifactFile = new File(repository.getBasedir(), md5path);
270         try (Writer writer =
271                 new OutputStreamWriter(new FileOutputStream(md5artifactFile), StandardCharsets.ISO_8859_1)) {
272             writer.append(printHexBinary(digest));
273         }
274     }
275 
276     protected Artifact createArtifact(String artifactId, String version) throws Exception {
277         return createArtifact(artifactId, version, "jar");
278     }
279 
280     protected Artifact createArtifact(String artifactId, String version, String type) throws Exception {
281         return createArtifact("org.apache.maven", artifactId, version, type);
282     }
283 
284     protected Artifact createArtifact(String groupId, String artifactId, String version, String type) throws Exception {
285         Artifact a = artifactFactory.createBuildArtifact(groupId, artifactId, version, type);
286 
287         return a;
288     }
289 
290     protected void deleteLocalArtifact(Artifact artifact) throws Exception {
291         deleteArtifact(artifact, localRepository());
292     }
293 
294     protected void deleteArtifact(Artifact artifact, ArtifactRepository repository) throws Exception {
295         String path = repository.pathOf(artifact);
296 
297         File artifactFile = new File(repository.getBasedir(), path);
298 
299         if (artifactFile.exists()) {
300             if (!artifactFile.delete()) {
301                 throw new IOException("Failure while attempting to delete artifact " + artifactFile);
302             }
303         }
304     }
305 
306     protected DefaultRepositorySystemSession initRepoSession() throws Exception {
307         DefaultRepositorySystemSession session = new DefaultRepositorySystemSession(h -> false);
308         session.setScopeManager(new ScopeManagerImpl(Maven4ScopeManagerConfiguration.INSTANCE));
309         session.setArtifactDescriptorPolicy(new SimpleArtifactDescriptorPolicy(true, true));
310         DependencyTraverser depTraverser = new FatArtifactTraverser();
311         session.setDependencyTraverser(depTraverser);
312 
313         DependencyManager depManager = new ClassicDependencyManager(true, session.getScopeManager());
314         session.setDependencyManager(depManager);
315 
316         DependencySelector depFilter = new AndDependencySelector(
317                 ScopeDependencySelector.legacy(
318                         null, Arrays.asList(DependencyScope.TEST.id(), DependencyScope.PROVIDED.id())),
319                 OptionalDependencySelector.fromDirect(),
320                 new ExclusionDependencySelector());
321         session.setDependencySelector(depFilter);
322 
323         ScopeManagerImpl scopeManager = new ScopeManagerImpl(Maven4ScopeManagerConfiguration.INSTANCE);
324         session.setScopeManager(scopeManager);
325         DependencyGraphTransformer transformer = new ConflictResolver(
326                 new NearestVersionSelector(), new ManagedScopeSelector(scopeManager),
327                 new SimpleOptionalitySelector(), new ManagedScopeDeriver(scopeManager));
328         transformer =
329                 new ChainedDependencyGraphTransformer(transformer, new ManagedDependencyContextRefiner(scopeManager));
330         session.setDependencyGraphTransformer(transformer);
331 
332         LocalRepository localRepo = new LocalRepository(localRepository().getBasedir());
333         session.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory().newInstance(session, localRepo));
334         return session;
335     }
336 
337     private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
338 
339     private static String printHexBinary(byte[] data) {
340         StringBuilder r = new StringBuilder(data.length * 2);
341         for (byte b : data) {
342             r.append(hexCode[(b >> 4) & 0xF]);
343             r.append(hexCode[(b & 0xF)]);
344         }
345         return r.toString();
346     }
347 }