KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > genimen > djeneric > repository > DjPersistenceManagerFactory


1 /*
2  * Copyright (c) 2001-2005 by Genimen BV (www.genimen.com) All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, is permitted provided that the following conditions are met: -
6  * Redistributions of source code must retain the above copyright notice, this
7  * list of conditions and the following disclaimer. - Redistributions in binary
8  * form must reproduce the above copyright notice, this list of conditions and
9  * the following disclaimer in the documentation and/or other materials
10  * provided with the distribution. - All advertising materials mentioning
11  * features or use of this software must display the following acknowledgment:
12  * "This product includes Djeneric." - Products derived from this software may
13  * not be called "Djeneric" nor may "Djeneric" appear in their names without
14  * prior written permission of Genimen BV. - Redistributions of any form
15  * whatsoever must retain the following acknowledgment: "This product includes
16  * Djeneric."
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL GENIMEN BV, DJENERIC.ORG, OR CONTRIBUTORS
22  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */

30 package com.genimen.djeneric.repository;
31
32 import java.io.BufferedReader JavaDoc;
33 import java.io.BufferedWriter JavaDoc;
34 import java.io.ByteArrayInputStream JavaDoc;
35 import java.io.File JavaDoc;
36 import java.io.FileInputStream JavaDoc;
37 import java.io.FileNotFoundException JavaDoc;
38 import java.io.FileWriter JavaDoc;
39 import java.io.InputStream JavaDoc;
40 import java.io.InputStreamReader JavaDoc;
41 import java.lang.reflect.Constructor JavaDoc;
42 import java.lang.reflect.InvocationTargetException JavaDoc;
43 import java.util.ArrayList JavaDoc;
44 import java.util.Collections JavaDoc;
45
46 import javax.xml.parsers.DocumentBuilder JavaDoc;
47 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
48 import javax.xml.transform.OutputKeys JavaDoc;
49 import javax.xml.transform.Transformer JavaDoc;
50 import javax.xml.transform.TransformerFactory JavaDoc;
51 import javax.xml.transform.dom.DOMSource JavaDoc;
52 import javax.xml.transform.stream.StreamResult JavaDoc;
53
54 import org.w3c.dom.Document JavaDoc;
55 import org.w3c.dom.Element JavaDoc;
56 import org.w3c.dom.NodeList JavaDoc;
57
58 import com.genimen.djeneric.language.Messages;
59 import com.genimen.djeneric.repository.exceptions.DjenericException;
60 import com.genimen.djeneric.repository.exceptions.ObjectNotDefinedException;
61 import com.genimen.djeneric.repository.rdbms.RdbmsPersistenceManager;
62 import com.genimen.djeneric.repository.rdbmsdirect.RdbmsDirectPersistenceManager;
63
64 /**
65  * Description of the Class
66  *
67  * @author Wido Riezebos @created 10 jan 2002
68  */

69 public class DjPersistenceManagerFactory
70 {
71   /**
72    * Description of the Field
73    */

74   public final static String JavaDoc TYPE_POLYMORPH = "Polymorph RDBMS";
75   /**
76    * Description of the Field
77    */

78   public final static String JavaDoc TYPE_DIRECT = "DirectMap RDBMS";
79
80   /**
81    * Description of the Field
82    */

83   public final static String JavaDoc REPOSITORIES = "repositories";
84   /**
85    * Description of the Field
86    */

87   public final static String JavaDoc REPOSITORY_ELEMENT = "repository";
88   /**
89    * Description of the Field
90    */

91   public final static String JavaDoc REPOSITORY_NAME = "name";
92   /**
93    * Description of the Field
94    */

95   public final static String JavaDoc REPOSITORY_LOCATION = "location";
96   /**
97    * Description of the Field
98    */

99   public final static String JavaDoc REPOSITORY_URL = "url";
100   /**
101    * Description of the Field
102    */

103   public final static String JavaDoc REPOSITORY_DRIVER = "driver";
104   /**
105    * Description of the Field
106    */

107   public final static String JavaDoc REPOSITORY_SHARED_CONN = "sharedconnection";
108   /**
109    * Description of the Field
110    */

111   public final static String JavaDoc REPOSITORY_USER = "shareduser";
112   /**
113    * Description of the Field
114    */

115   public final static String JavaDoc REPOSITORY_PASSWORD = "sharedpassword";
116   /**
117    * Description of the Field
118    */

119   public final static String JavaDoc REPOSITORY_TRACELEVEL = "tracelevel";
120
121   private final static String JavaDoc DEFAULT_CONFIGFILE_NAME = "repositories.xml";
122
123   private String JavaDoc _configFileName = DEFAULT_CONFIGFILE_NAME;
124
125   private DjMessenger _messenger = null;
126
127   ArrayList JavaDoc _allRepositoryDescriptors = new ArrayList JavaDoc();
128
129   /**
130    * Constructor for the DjPersistenceManagerFactory object
131    *
132    * @param mainFrame
133    * Description of the Parameter
134    * @param configFileName
135    * Description of the Parameter
136    * @exception DjenericException
137    * Description of the Exception
138    */

139   public DjPersistenceManagerFactory(DjMessenger messenger, String JavaDoc configFileName) throws DjenericException,
140       FileNotFoundException JavaDoc
141   {
142     setMessenger(messenger);
143     _configFileName = configFileName;
144     loadRepositoryDescriptors(configFileName);
145   }
146
147   public DjPersistenceManagerFactory(DjMessenger messenger, InputStream JavaDoc configInputStream) throws DjenericException
148   {
149     setMessenger(messenger);
150     _configFileName = "provided input stream";
151     loadRepositoryDescriptors(configInputStream);
152   }
153
154   /**
155    * Constructor for the DjPersistenceManagerFactory object
156    *
157    * @param mainFrame
158    * Description of the Parameter
159    * @exception DjenericException
160    * Description of the Exception
161    */

162   public DjPersistenceManagerFactory(DjMessenger messenger) throws DjenericException, FileNotFoundException JavaDoc
163   {
164     this(messenger, DEFAULT_CONFIGFILE_NAME);
165   }
166
167   /**
168    * Constructor for the DjPersistenceManagerFactory object
169    *
170    * @param configFileName
171    * Description of the Parameter
172    * @exception DjenericException
173    * Description of the Exception
174    */

175   public DjPersistenceManagerFactory(String JavaDoc configFileName) throws DjenericException, FileNotFoundException JavaDoc
176   {
177     this(null, configFileName);
178   }
179
180   public DjPersistenceManagerFactory(InputStream JavaDoc configStream) throws DjenericException
181   {
182     this(null, configStream);
183   }
184
185   /**
186    * Constructor for the DjPersistenceManagerFactory object
187    *
188    * @exception DjenericException
189    * Description of the Exception
190    */

191   public DjPersistenceManagerFactory() throws DjenericException, FileNotFoundException JavaDoc
192   {
193     this(null, DEFAULT_CONFIGFILE_NAME);
194   }
195
196   /**
197    * Description of the Method
198    *
199    * @return Description of the Return Value
200    * @exception DjenericException
201    * Description of the Exception
202    */

203   public DjPersistenceManager createInstance() throws DjenericException
204   {
205     DjRepositoryDescriptor selected = null;
206     if (_allRepositoryDescriptors.size() == 0)
207     {
208       throw new DjenericException(Messages.getString("DjPersistenceManagerFactory.NoRepositoriesDefinedIn",
209                                                      _configFileName));
210     }
211
212     if (_allRepositoryDescriptors.size() == 1)
213     {
214       selected = (DjRepositoryDescriptor) _allRepositoryDescriptors.get(0);
215     }
216     else
217     {
218       selected = _messenger.selectRepository(getRepositoryDescriptors());
219     }
220     return createInstance(selected);
221   }
222
223   /**
224    * Description of the Method
225    *
226    * @param repositoryName
227    * Description of the Parameter
228    * @return Description of the Return Value
229    * @exception DjenericException
230    * Description of the Exception
231    */

232   public DjPersistenceManager createInstance(String JavaDoc repositoryName) throws DjenericException
233   {
234     return createInstance(getRepositoryDescriptor(repositoryName));
235   }
236
237   public DjPersistenceManager createInstance(String JavaDoc repositoryName, String JavaDoc userid, String JavaDoc password)
238       throws DjenericException
239   {
240     return createInstance(getRepositoryDescriptor(repositoryName), userid, password);
241   }
242
243   public DjPersistenceManager createInstance(DjRepositoryDescriptor rdesc) throws DjenericException
244   {
245     return createInstance(rdesc, null, null);
246   }
247
248   /**
249    * Description of the Method
250    *
251    * @param rdesc
252    * Description of the Parameter
253    * @return Description of the Return Value
254    * @exception DjenericException
255    * Description of the Exception
256    */

257   public DjPersistenceManager createInstance(DjRepositoryDescriptor rdesc, String JavaDoc userid, String JavaDoc password)
258       throws DjenericException
259   {
260     DjPersistenceManager result;
261     if (rdesc.getRepositoryLocation().equals(TYPE_POLYMORPH))
262     {
263       result = new RdbmsPersistenceManager(_messenger, rdesc, userid, password);
264     }
265     else if (rdesc.getRepositoryLocation().equals(TYPE_DIRECT))
266     {
267       result = new RdbmsDirectPersistenceManager(_messenger, rdesc, userid, password);
268     }
269     else
270     {
271       Object JavaDoc mgr = null;
272       try
273       {
274         Class JavaDoc clz = Thread.currentThread().getContextClassLoader().loadClass(rdesc.getRepositoryLocation());
275         Class JavaDoc[] params = new Class JavaDoc[]{DjMessenger.class, DjRepositoryDescriptor.class, String JavaDoc.class, String JavaDoc.class};
276
277         Constructor JavaDoc constructor = clz.getConstructor(params);
278         mgr = constructor.newInstance(new Object JavaDoc[]{_messenger, rdesc, userid, password});
279       }
280       catch (InvocationTargetException JavaDoc ite)
281       {
282         throw new DjenericException(ite.getCause());
283       }
284       catch (Throwable JavaDoc x)
285       {
286         throw new DjenericException(x);
287       }
288
289       if (!(mgr instanceof DjPersistenceManager))
290       {
291         throw new DjenericException("Specified Persistence manager (" + mgr.getClass().getName()
292                                     + ") is not an instance of DjPersistenceManager.");
293       }
294
295       result = (DjPersistenceManager) mgr;
296     }
297
298     return result;
299   }
300
301   /**
302    * Returns the repositoryDescriptors of the DjPersistenceManagerFactory
303    * object
304    *
305    * @return The repositoryDescriptors value
306    */

307   public DjRepositoryDescriptor[] getRepositoryDescriptors()
308   {
309     return (DjRepositoryDescriptor[]) _allRepositoryDescriptors.toArray(new DjRepositoryDescriptor[0]);
310   }
311
312   /**
313    * Returns the repositoryDescriptor of the DjPersistenceManagerFactory object
314    *
315    * @param repositoryName
316    * Description of the Parameter
317    * @return The repositoryDescriptor value
318    * @exception ObjectNotDefinedException
319    * Description of the Exception
320    */

321   public DjRepositoryDescriptor getRepositoryDescriptor(String JavaDoc repositoryName) throws ObjectNotDefinedException
322   {
323     for (int i = 0; i < _allRepositoryDescriptors.size(); i++)
324     {
325       DjRepositoryDescriptor rd = (DjRepositoryDescriptor) _allRepositoryDescriptors.get(i);
326       if (rd.getName().equalsIgnoreCase(repositoryName)) return rd;
327     }
328     throw new ObjectNotDefinedException(Messages.getString("DjPersistenceManagerFactory.RepositoryUndefined",
329                                                            repositoryName));
330   }
331
332   /**
333    * Adds a feature to the RepositoryDescriptor attribute of the
334    * DjPersistenceManagerFactory object
335    *
336    * @param repos
337    * The feature to be added to the RepositoryDescriptor attribute
338    */

339   public void addRepositoryDescriptor(DjRepositoryDescriptor repos)
340   {
341     _allRepositoryDescriptors.add(repos);
342   }
343
344   /**
345    * Description of the Method
346    *
347    * @param repos
348    * Description of the Parameter
349    */

350   public void removeRepositoryDescriptor(DjRepositoryDescriptor repos)
351   {
352     _allRepositoryDescriptors.remove(repos);
353   }
354
355   public void loadRepositoryDescriptors(String JavaDoc configFileName) throws FileNotFoundException JavaDoc, DjenericException
356   {
357     try
358     {
359       File JavaDoc inFile = new File JavaDoc(configFileName);
360       FileInputStream JavaDoc fis = new FileInputStream JavaDoc(inFile);
361
362       loadRepositoryDescriptors(fis);
363     }
364     catch (FileNotFoundException JavaDoc fnf)
365     {
366       throw new FileNotFoundException JavaDoc(Messages.getString("DjPersistenceManagerFactory.CouldNotLoad", configFileName));
367     }
368
369   }
370
371   public void loadRepositoryDescriptors(InputStream JavaDoc configStream) throws DjenericException
372   {
373     StringBuffer JavaDoc src = new StringBuffer JavaDoc(10000);
374     try
375     {
376       _allRepositoryDescriptors.clear();
377       BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(configStream));
378       String JavaDoc ln;
379       while ((ln = br.readLine()) != null)
380       {
381         src.append(ln);
382         src.append("\n");
383       }
384       br.close();
385
386       if (src.toString().trim().length() == 0) return;
387
388       ByteArrayInputStream JavaDoc sr = new ByteArrayInputStream JavaDoc(new String JavaDoc(src).getBytes(DjPersistenceManager.ENCODING_METHOD));
389
390       DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
391       Document JavaDoc xmlDoc = dfactory.newDocumentBuilder().parse(sr);
392
393       NodeList JavaDoc repositories = xmlDoc.getElementsByTagName(REPOSITORY_ELEMENT);
394       for (int d = 0; d < repositories.getLength(); d++)
395       {
396         if (repositories.item(d) instanceof Element JavaDoc)
397         {
398           Element JavaDoc repository = (Element JavaDoc) (repositories.item(d));
399           DjRepositoryDescriptor theRepository = new DjRepositoryDescriptor(repository.getAttribute(REPOSITORY_NAME),
400               repository.getAttribute(REPOSITORY_LOCATION), repository.getAttribute(REPOSITORY_DRIVER), repository
401                   .getAttribute(REPOSITORY_URL));
402           if (repository.getAttribute(REPOSITORY_SHARED_CONN).equalsIgnoreCase("true"))
403           {
404             theRepository.setSharedUser(repository.getAttribute(REPOSITORY_USER));
405             theRepository.setSharedPassword(repository.getAttribute(REPOSITORY_PASSWORD));
406             theRepository.setSharedConnection(true);
407           }
408           theRepository.setTraceLevel(convert2Int(repository.getAttribute(REPOSITORY_TRACELEVEL)));
409           addRepositoryDescriptor(theRepository);
410         }
411       }
412     }
413     catch (Exception JavaDoc e)
414     {
415       throw new DjenericException(e);
416     }
417
418   }
419
420   /**
421    * Description of the Method
422    *
423    * @param configFileName
424    * Description of the Parameter
425    * @exception DjenericException
426    * Description of the Exception
427    */

428   public void saveRepositoryDescriptors(String JavaDoc configFileName) throws DjenericException
429   {
430     try
431     {
432       DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
433       DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
434       Document JavaDoc doc = builder.newDocument();
435
436       Element JavaDoc root = doc.createElement(REPOSITORIES);
437
438       doc.appendChild(root);
439
440       Collections.sort(_allRepositoryDescriptors);
441
442       DjRepositoryDescriptor[] reps = getRepositoryDescriptors();
443       for (int i = 0; i < reps.length; i++)
444       {
445         Element JavaDoc repElem = doc.createElement(REPOSITORY_ELEMENT);
446         repElem.setAttribute(REPOSITORY_NAME, reps[i].getName());
447         repElem.setAttribute(REPOSITORY_LOCATION, reps[i].getRepositoryLocation());
448         repElem.setAttribute(REPOSITORY_DRIVER, reps[i].getDriver());
449         repElem.setAttribute(REPOSITORY_URL, reps[i].getUrl());
450         repElem.setAttribute(REPOSITORY_USER, reps[i].getSharedUser());
451         repElem.setAttribute(REPOSITORY_PASSWORD, reps[i].getSharedPassword());
452         repElem.setAttribute(REPOSITORY_SHARED_CONN, "" + reps[i].isSharedConnection());
453         repElem.setAttribute(REPOSITORY_TRACELEVEL, "" + reps[i].getTraceLevel());
454
455         root.appendChild(repElem);
456       }
457
458       BufferedWriter JavaDoc w = new BufferedWriter JavaDoc(new FileWriter JavaDoc(configFileName));
459
460       Transformer JavaDoc serializer = TransformerFactory.newInstance().newTransformer();
461       serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
462       serializer.setOutputProperty(OutputKeys.INDENT, "yes");
463       serializer.transform(new DOMSource JavaDoc(doc), new StreamResult JavaDoc(w));
464       w.close();
465     }
466     catch (Exception JavaDoc x)
467     {
468       throw new DjenericException(x);
469     }
470   }
471
472   /**
473    * Description of the Method
474    *
475    * @param str
476    * Description of the Parameter
477    * @return Description of the Return Value
478    */

479   protected int convert2Int(String JavaDoc str)
480   {
481     int result = 0;
482     if (str.trim().length() > 0)
483     {
484       result = Integer.parseInt(str);
485     }
486     return result;
487   }
488
489   /**
490    * Sets the mainFrame of the DjPersistenceManagerFactory object
491    *
492    * @param mainFrame
493    * The new mainFrame value
494    */

495   public void setMessenger(DjMessenger messenger)
496   {
497     _messenger = messenger;
498   }
499
500 }
Popular Tags