View Javadoc
1   package org.apache.rat.mp;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one or more
5    * contributor license agreements.  See the NOTICE file distributed with
6    * this work for additional information regarding copyright ownership.
7    * The ASF licenses this file to You under the Apache License, Version 2.0
8    * (the "License"); you may not use this file except in compliance with
9    * the License.  You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  import org.apache.commons.io.IOUtils;
21  import org.apache.maven.artifact.factory.ArtifactFactory;
22  import org.apache.maven.artifact.factory.DefaultArtifactFactory;
23  import org.apache.maven.artifact.repository.ArtifactRepository;
24  import org.apache.maven.artifact.repository.DefaultArtifactRepository;
25  import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
26  import org.apache.maven.artifact.resolver.ArtifactResolver;
27  import org.apache.maven.artifact.resolver.DefaultArtifactResolver;
28  import org.apache.maven.doxia.siterenderer.Renderer;
29  import org.apache.maven.settings.Settings;
30  import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader;
31  import org.codehaus.plexus.PlexusContainer;
32  import org.codehaus.plexus.util.DirectoryScanner;
33  
34  import java.io.BufferedReader;
35  import java.io.File;
36  import java.io.FileInputStream;
37  import java.io.FileNotFoundException;
38  import java.io.FileOutputStream;
39  import java.io.FileReader;
40  import java.io.IOException;
41  import java.lang.reflect.InvocationHandler;
42  import java.lang.reflect.Method;
43  import java.lang.reflect.Proxy;
44  
45  /**
46   * Test helpers used when verifying mojo interaction in RAT integration tests.
47   */
48  public final class RatTestHelpers {
49  
50      /**
51       * @param pDir Removes the given directory recursively.
52       * @throws IOException in case of errors.
53       */
54      public static void remove(File pDir) throws IOException {
55          if (pDir.isFile()) {
56              if (!pDir.delete()) {
57                  throw new IOException("Unable to delete file: " + pDir);
58              }
59          } else if (pDir.isDirectory()) {
60              final File[] files = pDir.listFiles();
61              if (files != null) {
62                  for (File file : files) {
63                      remove(file);
64                  }
65              }
66              if (!pDir.delete()) {
67                  throw new IOException("Unable to delete directory: " + pDir);
68              }
69          } else if (pDir.exists()) {
70              throw new IOException("Unable to delete unknown object " + pDir);
71          }
72      }
73  
74      /**
75       * Copies the given files recursively in order to get all integration test
76       * files into a target directory.
77       *
78       * @param pSource source files.
79       * @param pTarget target directory
80       * @throws IOException in case of errors.
81       */
82      public static void copy(File pSource, File pTarget) throws IOException {
83          if (pSource.isDirectory()) {
84              if (!pTarget.isDirectory() && !pTarget.mkdirs()) {
85                  throw new IOException("Unable to create directory: " + pTarget);
86              }
87              final DirectoryScanner scanner = new DirectoryScanner();
88              scanner.setBasedir(pSource);
89              scanner.addDefaultExcludes();
90              scanner.setIncludes(new String[]{"*"});
91              scanner.scan();
92              final String[] dirs = scanner.getIncludedDirectories();
93  
94              for (final String dir : dirs) {
95                  if (!"".equals(dir)) {
96                      copy(new File(pSource, dir), new File(pTarget, dir));
97                  }
98              }
99              final String[] files = scanner.getIncludedFiles();
100             for (String file : files) {
101                 copy(new File(pSource, file), new File(pTarget, file));
102             }
103         } else if (pSource.isFile()) {
104             final FileInputStream fis = new FileInputStream(pSource);
105             final FileOutputStream fos = new FileOutputStream(pTarget);
106             final byte[] buffer = new byte[8192];
107             for (; ; ) {
108                 int res = fis.read(buffer);
109                 if (res == -1) {
110                     break;
111                 }
112                 if (res > 0) {
113                     fos.write(buffer, 0, res);
114                 }
115             }
116             fos.close();
117             fis.close();
118         } else {
119             throw new IOException("Unable to copy unknown object " + pSource);
120         }
121     }
122 
123     /**
124      * Creates a new instance of {@link Renderer}.
125      *
126      * @param container current plexus container.
127      * @return A configured instance of a Default renderer.
128      * @throws Exception Creating the object failed.
129      */
130     public static Renderer newSiteRenderer(PlexusContainer container)
131             throws Exception {
132         return (Renderer) container.lookup(Renderer.ROLE, "default");
133     }
134 
135     /**
136      * Creates a new instance of {@link ArtifactFactory}.
137      *
138      * @return A configured instance of {@link DefaultArtifactFactory}.
139      * @throws Exception Creating the object failed.
140      */
141     public static ArtifactFactory newArtifactFactory() throws Exception {
142         final InvocationHandler handler = new InvocationHandler() {
143             public Object invoke(Object pProxy, Method pMethod, Object[] pArgs)
144                     throws Throwable {
145                 System.out.println("Invoking method " + pMethod);
146                 throw new IllegalStateException("Not implemented");
147             }
148         };
149         return (ArtifactFactory) Proxy.newProxyInstance(Thread.currentThread()
150                         .getContextClassLoader(),
151                 new Class[]{ArtifactFactory.class}, handler);
152     }
153 
154     /**
155      * Creates a new instance of {@link ArtifactResolver}.
156      *
157      * @return A configured instance of {@link DefaultArtifactResolver}.
158      * @throws Exception Creating the object failed.
159      */
160     public static ArtifactResolver newArtifactResolver() throws Exception {
161         final InvocationHandler handler = new InvocationHandler() {
162             public Object invoke(Object pProxy, Method pMethod, Object[] pArgs)
163                     throws Throwable {
164                 System.out.println("Invoking method " + pMethod);
165                 throw new IllegalStateException("Not implemented");
166             }
167         };
168         return (ArtifactResolver) Proxy.newProxyInstance(Thread.currentThread()
169                         .getContextClassLoader(),
170                 new Class[]{ArtifactResolver.class}, handler);
171     }
172 
173     /**
174      * Creates an instance of {@link ArtifactRepository}.
175      *
176      * @param container current plexus container.
177      * @return A configured instance of {@link DefaultArtifactRepository}.
178      * @throws Exception Creating the object failed.
179      */
180     public static ArtifactRepository newArtifactRepository(
181             PlexusContainer container) throws Exception {
182         File m2Dir = new File(System.getProperty("user.home"), ".m2");
183         File settingsFile = new File(m2Dir, "settings.xml");
184         String localRepo = null;
185         if (settingsFile.exists()) {
186             Settings settings = new SettingsXpp3Reader().read(new FileReader(
187                     settingsFile));
188             localRepo = settings.getLocalRepository();
189         }
190         if (localRepo == null) {
191             localRepo = System.getProperty("user.home") + "/.m2/repository";
192         }
193         ArtifactRepositoryLayout repositoryLayout = (ArtifactRepositoryLayout) container
194                 .lookup(ArtifactRepositoryLayout.ROLE, "default");
195         return new DefaultArtifactRepository("local", "file://" + localRepo,
196                 repositoryLayout);
197     }
198 
199     public static File makeSourceDirectory(String mvnBaseDir, File pFile,
200                                            String pDir, boolean pCreateCopy) throws IOException {
201         if (!pCreateCopy) {
202             return pFile;
203         }
204 
205         final File targetDir = new File(new File(new File(mvnBaseDir),
206                 "target/it-source"), pDir);
207         remove(targetDir);
208         copy(pFile, targetDir);
209         return targetDir;
210     }
211 
212     public static File getSourceDirectory(String mvnBaseDir, String pDir,
213                                           boolean pCreateCopy, final File baseDir) throws IOException {
214         return makeSourceDirectory(mvnBaseDir, new File(new File(baseDir,
215                 "src/test/resources/unit"), pDir), pDir, pCreateCopy);
216     }
217 
218     /**
219      * Reads the created report file and verifies, whether the detected numbers
220      * are matching.
221      *
222      * @param pRatTxtFile        The file to read.
223      * @param pNumALFiles        The number of files with AL.
224      * @param pNumNoLicenseFiles The number of files without license.
225      * @throws IOException              An error occurred while reading the file or the file does not
226      *                                  exist at all.
227      * @throws IllegalArgumentException In case of mismatches in file numbers passed in as parameter.
228      */
229     public static void ensureRatReportIsCorrect(File pRatTxtFile,
230                                                 int pNumALFiles, int pNumNoLicenseFiles) throws IOException {
231         if (!pRatTxtFile.exists()) {
232             throw new FileNotFoundException("Could not find " + pRatTxtFile);
233         }
234         BufferedReader reader = null;
235         try {
236 
237             reader = new BufferedReader(new FileReader(pRatTxtFile));
238             Integer numALFiles = null;
239             Integer numNoLicenseFiles = null;
240             for (; ; ) {
241                 String line = reader.readLine();
242                 if (line == null) {
243                     break;
244                 }
245                 int offset = line.indexOf("Apache Licensed: ");
246                 if (offset >= 0) {
247                     numALFiles = new Integer(line.substring(
248                             offset + "Apache Licensed: ".length()).trim());
249                 }
250                 offset = line.indexOf("Unknown Licenses");
251                 if (offset >= 0) {
252                     numNoLicenseFiles = new Integer(line.substring(0, offset)
253                             .trim());
254                 }
255             }
256             reader.close();
257 
258             if (!new Integer(pNumALFiles).equals(numALFiles)) {
259                 throw new IllegalArgumentException(
260                         "Amount of licensed files does not match. Expected "
261                                 + pNumALFiles + ", got " + numALFiles);
262             }
263 
264             if (!new Integer(pNumNoLicenseFiles).equals(numNoLicenseFiles)) {
265                 throw new IllegalArgumentException(
266                         "Amount of licensed files does not match. Expected "
267                                 + pNumALFiles + ", got " + numALFiles);
268             }
269         } finally {
270             IOUtils.closeQuietly(reader);
271         }
272 
273     }
274 
275 }