View Javadoc

1   package org.archive.hcc.util;
2   
3   import java.io.File;
4   import java.io.FileInputStream;
5   import java.io.FileNotFoundException;
6   import java.io.InputStream;
7   import java.util.Properties;
8   import java.util.logging.Level;
9   import java.util.logging.Logger;
10  
11  
12  public class SmartPropertiesResolver {
13  	private static final Logger log = Logger.getLogger(SmartPropertiesResolver.class.getName());
14  
15  	public static Properties getProperties(String filePath) {
16  		if(filePath == null){
17  			throw new NullPointerException("filePath must be non null");
18  		}
19  		
20  
21  		//first try to resolve by system property
22  		
23  		InputStream is = null;
24  		
25  		if(filePath != null){
26  			File f = new File(filePath);
27  			
28  			if(!f.exists()){
29  				String fileName = filePath.substring(filePath.lastIndexOf(File.separator) +1);
30  				f = new File( 
31  					System.getProperty("user.home") + 
32  						File.separator + 
33  						fileName);
34  
35  				if(!f.exists()){
36  					f = new File(
37  							System.getProperty("user.dir") + 
38  								File.separator + 
39  								fileName);
40  					
41  				}
42  			}			
43  			
44  			try{
45  				if(!f.exists()){
46  					is = SmartPropertiesResolver.class.getResourceAsStream(filePath);
47  					if(is == null){
48  						throw new RuntimeException(new FileNotFoundException("cannot find resource: " + filePath));
49  					}
50  				}else{
51  					is = new FileInputStream(f);
52  				}
53  
54  				Properties p = new Properties();
55  				p.load(is);
56  				
57  				if(log.isLoggable(Level.FINE)){
58  					log.fine("loaded properties(" + filePath + ").");
59  				}
60  				return p;
61  
62  			}catch(Exception e){
63  
64  				if(log.isLoggable(Level.SEVERE)){
65  					log.severe("Failed to load property file: " + (f.exists()?f.getAbsolutePath():filePath) + "; message=" + e.getMessage());
66  				}
67  				throw new RuntimeException(e);
68  
69  			}
70  		}
71  
72  		if(log.isLoggable(Level.SEVERE))
73  			log.severe("Neither File (" + filePath + ")  not found anywhere.");
74  
75  		throw new RuntimeException(new FileNotFoundException(filePath));
76  			
77  		
78  	}
79  }