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.Proxy;
10  import java.nio.file.Files;
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      */
133     public static ArtifactFactory newArtifactFactory() {
134         final InvocationHandler handler = (pProxy, pMethod, pArgs) -> {
135             System.out.println("Invoking method " + pMethod);
136             throw new IllegalStateException("Not implemented");
137         };
138         return (ArtifactFactory) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
139                 new Class[] { ArtifactFactory.class }, handler);
140     }
141 
142     /**
143      * Creates an instance of {@link ArtifactRepository}.
144      *
145      * @param container current plexus container.
146      * @return A configured instance of {@link MavenArtifactRepository}.
147      * @throws Exception Creating the object failed.
148      */
149     public static ArtifactRepository newArtifactRepository(PlexusContainer container) throws Exception {
150         File m2Dir = new File(System.getProperty("user.home"), ".m2");
151         File settingsFile = new File(m2Dir, "settings.xml");
152         String localRepo = null;
153         if (settingsFile.exists()) {
154             Settings settings = new SettingsXpp3Reader().read(new FileReader(settingsFile));
155             localRepo = settings.getLocalRepository();
156         }
157         if (localRepo == null) {
158             localRepo = System.getProperty("user.home") + "/.m2/repository";
159         }
160         ArtifactRepositoryLayout repositoryLayout = (ArtifactRepositoryLayout) container
161                 .lookup(ArtifactRepositoryLayout.ROLE, "default");
162         return new MavenArtifactRepository("local", "file://" + localRepo, repositoryLayout,
163                 new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy());
164     }
165 
166     public static File makeSourceDirectory(String mvnBaseDir, File pFile, String pDir, boolean pCreateCopy)
167             throws IOException {
168         if (!pCreateCopy) {
169             return pFile;
170         }
171 
172         final File targetDir = new File(new File(new File(mvnBaseDir), "target/it-source"), pDir);
173         remove(targetDir);
174         copy(pFile, targetDir);
175         return targetDir;
176     }
177 
178     public static File getSourceDirectory(String mvnBaseDir, String pDir, boolean pCreateCopy, final File baseDir)
179             throws IOException {
180         return makeSourceDirectory(mvnBaseDir, new File(new File(baseDir, "src/test/resources/unit"), pDir), pDir,
181                 pCreateCopy);
182     }
183 
184     /**
185      * Reads the created report file and verifies, whether the detected numbers are
186      * matching.
187      *
188      * @param pRatTxtFile The file to read.
189      * @param in An array of regex expressions that must be in the file.
190      * @param notIn An array of regex expressions that must NOT be in the file.
191      * @throws IOException An error occurred while reading the file or the file does
192      * not exist at all.
193      * @throws IllegalArgumentException In case of mismatches in file numbers passed
194      * in as parameter.
195      */
196     public static void ensureRatReportIsCorrect(File pRatTxtFile, String[] in, String[] notIn) throws IOException {
197         List<String> lines = IOUtils.readLines(Files.newInputStream(pRatTxtFile.toPath()), Charsets.UTF_8);
198         String document = String.join("\n", lines);
199         for (String pattern : in) {
200             TextUtils.assertPatternInTarget(pattern, document);
201         }
202 
203         for (String pattern : notIn) {
204             TextUtils.assertPatternNotInTarget(pattern, document);
205         }
206     }
207 
208 }