KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgroups > conf > ClassConfigurator


1 // $Id: ClassConfigurator.java,v 1.11 2005/04/23 12:43:52 belaban Exp $
2

3 package org.jgroups.conf;
4
5
6 import org.apache.commons.logging.Log;
7 import org.apache.commons.logging.LogFactory;
8 import org.jgroups.util.Util;
9 import org.jgroups.ChannelException;
10
11 import java.util.HashMap JavaDoc;
12 import java.util.Iterator JavaDoc;
13 import java.util.Map JavaDoc;
14 import java.util.TreeMap JavaDoc;
15 import java.io.ObjectStreamClass JavaDoc;
16
17 /**
18  * This class will be replaced with the class that read info
19  * from the magic number configurator that reads info from the xml file.<br>
20  * The name and the relative path of the magic number map file can be specified
21  * as value of the property <code>org.jgroups.conf.magicNumberFile</code>.
22  * It must be relative to one of the classpath elements, to allow the
23  * classloader to locate the file. If a value is not specified,
24  * <code>MagicNumberReader.MAGIC_NUMBER_FILE</code> is used, which defaults
25  * to "jg-magic-map.xml".
26  *
27  * @author Filip Hanik
28  * @author Bela Ban
29  * @see org.jgroups.conf.MagicNumberReader
30  */

31 public class ClassConfigurator {
32     static ClassConfigurator instance=null;
33
34     //this is where we store magic numbers
35
private final Map JavaDoc classMap=new HashMap JavaDoc(); // key=Class, value=magic number
36
private final Map JavaDoc magicMap=new TreeMap JavaDoc(); // key=magic number, value=Class
37

38     /** Map<Integer,ObjectStreamClass> */
39     private final Map JavaDoc streamMapId=new TreeMap JavaDoc();
40
41     /** Map<ObjectStreamClass, Integer> */
42     private final Map JavaDoc streamMapClass=new HashMap JavaDoc();
43
44     protected final Log log=LogFactory.getLog(getClass());
45
46
47     private ClassConfigurator() {
48     }
49
50     public void init() throws ChannelException {
51         //populate the map
52
try {
53             // make sure we have a class for DocumentBuilderFactory
54
// getClass().getClassLoader().loadClass("javax.xml.parsers.DocumentBuilderFactory");
55
Thread.currentThread().getContextClassLoader().loadClass("javax.xml.parsers.DocumentBuilderFactory");
56
57             MagicNumberReader reader=new MagicNumberReader();
58             
59             // PropertyPermission not granted if running in an untrusted environment with JNLP.
60
try {
61                 String JavaDoc mnfile = System.getProperty("org.jgroups.conf.magicNumberFile");
62                 if(mnfile != null) {
63                     if(log.isDebugEnabled()) log.debug("Using " + mnfile + " as magic number file");
64                     reader.setFilename(mnfile);
65                 }
66             }
67             catch (SecurityException JavaDoc ex){
68             }
69
70             ObjectStreamClass JavaDoc objStreamClass;
71             ClassMap[] mapping=reader.readMagicNumberMapping();
72             if(mapping != null) {
73                 for(int i=0; i < mapping.length; i++) {
74                     Integer JavaDoc m=new Integer JavaDoc(mapping[i].getMagicNumber());
75                     try {
76                         Class JavaDoc clazz=mapping[i].getClassForMap();
77                         objStreamClass=ObjectStreamClass.lookup(clazz);
78                         if(objStreamClass == null)
79                             throw new ChannelException("ObjectStreamClass for " + clazz + " not found");
80                         if(magicMap.containsKey(m)) {
81                             throw new ChannelException("magic key " + m + " (" + clazz.getName() + ')' +
82                                                        " is already in map; please make sure that " +
83                                                        "all magic keys are unique");
84                         }
85                         else {
86                             magicMap.put(m, clazz);
87                             classMap.put(clazz, m);
88
89                             streamMapId.put(m, objStreamClass);
90                             streamMapClass.put(objStreamClass, m);
91                         }
92                     }
93                     catch(ClassNotFoundException JavaDoc cnf) {
94                         throw new ChannelException("failed loading class: " + cnf);
95                     }
96                 }
97                 if(log.isDebugEnabled()) log.debug("mapping is:\n" + printMagicMap());
98             }
99         }
100         catch(ChannelException ex) {
101             throw ex;
102         }
103         catch(Throwable JavaDoc x) {
104             // if(log.isErrorEnabled()) log.error("failed reading the magic number mapping file, reason: " + Util.print(x));
105
throw new ChannelException("failed reading the magic number mapping file", x);
106         }
107     }
108
109
110     public static ClassConfigurator getInstance(boolean init) throws ChannelException {
111         if(instance == null) {
112             instance=new ClassConfigurator();
113             if(init)
114                 instance.init();
115         }
116         return instance;
117     }
118
119
120     /**
121      * Returns a class for a magic number.
122      * Returns null if no class is found
123      *
124      * @param magic the magic number that maps to the class
125      * @return a Class object that represents a class that implements java.io.Externalizable
126      */

127     public Class JavaDoc get(int magic) {
128         return (Class JavaDoc)magicMap.get(new Integer JavaDoc(magic));
129     }
130
131     /**
132      * Loads and returns the class from the class name
133      *
134      * @param clazzname a fully classified class name to be loaded
135      * @return a Class object that represents a class that implements java.io.Externalizable
136      */

137     public Class JavaDoc get(String JavaDoc clazzname) {
138         try {
139             // return ClassConfigurator.class.getClassLoader().loadClass(clazzname);
140
return Thread.currentThread().getContextClassLoader().loadClass(clazzname);
141         }
142         catch(Exception JavaDoc x) {
143             if(log.isErrorEnabled()) log.error(Util.getStackTrace(x));
144         }
145         return null;
146     }
147
148     /**
149      * Returns the magic number for the class.
150      *
151      * @param clazz a class object that we want the magic number for
152      * @return the magic number for a class, -1 if no mapping is available
153      */

154     public int getMagicNumber(Class JavaDoc clazz) {
155         Integer JavaDoc i=(Integer JavaDoc)classMap.get(clazz);
156         if(i == null)
157             return -1;
158         else
159             return i.intValue();
160     }
161
162     public int getMagicNumberFromObjectStreamClass(ObjectStreamClass JavaDoc objStream) {
163         Integer JavaDoc i=(Integer JavaDoc)streamMapClass.get(objStream);
164         if(i == null)
165             return -1;
166         else
167             return i.intValue();
168     }
169
170     public ObjectStreamClass JavaDoc getObjectStreamClassFromMagicNumber(int magic_number) {
171         ObjectStreamClass JavaDoc retval=null;
172         retval=(ObjectStreamClass JavaDoc)streamMapId.get(new Integer JavaDoc(magic_number));
173         return retval;
174     }
175
176
177     public String JavaDoc toString() {
178         return printMagicMap();
179     }
180
181     public String JavaDoc printMagicMap() {
182         StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
183         Map.Entry JavaDoc entry;
184
185         for(Iterator JavaDoc it=magicMap.entrySet().iterator(); it.hasNext();) {
186             entry=(Map.Entry JavaDoc)it.next();
187             sb.append(entry.getKey()).append(":\t").append(entry.getValue()).append('\n');
188         }
189         return sb.toString();
190     }
191
192     public String JavaDoc printClassMap() {
193         StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
194         Map.Entry JavaDoc entry;
195
196         for(Iterator JavaDoc it=classMap.entrySet().iterator(); it.hasNext();) {
197             entry=(Map.Entry JavaDoc)it.next();
198             sb.append(entry.getKey()).append(": ").append(entry.getValue()).append('\n');
199         }
200         return sb.toString();
201     }
202
203
204
205     /* --------------------------------- Private methods ------------------------------------ */
206
207     /* ------------------------------ End of Pivate methods --------------------------------- */
208     public static void main(String JavaDoc[] args)
209             throws Exception JavaDoc {
210
211         ClassConfigurator test=getInstance(true);
212         System.out.println('\n' + test.printMagicMap());
213     }
214 }
215
Popular Tags