KickJava   Java API By Example, From Geeks To Geeks.

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


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.ByteArrayInputStream JavaDoc;
33 import java.io.ByteArrayOutputStream JavaDoc;
34 import java.io.InputStream JavaDoc;
35 import java.io.UnsupportedEncodingException JavaDoc;
36 import java.security.MessageDigest JavaDoc;
37 import java.security.NoSuchAlgorithmException JavaDoc;
38 import java.text.SimpleDateFormat JavaDoc;
39 import java.util.ArrayList JavaDoc;
40 import java.util.Arrays JavaDoc;
41 import java.util.Collections JavaDoc;
42 import java.util.Date JavaDoc;
43 import java.util.HashMap JavaDoc;
44 import java.util.Iterator 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.TransformerException JavaDoc;
51 import javax.xml.transform.TransformerFactory JavaDoc;
52 import javax.xml.transform.dom.DOMSource JavaDoc;
53 import javax.xml.transform.stream.StreamResult JavaDoc;
54
55 import org.apache.xpath.XPathAPI;
56 import org.w3c.dom.CDATASection JavaDoc;
57 import org.w3c.dom.Document JavaDoc;
58 import org.w3c.dom.Element JavaDoc;
59 import org.w3c.dom.NodeList JavaDoc;
60 import org.w3c.dom.traversal.NodeIterator;
61
62 import com.genimen.djeneric.language.Messages;
63 import com.genimen.djeneric.repository.exceptions.CatalogException;
64 import com.genimen.djeneric.repository.exceptions.DjenericException;
65 import com.genimen.djeneric.repository.exceptions.LogonException;
66 import com.genimen.djeneric.repository.exceptions.ObjectNotDefinedException;
67 import com.genimen.djeneric.util.DjExtentComparator;
68 import com.genimen.djeneric.util.DjLogger;
69 import com.genimen.djeneric.util.DjProgressDisplayer;
70 import com.genimen.djeneric.util.DjStringComparator;
71 import com.genimen.djeneric.util.DjVersion;
72
73 /**
74  * @author Wido Riezebos @created 25 november 2001
75  */

76 public abstract class DjPersistenceManager implements DjMessenger
77 {
78
79   /////////////////////////////////////////////////////////////////////
80

81   public static final String JavaDoc EMPTY_MODEL_XML_DOC = "<schema></schema>";
82   private static final String JavaDoc ORG_DJENERIC_DOMAINS = "org.djeneric.domains";
83   /**
84    * Encoding method for converting bytes
85    */

86   public final static String JavaDoc ENCODING_METHOD = "Cp1252";
87   public final static String JavaDoc LINE_SEPARATOR = System.getProperty("line.separator", "\n");
88
89   public final static String JavaDoc MAPPING_OBJECT_ID = "object_id";
90   public final static String JavaDoc MAPPING_STR = "str";
91   public final static String JavaDoc MAPPING_NUM = "num";
92   public final static String JavaDoc MAPPING_REL = "rel";
93   public final static String JavaDoc MAPPING_TXT = "txt";
94   public final static String JavaDoc MAPPING_LNG = "lng";
95   public final static String JavaDoc MAPPING_DAT = "dat";
96
97   public final static int MAPPING_COLUMN_COUNT_STR = 30;
98   public final static int MAPPING_COLUMN_COUNT_NUM = 30;
99   public final static int MAPPING_COLUMN_COUNT_REL = 20;
100   public final static int MAPPING_COLUMN_COUNT_TXT = 20;
101   public final static int MAPPING_COLUMN_COUNT_DAT = 20;
102   public final static int MAPPING_COLUMN_COUNT_LNG = 1;
103
104   public final static int MAPPING_ID_COLUMN_SIZE = 15;
105   public final static String JavaDoc INTERNAL_ID_COLUMN_TYPE = "long";
106   public final static int MAPPING_STR_MAX = 250;
107   public final static int MAPPING_NUM_MAX = 15;
108   public final static int MAPPING_TXT_MAX = 4000;
109   public final static int MAPPING_LNG_MAX = 99999999;
110
111   public final static int MAX_INTERNAL_CODE_LENGTH = 10;
112
113   public final static String JavaDoc SCHEMA = "schema";
114   public final static String JavaDoc SCHEMA_HISTORY = "history";
115   public final static String JavaDoc SCHEMA_VERSION = "version";
116   public final static String JavaDoc SCHEMA_STRUCTURE_VERSION = "structureversion";
117   public final static int SCHEMA_STRUCTURE_VERSION_NUMBER = 102;
118
119   public final static String JavaDoc EXTENT_ELEMENT = "extent";
120   public final static String JavaDoc EXTENT_OBJECT_TYPE = "objecttype";
121   public final static String JavaDoc EXTENT_NAME = "name";
122   public final static String JavaDoc EXTENT_SUPER = "super";
123   public final static String JavaDoc EXTENT_ALIAS = "alias";
124   public final static String JavaDoc EXTENT_TITLE = "title";
125   public final static String JavaDoc EXTENT_DESCRIPTOR = "descriptor";
126   public final static String JavaDoc EXTENT_NAME_SINGULAR = "namesingular";
127   public final static String JavaDoc EXTENT_NAME_PLURAL = "nameplural";
128   public final static String JavaDoc EXTENT_LARGE = "large";
129   public final static String JavaDoc EXTENT_TRANSIENT = "transient";
130   public final static String JavaDoc EXTENT_PACKAGE = "package";
131
132   public final static String JavaDoc DESCRIPTION_ELEMENT = "description";
133
134   public final static String JavaDoc PROPERTY_ELEMENT = "property";
135   public final static String JavaDoc PROPERTY_NAME = "name";
136   public final static String JavaDoc PROPERTY_ALIAS = "alias";
137   public final static String JavaDoc PROPERTY_PROMPT = "prompt";
138   public final static String JavaDoc PROPERTY_MAPPING = "mapping";
139   public final static String JavaDoc PROPERTY_TYPE = "type";
140   public final static String JavaDoc PROPERTY_REQUIRED = "required";
141   public final static String JavaDoc PROPERTY_SEQ = "seq";
142   public final static String JavaDoc PROPERTY_SORT_ORDER = "sortorder";
143   public final static String JavaDoc PROPERTY_QUERYABLE = "queryable";
144   public final static String JavaDoc PROPERTY_PART_OF_UID = "partofuid";
145   public final static String JavaDoc PROPERTY_DESCRIPTION = "description";
146   public final static String JavaDoc PROPERTY_DEFAULT_VALUE = "default";
147
148   public final static String JavaDoc RELATION_ELEMENT = "relation";
149   public final static String JavaDoc RELATION_NAME = "name";
150   public final static String JavaDoc RELATION_RESTRICTION = "restriction";
151   public final static String JavaDoc RELATION_DESCRIPTION = "description";
152   public final static String JavaDoc RELATION_MASTEREXTENT = "masterextent";
153   public final static String JavaDoc RELATION_DETAILPROPERTY = "detailproperty";
154   public final static String JavaDoc RELATION_TYPE = "type";
155   public final static String JavaDoc RELATION_UNICITY = "unicity";
156   public final static String JavaDoc RELATION_TYPE_CONTAINS = "contains";
157   public final static String JavaDoc RELATION_TYPE_REFERENCES = "references";
158
159   public final static String JavaDoc DOMAIN_ELEMENT = "domain";
160   public final static String JavaDoc DOMAIN_NAME = "name";
161   public final static String JavaDoc DOMAIN_PACKAGE = "package";
162   public final static String JavaDoc DOMAIN_SUPER = "super";
163   public final static String JavaDoc DOMAIN_LENGTH = "length";
164   public final static String JavaDoc DOMAIN_DECIMALS = "decimals";
165   public final static String JavaDoc DOMAIN_CASE_CONVERSION = "caseconversion";
166   public final static String JavaDoc DOMAIN_DESCRIPTION = "description";
167   public final static String JavaDoc DOMAIN_TYPE = "type";
168   public final static String JavaDoc DOMAIN_COMPONENT = "component";
169   public final static String JavaDoc DOMAIN_ENFORCE = "enforce";
170   public final static String JavaDoc DOMAIN_DISPLAY_WIDTH = "displaywidth";
171   public final static String JavaDoc DOMAIN_DISPLAY_HEIGHT = "displayheight";
172   public final static String JavaDoc DOMAIN_VALUE_ELEMENT = "domainvalue";
173   public final static String JavaDoc DOMAIN_VALUE_SEQ = "seq";
174   public final static String JavaDoc DOMAIN_VALUE_VALUE = "value";
175   public final static String JavaDoc DOMAIN_VALUE_HIGH = "high";
176   public final static String JavaDoc DOMAIN_FORMAT_MASK = "format";
177   public final static String JavaDoc DOMAIN_RE_MASK = "remask";
178   public final static String JavaDoc DOMAIN_RE_FAIL_MSG = "refailmsg";
179   public final static String JavaDoc DOMAIN_VALUE_DESCRIPTION = "description";
180
181   public final static String JavaDoc PACKAGE_ELEMENT = "package";
182   public final static String JavaDoc PACKAGE_NAME = "name";
183
184   public final static String JavaDoc ROLE_ELEMENT = "role";
185   public final static String JavaDoc ROLE_NAME = "name";
186
187   public final static int TRACE_NOTHING = 0;
188   public final static int TRACE_FLOW = 5;
189   public final static int TRACE_INTERNAL = 10;
190   public final static int TRACE_ALL = 100;
191
192   private DjIdProvider _idProvider = null;
193   private boolean _commitAllowed = true;
194   private boolean _useGlobalContext = false;
195   private boolean _checkReferentialIntegrity = true;
196   private String JavaDoc _originalModel = null;
197   private int _traceLevel = TRACE_NOTHING;
198   private int _schemaStructureVersion = 101;
199
200   DjMessenger _messenger;
201   HashMap JavaDoc _extentsByName;
202   HashMap JavaDoc _extentsByInternalCode;
203   HashMap JavaDoc _extentsByObjectType;
204   HashMap JavaDoc _extentsByQualifiedObjectType;
205   HashMap JavaDoc _extentsUnQualifiedClashed;
206   ArrayList JavaDoc _allExtents;
207   ArrayList JavaDoc _allRoles;
208
209   HashMap JavaDoc _domainsByName;
210   ArrayList JavaDoc _allDomains;
211   HashMap JavaDoc _packagesByName = new HashMap JavaDoc();
212   ArrayList JavaDoc _allPackages;
213
214   String JavaDoc _djenericUser = null;
215   String JavaDoc _djenericPassword = null;
216
217   String JavaDoc _repositoryUser = null;
218   String JavaDoc _repositoryPassword = null;
219
220   DjContextManager _contextManager = null;
221   DjRepositoryDescriptor _currentRepository;
222   String JavaDoc _modelLoadLog = "";
223   String JavaDoc _modelHistory = "";
224   int _modelVersion = 0;
225   SimpleDateFormat JavaDoc _traceTimestampFormatter = new SimpleDateFormat JavaDoc("yyyy.MM.dd HH:mm:ss");
226   private static boolean _bannerDisplayed = false;
227
228   static long _internalId = 0;
229
230   /////////////////////////////////////////////////////////////////////
231
/**
232    * Description of the Method
233    *
234    * @return Description of the Return Value
235    * @exception DjenericException
236    * Description of the Exception
237    */

238   protected abstract String JavaDoc retrieveModelXml() throws DjenericException;
239
240   /**
241    * Description of the Method
242    *
243    * @param xml
244    * Description of the Parameter
245    * @exception DjenericException
246    * Description of the Exception
247    */

248   protected abstract void storeModelXml(String JavaDoc xml) throws DjenericException;
249
250   /**
251    * Gets the views of the DjPersistenceManager object
252    *
253    * @return The views value
254    * @exception DjenericException
255    * Description of the Exception
256    */

257   public abstract DjModelView[] getViews() throws DjenericException;
258
259   /**
260    * Description of the Method
261    */

262   public abstract void close();
263
264   /**
265    * Description of the Method
266    *
267    * @return Description of the Return Value
268    * @exception DjenericException
269    * Description of the Exception
270    */

271   public abstract DjSession createSession() throws DjenericException;
272
273   /**
274    * Description of the Method
275    *
276    * @param mgr
277    * Description of the Parameter
278    * @return Description of the Return Value
279    */

280   public abstract DjContextManager createContextManager(DjPersistenceManager mgr);
281
282   /**
283    * Description of the Method
284    *
285    * @param objectType
286    * Description of the Parameter
287    * @param name
288    * Description of the Parameter
289    * @param alias
290    * Description of the Parameter
291    * @param internalCode
292    * Description of the Parameter
293    * @param title
294    * Description of the Parameter
295    * @param nameSingular
296    * Description of the Parameter
297    * @param namePlural
298    * Description of the Parameter
299    * @return Description of the Return Value
300    */

301   public abstract DjExtent createExtent(String JavaDoc objectType, String JavaDoc name, String JavaDoc alias, String JavaDoc internalCode,
302                                         String JavaDoc title, String JavaDoc nameSingular, String JavaDoc namePlural);
303
304   /**
305    * Description of the Method
306    *
307    * @return Description of the Return Value
308    */

309   public abstract DjIdProvider createIdProvider();
310
311   /**
312    * Description of the Method
313    *
314    * @param name
315    * Description of the Parameter
316    * @param masterExtent
317    * Description of the Parameter
318    * @param detailExtent
319    * Description of the Parameter
320    * @param detailProperty
321    * Description of the Parameter
322    * @param isContainedRelation
323    * Description of the Parameter
324    * @param description
325    * Description of the Parameter
326    * @return Description of the Return Value
327    */

328   public abstract DjRelation createRelation(String JavaDoc name, DjExtent masterExtent, DjExtent detailExtent,
329                                             DjProperty detailProperty, boolean isContainedRelation, String JavaDoc description);
330
331   /**
332    * Description of the Method
333    *
334    * @return Description of the Return Value
335    * @exception DjenericException
336    * Description of the Exception
337    */

338   public abstract DjModelView createModelView() throws DjenericException;
339
340   /**
341    * Description of the Method
342    *
343    * @exception CatalogException
344    * Description of the Exception
345    */

346   public abstract void lockModel() throws CatalogException;
347
348   /**
349    * Description of the Method
350    *
351    * @exception CatalogException
352    * Description of the Exception
353    */

354   public abstract void unlockModel() throws CatalogException;
355
356   /**
357    * Description of the Method
358    *
359    * @exception CatalogException
360    * Description of the Exception
361    */

362   public abstract void forceUnlockModel() throws CatalogException;
363
364   /**
365    * Gets the modelLocked of the DjPersistenceManager object
366    *
367    * @return The modelLocked value
368    */

369   public abstract boolean isModelLocked();
370
371   /**
372    * Gets the currentLockTag of the DjPersistenceManager object
373    *
374    * @return The currentLockTag value
375    * @exception CatalogException
376    * Description of the Exception
377    */

378   public abstract String JavaDoc getCurrentLockTag() throws CatalogException;
379
380   /**
381    * Sets the estimatedConcurrentSessions of the DjPersistenceManager object
382    *
383    * @param estimate
384    * The new estimatedConcurrentSessions value
385    */

386   public abstract void setEstimatedConcurrentSessions(int estimate);
387
388   /**
389    * Constructor for the DjPersistenceManager object
390    *
391    * @param mainFrame
392    * Description of the Parameter
393    * @param rdesc
394    * Description of the Parameter
395    * @exception DjenericException
396    * Description of the Exception
397    */

398   public DjPersistenceManager(DjMessenger messenger, DjRepositoryDescriptor rdesc)
399
400   {
401     // Display the banner only once..
402
if (!_bannerDisplayed) DjLogger.log("Running on Djeneric Persistence Manager version " + DjVersion.getVersion());
403     _bannerDisplayed = true;
404     setTraceLevel(rdesc.getTraceLevel());
405
406     if (rdesc.getTraceLevel() != TRACE_NOTHING)
407     {
408       DjLogger.log(Messages.getString("DjPersistenceManager.TraceLevel", String.valueOf(rdesc.getTraceLevel())));
409     }
410
411     if (messenger == null) _messenger = this;
412     else _messenger = messenger;
413
414     _idProvider = createIdProvider();
415     _currentRepository = rdesc;
416     _contextManager = createContextManager(this);
417
418     // All traffic through one uid/pw separate from Djeneric users?
419
if (rdesc.isSharedConnection())
420     {
421       _repositoryUser = rdesc.getSharedUser();
422       _repositoryPassword = rdesc.getSharedPassword();
423
424       // still need to ask for identity of user:
425
_djenericUser = null;
426       _djenericPassword = null;
427     }
428     else
429     {
430       _repositoryUser = rdesc.getUser();
431       // might be null
432
_repositoryPassword = rdesc.getPassword();
433       // might be null
434

435       _djenericUser = rdesc.getUser();
436       // might be null
437
_djenericPassword = rdesc.getPassword();
438       // might be null
439
}
440   }
441
442   /**
443    * Description of the Method
444    *
445    * @exception DjenericException
446    * Description of the Exception
447    */

448   public void loadModel() throws DjenericException
449   {
450     String JavaDoc src = retrieveModelXml();
451     if (src.trim().length() == 0)
452     {
453       src = EMPTY_MODEL_XML_DOC;
454     }
455
456     setOriginalModel(src);
457     rebuildModelDefinition(src);
458   }
459
460   public boolean isModelUpdatedExternally() throws DjenericException
461   {
462     String JavaDoc orgModel = getOriginalModel();
463     if (orgModel == null) orgModel = "";
464
465     String JavaDoc src = retrieveModelXml();
466     if (src == null) src = "";
467
468     return !src.equals(orgModel);
469   }
470
471   public boolean isModelModified() throws DjenericException
472   {
473     String JavaDoc orgModel = getOriginalModel();
474     if (orgModel == null) orgModel = "";
475
476     String JavaDoc src = getModel();
477     if (src == null) src = "";
478
479     return !src.equals(orgModel);
480   }
481
482   /**
483    * Sets the originalModel of the DjPersistenceManager object
484    *
485    * @param orgModel
486    * The new originalModel value
487    */

488   protected void setOriginalModel(String JavaDoc orgModel)
489   {
490     _originalModel = orgModel;
491   }
492
493   /**
494    * Gets the originalModel of the DjPersistenceManager object
495    *
496    * @return The originalModel value
497    */

498   protected String JavaDoc getOriginalModel()
499   {
500     return _originalModel;
501   }
502
503   /**
504    * Gets the modelVersion of the DjPersistenceManager object
505    *
506    * @return The modelVersion value
507    */

508   public int getModelVersion()
509   {
510     return _modelVersion;
511   }
512
513   /**
514    * Sets the modelVersion of the DjPersistenceManager object
515    *
516    * @param version
517    * The new modelVersion value
518    */

519   public void setModelVersion(int version)
520   {
521     _modelVersion = version;
522   }
523
524   /**
525    * Gets the modelHistory of the DjPersistenceManager object
526    *
527    * @return The modelHistory value
528    */

529   public String JavaDoc getModelHistory()
530   {
531     return _modelHistory;
532   }
533
534   /**
535    * Sets the modelHistory of the DjPersistenceManager object
536    *
537    * @param history
538    * The new modelHistory value
539    */

540   public void setModelHistory(String JavaDoc history)
541   {
542     _modelHistory = history;
543   }
544
545   /**
546    * Gets the schemaLoadLog of the DjPersistenceManager object
547    *
548    * @return The schemaLoadLog value
549    */

550   public String JavaDoc getSchemaLoadLog()
551   {
552     return _modelLoadLog.trim();
553   }
554
555   /**
556    * Description of the Method
557    *
558    * @exception DjenericException
559    * Description of the Exception
560    */

561   public void saveModel() throws DjenericException
562   {
563     validateModel(true);
564
565     // Check to see if the model was updated. If so we need to increase the
566
// version number and history
567
String JavaDoc model = getModel();
568     if (!getOriginalModel().equals(model))
569     {
570       setModelVersion(getModelVersion() + 1);
571
572       SimpleDateFormat JavaDoc sf = new SimpleDateFormat JavaDoc("dd-MM-yyyy HH:mm:ss");
573
574       Date JavaDoc date = new Date JavaDoc(System.currentTimeMillis());
575
576       String JavaDoc djuser = getDjenericUser();
577       if (djuser == null) djuser = getRepositoryUser();
578
579       setModelHistory(Messages.getString("DjPersistenceManager.VersionString", String.valueOf(getModelVersion()), sf
580           .format(date), djuser, getConnectionTitle())
581                       + "\n" + getModelHistory());
582       model = getModel();
583     }
584     storeModelXml(model);
585     setOriginalModel(model);
586   }
587
588   /**
589    * Sets the model of the DjPersistenceManager object
590    *
591    * @param modelXml
592    * The new model value
593    * @exception DjenericException
594    * Description of the Exception
595    */

596   public void setModel(String JavaDoc modelXml) throws DjenericException
597   {
598     rebuildModelDefinition(modelXml);
599   }
600
601   public void mergeModel(String JavaDoc modelXml, boolean overwriteExisting) throws DjenericException,
602       UnsupportedEncodingException JavaDoc
603   {
604     InputStream JavaDoc is = new ByteArrayInputStream JavaDoc(modelXml.getBytes(ENCODING_METHOD));
605     mergeModelDefinition(is, overwriteExisting);
606   }
607
608   /**
609    * Sets the model of the DjPersistenceManager object
610    *
611    * @param modelXml
612    * The new model value
613    * @exception DjenericException
614    * Description of the Exception
615    */

616   public void setModel(InputStream JavaDoc modelXml) throws DjenericException
617   {
618     rebuildModelDefinition(modelXml);
619   }
620
621   /**
622    * Sets the checkReferentialIntegrity of the DjPersistenceManager object
623    *
624    * @param b
625    * The new checkReferentialIntegrity value
626    */

627   public void setCheckReferentialIntegrity(boolean b)
628   {
629     _checkReferentialIntegrity = b;
630   }
631
632   /**
633    * Gets the checkReferentialIntegrity of the DjPersistenceManager object
634    *
635    * @return The checkReferentialIntegrity value
636    */

637   public boolean isCheckReferentialIntegrity()
638   {
639     return _checkReferentialIntegrity;
640   }
641
642   /**
643    * Sets the currentContext of the DjPersistenceManager object
644    *
645    * @param ctxt
646    * The new currentContext value
647    */

648   public void setCurrentContext(DjContext ctxt)
649   {
650     getContextManager().setCurrentContext(ctxt);
651   }
652
653   /**
654    * Sets the currentContext of the DjPersistenceManager object
655    *
656    * @param ctxt
657    * The new currentContext value
658    * @exception ObjectNotDefinedException
659    * Description of the Exception
660    * @exception DjenericException
661    * Description of the Exception
662    */

663   public void setCurrentContext(String JavaDoc ctxt) throws ObjectNotDefinedException, DjenericException
664   {
665     getContextManager().setCurrentContext(ctxt);
666   }
667
668   /**
669    * Gets the currentContext of the DjPersistenceManager object
670    *
671    * @return The currentContext value
672    */

673   public DjContext getCurrentContext()
674   {
675     return getContextManager().getCurrentContext();
676   }
677
678   private String JavaDoc nvl(String JavaDoc value)
679   {
680     if (value == null) return "";
681     return value;
682   }
683
684   public String JavaDoc getModel() throws DjenericException
685   {
686     DjExtent[] extents = getExtents();
687     DjDomain[] domains = getDomains();
688     return getModel(extents, domains);
689   }
690
691   public String JavaDoc getModel(DjExtent[] extents) throws DjenericException
692   {
693     DjDomain[] domains = getDomainsUsed(extents);
694     return getModel(extents, domains);
695   }
696
697   public DjDomain[] getDomainsUsed(DjExtent[] extents)
698   {
699     HashMap JavaDoc usedDomains = new HashMap JavaDoc();
700     for (int i = 0; i < extents.length; i++)
701     {
702       DjProperty[] props = extents[i].getPersonalProperties();
703       for (int p = 0; p < props.length; p++)
704       {
705         if (props[p].getType() instanceof DjDomain)
706         {
707           DjDomain dom = (DjDomain) props[p].getType();
708           while (dom != null)
709           {
710             usedDomains.put(dom.getName(), dom);
711             dom = dom.getSuperDomain();
712           }
713         }
714       }
715     }
716     DjDomain[] domains = new DjDomain[usedDomains.size()];
717     Iterator JavaDoc it = usedDomains.keySet().iterator();
718     int i = 0;
719     while (it.hasNext())
720       domains[i++] = (DjDomain) usedDomains.get(it.next());
721     return domains;
722   }
723
724   /**
725    * Gets the model of the DjPersistenceManager object
726    *
727    * @return The model value
728    * @exception DjenericException
729    * Description of the Exception
730    */

731   public String JavaDoc getModel(DjExtent[] extents, DjDomain[] domains) throws DjenericException
732   {
733     try
734     {
735       DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
736       DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
737       Document JavaDoc doc = builder.newDocument();
738
739       Element JavaDoc root = doc.createElement(SCHEMA);
740       root.setAttribute(SCHEMA_STRUCTURE_VERSION, String.valueOf(SCHEMA_STRUCTURE_VERSION_NUMBER));
741
742       doc.appendChild(root);
743
744       updateModelHistory(doc, root);
745
746       for (int i = 0; i < extents.length; i++)
747       {
748         Element JavaDoc extent = doc.createElement(EXTENT_ELEMENT);
749
750         extent.setAttribute(EXTENT_NAME, extents[i].getName());
751         if (extents[i].getSuper() != null) extent.setAttribute(EXTENT_SUPER, extents[i].getSuper().getName());
752         extent.setAttribute(EXTENT_ALIAS, extents[i].getInternalCode());
753         extent.setAttribute(EXTENT_OBJECT_TYPE, extents[i].getObjectType());
754         extent.setAttribute(EXTENT_DESCRIPTOR, extents[i].getPersonalDescriptorExpression());
755         extent.setAttribute(EXTENT_TITLE, extents[i].getTitle());
756         extent.setAttribute(EXTENT_NAME_SINGULAR, extents[i].getNameSingular());
757         extent.setAttribute(EXTENT_NAME_PLURAL, extents[i].getNamePlural());
758         extent.setAttribute(EXTENT_LARGE, String.valueOf(extents[i].isLarge()));
759         extent.setAttribute(EXTENT_TRANSIENT, String.valueOf(extents[i].isTransient()));
760
761         if ((extents[i].getDescription() != null) && (extents[i].getDescription().trim().length() > 0))
762         {
763           Element JavaDoc descrElem = doc.createElement(DESCRIPTION_ELEMENT);
764           CDATASection JavaDoc descr = doc.createCDATASection(extents[i].getDescription());
765           descrElem.appendChild(descr);
766           extent.appendChild(descrElem);
767         }
768
769         if (extents[i].getPackage() != null)
770         {
771           extent.setAttribute(EXTENT_PACKAGE, extents[i].getPackage().getName());
772         }
773
774         root.appendChild(extent);
775
776         DjProperty[] cols = extents[i].getPersonalProperties();
777         for (int c = 0; c < cols.length; c++)
778         {
779           Element JavaDoc property = doc.createElement(PROPERTY_ELEMENT);
780
781           property.setAttribute(PROPERTY_SEQ, "" + cols[c].getSeq());
782           property.setAttribute(PROPERTY_NAME, cols[c].getName());
783           property.setAttribute(PROPERTY_ALIAS, cols[c].getAlias());
784           property.setAttribute(PROPERTY_MAPPING, cols[c].getMapping());
785           property.setAttribute(PROPERTY_PROMPT, cols[c].getPrompt());
786           property.setAttribute(PROPERTY_TYPE, cols[c].getTypeName());
787           property.setAttribute(PROPERTY_REQUIRED, "" + cols[c].isRequired());
788           property.setAttribute(PROPERTY_QUERYABLE, "" + cols[c].isQueryable());
789           property.setAttribute(PROPERTY_PART_OF_UID, "" + cols[c].isPartOfUID());
790           property.setAttribute(PROPERTY_SORT_ORDER, "" + cols[c].getSortOrder());
791           property.setAttribute(PROPERTY_DEFAULT_VALUE, nvl(cols[c].getDefaultValue()));
792           property.setAttribute(PROPERTY_DESCRIPTION, nvl(cols[c].getDescription()));
793
794           extent.appendChild(property);
795         }
796
797         DjRelation[] rels = extents[i].getPersonalMasterRelations();
798         for (int r = 0; r < rels.length; r++)
799         {
800           Element JavaDoc relation = doc.createElement(RELATION_ELEMENT);
801
802           relation.setAttribute(RELATION_NAME, rels[r].getName());
803           relation.setAttribute(RELATION_MASTEREXTENT, rels[r].getMasterExtent().getName());
804           relation.setAttribute(RELATION_DETAILPROPERTY, rels[r].getDetailProperty().getName());
805           relation.setAttribute(RELATION_TYPE, rels[r].isDetailsContained()
806               ? RELATION_TYPE_CONTAINS
807               : RELATION_TYPE_REFERENCES);
808           relation.setAttribute(RELATION_UNICITY, String.valueOf(rels[r].getUnicity()));
809           relation.setAttribute(RELATION_DESCRIPTION, rels[r].getDescription());
810           relation.setAttribute(RELATION_RESTRICTION, rels[r].getRestrictionExpression());
811           extent.appendChild(relation);
812         }
813       }
814
815       for (int i = 0; i < domains.length; i++)
816       {
817         if (domains[i].isDynamic()) continue;
818
819         Element JavaDoc domain = doc.createElement(DOMAIN_ELEMENT);
820
821         domain.setAttribute(DOMAIN_NAME, domains[i].getName());
822         if (domains[i].getPackage() != null) domain.setAttribute(DOMAIN_PACKAGE, domains[i].getPackage().getName());
823         domain.setAttribute(DOMAIN_TYPE, domains[i].getNativeType());
824         domain.setAttribute(DOMAIN_LENGTH, "" + domains[i].getLength());
825         domain.setAttribute(DOMAIN_DECIMALS, "" + domains[i].getDecimals());
826         domain.setAttribute(DOMAIN_ENFORCE, "" + domains[i].isEnforced());
827         domain.setAttribute(DOMAIN_FORMAT_MASK, domains[i].getFormatMask());
828         domain.setAttribute(DOMAIN_CASE_CONVERSION, domains[i].getCaseConversion());
829         domain.setAttribute(DOMAIN_RE_MASK, (domains[i].getReValidationMask() == null ? "" : domains[i]
830             .getReValidationMask()));
831         domain.setAttribute(DOMAIN_RE_FAIL_MSG, (domains[i].getReFailureMessage() == null ? "" : domains[i]
832             .getReFailureMessage()));
833         domain.setAttribute(DOMAIN_COMPONENT, domains[i].getComponentTypeName());
834         domain.setAttribute(DOMAIN_DESCRIPTION, domains[i].getDescription());
835         if (domains[i].getSuperDomain() != null)
836         {
837           domain.setAttribute(DOMAIN_SUPER, domains[i].getSuperDomain().getName());
838         }
839         domain.setAttribute(DOMAIN_DISPLAY_WIDTH, "" + domains[i].getDisplayWidth());
840         domain.setAttribute(DOMAIN_DISPLAY_HEIGHT, "" + domains[i].getDisplayHeight());
841
842         root.appendChild(domain);
843
844         DjDomainValue[] dova = (DjDomainValue[]) domains[i].getPersonalDomainValues().toArray(new DjDomainValue[0]);
845         for (int d = 0; d < dova.length; d++)
846         {
847           Element JavaDoc valel = doc.createElement(DOMAIN_VALUE_ELEMENT);
848           valel.setAttribute(DOMAIN_VALUE_DESCRIPTION, dova[d].getDescription());
849           if (dova[d].isRange())
850           {
851             valel.setAttribute(DOMAIN_VALUE_VALUE, "" + dova[d].getValue());
852             valel.setAttribute(DOMAIN_VALUE_HIGH, "" + dova[d].getHigh());
853           }
854           else
855           {
856             valel.setAttribute(DOMAIN_VALUE_VALUE, dova[d].getValue().toString());
857           }
858           valel.setAttribute(DOMAIN_VALUE_SEQ, "" + dova[d].getSeq());
859           domain.appendChild(valel);
860         }
861       }
862
863       DjPackage[] packages = getPackages();
864
865       for (int i = 0; i < packages.length; i++)
866       {
867         Element JavaDoc pack = doc.createElement(PACKAGE_ELEMENT);
868         pack.setAttribute(PACKAGE_NAME, packages[i].getName());
869         root.appendChild(pack);
870       }
871
872       for (int i = 0; i < _allRoles.size(); i++)
873       {
874         Element JavaDoc role = doc.createElement(ROLE_ELEMENT);
875         role.setAttribute(ROLE_NAME, _allRoles.get(i).toString());
876         root.appendChild(role);
877       }
878
879       ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
880
881       Transformer JavaDoc serializer = TransformerFactory.newInstance().newTransformer();
882       serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
883       serializer.setOutputProperty(OutputKeys.INDENT, "yes");
884       serializer.transform(new DOMSource JavaDoc(doc), new StreamResult JavaDoc(baos));
885       return baos.toString();
886     }
887     catch (Exception JavaDoc x)
888     {
889       throw new DjenericException(x);
890     }
891   }
892
893   /**
894    * Sets the commitAllowed of the DjPersistenceManager object
895    *
896    * @param b
897    * The new commitAllowed value
898    */

899   public void setCommitAllowed(boolean b)
900   {
901     _commitAllowed = b;
902   }
903
904   /**
905    * Gets the commitAllowed of the DjPersistenceManager object
906    *
907    * @return The commitAllowed value
908    */

909   public boolean isCommitAllowed()
910   {
911     return _commitAllowed;
912   }
913
914   /**
915    * Description of the Method
916    *
917    * @param schema
918    * Description of the Parameter
919    * @exception DjenericException
920    * Description of the Exception
921    */

922   protected void createDomainsFromModel(Element JavaDoc schema) throws DjenericException
923   {
924     _allDomains.addAll(getDomainsFromModel(schema));
925     updateHashes();
926   }
927
928   protected ArrayList JavaDoc getDomainsFromModel(Element JavaDoc schema) throws DjenericException
929   {
930     ArrayList JavaDoc result = new ArrayList JavaDoc();
931     HashMap JavaDoc resultHashed = new HashMap JavaDoc();
932
933     NodeList JavaDoc domains = schema.getElementsByTagName(DOMAIN_ELEMENT);
934     for (int d = 0; d < domains.getLength(); d++)
935     {
936       if (domains.item(d) instanceof Element JavaDoc)
937       {
938         Element JavaDoc domain = (Element JavaDoc) (domains.item(d));
939         DjDomain theDomain = new DjDomain(domain.getAttribute(DOMAIN_NAME), domain.getAttribute(DOMAIN_TYPE),
940             convert2Int(domain.getAttribute(DOMAIN_LENGTH)), convert2Int(domain.getAttribute(DOMAIN_DECIMALS)), domain
941                 .getAttribute(DOMAIN_FORMAT_MASK), domain.getAttribute(DOMAIN_DESCRIPTION), convert2bool(domain
942                 .getAttribute(DOMAIN_ENFORCE)));
943         theDomain.setComponentType(domain.getAttribute(DOMAIN_COMPONENT));
944         theDomain.setDisplayWidth(convert2Int(domain.getAttribute(DOMAIN_DISPLAY_WIDTH)));
945         theDomain.setDisplayHeight(convert2Int(domain.getAttribute(DOMAIN_DISPLAY_HEIGHT)));
946         theDomain.setReValidationMask(domain.getAttribute(DOMAIN_RE_MASK));
947         theDomain.setReFailureMessage(domain.getAttribute(DOMAIN_RE_FAIL_MSG));
948         theDomain.setCaseConversion(nvl(domain.getAttribute(DOMAIN_CASE_CONVERSION), DjDomain.CASE_NONE));
949
950         String JavaDoc packageName = domain.getAttribute(DOMAIN_PACKAGE);
951         if (packageName != null && packageName.trim().length() > 0)
952         {
953           theDomain.setPackage(getOrCreatePackage(packageName));
954         }
955
956         result.add(theDomain);
957         resultHashed.put(theDomain.getName(), theDomain);
958
959         NodeList JavaDoc values = domain.getElementsByTagName(DOMAIN_VALUE_ELEMENT);
960         for (int idx = 0; idx < values.getLength(); idx++)
961         {
962           if (values.item(idx) instanceof Element JavaDoc)
963           {
964             Element JavaDoc dova = (Element JavaDoc) (values.item(idx));
965             if (!dova.getAttribute(DOMAIN_VALUE_HIGH).equals(""))
966             {
967               // ranged?
968
if (isValidInteger(dova.getAttribute(DOMAIN_VALUE_VALUE))
969                   && isValidInteger(dova.getAttribute(DOMAIN_VALUE_HIGH)))
970               {
971                 DjDomainValue dv = new DjDomainValue(theDomain, dova.getAttribute(DOMAIN_VALUE_VALUE), dova
972                     .getAttribute(DOMAIN_VALUE_HIGH), dova.getAttribute(DOMAIN_VALUE_DESCRIPTION));
973                 dv.setSeq(convert2Int(dova.getAttribute(DOMAIN_VALUE_SEQ)));
974                 theDomain.addDomainValue(dv);
975               }
976             }
977             else
978             {
979               DjDomainValue dv = new DjDomainValue(theDomain, dova.getAttribute(DOMAIN_VALUE_VALUE), dova
980                   .getAttribute(DOMAIN_VALUE_DESCRIPTION));
981               dv.setSeq(convert2Int(dova.getAttribute(DOMAIN_VALUE_SEQ)));
982               theDomain.addDomainValue(dv);
983             }
984           }
985         }
986         theDomain.sort();
987       }
988     }
989
990     // Now fix the inheritance of domains
991
domains = schema.getElementsByTagName(DOMAIN_ELEMENT);
992     for (int d = 0; d < domains.getLength(); d++)
993     {
994       if (domains.item(d) instanceof Element JavaDoc)
995       {
996         Element JavaDoc domain = (Element JavaDoc) (domains.item(d));
997         String JavaDoc superName = domain.getAttribute(DOMAIN_SUPER);
998         if (superName.length() > 0)
999         {
1000          DjDomain theDomain = (DjDomain) resultHashed.get(domain.getAttribute(DOMAIN_NAME));
1001          DjDomain theSuper = (DjDomain) resultHashed.get(superName);
1002          if (theSuper == null)
1003          {
1004            try
1005            {
1006              theSuper = getDomain(superName);
1007            }
1008            catch (ObjectNotDefinedException onde)
1009            {
1010              _modelLoadLog += Messages.getString("DjPersistenceManager.SuperDomainNotDefined", superName, theDomain
1011                  .getName());
1012            }
1013          }
1014          theDomain.setSuperDomain(theSuper);
1015        }
1016      }
1017    }
1018
1019    return result;
1020  }
1021
1022  protected ArrayList JavaDoc getRolesFromModel(Element JavaDoc schema) throws TransformerException JavaDoc
1023  {
1024    ArrayList JavaDoc result = new ArrayList JavaDoc();
1025
1026    NodeIterator roles = XPathAPI.selectNodeIterator(schema, "/schema/role");
1027    Element JavaDoc role;
1028    while ((role = (Element JavaDoc) roles.nextNode()) != null)
1029    {
1030      result.add(role.getAttribute("name").toLowerCase());
1031    }
1032    return result;
1033  }
1034
1035  protected void createPackagesFromModel(Element JavaDoc schema) throws DjenericException
1036  {
1037    ArrayList JavaDoc inModel = getPackagesFromModel(schema);
1038    Iterator JavaDoc it = inModel.iterator();
1039    while (it.hasNext())
1040    {
1041      DjPackage pack = (DjPackage) it.next();
1042      try
1043      {
1044        getPackage(pack.getName());
1045      }
1046      catch (ObjectNotDefinedException onde)
1047      {
1048        _allPackages.add(pack);
1049      }
1050    }
1051
1052    updatePackageHashes();
1053  }
1054
1055  protected ArrayList JavaDoc getPackagesFromModel(Element JavaDoc schema) throws DjenericException
1056  {
1057    ArrayList JavaDoc result = new ArrayList JavaDoc();
1058
1059    NodeList JavaDoc packages = schema.getElementsByTagName(PACKAGE_ELEMENT);
1060    for (int d = 0; d < packages.getLength(); d++)
1061    {
1062      if (packages.item(d) instanceof Element JavaDoc)
1063      {
1064        Element JavaDoc pack = (Element JavaDoc) (packages.item(d));
1065        String JavaDoc name = pack.getAttribute(PACKAGE_NAME);
1066        DjPackage thePackage = new DjPackage(name);
1067        result.add(thePackage);
1068      }
1069    }
1070
1071    return result;
1072  }
1073
1074  /**
1075   * Description of the Method
1076   *
1077   * @param schema
1078   * Description of the Parameter
1079   */

1080  protected void fetchModelHistory(Element JavaDoc schema)
1081  {
1082    _modelHistory = null;
1083
1084    NodeList JavaDoc descr = schema.getElementsByTagName(SCHEMA_HISTORY);
1085    for (int idx = 0; idx < descr.getLength(); idx++)
1086    {
1087      Element JavaDoc o = (Element JavaDoc) descr.item(idx);
1088      NodeList JavaDoc nl = o.getChildNodes();
1089      for (int x = 0; x < nl.getLength(); x++)
1090      {
1091        if (nl.item(x) instanceof CDATASection JavaDoc)
1092        {
1093          CDATASection JavaDoc d = (CDATASection JavaDoc) nl.item(x);
1094          _modelHistory = d.getData();
1095        }
1096      }
1097    }
1098
1099    if (_modelHistory == null) _modelHistory = "";
1100    _modelVersion = convert2Int(schema.getAttribute(SCHEMA_VERSION));
1101  }
1102
1103  /**
1104   * Description of the Method
1105   *
1106   * @param doc
1107   * Description of the Parameter
1108   * @param schema
1109   * Description of the Parameter
1110   */

1111  protected void updateModelHistory(Document JavaDoc doc, Element JavaDoc schema)
1112  {
1113    Element JavaDoc descrElem = doc.createElement(SCHEMA_HISTORY);
1114    CDATASection JavaDoc descr = doc.createCDATASection(_modelHistory);
1115    descrElem.appendChild(descr);
1116    schema.appendChild(descrElem);
1117
1118    schema.setAttribute(SCHEMA_VERSION, "" + _modelVersion);
1119  }
1120
1121  /**
1122   * Description of the Method
1123   *
1124   * @param schema
1125   * Description of the Parameter
1126   * @exception DjenericException
1127   * Description of the Exception
1128   */

1129  protected void createExtentsFromModel(Element JavaDoc schema, boolean overwriteExisting) throws DjenericException
1130  {
1131    updateHashes();
1132    HashMap JavaDoc ignoreList = new HashMap JavaDoc();
1133
1134    NodeList JavaDoc extents = schema.getElementsByTagName(EXTENT_ELEMENT);
1135    for (int t = 0; t < extents.getLength(); t++)
1136    {
1137      if (extents.item(t) instanceof Element JavaDoc)
1138      {
1139        Element JavaDoc extent = (Element JavaDoc) (extents.item(t));
1140        DjExtent theExtent = createExtent(extent.getAttribute(EXTENT_OBJECT_TYPE), extent.getAttribute(EXTENT_NAME),
1141                                          extent.getAttribute(EXTENT_ALIAS), extent.getAttribute(EXTENT_ALIAS), extent
1142                                              .getAttribute(EXTENT_TITLE), extent.getAttribute(EXTENT_NAME_SINGULAR),
1143                                          extent.getAttribute(EXTENT_NAME_PLURAL));
1144        theExtent.setDescriptorExpression(extent.getAttribute(EXTENT_DESCRIPTOR));
1145        theExtent.setLarge(Boolean.valueOf(extent.getAttribute(EXTENT_LARGE)).booleanValue());
1146        theExtent.setTransient(Boolean.valueOf(extent.getAttribute(EXTENT_TRANSIENT)).booleanValue());
1147
1148        String JavaDoc packageName = extent.getAttribute(EXTENT_PACKAGE);
1149        if (packageName != null && packageName.trim().length() > 0)
1150        {
1151          theExtent.setPackage(getOrCreatePackage(packageName));
1152        }
1153
1154        NodeList JavaDoc descr = extent.getElementsByTagName(DESCRIPTION_ELEMENT);
1155        for (int idx = 0; idx < descr.getLength(); idx++)
1156        {
1157          Element JavaDoc o = (Element JavaDoc) descr.item(idx);
1158
1159          NodeList JavaDoc nl = o.getChildNodes();
1160          for (int x = 0; x < nl.getLength(); x++)
1161          {
1162            if (nl.item(x) instanceof CDATASection JavaDoc)
1163            {
1164              CDATASection JavaDoc d = (CDATASection JavaDoc) nl.item(x);
1165              theExtent.setDescription(d.getData());
1166            }
1167          }
1168        }
1169
1170        try
1171        {
1172          DjExtent existing = getExtent(theExtent.getName());
1173          if (overwriteExisting)
1174          {
1175            theExtent.copyInto(existing);
1176            String JavaDoc msg = Messages.getString("DjPersistenceManager.ExtentOverwritten", theExtent.getName());
1177            _modelLoadLog += msg + "\n";
1178
1179          }
1180          else ignoreList.put(theExtent.getName(), null);
1181        }
1182        catch (ObjectNotDefinedException onde)
1183        {
1184          _allExtents.add(theExtent);
1185        }
1186      }
1187    }
1188
1189    updateHashes();
1190    // do this now, 'cause hashes are used below
1191

1192    // now create the properties
1193
extents = schema.getElementsByTagName(EXTENT_ELEMENT);
1194    for (int t = 0; t < extents.getLength(); t++)
1195    {
1196      if (extents.item(t) instanceof Element JavaDoc)
1197      {
1198        Element JavaDoc extent = (Element JavaDoc) (extents.item(t));
1199        DjExtent theExtent = (DjExtent) _extentsByName.get(extent.getAttribute(EXTENT_NAME).toLowerCase());
1200
1201        if (ignoreList.containsKey(theExtent.getName())) continue;
1202
1203        NodeList JavaDoc properties = extent.getElementsByTagName(PROPERTY_ELEMENT);
1204        for (int c = 0; c < properties.getLength(); c++)
1205        {
1206          if (properties.item(c) instanceof Element JavaDoc)
1207          {
1208            Element JavaDoc property = (Element JavaDoc) (properties.item(c));
1209
1210            DjPropertyType propType = null;
1211            try
1212            {
1213              propType = getType(property.getAttribute(PROPERTY_TYPE));
1214            }
1215            catch (Exception JavaDoc x)
1216            {
1217              propType = getTypeByMapping(property.getAttribute(PROPERTY_MAPPING));
1218              String JavaDoc msg = Messages.getString("DjPersistenceManager.PropTypeUnresolved", property
1219                  .getAttribute(PROPERTY_TYPE));
1220              _modelLoadLog += msg + "\n";
1221              System.err.println(msg);
1222            }
1223
1224            DjProperty theProperty = new DjProperty(property.getAttribute(PROPERTY_NAME), property
1225                .getAttribute(PROPERTY_MAPPING), property.getAttribute(PROPERTY_ALIAS), property
1226                .getAttribute(PROPERTY_PROMPT), propType, convert2bool(property.getAttribute(PROPERTY_REQUIRED)),
1227                convert2Int(property.getAttribute(PROPERTY_SEQ)), property.getAttribute(PROPERTY_DEFAULT_VALUE),
1228                property.getAttribute(PROPERTY_DESCRIPTION));
1229
1230            theProperty.setSortOrder(convert2Int(property.getAttribute(PROPERTY_SORT_ORDER)));
1231            theProperty.setPartOfUID(convert2bool(property.getAttribute(PROPERTY_PART_OF_UID)));
1232            theProperty.setQueryable(convert2bool(property.getAttribute(PROPERTY_QUERYABLE)));
1233            theExtent.addProperty(theProperty);
1234          }
1235        }
1236        theExtent.sortProperties();
1237      }
1238    }
1239
1240    // Now process the details definitions
1241
extents = schema.getElementsByTagName(EXTENT_ELEMENT);
1242    for (int t = 0; t < extents.getLength(); t++)
1243    {
1244      if (extents.item(t) instanceof Element JavaDoc)
1245      {
1246        Element JavaDoc extent = (Element JavaDoc) (extents.item(t));
1247
1248        DjExtent theExtent = (DjExtent) _extentsByName.get(extent.getAttribute(EXTENT_NAME).toLowerCase());
1249        NodeList JavaDoc masters = extent.getElementsByTagName(RELATION_ELEMENT);
1250        for (int c = 0; c < masters.getLength(); c++)
1251        {
1252          if (masters.item(c) instanceof Element JavaDoc)
1253          {
1254            Element JavaDoc master = (Element JavaDoc) (masters.item(c));
1255            String JavaDoc masterE = master.getAttribute(RELATION_MASTEREXTENT).toLowerCase();
1256            DjExtent masterExtent = (DjExtent) _extentsByName.get(masterE);
1257
1258            if (masterExtent == null)
1259            {
1260              String JavaDoc msg = Messages.getString("DjPersistenceManager.InvalidMaster", theExtent.getName(), masterE);
1261              _modelLoadLog += msg + "\n";
1262              System.err.println(msg);
1263              continue;
1264            }
1265            DjRelation rel = createRelation(master.getAttribute(RELATION_NAME), masterExtent, theExtent, theExtent
1266                .getProperty(master.getAttribute(RELATION_DETAILPROPERTY)), master.getAttribute(RELATION_TYPE)
1267                .equals(RELATION_TYPE_CONTAINS), master.getAttribute(RELATION_DESCRIPTION));
1268            String JavaDoc unicity = master.getAttribute(RELATION_UNICITY);
1269            if (unicity == null || unicity.trim().length() == 0) unicity = String.valueOf(DjRelation.ONE_TO_MANY);
1270            rel.setUnicity(Integer.parseInt(unicity));
1271            theExtent.addMasterRelation(rel);
1272            masterExtent.addDetailRelation(rel);
1273          }
1274        }
1275      }
1276    }
1277
1278    // Now process the super (inheritance) tree AND
1279
// process the restrictions; this must be in a separate phase because the
1280
// relations must
1281
// all be present to be able to parse the restrictions correctly.
1282
extents = schema.getElementsByTagName(EXTENT_ELEMENT);
1283    for (int t = 0; t < extents.getLength(); t++)
1284    {
1285      if (extents.item(t) instanceof Element JavaDoc)
1286      {
1287        Element JavaDoc extent = (Element JavaDoc) (extents.item(t));
1288
1289        DjExtent theExtent = (DjExtent) _extentsByName.get(extent.getAttribute(EXTENT_NAME).toLowerCase());
1290
1291        // Set the super if applicable:
1292
if (extent.getAttribute(EXTENT_SUPER) != null && extent.getAttribute(EXTENT_SUPER).trim().length() > 0)
1293        {
1294          theExtent.setSuper(getExtent(extent.getAttribute(EXTENT_SUPER)));
1295        }
1296
1297        NodeList JavaDoc masters = extent.getElementsByTagName(RELATION_ELEMENT);
1298        for (int c = 0; c < masters.getLength(); c++)
1299        {
1300          if (masters.item(c) instanceof Element JavaDoc)
1301          {
1302            Element JavaDoc master = (Element JavaDoc) (masters.item(c));
1303            String JavaDoc masterE = master.getAttribute(RELATION_MASTEREXTENT).toLowerCase();
1304            DjExtent masterExtent = (DjExtent) _extentsByName.get(masterE);
1305            if (masterExtent == null)
1306            {
1307              String JavaDoc msg = Messages.getString("DjPersistenceManager.InvalidRel", masterE, master
1308                  .getAttribute(RELATION_NAME));
1309              _modelLoadLog += msg + "\n";
1310              System.err.println(msg);
1311              continue;
1312            }
1313            DjRelation rel = masterExtent.getDetailRelation(master.getAttribute(RELATION_NAME));
1314            rel.setRestrictionExpression(master.getAttribute(RELATION_RESTRICTION));
1315            try
1316            {
1317              rel.getRestriction();
1318            }
1319            catch (Exception JavaDoc x)
1320            {
1321              // This is just to force the restriction to be created
1322
// if this fails do not abort loading since this will disable the
1323
// persistence manager entirely; no tools will work anymore
1324
// and we will try to avoid that!
1325
System.err.println(Messages.getString("global.InvalidRestriction", rel.getDetailExtent().getName() + "."
1326                                                                                 + rel.getName(), x.getMessage()));
1327            }
1328          }
1329        }
1330      }
1331    }
1332
1333    updateHashes();
1334
1335    DjExtent[] xs = getExtents();
1336    for (int i = 0; i < xs.length; i++)
1337    {
1338      // Now the super is set, check to make sure
1339
// that 1 property maps to object_id
1340
try
1341      {
1342        xs[i].updateHashes();
1343
1344        xs[i].getPropertyByMapping(MAPPING_OBJECT_ID);
1345      }
1346      catch (Exception JavaDoc x)
1347      {
1348        String JavaDoc msg = Messages.getString("global.IdNotMapped", xs[i].getName(), MAPPING_OBJECT_ID);
1349        _modelLoadLog += msg + "\n";
1350        System.err.println(msg);
1351      }
1352    }
1353  }
1354
1355  public void rebuildModelDefinition(String JavaDoc schemaDefinitionXml) throws DjenericException
1356  {
1357    try
1358    {
1359      rebuildModelDefinition(new ByteArrayInputStream JavaDoc(schemaDefinitionXml.getBytes(ENCODING_METHOD)));
1360    }
1361    catch (Exception JavaDoc x)
1362    {
1363      throw new DjenericException(x);
1364    }
1365  }
1366
1367  /**
1368   * Description of the Method
1369   *
1370   * @param schemaDefinitionXml
1371   * Description of the Parameter
1372   * @exception DjenericException
1373   * Description of the Exception
1374   */

1375  public void rebuildModelDefinition(InputStream JavaDoc schemaDefinitionXml) throws DjenericException
1376  {
1377    _allExtents = new ArrayList JavaDoc();
1378    _allDomains = new ArrayList JavaDoc();
1379    _allPackages = new ArrayList JavaDoc();
1380    _modelLoadLog = "";
1381
1382    try
1383    {
1384      DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
1385      Document JavaDoc xmlDoc = dfactory.newDocumentBuilder().parse(schemaDefinitionXml);
1386
1387      Element JavaDoc schema = (Element JavaDoc) xmlDoc.getElementsByTagName(SCHEMA).item(0);
1388      setSchemaStructureVersion(schema.getAttribute(SCHEMA_STRUCTURE_VERSION));
1389
1390      createDynamicDomains();
1391
1392      createPackagesFromModel(schema);
1393      _allRoles = getRolesFromModel(schema);
1394      createDomainsFromModel(schema);
1395      completeDomains();
1396      createExtentsFromModel(schema, true);
1397      fetchModelHistory(schema);
1398
1399      updateDynamicDomains();
1400      deleteInvalidRelationProperties();
1401
1402      updateHashes();
1403    }
1404    catch (Exception JavaDoc x)
1405    {
1406      throw new DjenericException(x);
1407    }
1408  }
1409
1410  public void mergeModelDefinition(InputStream JavaDoc schemaDefinitionXml, boolean overwriteExisting) throws DjenericException
1411  {
1412    _modelLoadLog = "";
1413
1414    try
1415    {
1416      DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance();
1417      Document JavaDoc xmlDoc = dfactory.newDocumentBuilder().parse(schemaDefinitionXml);
1418
1419      Element JavaDoc schema = (Element JavaDoc) xmlDoc.getElementsByTagName(SCHEMA).item(0);
1420
1421      if (schema != null)
1422      {
1423        ArrayList JavaDoc packs = getPackagesFromModel(schema);
1424        Iterator JavaDoc it = packs.iterator();
1425        while (it.hasNext())
1426        {
1427          DjPackage pack = (DjPackage) it.next();
1428          try
1429          {
1430            getPackage(pack.getName());
1431          }
1432          catch (ObjectNotDefinedException onde)
1433          {
1434            addPackage(pack);
1435          }
1436        }
1437
1438        ArrayList JavaDoc roles = getRolesFromModel(schema);
1439        it = roles.iterator();
1440        while (it.hasNext())
1441        {
1442          String JavaDoc role = (String JavaDoc) it.next();
1443          if (!_allRoles.contains(role)) _allRoles.add(role);
1444        }
1445
1446        ArrayList JavaDoc doms = getDomainsFromModel(schema);
1447        it = doms.iterator();
1448        while (it.hasNext())
1449        {
1450          DjDomain dom = (DjDomain) it.next();
1451          try
1452          {
1453            getDomain(dom.getName());
1454          }
1455          catch (ObjectNotDefinedException onde)
1456          {
1457            addDomain(dom);
1458          }
1459        }
1460
1461        updateHashes();
1462
1463        // Now all domains should be present in the model; BUT
1464
// there may be references to super domains that are outside
1465
// the model. So to make sure update the super references
1466
it = doms.iterator();
1467        while (it.hasNext())
1468        {
1469          DjDomain dom = (DjDomain) it.next();
1470          try
1471          {
1472            DjDomain existing = getDomain(dom.getName());
1473            if (overwriteExisting)
1474            {
1475              String JavaDoc msg = Messages.getString("DjPersistenceManager.DomainOverwritten", dom.getName());
1476              _modelLoadLog += msg + "\n";
1477
1478              String JavaDoc superName = null;
1479              if (dom.getSuperDomain() != null) superName = dom.getSuperDomain().getName();
1480              dom.copyInto(existing);
1481              if (superName != null)
1482              {
1483                dom.setSuperDomain(getDomain(superName));
1484              }
1485            }
1486          }
1487          catch (ObjectNotDefinedException onde)
1488          {
1489            // Cannot ever occur
1490
}
1491        }
1492
1493        createExtentsFromModel(schema, overwriteExisting);
1494      }
1495
1496      updateHashes();
1497      deleteInvalidRelationProperties();
1498    }
1499    catch (Exception JavaDoc x)
1500    {
1501      throw new DjenericException(x);
1502    }
1503  }
1504
1505  public void deleteInvalidRelationProperties()
1506  {
1507    DjExtent[] extents = getExtents();
1508    for (int i = 0; i < extents.length; i++)
1509      extents[i].deleteInvalidRelationProperties();
1510  }
1511
1512  private void createDynamicDomains() throws DjenericException
1513  {
1514    DjDomain extents = new DjDomain("_extents", "String", 100, 0, "", Messages
1515        .getString("DjPersistenceManager.DomainsExtent"), true);
1516    extents.setDynamic(true);
1517    extents.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1518    addDomain(extents);
1519
1520    DjDomain classes = new DjDomain("_classes", "String", 100, 0, "", Messages
1521        .getString("DjPersistenceManager.DomainsClass"), true);
1522    classes.setDynamic(true);
1523    classes.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1524    addDomain(classes);
1525
1526    DjDomain types = new DjDomain("_types", "String", 100, 0, "", Messages
1527        .getString("DjPersistenceManager.DomainsType"), true);
1528    types.setDynamic(true);
1529    types.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1530    addDomain(types);
1531
1532    DjDomain domains = new DjDomain("_domains", "String", 100, 0, "", Messages
1533        .getString("DjPersistenceManager.DomainsDomains"), true);
1534    domains.setDynamic(true);
1535    domains.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1536    addDomain(domains);
1537    updateHashes();
1538  }
1539
1540  private void updateDynamicDomains() throws DjenericException
1541  {
1542    int seq = 10;
1543
1544    DjDomain extents = getDomain("_extents");
1545    DjExtent[] exts = getExtentsSorted();
1546    for (int i = 0; i < exts.length; i++)
1547    {
1548      DjDomainValue dv = new DjDomainValue(extents, exts[i].getName(), exts[i].getName());
1549      dv.setSeq(seq);
1550      seq += 10;
1551      extents.addDomainValue(dv);
1552    }
1553
1554    ////
1555

1556    seq = 10;
1557    DjDomain classes = getDomain("_classes");
1558    for (int i = 0; i < exts.length; i++)
1559    {
1560      DjDomainValue dv = new DjDomainValue(classes, exts[i].getObjectType(), exts[i].getObjectType());
1561      dv.setSeq(seq);
1562      seq += 10;
1563      classes.addDomainValue(dv);
1564    }
1565
1566    ////
1567

1568    seq = 10;
1569    DjDomain types = getDomain("_types");
1570
1571    ArrayList JavaDoc allTypeNames = new ArrayList JavaDoc();
1572    for (int i = 0; i < exts.length; i++)
1573      allTypeNames.add(exts[i].getObjectType());
1574
1575    for (int i = 0; i < getDomainCount(); i++)
1576      if (!getDomain(i).isDynamic()) allTypeNames.add(getDomain(i).getName());
1577
1578    Collections.sort(allTypeNames, new DjStringComparator(false));
1579
1580    for (int i = 0; i < allTypeNames.size(); i++)
1581    {
1582      DjDomainValue dv = new DjDomainValue(types, allTypeNames.get(i).toString(), allTypeNames.get(i).toString());
1583      dv.setSeq(seq);
1584      seq += 10;
1585      types.addDomainValue(dv);
1586    }
1587
1588    DjDomainValue[] vals = types.getValidValues();
1589
1590    ////
1591

1592    seq = 10;
1593    DjDomain domains = getDomain("_domains");
1594
1595    allTypeNames = new ArrayList JavaDoc();
1596    for (int i = 0; i < getDomainCount(); i++)
1597      if (!getDomain(i).isDynamic()) allTypeNames.add(getDomain(i).getName());
1598
1599    Collections.sort(allTypeNames, new DjStringComparator(false));
1600
1601    for (int i = 0; i < allTypeNames.size(); i++)
1602    {
1603      DjDomainValue dv = new DjDomainValue(domains, allTypeNames.get(i).toString(), allTypeNames.get(i).toString());
1604      dv.setSeq(seq);
1605      seq += 10;
1606      domains.addDomainValue(dv);
1607    }
1608
1609    Collections.sort(_allDomains);
1610  }
1611
1612  private void setSchemaStructureVersion(String JavaDoc version)
1613  {
1614    if (version == null || version.trim().length() == 0) version = "100";
1615
1616    _schemaStructureVersion = Integer.parseInt(version);
1617  }
1618
1619  public int getSchemaStructureVersion()
1620  {
1621    return _schemaStructureVersion;
1622  }
1623
1624  /*
1625   * Returns false if the version of the loaded schema is higher than the
1626   * software currently running. So if this returns false saving the schema
1627   * might leave out schema information that was added using a newer version of
1628   * djeneric.
1629   */

1630  public boolean isVersionSafeToSave()
1631  {
1632    return getSchemaStructureVersion() <= SCHEMA_STRUCTURE_VERSION_NUMBER;
1633  }
1634
1635  /**
1636   * Gets the type of the DjPersistenceManager object
1637   *
1638   * @param typeName
1639   * Description of the Parameter
1640   * @return The type value
1641   * @exception DjenericException
1642   * Description of the Exception
1643   */

1644  public DjPropertyType getType(String JavaDoc typeName) throws DjenericException
1645  {
1646    if (isKnownDomain(typeName))
1647    {
1648      return getDomain(typeName);
1649    }
1650    return getExtentByObjectType(typeName);
1651  }
1652
1653  /**
1654   * Gets the typeByMapping of the DjPersistenceManager object
1655   *
1656   * @param mapping
1657   * Description of the Parameter
1658   * @return The typeByMapping value
1659   * @exception DjenericException
1660   * Description of the Exception
1661   */

1662  public DjPropertyType getTypeByMapping(String JavaDoc mapping) throws DjenericException
1663  {
1664    mapping = mapping.toLowerCase();
1665    if (mapping.startsWith(MAPPING_DAT)) return getType("Date");
1666    if (mapping.startsWith(MAPPING_LNG)) return getType("String");
1667    if (mapping.startsWith(MAPPING_NUM)) return getType("BigDecimal");
1668    if (mapping.startsWith(MAPPING_OBJECT_ID)) return getType("Long");
1669    if (mapping.startsWith(MAPPING_REL)) return getType("Long");
1670    if (mapping.startsWith(MAPPING_STR)) return getType("String");
1671    if (mapping.startsWith(MAPPING_TXT)) return getType("String");
1672    throw new CatalogException(Messages.getString("DjPersistenceManager.CouldNotFindMappingType", mapping));
1673  }
1674
1675  /**
1676   * Description of the Method
1677   *
1678   * @param typeName
1679   * Description of the Parameter
1680   * @return Description of the Return Value
1681   * @exception DjenericException
1682   * Description of the Exception
1683   */

1684  public DjPropertyType looslyFindType(String JavaDoc typeName) throws DjenericException
1685  {
1686    for (int i = 0; i < getDomainCount(); i++)
1687    {
1688      if (getDomain(i).getName().toLowerCase().startsWith(typeName.toLowerCase()))
1689      {
1690        return getDomain(i);
1691      }
1692    }
1693    DjExtent[] extents = getExtents();
1694    for (int i = 0; i < extents.length; i++)
1695    {
1696      if (extents[i].getObjectType().toLowerCase().startsWith(typeName.toLowerCase()))
1697      {
1698        return extents[i];
1699      }
1700    }
1701    throw new CatalogException(Messages.getString("DjPersistenceManager.TypeUndefined", typeName));
1702  }
1703
1704  /**
1705   * Description of the Method
1706   *
1707   * @exception DjenericException
1708   * Description of the Exception
1709   */

1710  protected void completeDomains() throws DjenericException
1711  {
1712    updateHashes();
1713
1714    if (!isKnownDomain("String"))
1715    {
1716      DjDomain dom = new DjDomain("String", "String", 0, 0, "", "Java native String type", false);
1717      addDomain(dom);
1718      dom.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1719    }
1720    if (!isKnownDomain("int"))
1721    {
1722      DjDomain dom = new DjDomain("int", "int", 10, 0, "", "Java native int type", false);
1723      addDomain(dom);
1724      dom.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1725    }
1726    if (!isKnownDomain("long"))
1727    {
1728      DjDomain dom = new DjDomain("long", "long", 15, 0, "", "Java native long type", false);
1729      addDomain(dom);
1730      dom.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1731    }
1732    if (!isKnownDomain(INTERNAL_ID_COLUMN_TYPE))
1733    {
1734      DjDomain dom = new DjDomain(INTERNAL_ID_COLUMN_TYPE, INTERNAL_ID_COLUMN_TYPE, 19, 0, "", "Java native long type",
1735          false);
1736      addDomain(dom);
1737      dom.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1738    }
1739    if (!isKnownDomain("byte[]"))
1740    {
1741      DjDomain dom = new DjDomain("byte[]", "byte[]", 0, 0, "", "Java native byte array", false);
1742      addDomain(dom);
1743      dom.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1744    }
1745    if (!isKnownDomain("BigDecimal"))
1746    {
1747      DjDomain dom = new DjDomain("BigDecimal", "BigDecimal", 15, 15, "", "Java native BigDecimal type", false);
1748      addDomain(dom);
1749      dom.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1750    }
1751    if (!isKnownDomain("Date"))
1752    {
1753      DjDomain dom = new DjDomain("Date", "Date", 0, 0, "dd-MM-yyyy", "Java Date type", false);
1754      addDomain(dom);
1755      dom.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1756    }
1757    if (!isKnownDomain("boolean"))
1758    {
1759      DjDomain dom = new DjDomain(getDomain("int"), "boolean", "int", 1, 0, "", Messages
1760          .getString("DjPersistenceManager.Java_boolean_type"), true);
1761      dom.addDomainValue(new DjDomainValue(dom, "1", "true"));
1762      dom.addDomainValue(new DjDomainValue(dom, "0", "false"));
1763      dom.getDomainValue(0).setSeq(10);
1764      dom.getDomainValue(1).setSeq(20);
1765
1766      dom.setComponentType(DjDomain.COMP_CHECKBOX);
1767      addDomain(dom);
1768      dom.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1769    }
1770
1771    if (!isKnownDomain("identifier"))
1772    {
1773      DjDomain dom = new DjDomain("identifier", "String", 100, 0, "", "String used for unique identifiers", false);
1774      addDomain(dom);
1775      dom.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1776    }
1777
1778    if (!isKnownDomain("description"))
1779    {
1780      DjDomain dom = new DjDomain("description", "String", 4000, 0, "", "String used for short descriptions", false);
1781      dom.setComponentType(DjDomain.COMP_MEMO);
1782      addDomain(dom);
1783      dom.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1784    }
1785
1786    if (!isKnownDomain("text"))
1787    {
1788      DjDomain dom = new DjDomain("text", "byte[]", 500000, 0, "", "String used for (large) texts", false);
1789
1790      dom.setComponentType(DjDomain.COMP_MEMO);
1791
1792      addDomain(dom);
1793      dom.setPackage(getOrCreatePackage(ORG_DJENERIC_DOMAINS));
1794    }
1795  }
1796
1797  /**
1798   * Gets the validTypeNames of the DjPersistenceManager object
1799   *
1800   * @return The validTypeNames value
1801   */

1802  public String JavaDoc[] getValidTypeNames()
1803  {
1804    ArrayList JavaDoc all = new ArrayList JavaDoc();
1805    for (int i = 0; i < getDomainCount(); i++)
1806    {
1807      all.add(getDomain(i).getName());
1808    }
1809    DjExtent[] extents = getExtents();
1810    for (int i = 0; i < extents.length; i++)
1811    {
1812      all.add(extents[i].getObjectType());
1813    }
1814    Collections.sort(all, new DjStringComparator(false));
1815
1816    return (String JavaDoc[]) all.toArray(new String JavaDoc[0]);
1817  }
1818
1819  /**
1820   * Sets the repositoryUser of the DjPersistenceManager object
1821   *
1822   * @param usr
1823   * The new repositoryUser value
1824   */

1825  public void setRepositoryUser(String JavaDoc usr)
1826  {
1827    _repositoryUser = usr;
1828  }
1829
1830  /**
1831   * Gets the repositoryUser of the DjPersistenceManager object
1832   *
1833   * @return The repositoryUser value
1834   */

1835  public String JavaDoc getRepositoryUser()
1836  {
1837    return _repositoryUser;
1838  }
1839
1840  /**
1841   * Sets the djenericUser of the DjPersistenceManager object
1842   *
1843   * @param usr
1844   * The new djenericUser value
1845   */

1846  public void setDjenericUser(String JavaDoc usr)
1847  {
1848    _djenericUser = usr;
1849  }
1850
1851  /**
1852   * Gets the djenericUser of the DjPersistenceManager object
1853   *
1854   * @return The djenericUser value
1855   */

1856  public String JavaDoc getDjenericUser()
1857  {
1858    return _djenericUser;
1859  }
1860
1861  /**
1862   * Sets the repositoryPassword of the DjPersistenceManager object
1863   *
1864   * @param pwd
1865   * The new repositoryPassword value
1866   */

1867  public void setRepositoryPassword(String JavaDoc pwd)
1868  {
1869    _repositoryPassword = pwd;
1870  }
1871
1872  /**
1873   * Gets the repositoryPassword of the DjPersistenceManager object
1874   *
1875   * @return The repositoryPassword value
1876   */

1877  public String JavaDoc getRepositoryPassword()
1878  {
1879    return _repositoryPassword;
1880  }
1881
1882  /**
1883   * Sets the djenericPassword of the DjPersistenceManager object
1884   *
1885   * @param pwd
1886   * The new djenericPassword value
1887   */

1888  public void setDjenericPassword(String JavaDoc pwd)
1889  {
1890    _djenericPassword = pwd;
1891  }
1892
1893  /**
1894   * Gets the djenericPassword of the DjPersistenceManager object
1895   *
1896   * @return The djenericPassword value
1897   */

1898  public String JavaDoc getDjenericPassword()
1899  {
1900    return _djenericPassword;
1901  }
1902
1903  /**
1904   * Gets the currentRepository of the DjPersistenceManager object
1905   *
1906   * @return The currentRepository value
1907   */

1908  public DjRepositoryDescriptor getCurrentRepository()
1909  {
1910    return _currentRepository;
1911  }
1912
1913  // Call this whenever a name, alias or objecttype is changed in a extent or
1914
// domain!
1915
/**
1916   * Description of the Method
1917   */

1918  private void updateHashes()
1919  {
1920    updateExtentHashes();
1921    updateDomainHashes();
1922    updatePackageHashes();
1923  }
1924
1925  private void updateDetailRelations()
1926  {
1927    for (int i = 0; i < _allExtents.size(); i++)
1928    {
1929      DjExtent theExtent = (DjExtent) _allExtents.get(i);
1930      theExtent.removeAllDetailRelations();
1931    }
1932    for (int i = 0; i < _allExtents.size(); i++)
1933    {
1934      DjExtent theExtent = (DjExtent) _allExtents.get(i);
1935      DjRelation[] rels = theExtent.getPersonalMasterRelations();
1936      for (int r = 0; r < rels.length; r++)
1937      {
1938        rels[r].getMasterExtent().addDetailRelation(rels[r]);
1939      }
1940    }
1941  }
1942
1943  private void updateSpecializations()
1944  {
1945    for (int i = 0; i < _allExtents.size(); i++)
1946    {
1947      DjExtent theExtent = (DjExtent) _allExtents.get(i);
1948      theExtent.clearSpecializations();
1949    }
1950    for (int i = 0; i < _allExtents.size(); i++)
1951    {
1952      DjExtent theExtent = (DjExtent) _allExtents.get(i);
1953      theExtent.refreshSpecializations();
1954    }
1955  }
1956
1957  /**
1958   * Description of the Method
1959   */

1960  public void updateExtentHashes()
1961  {
1962    _extentsByName = new HashMap JavaDoc();
1963    _extentsByInternalCode = new HashMap JavaDoc();
1964    _extentsByObjectType = new HashMap JavaDoc();
1965    _extentsByQualifiedObjectType = new HashMap JavaDoc();
1966    _extentsUnQualifiedClashed = new HashMap JavaDoc();
1967
1968    for (int i = 0; i < _allExtents.size(); i++)
1969    {
1970      DjExtent theExtent = (DjExtent) _allExtents.get(i);
1971      _extentsByName.put(theExtent.getName().toLowerCase(), theExtent);
1972      _extentsByInternalCode.put(theExtent.getInternalCode().toLowerCase(), theExtent);
1973
1974      if (_extentsByObjectType.containsKey(theExtent.getObjectType()))
1975      {
1976        _extentsUnQualifiedClashed.put(theExtent.getObjectType(), theExtent);
1977      }
1978      _extentsByObjectType.put(theExtent.getObjectType(), theExtent);
1979      _extentsByQualifiedObjectType.put(theExtent.getQualifiedObjectType(), theExtent);
1980    }
1981    if (_extentsUnQualifiedClashed.size() == 0) _extentsUnQualifiedClashed = null;
1982  }
1983
1984  public void updateDomainHashes()
1985  {
1986    _domainsByName = new HashMap JavaDoc();
1987    for (int i = 0; i < _allDomains.size(); i++)
1988    {
1989      DjDomain theDomain = (DjDomain) _allDomains.get(i);
1990      _domainsByName.put(theDomain.getName().toLowerCase(), theDomain);
1991    }
1992  }
1993
1994  public void updatePackageHashes()
1995  {
1996    _packagesByName = new HashMap JavaDoc();
1997    for (int i = 0; i < _allPackages.size(); i++)
1998    {
1999      DjPackage thePackage = (DjPackage) _allPackages.get(i);
2000      _packagesByName.put(thePackage.getName(), thePackage);
2001    }
2002  }
2003
2004  /**
2005   * Gets the knownDomain of the DjPersistenceManager object
2006   *
2007   * @param name
2008   * Description of the Parameter
2009   * @return The knownDomain value
2010   */

2011  public boolean isKnownDomain(String JavaDoc name)
2012  {
2013    return _domainsByName.containsKey(name.toLowerCase());
2014  }
2015
2016  /**
2017   * Gets the relationsForProperty of the DjPersistenceManager object
2018   *
2019   * @param extentName
2020   * Description of the Parameter
2021   * @param propertyName
2022   * Description of the Parameter
2023   * @return The relationsForProperty value
2024   */

2025  public DjRelation[] getRelationsForProperty(String JavaDoc extentName, String JavaDoc propertyName)
2026  {
2027    ArrayList JavaDoc result = new ArrayList JavaDoc();
2028
2029    DjExtent[] extents = getExtents();
2030    for (int i = 0; i < extents.length; i++)
2031    {
2032      DjRelation[] rels = extents[i].getPersonalMasterRelations();
2033      for (int r = 0; r < rels.length; r++)
2034      {
2035        if (rels[r].getDetailExtent().getName().equalsIgnoreCase(extentName)
2036            && rels[r].getDetailProperty().getName().equalsIgnoreCase(propertyName))
2037        {
2038          result.add(rels[r]);
2039        }
2040      }
2041    }
2042    return (DjRelation[]) result.toArray(new DjRelation[0]);
2043  }
2044
2045  /**
2046   * Gets the nextInternalId of the DjPersistenceManager class
2047   *
2048   * @return The nextInternalId value
2049   */

2050  protected static long getNextInternalId()
2051  {
2052    return _internalId++;
2053  }
2054
2055  /**
2056   * Gets the validInteger of the DjPersistenceManager object
2057   *
2058   * @param str
2059   * Description of the Parameter
2060   * @return The validInteger value
2061   */

2062  protected boolean isValidInteger(String JavaDoc str)
2063  {
2064    try
2065    {
2066      Integer.parseInt(str);
2067      return true;
2068    }
2069    catch (Exception JavaDoc x)
2070    { // Ignore, return false
2071
}
2072    return false;
2073  }
2074
2075  /**
2076   * Description of the Method
2077   *
2078   * @param str
2079   * Description of the Parameter
2080   * @return Description of the Return Value
2081   */

2082  protected int convert2Int(String JavaDoc str)
2083  {
2084    int result = 0;
2085    if (str.trim().length() > 0)
2086    {
2087      result = Integer.parseInt(str);
2088    }
2089    return result;
2090  }
2091
2092  protected String JavaDoc nvl(String JavaDoc str, String JavaDoc valueWhenNull)
2093  {
2094    if (str == null) return valueWhenNull;
2095    return str;
2096  }
2097
2098  /**
2099   * Description of the Method
2100   *
2101   * @param str
2102   * Description of the Parameter
2103   * @return Description of the Return Value
2104   */

2105  protected boolean convert2bool(String JavaDoc str)
2106  {
2107    if (str == null) return false;
2108    return str.equalsIgnoreCase("true");
2109  }
2110
2111  // Tries to find a extent by name, if not found by internal code (alias),
2112
// if not found by object type
2113
// If not found by either 3 ways: null is returned
2114
/**
2115   * Description of the Method
2116   *
2117   * @param extent
2118   * Description of the Parameter
2119   * @return Description of the Return Value
2120   */

2121  public DjExtent findExtent(DjExtent extent)
2122  {
2123    DjExtent result = null;
2124    try
2125    {
2126      result = getExtentByObjectId(extent);
2127    }
2128    catch (Exception JavaDoc x)
2129    {
2130      // ignore
2131
}
2132    if (result == null) try
2133    {
2134      result = getExtent(extent.getName());
2135    }
2136    catch (Exception JavaDoc x)
2137    {
2138      // ignore
2139
}
2140    if (result == null) try
2141    {
2142      result = getExtentByInternalCode(extent.getInternalCode());
2143    }
2144    catch (Exception JavaDoc x)
2145    {
2146      // ignore
2147
}
2148    if (result == null) try
2149    {
2150      result = getExtentByObjectType(extent.getObjectType());
2151    }
2152    catch (Exception JavaDoc x)
2153    {
2154      // ignore
2155
}
2156    return result;
2157  }
2158
2159  /**
2160   * Gets the extent of the DjPersistenceManager object
2161   *
2162   * @param extentName
2163   * Description of the Parameter
2164   * @return The extent value
2165   * @exception ObjectNotDefinedException
2166   * Description of the Exception
2167   */

2168  public DjExtent getExtent(String JavaDoc extentName) throws ObjectNotDefinedException
2169  {
2170    DjExtent result = (DjExtent) _extentsByName.get(extentName.toLowerCase());
2171    if (result == null) throw new ObjectNotDefinedException(Messages.getString("DjPersistenceManager.UnknownExtent",
2172                                                                               extentName));
2173    return result;
2174  }
2175
2176  /**
2177   * Gets the domainCount of the DjPersistenceManager object
2178   *
2179   * @return The domainCount value
2180   */

2181  public int getDomainCount()
2182  {
2183    return _allDomains.size();
2184  }
2185
2186  /**
2187   * Gets the domain of the DjPersistenceManager object
2188   *
2189   * @param domainName
2190   * Description of the Parameter
2191   * @return The domain value
2192   * @exception ObjectNotDefinedException
2193   * Description of the Exception
2194   */

2195  public DjDomain getDomain(String JavaDoc domainName) throws ObjectNotDefinedException
2196  {
2197    DjDomain result = (DjDomain) _domainsByName.get(domainName.toLowerCase());
2198    if (result == null) throw new ObjectNotDefinedException(Messages.getString("DjPersistenceManager.UnknownDomain",
2199                                                                               domainName));
2200    return result;
2201  }
2202
2203  /**
2204   * Gets the domain of the DjPersistenceManager object
2205   *
2206   * @param idx
2207   * Description of the Parameter
2208   * @return The domain value
2209   */

2210  public DjDomain getDomain(int idx)
2211  {
2212    return (DjDomain) _allDomains.get(idx);
2213  }
2214
2215  /**
2216   * Gets the package of the DjPersistenceManager object
2217   *
2218   * @param domainName
2219   * Description of the Parameter
2220   * @return The domain value
2221   * @exception ObjectNotDefinedException
2222   * Description of the Exception
2223   */

2224  public DjPackage getPackage(String JavaDoc packageName) throws ObjectNotDefinedException
2225  {
2226    DjPackage result = (DjPackage) _packagesByName.get(packageName);
2227    if (result == null) throw new ObjectNotDefinedException(Messages.getString("DjPersistenceManager.UnknownPackage",
2228                                                                               packageName));
2229    return result;
2230  }
2231
2232  public DjPackage getOrCreatePackage(String JavaDoc packageName) throws ObjectNotDefinedException
2233  {
2234    DjPackage result = (DjPackage) _packagesByName.get(packageName);
2235    if (result == null)
2236    {
2237      result = new DjPackage(packageName);
2238      addPackage(result);
2239    }
2240    return result;
2241  }
2242
2243  /**
2244   * Gets the domain of the DjPersistenceManager object
2245   *
2246   * @param idx
2247   * Description of the Parameter
2248   * @return The domain value
2249   */

2250  public DjPackage getPackage(int idx)
2251  {
2252    return (DjPackage) _allPackages.get(idx);
2253  }
2254
2255  public int getPackageCount()
2256  {
2257    return _allPackages.size();
2258  }
2259
2260  /**
2261   * Gets the extents of the DjPersistenceManager object
2262   *
2263   * @return The extents value
2264   */

2265  public DjExtent[] getExtents()
2266  {
2267    return (DjExtent[]) _allExtents.toArray(new DjExtent[0]);
2268  }
2269
2270  public DjExtent[] getExtents(DjPackage pack)
2271  {
2272    ArrayList JavaDoc filtered = new ArrayList JavaDoc();
2273    filtered.addAll(_allExtents);
2274
2275    int i = 0;
2276    while (i < filtered.size())
2277    {
2278      DjExtent ext = (DjExtent) filtered.get(i);
2279      if (ext.getPackage() != pack) filtered.remove(i);
2280      else i++;
2281    }
2282
2283    return (DjExtent[]) filtered.toArray(new DjExtent[0]);
2284  }
2285
2286  /**
2287   * Gets the extentsSorted of the DjPersistenceManager object
2288   *
2289   * @return The extentsSorted value
2290   */

2291  public DjExtent[] getExtentsSorted()
2292  {
2293    return (DjExtent[]) getExtentsAsArrayList().toArray(new DjExtent[0]);
2294  }
2295
2296  /**
2297   * Gets the domains of the DjPersistenceManager object
2298   *
2299   * @return The domains value
2300   */

2301  public DjDomain[] getDomains()
2302  {
2303    return (DjDomain[]) _allDomains.toArray(new DjDomain[0]);
2304  }
2305
2306  public DjDomain[] getDomains(DjPackage pack)
2307  {
2308    ArrayList JavaDoc filtered = new ArrayList JavaDoc();
2309    filtered.addAll(_allDomains);
2310
2311    int i = 0;
2312    while (i < filtered.size())
2313    {
2314      DjDomain dom = (DjDomain) filtered.get(i);
2315      if (dom.getPackage() != pack) filtered.remove(i);
2316      else i++;
2317    }
2318
2319    return (DjDomain[]) filtered.toArray(new DjDomain[0]);
2320  }
2321
2322  public DjPackage[] getPackages()
2323  {
2324    ArrayList JavaDoc lst = new ArrayList JavaDoc();
2325    lst.addAll(_allPackages);
2326    Collections.sort(lst, new DjStringComparator(true));
2327    return (DjPackage[]) lst.toArray(new DjPackage[0]);
2328  }
2329
2330  /**
2331   * Gets the extentsAsArrayList of the DjPersistenceManager object
2332   *
2333   * @return The extentsAsArrayList value
2334   */

2335  public ArrayList JavaDoc getExtentsAsArrayList()
2336  {
2337    ArrayList JavaDoc lst = new ArrayList JavaDoc();
2338    lst.addAll(_allExtents);
2339    Collections.sort(lst, new DjExtentComparator());
2340    return lst;
2341  }
2342
2343  /**
2344   * Adds a feature to the Extent attribute of the DjPersistenceManager object
2345   *
2346   * @param tab
2347   * The feature to be added to the Extent attribute
2348   */

2349  public void addExtent(DjExtent tab)
2350  {
2351    _allExtents.add(tab);
2352    updateHashes();
2353  }
2354
2355  /**
2356   * Adds a feature to the Domain attribute of the DjPersistenceManager object
2357   *
2358   * @param dom
2359   * The feature to be added to the Domain attribute
2360   */

2361  public void addDomain(DjDomain dom)
2362  {
2363    _allDomains.add(dom);
2364    updateHashes();
2365  }
2366
2367  /**
2368   * Adds a feature to the Domain attribute of the DjPersistenceManager object
2369   *
2370   * @param atIdx
2371   * The feature to be added to the Domain attribute
2372   * @param dom
2373   * The feature to be added to the Domain attribute
2374   */

2375  public void addDomain(int atIdx, DjDomain dom)
2376  {
2377    _allDomains.add(atIdx, dom);
2378    updateHashes();
2379  }
2380
2381  public void addPackage(DjPackage pack)
2382  {
2383    _allPackages.add(pack);
2384    updateHashes();
2385  }
2386
2387  public void removePackage(DjPackage pack)
2388  {
2389    _allPackages.remove(pack);
2390    updateHashes();
2391  }
2392
2393  /**
2394   * Description of the Method
2395   *
2396   * @param extent
2397   * Description of the Parameter
2398   */

2399  public void removeExtent(DjExtent extent) throws DjenericException
2400  {
2401    DjExtent[] extents = getExtents();
2402
2403    // First reset properties of the type that is about te get deleted
2404
// AND fix the super type references pointing to the extent
2405
DjDomain dom = null;
2406    try
2407    {
2408      dom = getDomain(INTERNAL_ID_COLUMN_TYPE);
2409    }
2410    catch (ObjectNotDefinedException ond)
2411    {
2412      throw new RuntimeException JavaDoc(Messages.getString("DjPersistenceManager.DomainNotFound", INTERNAL_ID_COLUMN_TYPE));
2413    }
2414
2415    // Now delete any relations that use the extent as master / detail
2416
for (int i = 0; i < extents.length; i++)
2417    {
2418      // Delete all master relations where this extent plays a role:
2419
DjRelation[] rels = extents[i].getMasterRelations();
2420      for (int r = 0; r < rels.length; r++)
2421      {
2422        if (rels[r].getMasterExtent().getTypeName().equals(extent.getTypeName()))
2423        {
2424          extents[i].removeMasterRelation(rels[r]);
2425        }
2426        if (rels[r].getDetailExtent().getTypeName().equals(extent.getTypeName()))
2427        {
2428          extents[i].removeMasterRelation(rels[r]);
2429        }
2430      }
2431      // Delete all detail relations where this extent plays a role:
2432
rels = extents[i].getDetailRelations();
2433      for (int r = 0; r < rels.length; r++)
2434      {
2435        if (rels[r].getMasterExtent().getTypeName().equals(extent.getTypeName()))
2436        {
2437          extents[i].removeDetailRelation(rels[r]);
2438        }
2439        if (rels[r].getDetailExtent().getTypeName().equals(extent.getTypeName()))
2440        {
2441          extents[i].removeDetailRelation(rels[r]);
2442        }
2443      }
2444    }
2445
2446    for (int i = 0; i < extents.length; i++)
2447    {
2448      // Fix the super:
2449
if (extents[i].getSuper() != null)
2450      {
2451        if (extents[i].getSuper().getTypeName().equals(extent.getTypeName()))
2452        {
2453          extents[i].setSuper(null);
2454        }
2455      }
2456      // Fix the property types
2457
DjProperty[] properties = extents[i].getProperties();
2458      for (int c = 0; c < properties.length; c++)
2459      {
2460        if (properties[c].getTypeName().equals(extent.getTypeName()))
2461        {
2462          DjSession session = null;
2463          try
2464          {
2465            session = createSession();
2466            if (extents[i].isEmpty(session))
2467            {
2468              extents[i].removeProperty(properties[c]);
2469            }
2470            else properties[c].setType(dom);
2471          }
2472          finally
2473          {
2474            if (session != null) session.close();
2475          }
2476        }
2477      }
2478    }
2479
2480    _allExtents.remove(extent);
2481    updateHashes();
2482  }
2483
2484  /**
2485   * Description of the Method
2486   *
2487   * @param dom
2488   * Description of the Parameter
2489   */

2490  public void removeDomain(DjDomain dom)
2491  {
2492    _allDomains.remove(dom);
2493    updateHashes();
2494  }
2495
2496  /**
2497   * Gets the domainUsed of the DjPersistenceManager object
2498   *
2499   * @param dom
2500   * Description of the Parameter
2501   * @return The domainUsed value
2502   */

2503  public boolean isDomainUsed(DjDomain dom)
2504  {
2505    DjExtent[] extents = getExtents();
2506    for (int i = 0; i < extents.length; i++)
2507    {
2508      DjProperty[] cols = extents[i].getProperties();
2509      for (int c = 0; c < cols.length; c++)
2510      {
2511        if (cols[c].getType() == dom) return true;
2512      }
2513    }
2514    DjDomain[] doms = getDomains();
2515    for (int i = 0; i < extents.length; i++)
2516    {
2517      if (doms[i].getSuperDomain() == dom) return true;
2518    }
2519    return false;
2520  }
2521
2522  /**
2523   * Gets the validType of the DjPersistenceManager object
2524   *
2525   * @param typeName
2526   * Description of the Parameter
2527   * @return The validType value
2528   */

2529  public boolean isValidType(String JavaDoc typeName)
2530  {
2531    if (isKnownDomain(typeName)) return true;
2532    if (_extentsByQualifiedObjectType.containsKey(typeName)) return true;
2533    if (_extentsByObjectType.containsKey(typeName)) return true;
2534    return false;
2535  }
2536
2537  /**
2538   * Gets the extentByObjectId of the DjPersistenceManager object
2539   *
2540   * @param extent
2541   * Description of the Parameter
2542   * @return The extentByObjectId value
2543   * @exception ObjectNotDefinedException
2544   * Description of the Exception
2545   */

2546  public DjExtent getExtentByObjectId(DjExtent extent) throws ObjectNotDefinedException
2547  {
2548    for (int i = 0; i < _allExtents.size(); i++)
2549    {
2550      DjExtent e = (DjExtent) _allExtents.get(i);
2551      if (e.getInternalId() == extent.getInternalId()) return e;
2552    }
2553    throw new ObjectNotDefinedException(Messages.getString("DjPersistenceManager.UnknownExtent", extent.getName()));
2554  }
2555
2556  /**
2557   * Gets the extentByInternalCode of the DjPersistenceManager object
2558   *
2559   * @param alias
2560   * Description of the Parameter
2561   * @return The extentByInternalCode value
2562   * @exception ObjectNotDefinedException
2563   * Description of the Exception
2564   */

2565  public DjExtent getExtentByInternalCode(String JavaDoc alias) throws ObjectNotDefinedException
2566  {
2567    DjExtent result = (DjExtent) _extentsByInternalCode.get(alias.toLowerCase());
2568    if (result == null) throw new ObjectNotDefinedException(Messages
2569        .getString("DjPersistenceManager.UnknownInternalExtentCode", alias));
2570    return result;
2571  }
2572
2573  /**
2574   * Gets the extentByObjectType of the DjPersistenceManager object
2575   *
2576   * @param objectType
2577   * Description of the Parameter
2578   * @return The extentByObjectType value
2579   * @exception ObjectNotDefinedException
2580   * Description of the Exception
2581   */

2582  public DjExtent getExtentByObjectType(String JavaDoc objectType) throws ObjectNotDefinedException
2583  {
2584    DjExtent result;
2585    if (objectType.indexOf('.') != -1) result = (DjExtent) _extentsByQualifiedObjectType.get(objectType);
2586    else
2587    {
2588      if (_extentsUnQualifiedClashed != null && _extentsUnQualifiedClashed.containsKey(objectType)) throw new ObjectNotDefinedException(
2589          Messages.getString("DjPersistenceManager.UnqualifiedClash", objectType));
2590      result = (DjExtent) _extentsByObjectType.get(objectType);
2591    }
2592
2593    if (result == null) throw new ObjectNotDefinedException(Messages
2594        .getString("DjPersistenceManager.UnknownObjectType", objectType));
2595    return result;
2596  }
2597
2598  /**
2599   * Sets the useGlobalContext of the DjPersistenceManager object
2600   *
2601   * @param useGlobal
2602   * The new useGlobalContext value
2603   */

2604  public void setUseGlobalContext(boolean useGlobal)
2605  {
2606    if (useGlobal) _contextManager.setCurrentContext((DjContext) null);
2607    _useGlobalContext = useGlobal;
2608  }
2609
2610  /**
2611   * Gets the usingGlobalContext of the DjPersistenceManager object
2612   *
2613   * @return The usingGlobalContext value
2614   */

2615  public boolean isUsingGlobalContext()
2616  {
2617    return _useGlobalContext;
2618  }
2619
2620  /**
2621   * Gets the loggedIn of the DjPersistenceManager object
2622   *
2623   * @return The loggedIn value
2624   */

2625  public boolean isLoggedIn()
2626  {
2627    return (getDjenericUser() != null);
2628  }
2629
2630  /**
2631   * Gets the repositoryUserKnown of the DjPersistenceManager object
2632   *
2633   * @return The repositoryUserKnown value
2634   */

2635  public boolean isRepositoryUserKnown()
2636  {
2637    return (getRepositoryUser() != null);
2638  }
2639
2640  /**
2641   * Description of the Method
2642   *
2643   * @exception DjenericException
2644   * Description of the Exception
2645   */

2646  public void login() throws DjenericException
2647  {
2648    DjCredentials credentials = _messenger.getCredentials(_currentRepository);
2649
2650    _djenericUser = credentials.getUserid();
2651    try
2652    {
2653      _djenericPassword = encodePassword(credentials.getPassword());
2654    }
2655    catch (NoSuchAlgorithmException JavaDoc nsae)
2656    {
2657      throw new DjenericException(nsae);
2658    }
2659
2660    if (_currentRepository.isSharedConnection())
2661    {
2662      // do not change the shared repository user/pw
2663
// just the person's ID
2664
}
2665    else
2666    {
2667      _repositoryUser = credentials.getUserid();
2668      _repositoryPassword = credentials.getPassword();
2669    }
2670
2671    if (getCurrentRepository().isSharedConnection())
2672    {
2673      DjUser usr = _contextManager.getUser(_djenericUser);
2674      if (!usr.getPassword().equals(_djenericPassword))
2675      {
2676        throw new LogonException(Messages.getString("DjPersistenceManager.InvalidPasswordForUser", _djenericUser));
2677      }
2678    }
2679  }
2680
2681  /**
2682   * Forces the persistence manager to choose a context; default is the global context (no context)
2683   *
2684   * @exception DjenericException
2685   */

2686  public void determineContext() throws DjenericException
2687  {
2688    try
2689    {
2690      DjContext[] ctxts;
2691      DjUser dev = getCurrentUser();
2692
2693      if (dev.isAdministrator()) ctxts = getContextManager().getContexts();
2694      else
2695      {
2696        DjUserContextAssociation[] assocs = dev.getContextAssociations();
2697        ctxts = new DjContext[assocs.length];
2698        for (int i = 0; i < assocs.length; i++)
2699        {
2700          ctxts[i] = assocs[i].getContext();
2701        }
2702      }
2703
2704      DjContext ctxt = _messenger.selectContext(ctxts);
2705      _contextManager.setCurrentContext(ctxt);
2706    }
2707    catch (Exception JavaDoc x)
2708    {
2709      throw new LogonException(x);
2710    }
2711  }
2712
2713  /**
2714   * Gets the currentUser of the DjPersistenceManager object
2715   *
2716   * @return The currentUser value
2717   * @exception DjenericException
2718   * Description of the Exception
2719   */

2720  public DjUser getCurrentUser() throws DjenericException
2721  {
2722    if (!isLoggedIn()) login();
2723
2724    return _contextManager.getUser(_djenericUser);
2725  }
2726
2727  /**
2728   * Gets the contextManager of the DjPersistenceManager object
2729   *
2730   * @return The contextManager value
2731   */

2732  public DjContextManager getContextManager()
2733  {
2734    return _contextManager;
2735  }
2736
2737  /**
2738   * Gets the nextObjectId of the DjPersistenceManager object
2739   *
2740   * @return The nextObjectId value
2741   * @exception DjenericException
2742   * Description of the Exception
2743   */

2744  public long getNextObjectId() throws DjenericException
2745  {
2746    return _idProvider.getNextId(this);
2747  }
2748
2749  /**
2750   * Description of the Method
2751   *
2752   * @param strictChecking
2753   * Description of the Parameter
2754   * @exception CatalogException
2755   * Description of the Exception
2756   */

2757  public void validateModel(boolean strictChecking) throws CatalogException
2758  {
2759    updateDetailRelations();
2760    updateSpecializations();
2761    // first check for duplicate extent names
2762
DjExtent[] exts = getExtents();
2763    DjDomain[] doms = getDomains();
2764    for (int i = 0; i < exts.length; i++)
2765    {
2766      for (int j = 0; j < exts.length; j++)
2767      {
2768        if (exts[i] != exts[j])
2769        {
2770          if (exts[i].getName().equalsIgnoreCase(exts[j].getName())) throw new CatalogException(Messages
2771              .getString("DjPersistenceManager.DuplicateExtentName", exts[j].getName()));
2772          if (exts[i].getInternalCode().equalsIgnoreCase(exts[j].getInternalCode())) throw new CatalogException(
2773              Messages.getString("DjPersistenceManager.DuplicateExtentAlias", exts[j].getInternalCode(), exts[i]
2774                  .getName(), exts[j].getName()));
2775          if (exts[i].getObjectType().equalsIgnoreCase(exts[j].getObjectType())
2776              && exts[i].getPackage() == exts[j].getPackage()) throw new CatalogException(Messages
2777              .getString("DjPersistenceManager.DuplicateExtentType", exts[j].getObjectType(), exts[i].getName(),
2778                         exts[j].getName()));
2779        }
2780      }
2781      for (int j = 0; j < doms.length; j++)
2782      {
2783        if (exts[i].getObjectType().equalsIgnoreCase(doms[j].getName())) throw new CatalogException(Messages
2784            .getString("DjPersistenceManager.NameAlsoDomain", exts[i].getName(), exts[i].getObjectType(), doms[j]
2785                .getName()));
2786      }
2787    }
2788
2789    for (int i = 0; i < exts.length; i++)
2790    {
2791      exts[i].updateHashes();
2792    }
2793
2794    for (int i = 0; i < exts.length; i++)
2795    {
2796      exts[i].validate(this, strictChecking);
2797    }
2798
2799    for (int i = 0; i < getDomainCount(); i++)
2800    {
2801      getDomain(i).validate(this, strictChecking);
2802    }
2803  }
2804
2805  /**
2806   * Sets the mainFrame of the DjPersistenceManager object
2807   *
2808   * @param mainFrame
2809   * The new mainFrame value
2810   */

2811  public void setMessenger(DjMessenger messenger)
2812  {
2813    _messenger = messenger;
2814  }
2815
2816  /**
2817   * Gets the connectionTitle of the DjPersistenceManager object
2818   *
2819   * @return The connectionTitle value
2820   * @exception DjenericException
2821   * Description of the Exception
2822   */

2823  public String JavaDoc getConnectionTitle()
2824  {
2825    String JavaDoc dev = Messages.getString("DjPersistenceManager.anonymous");
2826    String JavaDoc ctx = Messages.getString("DjPersistenceManager.global");
2827    String JavaDoc rep = Messages.getString("DjPersistenceManager.unknown");
2828
2829    String JavaDoc djUser = getDjenericUser();
2830    if (djUser == null) djUser = getRepositoryUser();
2831
2832    if (djUser != null) dev = djUser;
2833    if (getCurrentContext() != null) ctx = getCurrentContext().getCode();
2834    if (getCurrentRepository() != null) rep = getCurrentRepository().getName();
2835
2836    return dev + "@" + ctx + "/" + rep;
2837  }
2838
2839  /**
2840   * Gets the directSubExtentsOf of the DjPersistenceManager object
2841   *
2842   * @param extent
2843   * Description of the Parameter
2844   * @return The directSubExtentsOf value
2845   */

2846  public DjExtent[] getDirectSubExtentsOf(DjExtent extent)
2847  {
2848    DjExtent[] all = getExtents();
2849    ArrayList JavaDoc result = new ArrayList JavaDoc();
2850
2851    for (int i = 0; i < all.length; i++)
2852    {
2853      if (all[i].getSuper() == extent) result.add(all[i]);
2854    }
2855    return (DjExtent[]) result.toArray(new DjExtent[0]);
2856  }
2857
2858  /**
2859   * Gets the subExtentsOf of the DjPersistenceManager object
2860   *
2861   * @param extent
2862   * Description of the Parameter
2863   * @return The subExtentsOf value
2864   */

2865  public DjExtent[] getSubExtentsOf(DjExtent extent)
2866  {
2867    DjExtent[] all = getExtents();
2868    ArrayList JavaDoc result = new ArrayList JavaDoc();
2869
2870    for (int i = 0; i < all.length; i++)
2871    {
2872      if (all[i].getSuper() == extent)
2873      {
2874        result.add(all[i]);
2875        DjExtent[] subs = getSubExtentsOf(all[i]);
2876        result.addAll(Arrays.asList(subs));
2877      }
2878    }
2879    return (DjExtent[]) result.toArray(new DjExtent[0]);
2880  }
2881
2882  /**
2883   * Gets the validName of the DjPersistenceManager class
2884   *
2885   * @param name
2886   * Description of the Parameter
2887   * @return The validName value
2888   */

2889  public static boolean isValidName(String JavaDoc name)
2890  {
2891    final String JavaDoc valids = "abcdefghijklmnopqrstuvwxyz1234567890_@#$";
2892
2893    if (name == null || name.length() == 0) return false;
2894
2895    name = name.toLowerCase();
2896    for (int i = 0; i < name.length(); i++)
2897    {
2898      if (valids.indexOf(name.charAt(i)) == -1) return false;
2899    }
2900    return true;
2901  }
2902
2903  /**
2904   * Description of the Method
2905   *
2906   * @param disp
2907   * Description of the Parameter
2908   * @return Description of the Return Value
2909   * @exception DjenericException
2910   * Description of the Exception
2911   */

2912  public String JavaDoc[] validateRepositoryContents(DjProgressDisplayer disp) throws DjenericException
2913  {
2914    DjSession session = createSession();
2915    ArrayList JavaDoc result = new ArrayList JavaDoc();
2916    HashMap JavaDoc allErrors = new HashMap JavaDoc();
2917
2918    try
2919    {
2920      DjExtent[] allExtents = getExtents();
2921
2922      // First check required fields
2923
for (int i = 0; i < allExtents.length; i++)
2924      {
2925        DjExtent ext = allExtents[i];
2926
2927        disp.displayProgress(Messages.getString("DjPersistenceManager.CheckingExtent", ext.getName()));
2928        DjCursor cursor = session.getObjectsCursor(ext);
2929        DjObject obj = null;
2930        int errCount = 10;
2931        do
2932        {
2933          try
2934          {
2935            obj = null;
2936            obj = cursor.getNext();
2937            if (obj != null) obj.checkRequiredProperties();
2938          }
2939          catch (Exception JavaDoc x)
2940          {
2941            if (--errCount == 0)
2942            {
2943              result.add(Messages.getString("DjPersistenceManager.MoreThan10Errors"));
2944              obj = null;
2945            }
2946            else if (obj == null) result.add(Messages.getString("DjPersistenceManager.ExtentError", ext.getName(), x
2947                .getMessage()));
2948            else
2949            {
2950              Long JavaDoc key = new Long JavaDoc(obj.getObjectId());
2951              if (allErrors.containsKey(key)) continue;
2952              allErrors.put(key, key);
2953              result.add(Messages.getString("DjPersistenceManager.SpecificExtentError", ext.getName(), ext
2954                  .getIdProperty().getName(), String.valueOf(obj.getObjectId()), x.getMessage()));
2955            }
2956          }
2957        }
2958        while (obj != null);
2959        cursor.close();
2960      }
2961    }
2962    finally
2963    {
2964      session.close();
2965    }
2966    disp.displayProgress(Messages.getString("DjPersistenceManager.Done"));
2967    return (String JavaDoc[]) result.toArray(new String JavaDoc[0]);
2968  }
2969
2970  /**
2971   * Description of the Method
2972   *
2973   * @param session
2974   * Description of the Parameter
2975   * @param master
2976   * Description of the Parameter
2977   * @param rel
2978   * Description of the Parameter
2979   * @return Description of the Return Value
2980   */

2981  public DjAssociation createAssociation(DjSession session, DjObject master, DjRelation rel,
2982                                         DjExtent specificDetailExtent)
2983  {
2984    return new DjAssociation(session, master, rel, specificDetailExtent);
2985  }
2986
2987  /**
2988   * Description of the Method
2989   *
2990   * @param password
2991   * Description of the Parameter
2992   * @return Description of the Return Value
2993   * @exception NoSuchAlgorithmException
2994   * Description of the Exception
2995   */

2996  public static String JavaDoc encodePassword(String JavaDoc password) throws NoSuchAlgorithmException JavaDoc
2997  {
2998    if (password == null || password.trim().length() == 0) return "";
2999
3000    MessageDigest JavaDoc md = MessageDigest.getInstance("SHA");
3001    md.update("test".getBytes());
3002    byte[] digest = md.digest();
3003
3004    StringBuffer JavaDoc sb = new StringBuffer JavaDoc(50);
3005    for (int i = 0; i < digest.length; i++)
3006    {
3007      sb.append(Integer.toHexString(digest[i] & 0xff));
3008    }
3009    return sb.toString();
3010  }
3011
3012  /**
3013   * Print a message formatted as a trace message on the console
3014   *
3015   * @param msg
3016   * The message to print
3017   */

3018  protected void trace(String JavaDoc msg)
3019  {
3020    DjLogger.log(_traceTimestampFormatter.format(new Date JavaDoc()) + ": " + msg);
3021  }
3022
3023  /**
3024   * Returns true if the trace level is high enough for the provided level This
3025   * check is deliberately not put into the trace call itself to avoid the
3026   * unnecessary overhead of constructing messages with a trace level that is
3027   * too low (and will be discarded)
3028   *
3029   * @param level
3030   * Description of the Parameter
3031   * @return Description of the Return Value
3032   */

3033  protected boolean shouldTrace(int level)
3034  {
3035    return (level <= _traceLevel);
3036  }
3037
3038  /**
3039   * Sets the traceLevel for use with the trace method
3040   *
3041   * @param level
3042   * The new traceLevel value
3043   */

3044  public void setTraceLevel(int level)
3045  {
3046    _traceLevel = level;
3047  }
3048
3049  /**
3050   * Returns the traceLevel of the DjPersistenceManager object
3051   *
3052   * @return The traceLevel value
3053   */

3054  public int getTraceLevel()
3055  {
3056    return _traceLevel;
3057  }
3058
3059  public boolean bootstrapRepositoryIfNeeded(DjProgressDisplayer pd) throws DjenericException
3060  {
3061    DjContextManager cmgr = getContextManager();
3062    DjSession session = createSession();
3063    String JavaDoc msg = "";
3064    boolean strapped = false;
3065
3066    try
3067    {
3068      DjContext ctxt = null;
3069      DjUser dev = null;
3070      if (cmgr.getContexts().length == 0)
3071      {
3072        // Bootstrap this repository with a default context
3073
ctxt = cmgr.createNewContext();
3074        ctxt.setCode("dflt");
3075        ctxt.setName(Messages.getString("DjPersistenceManager.DefaultContext"));
3076        ctxt.persist(session);
3077        msg += Messages.getString("DjPersistenceManager.DefaultContextCreated");
3078        strapped = true;
3079      }
3080      session.commit();
3081
3082      if (cmgr.getUsers().length == 0)
3083      {
3084        // Bootstrap this repository with a default administrator
3085
dev = cmgr.createNewUser();
3086        dev.setCode(getRepositoryUser());
3087        dev.setPassword(encodePassword(getRepositoryPassword()));
3088        dev.setName(Messages.getString("DjPersistenceManager.RepositoryAdministrator"));
3089        dev.setAdministrator(true);
3090        dev.setModeler(true);
3091        dev.persist(session);
3092        if (msg.length() > 0) msg += " " + Messages.getString("global.and") + " ";
3093
3094        msg += Messages.getString("DjPersistenceManager.AdministrativeUserCreated");
3095        strapped = true;
3096      }
3097      session.commit();
3098
3099      if (ctxt != null && dev != null)
3100      {
3101        DjUserContextAssociation dca = cmgr.createNewUserContextAssociation();
3102        dca.setContext(ctxt);
3103        dca.setUser(dev);
3104        dca.setCreate(true);
3105        dca.setDelete(true);
3106        dca.setModify(true);
3107        dca.setQuery(true);
3108        dca.persist(session);
3109        session.commit();
3110      }
3111    }
3112    catch (NoSuchAlgorithmException JavaDoc e)
3113    {
3114      throw new DjenericException(e);
3115    }
3116    finally
3117    {
3118      session.close();
3119    }
3120    pd.displayProgress(msg);
3121    return strapped;
3122  }
3123
3124  public DjCredentials getCredentials(DjRepositoryDescriptor repository) throws LogonException
3125  {
3126    throw new LogonException(Messages.getString("DjPersistenceManager.NoDjMessengerCredentials"));
3127  }
3128
3129  public DjContext selectContext(DjContext[] ctxts) throws LogonException
3130  {
3131    throw new LogonException(Messages.getString("DjPersistenceManager.NoDjMessengerContext"));
3132  }
3133
3134  public DjRepositoryDescriptor selectRepository(DjRepositoryDescriptor[] descriptors) throws DjenericException
3135  {
3136    throw new LogonException(Messages.getString("DjPersistenceManager.NoDjMessengerRepository"));
3137  }
3138
3139  public void showMessage(String JavaDoc title, String JavaDoc msg)
3140  {
3141    System.out.println(title);
3142    System.out.println(msg);
3143  }
3144
3145  public void showWarning(String JavaDoc title, String JavaDoc msg)
3146  {
3147    System.err.println(title);
3148    System.err.println(msg);
3149  }
3150
3151  public void rebuildDependancies()
3152  {
3153    updateDetailRelations();
3154    updateSpecializations();
3155    updateHashes();
3156  }
3157
3158  public static int getMaxMappingCount(String JavaDoc mappingCode)
3159  {
3160    int sz = 0;
3161    if (mappingCode.equals(DjPersistenceManager.MAPPING_DAT)) sz = DjPersistenceManager.MAPPING_COLUMN_COUNT_DAT;
3162    if (mappingCode.equals(DjPersistenceManager.MAPPING_LNG)) sz = DjPersistenceManager.MAPPING_COLUMN_COUNT_LNG;
3163    if (mappingCode.equals(DjPersistenceManager.MAPPING_NUM)) sz = DjPersistenceManager.MAPPING_COLUMN_COUNT_NUM;
3164    if (mappingCode.equals(DjPersistenceManager.MAPPING_REL)) sz = DjPersistenceManager.MAPPING_COLUMN_COUNT_REL;
3165    if (mappingCode.equals(DjPersistenceManager.MAPPING_STR)) sz = DjPersistenceManager.MAPPING_COLUMN_COUNT_STR;
3166    if (mappingCode.equals(DjPersistenceManager.MAPPING_TXT)) sz = DjPersistenceManager.MAPPING_COLUMN_COUNT_TXT;
3167    return sz;
3168  }
3169
3170  public String JavaDoc[] getRoles()
3171  {
3172    return (String JavaDoc[]) _allRoles.toArray(new String JavaDoc[_allRoles.size()]);
3173  }
3174
3175  public void addRole(String JavaDoc role)
3176  {
3177    role = role.toLowerCase();
3178    if (!_allRoles.contains(role))
3179    {
3180      Collections.sort(_allRoles);
3181      _allRoles.add(role);
3182    }
3183  }
3184
3185  public void setRoles(String JavaDoc[] roles)
3186  {
3187    _allRoles.clear();
3188    if (roles != null)
3189    {
3190      for (int i = 0; i < roles.length; i++)
3191        _allRoles.add(roles[i]);
3192    }
3193  }
3194}
Popular Tags