View Javadoc
1   package org.codehaus.plexus.compiler;
2   
3   /**
4    * The MIT License
5    *
6    * Copyright (c) 2004, The Codehaus
7    *
8    * Permission is hereby granted, free of charge, to any person obtaining a copy of
9    * this software and associated documentation files (the "Software"), to deal in
10   * the Software without restriction, including without limitation the rights to
11   * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
12   * of the Software, and to permit persons to whom the Software is furnished to do
13   * so, subject to the following conditions:
14   *
15   * The above copyright notice and this permission notice shall be included in all
16   * copies or substantial portions of the Software.
17   *
18   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24   * SOFTWARE.
25   */
26  
27  import org.apache.maven.artifact.Artifact;
28  import org.apache.maven.artifact.DefaultArtifact;
29  import org.apache.maven.artifact.handler.DefaultArtifactHandler;
30  import org.apache.maven.artifact.test.ArtifactTestCase;
31  import org.apache.maven.artifact.versioning.VersionRange;
32  
33  import org.codehaus.plexus.util.FileUtils;
34  import org.codehaus.plexus.util.StringUtils;
35  
36  import javax.print.DocFlavor;
37  import java.io.File;
38  import java.util.ArrayList;
39  import java.util.Collection;
40  import java.util.Collections;
41  import java.util.Iterator;
42  import java.util.List;
43  import java.util.TreeSet;
44  
45  /**
46   *
47   */
48  public abstract class AbstractCompilerTest
49      extends ArtifactTestCase
50  {
51      private boolean compilerDebug = false;
52  
53      private boolean compilerDeprecationWarnings = false;
54  
55      private boolean forceJavacCompilerUse = false;
56  
57      protected abstract String getRoleHint();
58  
59      protected void setCompilerDebug( boolean flag )
60      {
61          compilerDebug = flag;
62      }
63  
64      protected void setCompilerDeprecationWarnings( boolean flag )
65      {
66          compilerDeprecationWarnings = flag;
67      }
68  
69      public void setForceJavacCompilerUse( boolean forceJavacCompilerUse )
70      {
71          this.forceJavacCompilerUse = forceJavacCompilerUse;
72      }
73  
74      protected List<String> getClasspath()
75          throws Exception
76      {
77          List<String> cp = new ArrayList<>();
78  
79          File file = getLocalArtifactPath( "commons-lang", "commons-lang", "2.0", "jar" );
80  
81          assertTrue( "test prerequisite: commons-lang library must be available in local repository, expected "
82                          + file.getAbsolutePath(), file.canRead() );
83  
84          cp.add( file.getAbsolutePath() );
85  
86          return cp;
87      }
88  
89      protected void configureCompilerConfig( CompilerConfiguration compilerConfig )
90      {
91  
92      }
93  
94      public void testCompilingSources()
95          throws Exception
96      {
97          List<CompilerMessage> messages = new ArrayList<>();
98          Collection<String> files = new TreeSet<>();
99  
100         for ( CompilerConfiguration compilerConfig : getCompilerConfigurations() )
101         {
102             File outputDir = new File( compilerConfig.getOutputLocation() );
103 
104             Compiler compiler = (Compiler) lookup( Compiler.ROLE, getRoleHint() );
105 
106             messages.addAll( compiler.performCompile( compilerConfig ).getCompilerMessages() );
107 
108             if ( outputDir.isDirectory() )
109             {
110                 files.addAll( normalizePaths( FileUtils.getFileNames( outputDir, null, null, false ) ) );
111             }
112         }
113 
114         int numCompilerErrors = compilerErrorCount( messages );
115 
116         int numCompilerWarnings = messages.size() - numCompilerErrors;
117 
118         if ( expectedErrors() != numCompilerErrors )
119         {
120             System.out.println( numCompilerErrors + " error(s) found:" );
121             for ( CompilerMessage error : messages )
122             {
123                 if ( !error.isError() )
124                 {
125                     continue;
126                 }
127 
128                 System.out.println( "----" );
129                 System.out.println( error.getFile() );
130                 System.out.println( error.getMessage() );
131                 System.out.println( "----" );
132             }
133 
134             assertEquals( "Wrong number of compilation errors: " + messages, expectedErrors(), numCompilerErrors );
135         }
136 
137         if ( expectedWarnings() != numCompilerWarnings )
138         {
139             System.out.println( numCompilerWarnings + " warning(s) found:" );
140             for ( CompilerMessage error : messages )
141             {
142                 if ( error.isError() )
143                 {
144                     continue;
145                 }
146 
147                 System.out.println( "----" );
148                 System.out.println( error.getFile() );
149                 System.out.println( error.getMessage() );
150                 System.out.println( "----" );
151             }
152 
153             assertEquals( "Wrong number of compilation warnings.", expectedWarnings(), numCompilerWarnings );
154         }
155 
156         assertEquals( new TreeSet<>( normalizePaths( expectedOutputFiles() ) ), files );
157     }
158 
159     private List<CompilerConfiguration> getCompilerConfigurations()
160         throws Exception
161     {
162         String sourceDir = getBasedir() + "/src/test-input/src/main";
163 
164         List<String> filenames =
165             FileUtils.getFileNames( new File( sourceDir ), "**/*.java", null, false, true );
166         Collections.sort( filenames );
167 
168         List<CompilerConfiguration> compilerConfigurations = new ArrayList<>();
169 
170         int index = 0;
171         for ( Iterator<String> it = filenames.iterator(); it.hasNext(); index++ )
172         {
173             String filename = it.next();
174 
175             CompilerConfiguration compilerConfig = new CompilerConfiguration();
176 
177             compilerConfig.setDebug( compilerDebug );
178 
179             compilerConfig.setShowDeprecation( compilerDeprecationWarnings );
180 
181             compilerConfig.setClasspathEntries( getClasspath() );
182 
183             compilerConfig.addSourceLocation( sourceDir );
184 
185             compilerConfig.setOutputLocation( getBasedir() + "/target/" + getRoleHint() + "/classes-" + index );
186 
187             FileUtils.deleteDirectory( compilerConfig.getOutputLocation() );
188 
189             compilerConfig.addInclude( filename );
190 
191             compilerConfig.setForceJavacCompilerUse( this.forceJavacCompilerUse );
192 
193             configureCompilerConfig( compilerConfig );
194 
195             String target = getTargetVersion();
196             if( StringUtils.isNotEmpty( target) )
197             {
198                 compilerConfig.setTargetVersion( target );
199             }
200 
201             String source = getSourceVersion();
202             if( StringUtils.isNotEmpty( source) )
203             {
204                 compilerConfig.setSourceVersion( source );
205             }
206 
207             compilerConfigurations.add( compilerConfig );
208 
209         }
210 
211         return compilerConfigurations;
212     }
213 
214     public String getTargetVersion()
215     {
216         return null;
217     }
218 
219     public String getSourceVersion()
220     {
221         return null;
222     }
223 
224 
225     private List<String> normalizePaths( Collection<String> relativePaths )
226     {
227         List<String> normalizedPaths = new ArrayList<String>();
228         for ( String relativePath : relativePaths )
229         {
230             normalizedPaths.add( relativePath.replace( File.separatorChar, '/' ) );
231         }
232         return normalizedPaths;
233     }
234 
235     protected int compilerErrorCount( List<CompilerMessage> messages )
236     {
237         int count = 0;
238 
239         for ( CompilerMessage message : messages )
240         {
241             count += message.isError() ? 1 : 0;
242         }
243 
244         return count;
245     }
246 
247     protected int expectedErrors()
248     {
249         return 1;
250     }
251 
252     protected int expectedWarnings()
253     {
254         return 0;
255     }
256 
257     protected Collection<String> expectedOutputFiles()
258     {
259         return Collections.emptyList();
260     }
261 
262     protected File getLocalArtifactPath( String groupId, String artifactId, String version, String type )
263     {
264         VersionRange versionRange = VersionRange.createFromVersion( version );
265 
266         Artifact artifact = new DefaultArtifact( groupId, artifactId, versionRange, Artifact.SCOPE_COMPILE, type, null,
267                                                  new DefaultArtifactHandler( type ) );
268 
269         return getLocalArtifactPath( artifact );
270     }
271 
272     protected String getJavaVersion()
273     {
274 
275         String javaVersion = System.getProperty( "java.version" );
276         String realJavaVersion = javaVersion;
277 
278         int dotIdx = javaVersion.indexOf( "." );
279         if ( dotIdx > -1 )
280         {
281             int lastDot = dotIdx;
282 
283             // find the next dot, so we can trim up to this point.
284             dotIdx = javaVersion.indexOf( ".", lastDot + 1 );
285             if ( dotIdx > lastDot )
286             {
287                 javaVersion = javaVersion.substring( 0, dotIdx );
288             }
289         }
290 
291         System.out.println( "java.version is: " + realJavaVersion + "\ntrimmed java version is: " + javaVersion
292                                 + "\ncomparison: \"1.5\".compareTo( \"" + javaVersion + "\" ) == " + ( "1.5".compareTo(
293             javaVersion ) ) + "\n" );
294 
295         return javaVersion;
296     }
297 
298 }