View Javadoc
1   package org.apache.maven.plugin.checkstyle.exec;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.ByteArrayInputStream;
23  import java.io.Closeable;
24  import java.io.File;
25  import java.io.FileInputStream;
26  import java.io.IOException;
27  import java.net.MalformedURLException;
28  import java.net.URL;
29  import java.net.URLClassLoader;
30  import java.security.AccessController;
31  import java.security.PrivilegedAction;
32  import java.util.ArrayList;
33  import java.util.Collection;
34  import java.util.HashMap;
35  import java.util.LinkedHashSet;
36  import java.util.List;
37  import java.util.Map;
38  import java.util.Properties;
39  import java.util.Set;
40  
41  import org.apache.commons.io.IOUtils;
42  import org.apache.maven.artifact.Artifact;
43  import org.apache.maven.artifact.DependencyResolutionRequiredException;
44  import org.apache.maven.model.Resource;
45  import org.apache.maven.project.MavenProject;
46  import org.codehaus.plexus.component.annotations.Component;
47  import org.codehaus.plexus.component.annotations.Requirement;
48  import org.codehaus.plexus.logging.AbstractLogEnabled;
49  import org.codehaus.plexus.resource.ResourceManager;
50  import org.codehaus.plexus.resource.loader.FileResourceCreationException;
51  import org.codehaus.plexus.resource.loader.FileResourceLoader;
52  import org.codehaus.plexus.resource.loader.ResourceNotFoundException;
53  import org.codehaus.plexus.util.FileUtils;
54  import org.codehaus.plexus.util.StringUtils;
55  
56  import com.puppycrawl.tools.checkstyle.Checker;
57  import com.puppycrawl.tools.checkstyle.ConfigurationLoader;
58  import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
59  import com.puppycrawl.tools.checkstyle.PackageNamesLoader;
60  import com.puppycrawl.tools.checkstyle.PropertiesExpander;
61  import com.puppycrawl.tools.checkstyle.api.AuditListener;
62  import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
63  import com.puppycrawl.tools.checkstyle.api.Configuration;
64  import com.puppycrawl.tools.checkstyle.api.FilterSet;
65  import com.puppycrawl.tools.checkstyle.filters.SuppressionsLoader;
66  
67  /**
68   * @author Olivier Lamy
69   * @since 2.5
70   * @version $Id: DefaultCheckstyleExecutor.html 937799 2015-01-27 00:57:50Z hboutemy $
71   */
72  @Component( role = CheckstyleExecutor.class, hint = "default", instantiationStrategy = "per-lookup" )
73  public class DefaultCheckstyleExecutor
74      extends AbstractLogEnabled
75      implements CheckstyleExecutor
76  {
77      @Requirement( hint = "default" )
78      private ResourceManager locator;
79      
80      @Requirement( hint = "license" )
81      private ResourceManager licenseLocator;
82  
83      public CheckstyleResults executeCheckstyle( CheckstyleExecutorRequest request )
84          throws CheckstyleExecutorException, CheckstyleException
85      {
86          // Checkstyle will always use the context classloader in order
87          // to load resources (dtds),
88          // so we have to fix it
89          // olamy this hack is not anymore needed in Maven 3.x
90          ClassLoader checkstyleClassLoader = PackageNamesLoader.class.getClassLoader();
91          Thread.currentThread().setContextClassLoader( checkstyleClassLoader );
92  
93          if ( getLogger().isDebugEnabled() )
94          {
95              getLogger().debug( "executeCheckstyle start headerLocation : " + request.getHeaderLocation() );
96          }
97  
98          MavenProject project = request.getProject();
99  
100         configureResourceLocator( locator, request, null );
101         
102         configureResourceLocator( licenseLocator, request, request.getLicenseArtifacts() );
103 
104         // Config is less critical than License, locator can still be used.
105         // configureResourceLocator( configurationLocator, request, request.getConfigurationArtifacts() );
106 
107         List<File> files;
108         try
109         {
110             files = getFilesToProcess( request );
111         }
112         catch ( IOException e )
113         {
114             throw new CheckstyleExecutorException( "Error getting files to process", e );
115         }
116 
117         final String suppressionsFilePath = getSuppressionsFilePath( request );
118         FilterSet filterSet = getSuppressionsFilterSet( suppressionsFilePath );
119 
120         Checker checker = new Checker();
121 
122         // setup classloader, needed to avoid "Unable to get class information for ..." errors
123         List<String> classPathStrings = new ArrayList<String>();
124         List<String> outputDirectories = new ArrayList<String>();
125         
126         // stand-alone
127         Collection<File> sourceDirectories = null;
128         Collection<File> testSourceDirectories = request.getTestSourceDirectories();
129         
130         // aggregator
131         Map<MavenProject, Collection<File>> sourceDirectoriesByProject = new HashMap<MavenProject, Collection<File>>();
132         Map<MavenProject, Collection<File>> testSourceDirectoriesByProject =
133             new HashMap<MavenProject, Collection<File>>();
134         
135         if ( request.isAggregate() )
136         {
137             for ( MavenProject childProject : request.getReactorProjects() )
138             {
139                 sourceDirectories = new ArrayList<File>( childProject.getCompileSourceRoots().size() );
140                 List<String> compileSourceRoots = childProject.getCompileSourceRoots();
141                 for ( String compileSourceRoot : compileSourceRoots )
142                 {
143                     sourceDirectories.add( new File( compileSourceRoot ) );
144                 }
145                 sourceDirectoriesByProject.put( childProject, sourceDirectories );
146                 
147                 testSourceDirectories = new ArrayList<File>( childProject.getTestCompileSourceRoots().size() );
148                 List<String> testCompileSourceRoots = childProject.getTestCompileSourceRoots();
149                 for ( String testCompileSourceRoot : testCompileSourceRoots )
150                 {
151                     testSourceDirectories.add( new File( testCompileSourceRoot ) );
152                 }
153                 testSourceDirectoriesByProject.put( childProject, testSourceDirectories );
154                 
155                 prepareCheckstylePaths( request, childProject, classPathStrings, outputDirectories,
156                                         sourceDirectories, testSourceDirectories );
157             }
158         }
159         else
160         {
161             sourceDirectories = request.getSourceDirectories();
162             prepareCheckstylePaths( request, project, classPathStrings, outputDirectories, sourceDirectories,
163                                     testSourceDirectories );
164         }
165 
166         final List<URL> urls = new ArrayList<URL>( classPathStrings.size() );
167 
168         for ( String path : classPathStrings )
169         {
170             try
171             {
172                 urls.add( new File( path ).toURL() );
173             }
174             catch ( MalformedURLException e )
175             {
176                 throw new CheckstyleExecutorException( e.getMessage(), e );
177             }
178         }
179 
180         for ( String outputDirectoryString : outputDirectories )
181         {
182             try
183             {
184                 if ( outputDirectoryString != null )
185                 {
186                     File outputDirectoryFile = new File( outputDirectoryString );
187                     if ( outputDirectoryFile.exists() )
188                     {
189                         URL outputDirectoryUrl = outputDirectoryFile.toURL();
190                         getLogger().debug( "Adding the outputDirectory " + outputDirectoryUrl.toString()
191                                                + " to the Checkstyle class path" );
192                         urls.add( outputDirectoryUrl );
193                     }
194                 }
195             }
196             catch ( MalformedURLException e )
197             {
198                 throw new CheckstyleExecutorException( e.getMessage(), e );
199             }
200         }
201 
202         URLClassLoader projectClassLoader = AccessController.doPrivileged( new PrivilegedAction<URLClassLoader>()
203         {
204             public URLClassLoader run()
205             {
206                 return new URLClassLoader( urls.toArray( new URL[urls.size()] ), null );
207             }
208         } );
209 
210         checker.setClassloader( projectClassLoader );
211 
212         checker.setModuleClassLoader( Thread.currentThread().getContextClassLoader() );
213 
214         if ( filterSet != null )
215         {
216             checker.addFilter( filterSet );
217         }
218         Configuration configuration = getConfiguration( request );
219         checker.configure( configuration );
220 
221         AuditListener listener = request.getListener();
222 
223         if ( listener != null )
224         {
225             checker.addListener( listener );
226         }
227 
228         if ( request.isConsoleOutput() )
229         {
230             checker.addListener( request.getConsoleListener() );
231         }
232 
233         CheckstyleCheckerListener checkerListener = new CheckstyleCheckerListener( configuration );
234         if ( request.isAggregate() )
235         {
236             for ( MavenProject childProject : request.getReactorProjects() )
237             {
238                 sourceDirectories = sourceDirectoriesByProject.get( childProject );
239                 testSourceDirectories = testSourceDirectoriesByProject.get( childProject );
240                 addSourceDirectory( checkerListener, sourceDirectories,
241                                     testSourceDirectories,
242                                     childProject.getResources(), request );
243             }
244         }
245         else
246         {
247             addSourceDirectory( checkerListener, sourceDirectories, testSourceDirectories, request.getResources(),
248                                 request );
249         }
250 
251         checker.addListener( checkerListener );
252 
253         int nbErrors = checker.process( files );
254 
255         checker.destroy();
256 
257         if ( projectClassLoader instanceof Closeable )
258         {
259             try
260             {
261                 ( ( Closeable ) projectClassLoader ).close();
262             }
263             catch ( IOException ex ) 
264             {
265                 // Nothing we can do - and not detrimental to the build (save running out of file handles).
266                 getLogger().info( "Failed to close custom Classloader - this indicated a bug in the code.", ex );
267             }
268         }
269 
270         if ( request.getStringOutputStream() != null )
271         {
272             String message = request.getStringOutputStream().toString().trim();
273 
274             if ( message.length() > 0 )
275             {
276                 getLogger().info( message );
277             }
278         }
279 
280         if ( nbErrors > 0 )
281         {
282             String message = "There are " + nbErrors + " checkstyle errors.";
283 
284             if ( request.isFailsOnError() )
285             {
286                 // TODO: should be a failure, not an error. Report is not meant to
287                 // throw an exception here (so site would
288                 // work regardless of config), but should record this information
289                 throw new CheckstyleExecutorException( message );
290             }
291             else
292             {
293                 getLogger().info( message );
294             }
295         }
296 
297         return checkerListener.getResults();
298     }
299 
300     protected void addSourceDirectory( CheckstyleCheckerListener sinkListener, Collection<File> sourceDirectories,
301                                        Collection<File> testSourceDirectories, List<Resource> resources,
302                                        CheckstyleExecutorRequest request )
303     {
304         if ( sourceDirectories != null )
305         {
306             for ( File sourceDirectory : sourceDirectories )
307             {
308                 if ( sourceDirectory.exists() )
309                 {
310                     sinkListener.addSourceDirectory( sourceDirectory );
311                 }
312             }
313         }
314 
315         if ( request.isIncludeTestSourceDirectory() && ( testSourceDirectories != null ) )
316         {
317             for ( File testSourceDirectory : testSourceDirectories )
318             {
319                 if ( testSourceDirectory.isDirectory() )
320                 {
321                     sinkListener.addSourceDirectory( testSourceDirectory );
322                 }
323             }
324         }
325 
326         if ( resources != null )
327         {
328             for ( Resource resource : resources )
329             {
330                 if ( resource.getDirectory() != null )
331                 {
332                     File resourcesDirectory = new File( resource.getDirectory() );
333                     if ( resourcesDirectory.exists() && resourcesDirectory.isDirectory() )
334                     {
335                         sinkListener.addSourceDirectory( resourcesDirectory );
336                         getLogger().debug( "Added '" + resourcesDirectory.getAbsolutePath()
337                                 + "' as a source directory." );
338                     }
339                 }
340             }
341         }
342     }
343 
344     public Configuration getConfiguration( CheckstyleExecutorRequest request )
345         throws CheckstyleExecutorException
346     {
347         try
348         {
349             // Checkstyle will always use the context classloader in order
350             // to load resources (dtds),
351             // so we have to fix it
352             ClassLoader checkstyleClassLoader = PackageNamesLoader.class.getClassLoader();
353             Thread.currentThread().setContextClassLoader( checkstyleClassLoader );
354             String configFile = getConfigFile( request );
355             Properties overridingProperties = getOverridingProperties( request );
356             Configuration config = ConfigurationLoader
357                 .loadConfiguration( configFile, new PropertiesExpander( overridingProperties ) );
358             String effectiveEncoding = StringUtils.isNotEmpty( request.getEncoding() ) ? request.getEncoding() : System
359                 .getProperty( "file.encoding", "UTF-8" );
360             
361             if ( StringUtils.isEmpty( request.getEncoding() ) )
362             {
363                 getLogger().warn( "File encoding has not been set, using platform encoding " + effectiveEncoding
364                                       + ", i.e. build is platform dependent!" );
365             }
366 
367             if ( "Checker".equals( config.getName() )
368                     || "com.puppycrawl.tools.checkstyle.Checker".equals( config.getName() ) )
369             {
370                 if ( config instanceof DefaultConfiguration )
371                 {
372                     // MCHECKSTYLE-173 Only add the "charset" attribute if it has not been set
373                     try
374                     {
375                         if ( config.getAttribute( "charset" ) == null )
376                         {
377                             ( (DefaultConfiguration) config ).addAttribute( "charset", effectiveEncoding );
378                         }
379                     }
380                     catch ( CheckstyleException ex )
381                     {
382                         // Checkstyle 5.4+ throws an exception when trying to access an attribute that doesn't exist
383                         ( (DefaultConfiguration) config ).addAttribute( "charset", effectiveEncoding );
384                     }
385                 }
386                 else
387                 {
388                     getLogger().warn( "Failed to configure file encoding on module " + config );
389                 }
390             }
391             Configuration[] modules = config.getChildren();
392             for ( Configuration module : modules )
393             {
394                 if ( "TreeWalker".equals( module.getName() )
395                     || "com.puppycrawl.tools.checkstyle.TreeWalker".equals( module.getName() ) )
396                 {
397                     if ( module instanceof DefaultConfiguration )
398                     {
399                         // MCHECKSTYLE-132 DefaultConfiguration addAttribute has changed in checkstyle 5.3
400                         try
401                         {
402                             if ( module.getAttribute( "cacheFile" ) == null )
403                             {
404                                 ( (DefaultConfiguration) module ).addAttribute( "cacheFile", request.getCacheFile() );
405                             }
406                         }
407                         catch ( CheckstyleException ex )
408                         {
409                             // MCHECKSTYLE-159 - checkstyle 5.4 throws an exception instead of return null if
410                             // "cacheFile"
411                             // doesn't exist
412                             ( (DefaultConfiguration) module ).addAttribute( "cacheFile", request.getCacheFile() );
413                         }
414                     }
415                     else
416                     {
417                         getLogger().warn( "Failed to configure cache file on module " + module );
418                     }
419                 }
420             }
421             return config;
422         }
423         catch ( CheckstyleException e )
424         {
425             throw new CheckstyleExecutorException( "Failed during checkstyle configuration", e );
426         }
427     }
428 
429     private void prepareCheckstylePaths( CheckstyleExecutorRequest request, MavenProject project,
430                                          List<String> classPathStrings, List<String> outputDirectories,
431                                          Collection<File> sourceDirectories, Collection<File> testSourceDirectories )
432         throws CheckstyleExecutorException
433     {
434         try
435         {
436             outputDirectories.add( project.getBuild().getOutputDirectory() );
437 
438             if ( request.isIncludeTestSourceDirectory() && ( testSourceDirectories != null )
439                 && anyDirectoryExists( testSourceDirectories ) )
440             {
441                 classPathStrings.addAll( project.getTestClasspathElements() );
442                 outputDirectories.add( project.getBuild().getTestOutputDirectory() );
443             }
444             else
445             {
446                 classPathStrings.addAll( project.getCompileClasspathElements() );
447             }
448         }
449         catch ( DependencyResolutionRequiredException e )
450         {
451             throw new CheckstyleExecutorException( e.getMessage(), e );
452         }
453     }
454     
455     private boolean anyDirectoryExists( Collection<File> files )
456     {
457         for ( File file : files )
458         {
459             if ( file.isDirectory() )
460             {
461                 return true;
462             }
463         }
464         return false;
465     }
466 
467     private Properties getOverridingProperties( CheckstyleExecutorRequest request )
468         throws CheckstyleExecutorException
469     {
470         Properties p = new Properties();
471 
472         try
473         {
474             if ( request.getPropertiesLocation() != null )
475             {
476                 if ( getLogger().isDebugEnabled() )
477                 {
478                     getLogger().debug( "request.getPropertiesLocation() " + request.getPropertiesLocation() );
479                 }
480 
481                 File propertiesFile = locator.getResourceAsFile( request.getPropertiesLocation(),
482                                                                  "checkstyle-checker.properties" );
483 
484                 FileInputStream properties = new FileInputStream( propertiesFile );
485                 try
486                 {
487                     if ( propertiesFile != null )
488                     {
489                         p.load( properties );
490                     }
491                 }
492                 finally
493                 {
494                     IOUtils.closeQuietly( properties );
495                 }
496             }
497 
498             if ( StringUtils.isNotEmpty( request.getPropertyExpansion() ) )
499             {
500                 String propertyExpansion = request.getPropertyExpansion();
501                 // Convert \ to \\, so that p.load will convert it back properly
502                 propertyExpansion = StringUtils.replace( propertyExpansion, "\\", "\\\\" );
503                 p.load( new ByteArrayInputStream( propertyExpansion.getBytes() ) );
504             }
505 
506             // Workaround for MCHECKSTYLE-48
507             // Make sure that "config/maven-header.txt" is the default value
508             // for headerLocation, if configLocation="config/maven_checks.xml"
509             String headerLocation = request.getHeaderLocation();
510             if ( "config/maven_checks.xml".equals( request.getConfigLocation() ) )
511             {
512 
513                 if ( "LICENSE.txt".equals( request.getHeaderLocation() ) )
514                 {
515                     headerLocation = "config/maven-header.txt";
516                 }
517             }
518             if ( getLogger().isDebugEnabled() )
519             {
520                 getLogger().debug( "headerLocation " + headerLocation );
521             }
522 
523             if ( StringUtils.isNotEmpty( headerLocation ) )
524             {
525                 try
526                 {
527                     File headerFile = licenseLocator.getResourceAsFile( headerLocation, "checkstyle-header.txt" );
528 
529                     if ( headerFile != null )
530                     {
531                         p.setProperty( "checkstyle.header.file", headerFile.getAbsolutePath() );
532                     }
533                 }
534                 catch ( FileResourceCreationException e )
535                 {
536                     getLogger().debug( "Unable to process header location: " + headerLocation );
537                     getLogger().debug( "Checkstyle will throw exception if ${checkstyle.header.file} is used" );
538                 }
539                 catch ( ResourceNotFoundException e )
540                 {
541                     getLogger().debug( "Unable to process header location: " + headerLocation );
542                     getLogger().debug( "Checkstyle will throw exception if ${checkstyle.header.file} is used" );
543                 }
544             }
545 
546             if ( request.getCacheFile() != null )
547             {
548                 p.setProperty( "checkstyle.cache.file", request.getCacheFile() );
549             }
550         }
551         catch ( IOException e )
552         {
553             throw new CheckstyleExecutorException( "Failed to get overriding properties", e );
554         }
555         catch ( FileResourceCreationException e )
556         {
557             throw new CheckstyleExecutorException( "Failed to get overriding properties", e );
558         }
559         catch ( ResourceNotFoundException e )
560         {
561             throw new CheckstyleExecutorException( "Failed to get overriding properties", e );
562         }
563         if ( request.getSuppressionsFileExpression() != null )
564         {
565             String suppressionsFilePath = getSuppressionsFilePath( request );
566 
567             if ( suppressionsFilePath != null )
568             {
569                 p.setProperty( request.getSuppressionsFileExpression(), suppressionsFilePath );
570             }
571         }
572 
573         return p;
574     }
575 
576     private List<File> getFilesToProcess( CheckstyleExecutorRequest request )
577         throws IOException
578     {
579         StringBuilder excludesStr = new StringBuilder();
580 
581         if ( StringUtils.isNotEmpty( request.getExcludes() ) )
582         {
583             excludesStr.append( request.getExcludes() );
584         }
585 
586         String[] defaultExcludes = FileUtils.getDefaultExcludes();
587         for ( String defaultExclude : defaultExcludes )
588         {
589             if ( excludesStr.length() > 0 )
590             {
591                 excludesStr.append( "," );
592             }
593 
594             excludesStr.append( defaultExclude );
595         }
596 
597         Set<File> files = new LinkedHashSet<File>();
598         if ( request.isAggregate() )
599         {
600             for ( MavenProject project : request.getReactorProjects() )
601             {
602                 Set<File> sourceDirectories = new LinkedHashSet<File>();
603                 
604                 // CompileSourceRoots are absolute paths
605                 List<String> compileSourceRoots = project.getCompileSourceRoots(); 
606                 for ( String compileSourceRoot : compileSourceRoots )
607                 {
608                     sourceDirectories.add( new File( compileSourceRoot ) );
609                 }
610 
611                 Set<File> testSourceDirectories = new LinkedHashSet<File>();
612                 // CompileSourceRoots are absolute paths
613                 List<String> testCompileSourceRoots = project.getTestCompileSourceRoots(); 
614                 for ( String testCompileSourceRoot : testCompileSourceRoots )
615                 {
616                     testSourceDirectories.add( new File( testCompileSourceRoot ) );
617                 }
618 
619                 addFilesToProcess( request, sourceDirectories, project.getResources(), project.getTestResources(),
620                                    files, testSourceDirectories );
621             }
622         }
623         else
624         {
625             Collection<File> sourceDirectories = request.getSourceDirectories();
626             addFilesToProcess( request, sourceDirectories, request.getResources(),
627                 request.getTestResources(), files, request.getTestSourceDirectories() );
628         }
629 
630         getLogger().debug( "Added " + files.size() + " files to process." );
631 
632         return new ArrayList<File>( files );
633     }
634 
635     private void addFilesToProcess( CheckstyleExecutorRequest request, Collection<File> sourceDirectories,
636                                     List<Resource> resources, List<Resource> testResources, Collection<File> files,
637                                     Collection<File> testSourceDirectories )
638         throws IOException
639     {
640         if ( sourceDirectories != null )
641         {
642             for ( File sourceDirectory : sourceDirectories )
643             {
644                 if ( sourceDirectory.isDirectory() )
645                 {
646                     final List<File> sourceFiles =
647                         FileUtils.getFiles( sourceDirectory, request.getIncludes(), request.getExcludes() );
648                     files.addAll( sourceFiles );
649                     getLogger().debug( "Added " + sourceFiles.size() + " source files found in '"
650                                            + sourceDirectory.getAbsolutePath() + "'." );
651                 }
652             }
653         }
654 
655         if ( request.isIncludeTestSourceDirectory() && testSourceDirectories != null )
656         {
657             for ( File testSourceDirectory : testSourceDirectories )
658             {
659                 if ( testSourceDirectory.isDirectory() )
660                 {
661                     final List<File> testSourceFiles =
662                         FileUtils.getFiles( testSourceDirectory, request.getIncludes(), request.getExcludes() );
663                     
664                     files.addAll( testSourceFiles );
665                     getLogger().debug( "Added " + testSourceFiles.size() + " test source files found in '"
666                             + testSourceDirectory.getAbsolutePath() + "'." );
667                 }
668             }
669         }
670 
671         if ( resources != null && request.isIncludeResources() )
672         {
673             addResourceFilesToProcess( request, resources, files );
674         }
675         else
676         {
677             getLogger().debug( "No resources found in this project." );
678         }
679 
680         if ( testResources != null && request.isIncludeTestResources() )
681         {
682             addResourceFilesToProcess( request, testResources, files );
683         }
684         else
685         {
686             getLogger().debug( "No test resources found in this project." );
687         }
688     }
689 
690     private void addResourceFilesToProcess( CheckstyleExecutorRequest request, List<Resource> resources,
691                                             Collection<File> files )
692         throws IOException
693     {
694         for ( Resource resource : resources )
695         {
696             if ( resource.getDirectory() != null )
697             {
698                 File resourcesDirectory = new File( resource.getDirectory() );
699                 if ( resourcesDirectory.isDirectory() )
700                 {
701                     String includes = request.getResourceIncludes();
702                     String excludes = request.getResourceExcludes();
703 
704                     // MCHECKSTYLE-214: Only with project-root respect in/excludes, otherwise you'll get every file
705                     if ( resourcesDirectory.equals( request.getProject().getBasedir() ) )
706                     {
707                         String resourceIncludes = StringUtils.join( resource.getIncludes().iterator(), "," );
708                         if ( StringUtils.isEmpty( includes ) )
709                         {
710                             includes = resourceIncludes;
711                         }
712                         else
713                         {
714                             includes += "," + resourceIncludes;
715                         }
716                         
717                         String resourceExcludes = StringUtils.join( resource.getExcludes().iterator(), "," );
718                         if ( StringUtils.isEmpty( excludes ) )
719                         {
720                             excludes = resourceExcludes;
721                         }
722                         else
723                         {
724                             excludes += "," + resourceExcludes;
725                         }
726                     }
727                     
728                     List<File> resourceFiles =
729                         FileUtils.getFiles( resourcesDirectory, includes, excludes );
730                     files.addAll( resourceFiles );
731                     getLogger().debug( "Added " + resourceFiles.size() + " resource files found in '"
732                             + resourcesDirectory.getAbsolutePath() + "'." );
733                 }
734                 else
735                 {
736                     getLogger().debug( "The resources directory '" + resourcesDirectory.getAbsolutePath()
737                             + "' does not exist or is not a directory." );
738                 }
739             }
740         }
741     }
742 
743     private FilterSet getSuppressionsFilterSet( final String suppressionsFilePath )
744         throws CheckstyleExecutorException
745     {
746         if ( suppressionsFilePath == null )
747         {
748             return null;
749         }
750 
751         try
752         {
753             return SuppressionsLoader.loadSuppressions( suppressionsFilePath );
754         }
755         catch ( CheckstyleException ce )
756         {
757             throw new CheckstyleExecutorException( "Failed to load suppressions file from: "
758                 + suppressionsFilePath, ce );
759         }
760     }
761 
762     private String getSuppressionsFilePath( final CheckstyleExecutorRequest request )
763         throws CheckstyleExecutorException
764     {
765         final String suppressionsLocation = request.getSuppressionsLocation();
766         if ( StringUtils.isEmpty( suppressionsLocation ) )
767         {
768             return null;
769         }
770         
771         try
772         {
773             File suppressionsFile = locator.getResourceAsFile( suppressionsLocation, "checkstyle-suppressions.xml" );
774             return suppressionsFile == null ? null : suppressionsFile.getAbsolutePath();
775         }
776         catch ( ResourceNotFoundException e )
777         {
778             throw new CheckstyleExecutorException( "Unable to find suppressions file at location: "
779                 + suppressionsLocation, e );
780         }
781         catch ( FileResourceCreationException e )
782         {
783             throw new CheckstyleExecutorException( "Unable to process suppressions file location: "
784                 + suppressionsLocation, e );
785         }
786     }
787 
788     private String getConfigFile( CheckstyleExecutorRequest request )
789         throws CheckstyleExecutorException
790     {
791         try
792         {
793             if ( getLogger().isDebugEnabled() )
794             {
795                 getLogger().debug( "request.getConfigLocation() " + request.getConfigLocation() );
796             }
797 
798             File configFile = locator.getResourceAsFile( request.getConfigLocation(), "checkstyle-checker.xml" );
799             if ( configFile == null )
800             {
801                 throw new CheckstyleExecutorException( "Unable to process config location: "
802                     + request.getConfigLocation() );
803             }
804             return configFile.getAbsolutePath();
805         }
806         catch ( ResourceNotFoundException e )
807         {
808             throw new CheckstyleExecutorException( "Unable to find configuration file at location: "
809                 + request.getConfigLocation(), e );
810         }
811         catch ( FileResourceCreationException e )
812         {
813             throw new CheckstyleExecutorException( "Unable to process configuration file at location: "
814                 + request.getConfigLocation(), e );
815         }
816 
817     }
818 
819     /**
820      * Configures search paths in the resource locator.
821      * This method should only be called once per execution.
822      *
823      * @param request executor request data.
824      */
825     private void configureResourceLocator( final ResourceManager resourceManager,
826                                            final CheckstyleExecutorRequest request,
827                                            final List<Artifact> additionalArtifacts )
828     {
829         final MavenProject project = request.getProject();
830         resourceManager.setOutputDirectory( new File( project.getBuild().getDirectory() ) );
831 
832         // Recurse up the parent hierarchy and add project directories to the search roots
833         MavenProject parent = project;
834         while ( parent != null && parent.getFile() != null )
835         {
836             // MCHECKSTYLE-131 ( olamy ) I don't like this hack.
837             // (dkulp) Me either.   It really pollutes the location stuff
838             // by allowing searches of stuff outside the current module.
839             File dir = parent.getFile().getParentFile();
840             resourceManager.addSearchPath( FileResourceLoader.ID, dir.getAbsolutePath() );
841             parent = parent.getParent();
842         }
843         resourceManager.addSearchPath( "url", "" );
844         
845         // MCHECKSTYLE-225: load licenses from additional artifacts, not from classpath
846         if ( additionalArtifacts != null )
847         {
848             for ( Artifact licenseArtifact : additionalArtifacts )
849             {
850                 try
851                 {
852                     resourceManager.addSearchPath( "jar", "jar:" + licenseArtifact.getFile().toURI().toURL() );
853                 }
854                 catch ( MalformedURLException e )
855                 {
856                     // noop
857                 }
858             }
859         }
860     }
861 }