View Javadoc
1   package org.apache.rat.mp;
2   
3   import java.io.File;
4   import java.io.FileInputStream;
5   import java.io.FileOutputStream;
6   import java.io.FileReader;
7   import java.io.IOException;
8   import java.lang.reflect.InvocationHandler;
9   import java.lang.reflect.Method;
10  import java.lang.reflect.Proxy;
11  import java.util.List;
12  
13  import org.apache.commons.io.FileUtils;
14  
15  /*
16   * Licensed to the Apache Software Foundation (ASF) under one or more
17   * contributor license agreements.  See the NOTICE file distributed with
18   * this work for additional information regarding copyright ownership.
19   * The ASF licenses this file to You under the Apache License, Version 2.0
20   * (the "License"); you may not use this file except in compliance with
21   * the License.  You may obtain a copy of the License at
22   *
23   *      http://www.apache.org/licenses/LICENSE-2.0
24   *
25   * Unless required by applicable law or agreed to in writing, software
26   * distributed under the License is distributed on an "AS IS" BASIS,
27   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28   * See the License for the specific language governing permissions and
29   * limitations under the License.
30   */
31  
32  import org.apache.commons.io.IOUtils;
33  import org.apache.maven.artifact.factory.ArtifactFactory;
34  import org.apache.maven.artifact.factory.DefaultArtifactFactory;
35  import org.apache.maven.artifact.repository.ArtifactRepository;
36  import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy;
37  import org.apache.maven.artifact.repository.MavenArtifactRepository;
38  import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
39  import org.apache.maven.doxia.siterenderer.Renderer;
40  import org.apache.maven.settings.Settings;
41  import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader;
42  import org.apache.rat.testhelpers.TextUtils;
43  import org.codehaus.plexus.PlexusContainer;
44  import org.codehaus.plexus.util.DirectoryScanner;
45  
46  import com.google.common.base.Charsets;
47  
48  /**
49   * Test helpers used when verifying mojo interaction in RAT integration tests.
50   */
51  public final class RatTestHelpers {
52  
53      /**
54       * @param pDir Removes the given directory recursively.
55       * @throws IOException in case of errors.
56       */
57      public static void remove(File pDir) throws IOException {
58          if (pDir.isFile()) {
59              if (!pDir.delete()) {
60                  throw new IOException("Unable to delete file: " + pDir);
61              }
62          } else if (pDir.isDirectory()) {
63          	FileUtils.deleteDirectory(pDir);
64          } else if (pDir.exists()) {
65              throw new IOException("Unable to delete unknown object " + pDir);
66          }
67      }
68  
69      /**
70       * Copies the given files recursively in order to get all integration test files
71       * into a target directory.
72       *
73       * @param pSource source files.
74       * @param pTarget target directory
75       * @throws IOException in case of errors.
76       */
77      public static void copy(File pSource, File pTarget) throws IOException {
78          if (pSource.isDirectory()) {
79              if (!pTarget.isDirectory() && !pTarget.mkdirs()) {
80                  throw new IOException("Unable to create directory: " + pTarget);
81              }
82              final DirectoryScanner scanner = new DirectoryScanner();
83              scanner.setBasedir(pSource);
84              scanner.addDefaultExcludes();
85              scanner.setIncludes(new String[] { "*" });
86              scanner.scan();
87              final String[] dirs = scanner.getIncludedDirectories();
88  
89              for (final String dir : dirs) {
90                  if (!"".equals(dir)) {
91                      copy(new File(pSource, dir), new File(pTarget, dir));
92                  }
93              }
94              final String[] files = scanner.getIncludedFiles();
95              for (String file : files) {
96                  copy(new File(pSource, file), new File(pTarget, file));
97              }
98          } else if (pSource.isFile()) {
99              try (final FileInputStream fis = new FileInputStream(pSource);
100                     final FileOutputStream fos = new FileOutputStream(pTarget);) {
101                 final byte[] buffer = new byte[8192];
102                 for (;;) {
103                     int res = fis.read(buffer);
104                     if (res == -1) {
105                         break;
106                     }
107                     if (res > 0) {
108                         fos.write(buffer, 0, res);
109                     }
110                 }
111             }
112         } else {
113             throw new IOException("Unable to copy unknown object " + pSource);
114         }
115     }
116 
117     /**
118      * Creates a new instance of {@link Renderer}.
119      *
120      * @param container current plexus container.
121      * @return A configured instance of a Default renderer.
122      * @throws Exception Creating the object failed.
123      */
124     public static Renderer newSiteRenderer(PlexusContainer container) throws Exception {
125         return (Renderer) container.lookup(Renderer.ROLE, "default");
126     }
127 
128     /**
129      * Creates a new instance of {@link ArtifactFactory}.
130      *
131      * @return A configured instance of {@link DefaultArtifactFactory}.
132      * @throws Exception Creating the object failed.
133      */
134     public static ArtifactFactory newArtifactFactory() throws Exception {
135         final InvocationHandler handler = new InvocationHandler() {
136             @Override
137             public Object invoke(Object pProxy, Method pMethod, Object[] pArgs) throws Throwable {
138                 System.out.println("Invoking method " + pMethod);
139                 throw new IllegalStateException("Not implemented");
140             }
141         };
142         return (ArtifactFactory) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
143                 new Class[] { ArtifactFactory.class }, handler);
144     }
145 
146     /**
147      * Creates an instance of {@link ArtifactRepository}.
148      *
149      * @param container current plexus container.
150      * @return A configured instance of {@link MavenArtifactRepository}.
151      * @throws Exception Creating the object failed.
152      */
153     public static ArtifactRepository newArtifactRepository(PlexusContainer container) throws Exception {
154         File m2Dir = new File(System.getProperty("user.home"), ".m2");
155         File settingsFile = new File(m2Dir, "settings.xml");
156         String localRepo = null;
157         if (settingsFile.exists()) {
158             Settings settings = new SettingsXpp3Reader().read(new FileReader(settingsFile));
159             localRepo = settings.getLocalRepository();
160         }
161         if (localRepo == null) {
162             localRepo = System.getProperty("user.home") + "/.m2/repository";
163         }
164         ArtifactRepositoryLayout repositoryLayout = (ArtifactRepositoryLayout) container
165                 .lookup(ArtifactRepositoryLayout.ROLE, "default");
166         return new MavenArtifactRepository("local", "file://" + localRepo, repositoryLayout,
167                 new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy());
168     }
169 
170     public static File makeSourceDirectory(String mvnBaseDir, File pFile, String pDir, boolean pCreateCopy)
171             throws IOException {
172         if (!pCreateCopy) {
173             return pFile;
174         }
175 
176         final File targetDir = new File(new File(new File(mvnBaseDir), "target/it-source"), pDir);
177         remove(targetDir);
178         copy(pFile, targetDir);
179         return targetDir;
180     }
181 
182     public static File getSourceDirectory(String mvnBaseDir, String pDir, boolean pCreateCopy, final File baseDir)
183             throws IOException {
184         return makeSourceDirectory(mvnBaseDir, new File(new File(baseDir, "src/test/resources/unit"), pDir), pDir,
185                 pCreateCopy);
186     }
187 
188     /**
189      * Reads the created report file and verifies, whether the detected numbers are
190      * matching.
191      *
192      * @param pRatTxtFile The file to read.
193      * @param in An array of regex expressions that must be in the file.
194      * @param notIn An array of regex expressions that must NOT be in the file.
195      * @throws IOException An error occurred while reading the file or the file does
196      * not exist at all.
197      * @throws IllegalArgumentException In case of mismatches in file numbers passed
198      * in as parameter.
199      */
200     public static void ensureRatReportIsCorrect(File pRatTxtFile, String[] in, String[] notIn) throws IOException {
201         List<String> lines = IOUtils.readLines(new FileInputStream(pRatTxtFile), Charsets.UTF_8);
202         String document = String.join("\n", lines);
203         for (String pattern : in) {
204             TextUtils.assertPatternInOutput(pattern, document);
205         }
206 
207         for (String pattern : notIn) {
208             TextUtils.assertPatternInOutput(pattern, document);
209         }
210     }
211 }