View Javadoc

1   package org.astrogrid.common.registry;
2   
3   import java.io.FileInputStream;
4   import java.io.FileNotFoundException;
5   import java.io.IOException;
6   import java.io.InputStream;
7   import java.util.Properties;
8   
9   import org.astrogrid.common.creator.InstanceCreator;
10  import org.astrogrid.common.creator.InstanceCreatorException;
11  
12  /***
13   * @author peter.shillan <mailto:gps@roe.ac.uk />
14   */
15  public class InstanceRegistry {
16    // Members.
17    private Properties registry;
18    private InstanceCreator creator;
19    
20    public InstanceRegistry(Properties registry) {
21      this(registry, new InstanceCreator());
22    }
23    
24    public InstanceRegistry(String filename) throws FileNotFoundException, IOException {
25      this(new FileInputStream(filename));
26    }
27  
28    public InstanceRegistry(InputStream inStream) throws IOException {
29      this(new Properties());
30      registry.load(inStream);
31    }
32  
33    public InstanceRegistry(Properties registry, InstanceCreator creator) {
34      this.registry = registry;
35      this.creator = creator;
36    }
37    
38    public Object getInstance(String property) throws InstanceCreatorException {
39      return getInstance(property, (String) null, (Object[]) null);
40    }
41    
42    public Object getInstance(String property, String methodName, Object[] parameters) throws InstanceCreatorException {
43      Object result = null;
44      
45      String className = registry.getProperty(property);
46      if(className != null && className.length() > 0) {
47        result = creator.getInstance(className, methodName, parameters);
48      }
49          
50      return result;
51    }
52    
53    public Object getInstance(String property, Class clazz) throws InstanceCreatorException, ClassCastException {
54      return getInstance(property, (String) null, (Object[]) null, clazz);
55    }
56  
57    public Object getInstance(String property, String methodName, Object[] parameters, Class clazz) throws InstanceCreatorException, ClassCastException {
58      Object result = getInstance(property, methodName, parameters);
59      
60      if(!clazz.isInstance(result)) {
61        throw new ClassCastException();
62      }
63      
64      return result;
65    }
66    
67  }