View Javadoc

1   package pl.psnc.dl.ege.webapp.config;
2   
3   import java.io.File;
4   import java.io.FileInputStream;
5   import java.io.FilenameFilter;
6   import java.util.HashMap;
7   import java.util.Locale;
8   import java.util.Map;
9   import java.util.Properties;
10  
11  import org.apache.log4j.Logger;
12  
13  /**
14   * Singleton class which provides EGE web application
15   * with access to local labels and names.
16   * 
17   * @author mariuszs
18   *
19   */
20  public final class LabelProvider
21  {
22  	private static LabelProvider instance = null;
23  	
24  	private static final String DEFAULT_LOCALE = "en"; 
25  	
26  	private static final String REGEXP_LABEL_CONT = "labels_[a-z][a-z].xml";
27  	
28  	private static final Logger LOGGER = Logger.getLogger(LabelProvider.class);
29  	
30  	private Map<String,Properties> labels; 
31  	
32  	private LabelProvider(String path){
33  		File dir = new File(path);
34  		FilenameFilter fnf = new FilenameFilter(){
35  			@Override
36  			public boolean accept(File dir, String name)
37  			{
38  				if(name.matches(REGEXP_LABEL_CONT)){
39  					return true;
40  				}
41  				return false;
42  			}
43  			
44  		};
45  		labels = new HashMap<String,Properties>();
46  		for(File lc : dir.listFiles(fnf)){
47  			Properties props = new Properties();
48  			try{
49  				props.loadFromXML(new FileInputStream(lc));
50  				String loc = lc.toString();
51  				loc = loc.substring(loc.length() - 6, loc.length() - 4);
52  				labels.put(loc, props);
53  			}
54  			catch(Exception ex){
55  				LOGGER.error(ex.getMessage(), ex);
56  			}
57  		}
58  	}
59  	
60  	public static LabelProvider getInstance(String path){
61  		if(instance == null){
62  			instance = new LabelProvider(path); 
63  		}
64  		return instance;
65  	}
66  	
67  	/**
68  	 * Returns specified label
69  	 * of default locale.<br/> 
70  	 * If label does not exists method
71  	 * will return an empty String.  
72  	 * 
73  	 * @param key
74  	 * @return
75  	 */
76  	public String getLabel(String key){
77  		return getLabel(key,DEFAULT_LOCALE);
78  	}
79  	
80  	/**
81  	 * Returns label 
82  	 * in language specified by locale.<br/> 
83  	 * If label does not exists method
84  	 * will return an empty String.  
85  	 * 
86  	 * @param key
87  	 * @param locale
88  	 * @return
89  	 */
90  	public String getLabel(String key, String locale){
91  		Properties props = labels.get(locale);
92  		if(props != null){
93  			return props.getProperty(key);
94  		}
95  		return "";
96  	}
97  	
98  	/**
99  	 * Returns label 
100 	 * in language specified by locale.<br/>
101 	 * If label does not exists method
102 	 * will return an empty String.     
103 	 * 
104 	 * @param key
105 	 * @param locale
106 	 * @return
107 	 */
108 	public String getLabel(String key, Locale locale){
109 		return getLabel(key,locale.getCountry());
110 	}
111 	
112 	
113 	
114 }