KickJava   Java API By Example, From Geeks To Geeks.

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


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

24 package com.sun.enterprise.repository;
25
26 import java.util.*;
27 import java.io.*;
28 import com.sun.enterprise.ServerConfiguration;
29 import com.sun.enterprise.util.FileUtil;
30 import javax.rmi.PortableRemoteObject JavaDoc;
31 import javax.naming.*;
32 // IASRI 4660742 START
33
import java.util.logging.*;
34 import com.sun.logging.*;
35 // IASRI 4660742 END
36

37 /**
38  * Implementation of J2EEResourceFactory. Reads and writes
39  * file properties and converts them to J2EEResources.
40  *
41  * @author Kenneth Saks
42  */

43 public class J2EEResourceFactoryImpl implements J2EEResourceFactory {
44
45 // IASRI 4660742 START
46
private static Logger _logger=null;
47     static{
48        _logger=LogDomains.getLogger(LogDomains.ROOT_LOGGER);
49         }
50 // IASRI 4660742 END
51
private static final String JavaDoc FIELD_SEPARATOR = ".";
52     private static final String JavaDoc PROP_INDICATOR = "prop";
53     private static final String JavaDoc NAME_ATTRIBUTE = "name";
54
55     private static final String JavaDoc RESOURCE_PROP_RELATIVE_PATH =
56         "config" + File.separator + "resource.properties";
57
58     // For comparators
59
private static final int EQUAL = 0;
60     private static final int SORT_BEFORE = -1;
61     private static final int SORT_AFTER = 1;
62
63     private static final boolean debug = false;
64
65     // Used to store properties to disk.
66
private Properties outputProperties_;
67
68     public J2EEResourceFactoryImpl() {
69         outputProperties_ = new Properties();
70     }
71
72     public J2EEResourceCollection loadDefaultResourceCollection()
73         throws J2EEResourceException {
74         String JavaDoc resourceFile =
75             FileUtil.getAbsolutePath(RESOURCE_PROP_RELATIVE_PATH);
76         return loadResourceCollection(resourceFile);
77     }
78
79     public J2EEResourceCollection loadResourceCollection(String JavaDoc resourcesURL)
80         throws J2EEResourceException {
81
82         J2EEResourceCollection resources = new J2EEResourceCollectionImpl();
83         InputStream inputStream = null;
84
85         try {
86             Properties resourceProperties = new Properties();
87             if( debug ) {
88 // IASRI 4660742 System.out.println("Loading resource properties from " +
89
// IASRI 4660742 resourcesURL);
90
// START OF IASRI 4660742
91
if(_logger.isLoggable(Level.FINE))
92             _logger.log(Level.FINE,"Loading resource properties from " +resourcesURL);
93 // END OF IASRI 4660742
94
}
95
96             // Treat the URL as a file containing the properties
97
// and load them into an input stream.
98
File resourceFile = new File(resourcesURL);
99             if( !resourceFile.exists() ) {
100                 boolean created = resourceFile.createNewFile();
101                 if( !created ) {
102                     throw new IOException("Could not create " + resourceFile);
103                 }
104             }
105             FileInputStream fis = new FileInputStream(resourceFile);
106             inputStream = new BufferedInputStream(fis);
107             resourceProperties.load(inputStream);
108
109             // Convert the properties to raw resource information.
110
List rawInfoList = propsToRawResourceInfo(resourceProperties);
111
112             J2EEResourceConverter converter = new GenericConverter();
113             for(Iterator iter = rawInfoList.iterator(); iter.hasNext(); ) {
114                 RawResourceInfo rawInfo = (RawResourceInfo) iter.next();
115                 try {
116                     J2EEResource resource =
117                         converter.rawInfoToResource(rawInfo);
118                     resources.addResource(resource);
119                 } catch(J2EEResourceException jre) {
120 // IASRI 4660742 System.out.println(jre);
121
// IASRI 4660742 jre.printStackTrace();
122
// START OF IASRI 4660742
123
_logger.log(Level.SEVERE,"enterprise.resource_exception",jre);
124 // END OF IASRI 4660742
125
}
126             }
127             
128         } catch(Exception JavaDoc e) {
129             throw new J2EEResourceException(e);
130         } finally {
131             if( inputStream != null ) {
132                 try {
133                     inputStream.close();
134                 } catch(IOException ioe) {}
135             }
136         }
137
138         return resources;
139     }
140
141     public void storeDefaultResourceCollection(J2EEResourceCollection
142                                                resources)
143         throws J2EEResourceException {
144         String JavaDoc resourceFile =
145             FileUtil.getAbsolutePath(RESOURCE_PROP_RELATIVE_PATH);
146         storeResourceCollection(resources, resourceFile);
147     }
148     
149     public void storeResourceCollection(J2EEResourceCollection resources,
150                                         String JavaDoc resourcesURL)
151         throws J2EEResourceException {
152
153         OutputStream tempResourceOutputStream = null;
154         InputStream tempResourceInputStream = null;
155         OutputStream resourceOutputStream = null;
156         
157         try {
158             if( debug ) {
159 // IASRI 4660742 System.out.println("Storing resource properties to " +
160
// IASRI 4660742 resourcesURL);
161
// START OF IASRI 4660742
162
if(_logger.isLoggable(Level.FINE))
163             _logger.log(Level.FINE,"Storing resource properties to " +resourcesURL);
164 // END OF IASRI 4660742
165
}
166
167             // Open a file to store the properties.
168
File tempResourceFile = File.createTempFile("resource","");
169             tempResourceFile.deleteOnExit();
170             tempResourceOutputStream = new FileOutputStream(tempResourceFile);
171
172             // Convert each resource to raw info.
173
List allRawInfo = new Vector();
174             Set allResources = resources.getAllResources();
175             J2EEResourceConverter converter = new GenericConverter();
176             for(Iterator iter = allResources.iterator(); iter.hasNext(); ) {
177                 J2EEResource next = (J2EEResource) iter.next();
178                 RawResourceInfo rawInfo = converter.resourceToRawInfo(next);
179                 allRawInfo.add(rawInfo);
180             }
181
182             // Convert raw info to a sorted set of properties and store
183
// in a temporary file.
184
storeRawInfoToPropsFile(allRawInfo, tempResourceOutputStream);
185             tempResourceOutputStream.close();
186             tempResourceOutputStream = null;
187
188             // Remove extraneous comment lines from temporary resource output
189
tempResourceInputStream = new FileInputStream(tempResourceFile);
190             BufferedReader tempResourceReader = new BufferedReader
191                 (new InputStreamReader(tempResourceInputStream));
192                 
193             resourceOutputStream = new FileOutputStream(resourcesURL);
194             BufferedWriter resourceWriter = new BufferedWriter
195                 (new OutputStreamWriter(resourceOutputStream));
196             String JavaDoc nextLine;
197
198             while( (nextLine = tempResourceReader.readLine()) != null ) {
199                 if( !nextLine.startsWith("#") ) {
200                     resourceWriter.write(nextLine);
201                     resourceWriter.newLine();
202                 }
203             }
204             resourceWriter.close();
205
206         } catch(Exception JavaDoc e) {
207 // IASRI 4660742 e.printStackTrace();
208
// START OF IASRI 4660742
209
_logger.log(Level.SEVERE,"enterprise.resource_exception",e);
210 // END OF IASRI 4660742
211
throw new J2EEResourceException(e);
212         } finally {
213             if( tempResourceOutputStream != null ) {
214                 try {
215                     tempResourceOutputStream.close();
216                 } catch(IOException ioe) {}
217             }
218             if( tempResourceInputStream != null ) {
219                 try {
220                     tempResourceInputStream.close();
221                 } catch(IOException ioe) {}
222             }
223             if( resourceOutputStream != null ) {
224                 try {
225                     resourceOutputStream.close();
226                 } catch(IOException ioe) {}
227             }
228             
229         }
230     }
231
232     public J2EEResource createResource(int type, String JavaDoc name) {
233
234         J2EEResource resource = null;
235
236         switch(type) {
237             case J2EEResource.JMS_DESTINATION :
238                 resource = new JmsDestinationResource(name);
239                 break;
240             case J2EEResource.JMS_CNX_FACTORY :
241                 resource = new JmsCnxFactoryResource(name);
242                 break;
243             case J2EEResource.JDBC_RESOURCE :
244                 resource = new JdbcResource(name);
245                 break;
246             case J2EEResource.JDBC_XA_RESOURCE :
247                 resource = new JdbcXAResource(name);
248                 break;
249             case J2EEResource.JDBC_DRIVER :
250                 resource = new JdbcDriver(name);
251                 break;
252             default :
253                 throw new java.lang.IllegalArgumentException JavaDoc();
254         }
255
256         return resource;
257     }
258
259     public ResourceProperty createProperty(String JavaDoc name) {
260         return new ResourcePropertyImpl(name);
261     }
262
263     /**
264      * Convert properties to an intermediate representation
265      * (RawResourceInfo) that is independent of resource info type.
266      */

267     private List propsToRawResourceInfo(Properties resourceProperties)
268         throws Exception JavaDoc {
269
270         Vector allRawInfo = new Vector();
271         Enumeration propNames = resourceProperties.propertyNames();
272
273         // Input name/value pairs can be one of two types :
274
// resource attributes and resource properties.
275
//
276
// Resource attributes have form
277
// <resourceType>.<index>.<name>=<value>
278
//
279
// Resource properties have form
280
// <resourceType>.<index>.prop.<name>=<value>
281
//
282

283         while(propNames.hasMoreElements()) {
284
285             // Parse resource type and index.
286
String JavaDoc nextProp = (String JavaDoc) propNames.nextElement();
287             StringTokenizer tokenizer = new StringTokenizer(nextProp,
288                                                             FIELD_SEPARATOR);
289
290             String JavaDoc resourceType = tokenizer.nextToken();
291             String JavaDoc numberStr = tokenizer.nextToken();
292             int resourceIndex = Integer.parseInt(numberStr);
293             
294             RawResourceInfo info =
295                 new RawResourceInfo(resourceType, resourceIndex);
296
297             // If new resource, add it to list.
298
int elementIndex = allRawInfo.indexOf(info);
299             if( elementIndex == -1 ) {
300                 allRawInfo.add(info);
301             } else {
302                 info = (RawResourceInfo) allRawInfo.elementAt(elementIndex);
303             }
304             
305             // Parse property/attribute name and vlaue and set
306
// raw info.
307
String JavaDoc key = tokenizer.nextToken();
308             String JavaDoc propValue = (String JavaDoc) resourceProperties.get(nextProp);
309
310             if( key.equals(PROP_INDICATOR) && tokenizer.hasMoreTokens()) {
311                 key = tokenizer.nextToken();
312                 info.getProperties().put(key, propValue);
313             } else {
314                 info.getAttributes().put(key, propValue);
315             }
316         }
317         return allRawInfo;
318     }
319
320     /**
321      * Convert intermediate representation back to a properties
322      * file format.
323      */

324     private void storeRawInfoToPropsFile(List allRawInfo, OutputStream out)
325         throws IOException {
326
327         
328         // Sort resources alphabetically by resource type
329
// and name.
330
Object JavaDoc[] rawInfoArray = allRawInfo.toArray();
331         Arrays.sort(rawInfoArray, new RawInfoSorter());
332
333         // For generating unique resource indexes.
334
Hashtable indexCounters = new Hashtable();
335         
336         for(int rawIndex = 0; rawIndex < rawInfoArray.length; rawIndex++) {
337             RawResourceInfo rawInfo =
338                 (RawResourceInfo) rawInfoArray[rawIndex];
339             String JavaDoc resourceType = rawInfo.getResourceType();
340             Integer JavaDoc index = (Integer JavaDoc) indexCounters.get(resourceType);
341
342             if( index == null ) {
343                 index = new Integer JavaDoc(0);
344             }
345
346             String JavaDoc propNamePrefix =
347                 resourceType + FIELD_SEPARATOR + index + FIELD_SEPARATOR;
348
349             // Increment counter for this resource type
350
indexCounters.put(resourceType,
351                               new Integer JavaDoc(index.intValue() + 1));
352             
353             writeNameValueCollection(out, propNamePrefix,
354                                      rawInfo.getAttributes());
355             
356             writeNameValueCollection(out, propNamePrefix + PROP_INDICATOR +
357                                      FIELD_SEPARATOR,
358                                      rawInfo.getProperties());
359         }
360         return;
361     }
362
363     private void writeNameValueCollection(OutputStream out,
364                                           String JavaDoc prefix,
365                                           Hashtable nameValueCollection)
366         throws IOException {
367
368         // Print key/value pairs alphabetically by key name,
369
// but always put resource's name first.
370
Set entrySet = nameValueCollection.entrySet();
371         Object JavaDoc[] nameValueArray = entrySet.toArray();
372         Arrays.sort(nameValueArray, new NameValueSorter());
373         for(int index = 0; index < nameValueArray.length; index++) {
374             Map.Entry next = (Map.Entry) nameValueArray[index];
375             writeNameValuePair(out, prefix, next.getKey().toString(),
376                                next.getValue().toString());
377         }
378     }
379
380     private void writeNameValuePair(OutputStream out, String JavaDoc prefix,
381                                     String JavaDoc name, String JavaDoc value)
382         throws IOException {
383         // Use properties object so encoding of non-ASCII characters
384
// is handled properly. Only call store for one property
385
// at a time, since properties object has no sorting capability.
386
outputProperties_.clear();
387         outputProperties_.put(prefix + name, value);
388         outputProperties_.store(out, null);
389     }
390                                     
391     private static class RawInfoSorter implements Comparator {
392
393         public int compare(Object JavaDoc o1, Object JavaDoc o2) {
394             
395             int sortResult = EQUAL;
396
397             RawResourceInfo raw1 = (RawResourceInfo) o1;
398             RawResourceInfo raw2 = (RawResourceInfo) o2;
399
400             if( !raw1.equals(raw2) ) {
401                 String JavaDoc type1 = raw1.getResourceType();
402                 String JavaDoc type2 = raw2.getResourceType();
403                 if( type1.equals(type2) ) {
404                     // Sort by name within same type.
405
String JavaDoc name1 =
406                         (String JavaDoc) raw1.getAttributes().get(NAME_ATTRIBUTE);
407                     String JavaDoc name2 =
408                         (String JavaDoc) raw2.getAttributes().get(NAME_ATTRIBUTE);
409                     sortResult = name1.compareTo(name2);
410                 } else {
411                     // Sort different types by resource type name.
412
sortResult = type1.compareTo(type2);
413                 }
414             }
415             return sortResult;
416         }
417     }
418
419     private static class NameValueSorter implements Comparator {
420
421         public int compare(Object JavaDoc o1, Object JavaDoc o2) {
422             
423             int sortResult = EQUAL;
424
425             Map.Entry pair1 = (Map.Entry) o1;
426             Map.Entry pair2 = (Map.Entry) o2;
427
428             if( !pair1.equals(pair2) ) {
429                 String JavaDoc key1 = (String JavaDoc) pair1.getKey();
430                 String JavaDoc key2 = (String JavaDoc) pair2.getKey();
431                 if( key1.equals(NAME_ATTRIBUTE) ) {
432                     sortResult = SORT_BEFORE;
433                 } else if( key2.equals(NAME_ATTRIBUTE) ) {
434                     sortResult = SORT_AFTER;
435                 } else {
436                     sortResult = key1.compareTo(key2);
437                 }
438             }
439             return sortResult;
440         }
441     }
442         
443 }
444
Popular Tags