KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > repository > GenericConverter


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.enterprise.repository;
24
25 import java.util.*;
26 import java.lang.reflect.*;
27 import com.sun.enterprise.util.Utility;
28 import com.sun.enterprise.util.LocalStringManagerImpl;
29 // IASRI 4660742 START
30
import java.util.logging.*;
31 import com.sun.logging.*;
32 // IASRI 4660742 END
33

34 /**
35  * Generic class for converting raw resource info to a
36  * J2EEResource and vice versa. Makes following assumptions
37  * about J2EEResource implementation classes.
38  * 1. Has public constructor that takes a single java.lang.String arg
39  * 2. Any public getX method represents a resource attribute.
40  * 3. Every such getX method except getName() has a corresponding
41  * public setX method.
42  *
43  * @author Kenneth Saks
44  */

45 public class GenericConverter implements J2EEResourceConverter {
46
47 // IASRI 4660742 START
48
private static Logger _logger=null;
49     static{
50        _logger=LogDomains.getLogger(LogDomains.ROOT_LOGGER);
51         }
52 // IASRI 4660742 END
53
private static LocalStringManagerImpl localStrings =
54     new LocalStringManagerImpl(GenericConverter.class);
55
56     private static final String JavaDoc RESOURCE_NAME_ATTR = "name";
57
58     private static Hashtable resourceImplClasses;
59     private static Hashtable attributeMethods;
60
61     private int counter = 0;
62     
63     //
64
// Resource type to concrete J2EEResource class mappings.
65
//
66
static {
67         resourceImplClasses = new Hashtable();
68         attributeMethods = new Hashtable();
69
70         resourceImplClasses.put
71             ("jmsCnxFactory",
72              com.sun.enterprise.repository.JmsCnxFactoryResource.class);
73         resourceImplClasses.put
74             ("jmsDestination",
75              com.sun.enterprise.repository.JmsDestinationResource.class);
76         resourceImplClasses.put
77             ("jdbcDataSource",
78              com.sun.enterprise.repository.JdbcResource.class);
79         resourceImplClasses.put
80             ("jdbcXADataSource",
81              com.sun.enterprise.repository.JdbcXAResource.class);
82         resourceImplClasses.put
83             ("jdbcDriver",
84              com.sun.enterprise.repository.JdbcDriver.class);
85         /**IASRI 4633236
86          resourceImplClasses.put
87             ("connectorCnxFactory",
88             com.sun.enterprise.repository.ConnectorResource.class);
89         resourceImplClasses.put
90             ("resourceAdapter",
91              com.sun.enterprise.repository.ResourceAdapter.class);
92         **/

93     }
94
95     public GenericConverter() {
96     }
97     
98     public J2EEResource rawInfoToResource(RawResourceInfo rawInfo)
99         throws J2EEResourceException {
100         J2EEResource resource = null;
101         try {
102             Class JavaDoc resourceClass =
103                 (Class JavaDoc) resourceImplClasses.get(rawInfo.getResourceType());
104
105             if( resourceClass == null ) {
106                 String JavaDoc errMsg = localStrings.getLocalString
107                     ("GenericConverter.unknown.resource.type",
108                      "Unknown resource type {0}",
109                      new Object JavaDoc[] { rawInfo.getResourceType() });
110                 throw new J2EEResourceException(errMsg);
111             }
112
113             // Create an instance of the concrete J2EEResource class
114
// by passing in the name.
115
Class JavaDoc paramTypes[] = { java.lang.String JavaDoc.class };
116             Constructor nameConstructor =
117                 resourceClass.getConstructor(paramTypes);
118
119             String JavaDoc name = (String JavaDoc)
120                 rawInfo.getAttributes().get(RESOURCE_NAME_ATTR);
121             
122             if( name == null ) {
123                 String JavaDoc errMsg = localStrings.getLocalString
124                     ("GenericConverter.name.attribute.required",
125                      "Resource type {0} with index {1} is " +
126                      "missing a 'name' attribute",
127                      new Object JavaDoc[] { rawInfo.getResourceType(),
128                                     new Integer JavaDoc(rawInfo.getIndex()) });
129                 throw new J2EEResourceException(errMsg);
130             }
131
132             Object JavaDoc initArgs[] = { name };
133             resource = (J2EEResource) nameConstructor.newInstance(initArgs);
134
135             //
136
// Call the mutator for each resource attribute.
137
//
138
Set attributes = rawInfo.getAttributes().entrySet();
139
140             for(Iterator iter = attributes.iterator(); iter.hasNext(); ) {
141                 Map.Entry next = (Map.Entry) iter.next();
142                 String JavaDoc attrName = (String JavaDoc) next.getKey();
143                 String JavaDoc attrValue = (String JavaDoc) next.getValue();
144                 try {
145                     if( !attrName.equals(RESOURCE_NAME_ATTR) ) {
146                         Utility.invokeSetMethod(resource, attrName, attrValue);
147                     }
148                 } catch(NoSuchMethodException JavaDoc nsme) {
149                     String JavaDoc errMsg = localStrings.getLocalString
150                         ("GenericConverter.invalid.attribute",
151                          "Attribute {0} of resource type {1} with index {2} "
152                          + "is invalid",
153                          new Object JavaDoc[] { attrName, rawInfo.getResourceType(),
154                                         new Integer JavaDoc(rawInfo.getIndex()) });
155                     throw new J2EEResourceException(errMsg);
156                 }
157             }
158
159             //
160
// Add each resource property.
161
//
162
Set properties = rawInfo.getProperties().entrySet();
163
164             for(Iterator iter = properties.iterator(); iter.hasNext(); ) {
165                 Map.Entry next = (Map.Entry) iter.next();
166                 String JavaDoc propName = (String JavaDoc) next.getKey();
167
168                 ResourceProperty property = new ResourcePropertyImpl(propName);
169                 property.setValue(next.getValue());
170                 resource.addProperty(property);
171             }
172         } catch(J2EEResourceException jre) {
173             throw jre;
174         } catch(Exception JavaDoc e) {
175 //IASRI 4660742 e.printStackTrace();
176
// START OF IASRI 4660742
177
_logger.log(Level.SEVERE,"enterprise.rawinfotoresource_exception",e);
178 // END OF IASRI 4660742
179
throw new J2EEResourceException(e);
180         }
181         return resource;
182     }
183     
184     public RawResourceInfo resourceToRawInfo(J2EEResource resource)
185         throws J2EEResourceException {
186         RawResourceInfo rawInfo = null;
187         try {
188             // First create an instance of raw resource info with
189
// the resource type and a unique index.
190
Class JavaDoc[] emptyArgs = new Class JavaDoc[] {};
191             Class JavaDoc resourceClass = resource.getClass();
192             String JavaDoc resourceType = getResourceType(resourceClass.getName());
193             rawInfo = new RawResourceInfo(resourceType, counter);
194             counter++;
195
196             //
197
// Get the value of each storable resource attribute and
198
// add it to the raw info.
199
//
200
List attrMethods = getAttributeMethods(resourceClass);
201             for(Iterator iter = attrMethods.iterator(); iter.hasNext(); ) {
202                 Method method = (Method) iter.next();
203                 Object JavaDoc value = method.invoke(resource, (Object JavaDoc[]) emptyArgs);
204                 if( value == null ) {
205                     value = "";
206                 }
207                 // Skip "get" to form attribute name.
208
String JavaDoc propName = method.getName().substring(3);
209                 // Convert first letter to lower case.
210
propName = propName.substring(0,1).toLowerCase() +
211                     propName.substring(1);
212                 rawInfo.getAttributes().put(propName, value);
213             }
214
215             // Add each resource property.
216
Set properties = resource.getProperties();
217             for(Iterator iter = properties.iterator(); iter.hasNext(); ) {
218                 ResourceProperty next = (ResourceProperty) iter.next();
219                 rawInfo.getProperties().put(next.getName(), next.getValue());
220             }
221         } catch(Exception JavaDoc e) {
222 //IASRI 4660742 e.printStackTrace();
223
// START OF IASRI 4660742
224
_logger.log(Level.SEVERE,"enterprise.resourcetorawinfo_exception",e);
225 // END OF IASRI 4660742
226
throw new J2EEResourceException(e);
227         }
228
229         return rawInfo;
230     }
231
232
233     /**
234      * Get the corresonding resource type string for a
235      * concrete J2EEResource class.
236      */

237     private String JavaDoc getResourceType(String JavaDoc className) {
238         Set implClasses = resourceImplClasses.entrySet();
239         for(Iterator iter = implClasses.iterator(); iter.hasNext(); ) {
240             Map.Entry next = (Map.Entry) iter.next();
241             Class JavaDoc nextClass = (Class JavaDoc) next.getValue();
242             if( nextClass.getName().equals(className) ) {
243                 return (String JavaDoc) next.getKey();
244             }
245         }
246         throw new java.lang.IllegalArgumentException JavaDoc();
247     }
248
249     /**
250      * Get the set of attribute methods whose values should
251      * be converted.
252      */

253     private static List getAttributeMethods(Class JavaDoc resourceClass)
254         throws Exception JavaDoc
255     {
256
257         Class JavaDoc[] emptyArgs = new Class JavaDoc[] {};
258
259         Method[] methodsToSkip =
260         {
261             // Immutable J2EEResource attribute
262
resourceClass.getMethod("getType", emptyArgs),
263
264             // java.lang.Object accessors
265
resourceClass.getMethod("getProperties", emptyArgs),
266             resourceClass.getMethod("getProperty",
267                                     new Class JavaDoc[] { String JavaDoc.class }),
268             java.lang.Object JavaDoc.class.getMethod("getClass", emptyArgs)
269         };
270
271         List methodsForClass =
272             (List) attributeMethods.get(resourceClass.getName());
273
274         // If we haven't already generated the list of attribute
275
// methods for this concrete J2EEResource class.
276
if( methodsForClass == null ) {
277             methodsForClass = new Vector();
278
279             Method[] allMethods = resourceClass.getMethods();
280             for(int methodIndex = 0; methodIndex < allMethods.length;
281                 methodIndex++) {
282                 Method method = allMethods[methodIndex];
283                 if( isStorableAttrMethod(method, methodsToSkip) ) {
284                     methodsForClass.add(method);
285                 }
286             }
287
288             attributeMethods.put(resourceClass.getName(),
289                                  methodsForClass);
290         }
291         return methodsForClass;
292     }
293
294     private static boolean isStorableAttrMethod(Method method,
295                                                 Method[] methodsToSkip) {
296         for(int methodIndex = 0; methodIndex < methodsToSkip.length;
297             methodIndex++ ) {
298             if( method.equals(methodsToSkip[methodIndex]) ) {
299                 return false;
300             }
301         }
302         return method.getName().startsWith("get");
303     }
304
305 }
306
Popular Tags