View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.cpd;
5   
6   import java.util.HashMap;
7   import java.util.Map;
8   import java.util.Properties;
9   import java.util.ServiceLoader;
10  
11  public final class LanguageFactory {
12  
13      public static final String EXTENSION = "extension";
14      public static final String BY_EXTENSION = "by_extension";
15  
16      private static LanguageFactory instance = new LanguageFactory();
17  
18      public static String[] supportedLanguages;
19      static {
20         supportedLanguages = instance.languages.keySet().toArray(new String[instance.languages.size()]);
21      }
22  
23     private Map<String, Language> languages = new HashMap<>();
24  
25     private LanguageFactory() {
26         ServiceLoader<Language> languageLoader = ServiceLoader.load(Language.class);
27         for (Language language : languageLoader) {
28             languages.put(language.getTerseName().toLowerCase(), language);
29         }
30     }
31     
32      public static Language createLanguage(String language) {
33          return createLanguage(language, new Properties());
34      }
35  
36     public static Language createLanguage(String language, Properties properties)
37     {
38       Language implementation; 
39       if (BY_EXTENSION.equals(language)) {
40           implementation = instance.getLanguageByExtension(properties.getProperty(EXTENSION));
41       } else {
42           implementation = instance.languages.get(instance.languageAliases(language).toLowerCase());
43       }
44       if (implementation == null) {
45           // No proper implementation
46           // FIXME: We should log a warning, shouldn't we ?
47           implementation = new AnyLanguage(language);
48       }
49       implementation.setProperties(properties);
50       return implementation;
51     }
52  
53       private String languageAliases(String language)
54       {
55         // CPD and C language share the same parser
56         if ( "c".equals(language) ) {
57           return "cpp";
58         }
59         return language;
60       }
61       
62       private Language getLanguageByExtension(String extension) {
63           Language result = null;
64  
65           for (Language language : languages.values()) {
66               if (language.getExtensions().contains(extension)) {
67                   result = language;
68                   break;
69               }
70           }
71           return result;
72       }
73  }