View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang;
5   
6   import java.io.File;
7   import java.io.FilenameFilter;
8   import java.util.Collections;
9   import java.util.List;
10  import java.util.Set;
11  
12  /**
13   * This is an implementation of the {@link FilenameFilter} interface which
14   * compares a file against a collection of Languages to see if the any are
15   * applicable.
16   *
17   * @author Pieter_Van_Raemdonck - Application Engineers NV/SA - www.ae.be
18   */
19  public class LanguageFilenameFilter implements FilenameFilter {
20  
21  	private final Set<Language> languages;
22  
23  	/**
24  	 * Create a LanguageFilenameFilter for a single Language.
25  	 * @param language The Language.
26  	 */
27  	public LanguageFilenameFilter(Language language) {
28  		this(Collections.singleton(language));
29  	}
30  
31  	/**
32  	 * Create a LanguageFilenameFilter for a List of Languages.
33  	 * @param languages The List of Languages.
34  	 */
35  	public LanguageFilenameFilter(Set<Language> languages) {
36  		this.languages = languages;
37  	}
38  
39  	/**
40  	 * Check if a file should be checked by PMD.
41  	 * {@inheritDoc}
42  	 */
43  	public boolean accept(File dir, String name) {
44  		// Any source file should have a '.' in its name...
45  		int lastDotIndex = name.lastIndexOf('.');
46  		if (lastDotIndex < 0) {
47  			return false;
48  		}
49  
50  		String extension = name.substring(1 + lastDotIndex).toUpperCase();
51  		for (Language language : languages) {
52  			for (String ext : language.getExtensions()) {
53  				if (extension.equalsIgnoreCase(ext)) {
54  					return true;
55  				}
56  			}
57  		}
58  		return false;
59  	}
60  
61  	public String toString() {
62  		StringBuilder buffer = new StringBuilder("(Extension is one of: ");
63  		for (Language language : languages) {
64  			List<String> extensions = language.getExtensions();
65  			for (int i = 0; i < extensions.size(); i++) {
66  				if (i > 0) {
67  					buffer.append(", ");
68  				}
69  				buffer.append(extensions.get(i));
70  			}
71  		}
72  		buffer.append(')');
73  		return buffer.toString();
74  	}
75  }