KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > entity > model > ModelEntity


1 /*
2  * $Id: ModelEntity.java 6327 2005-12-14 18:56:54Z jaz $
3  *
4  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24 package org.ofbiz.entity.model;
25
26 import java.io.Serializable JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Set JavaDoc;
32
33 import javolution.util.FastList;
34 import javolution.util.FastMap;
35 import org.w3c.dom.Document JavaDoc;
36 import org.w3c.dom.Element JavaDoc;
37 import org.w3c.dom.NodeList JavaDoc;
38
39 import org.ofbiz.base.util.Debug;
40 import org.ofbiz.base.util.GeneralException;
41 import org.ofbiz.base.util.ObjectType;
42 import org.ofbiz.base.util.UtilMisc;
43 import org.ofbiz.base.util.UtilTimer;
44 import org.ofbiz.base.util.UtilXml;
45 import org.ofbiz.base.util.UtilValidate;
46 import org.ofbiz.entity.GenericDelegator;
47 import org.ofbiz.entity.GenericEntity;
48 import org.ofbiz.entity.GenericEntityException;
49 import org.ofbiz.entity.GenericValue;
50 import org.ofbiz.entity.config.DatasourceInfo;
51 import org.ofbiz.entity.config.EntityConfigUtil;
52 import org.ofbiz.entity.jdbc.DatabaseUtil;
53
54 /**
55  * Generic Entity - Entity model class
56  *
57  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
58  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
59  * @version $Rev: 6327 $
60  * @since 2.0
61  */

62 public class ModelEntity extends ModelInfo implements Comparable JavaDoc, Serializable JavaDoc {
63
64     public static final String JavaDoc module = ModelEntity.class.getName();
65
66     /** The name of the time stamp field for locking/syncronization */
67     public static final String JavaDoc STAMP_FIELD = "lastUpdatedStamp";
68     public static final String JavaDoc STAMP_TX_FIELD = "lastUpdatedTxStamp";
69     public static final String JavaDoc CREATE_STAMP_FIELD = "createdStamp";
70     public static final String JavaDoc CREATE_STAMP_TX_FIELD = "createdTxStamp";
71
72     /** The ModelReader that created this Entity */
73     protected ModelReader modelReader = null;
74
75     /** The entity-name of the Entity */
76     protected String JavaDoc entityName = "";
77
78     /** The table-name of the Entity */
79     protected String JavaDoc tableName = "";
80
81     /** The package-name of the Entity */
82     protected String JavaDoc packageName = "";
83
84     /** The default-resource-name of the Entity, used with the getResource call to check for a value in a resource bundle */
85     protected String JavaDoc defaultResourceName = "";
86
87     /** The entity-name of the Entity that this Entity is dependent on, if empty then no dependency */
88     protected String JavaDoc dependentOn = "";
89
90     /** A List of the Field objects for the Entity */
91     protected List JavaDoc fields = FastList.newInstance();
92     protected Map JavaDoc fieldsMap = null;
93
94     /** A List of the Field objects for the Entity, one for each Primary Key */
95     protected List JavaDoc pks = FastList.newInstance();
96
97     /** A List of the Field objects for the Entity, one for each NON Primary Key */
98     protected List JavaDoc nopks = FastList.newInstance();
99
100     /** relations defining relationships between this entity and other entities */
101     protected List JavaDoc relations = FastList.newInstance();
102
103     /** indexes on fields/columns in this entity */
104     protected List JavaDoc indexes = FastList.newInstance();
105
106     /** map of ModelViewEntities that references this model */
107     protected Map JavaDoc viewEntities = FastMap.newInstance();
108
109     /** An indicator to specify if this entity requires locking for updates */
110     protected boolean doLock = false;
111
112     /** Can be used to disable automatically creating update stamp fields and populating them on inserts and updates */
113     protected boolean noAutoStamp = false;
114
115     /** An indicator to specify if this entity is never cached.
116      * If true causes the delegator to not clear caches on write and to not get
117      * from cache on read showing a warning messages to that effect
118      */

119     protected boolean neverCache = false;
120
121     protected boolean autoClearCache = true;
122
123     // ===== CONSTRUCTORS =====
124
/** Default Constructor */
125     public ModelEntity() {}
126
127     /** XML Constructor */
128     protected ModelEntity(ModelReader reader, Element JavaDoc entityElement, ModelInfo def) {
129         super(def);
130         populateFromAttributes(entityElement);
131         this.modelReader = reader;
132     }
133
134     /** XML Constructor */
135     public ModelEntity(ModelReader reader, Element JavaDoc entityElement, UtilTimer utilTimer, ModelInfo def) {
136         this(reader, entityElement, def);
137
138         if (utilTimer != null) utilTimer.timerString(" createModelEntity: before general/basic info");
139         this.populateBasicInfo(entityElement);
140
141         if (utilTimer != null) utilTimer.timerString(" createModelEntity: before fields");
142         NodeList JavaDoc fieldList = entityElement.getElementsByTagName("field");
143         for (int i = 0; i < fieldList.getLength(); i++) {
144             ModelField field = reader.createModelField((Element JavaDoc) fieldList.item(i));
145             if (field != null) {
146                 field.setModelEntity(this);
147                 this.fields.add(field);
148             }
149         }
150
151         // if applicable automatically add the STAMP_FIELD and STAMP_TX_FIELD fields
152
if ((this.doLock || !this.noAutoStamp) && !this.isField(STAMP_FIELD)) {
153             ModelField newField = reader.createModelField(STAMP_FIELD, "date-time", null, false);
154             newField.setIsAutoCreatedInternal(true);
155             newField.setModelEntity(this);
156             this.fields.add(newField);
157         }
158         if (!this.noAutoStamp && !this.isField(STAMP_TX_FIELD)) {
159             ModelField newField = reader.createModelField(STAMP_TX_FIELD, "date-time", null, false);
160             newField.setIsAutoCreatedInternal(true);
161             newField.setModelEntity(this);
162             this.fields.add(newField);
163
164             // also add an index for this field
165
String JavaDoc indexName = ModelUtil.shortenDbName(this.tableName + "_TXSTMP", 18);
166             ModelIndex txIndex = new ModelIndex(this, indexName, false);
167             txIndex.addIndexField(ModelEntity.STAMP_TX_FIELD);
168             txIndex.setModelEntity(this);
169             indexes.add(txIndex);
170         }
171
172         // if applicable automatically add the CREATE_STAMP_FIELD and CREATE_STAMP_TX_FIELD fields
173
if ((this.doLock || !this.noAutoStamp) && !this.isField(CREATE_STAMP_FIELD)) {
174             ModelField newField = reader.createModelField(CREATE_STAMP_FIELD, "date-time", null, false);
175             newField.setIsAutoCreatedInternal(true);
176             newField.setModelEntity(this);
177             this.fields.add(newField);
178         }
179         if (!this.noAutoStamp && !this.isField(CREATE_STAMP_TX_FIELD)) {
180             ModelField newField = reader.createModelField(CREATE_STAMP_TX_FIELD, "date-time", null, false);
181             newField.setIsAutoCreatedInternal(true);
182             newField.setModelEntity(this);
183             this.fields.add(newField);
184
185             // also add an index for this field
186
String JavaDoc indexName = ModelUtil.shortenDbName(this.tableName + "_TXCRTS", 18);
187             ModelIndex txIndex = new ModelIndex(this, indexName, false);
188             txIndex.addIndexField(ModelEntity.CREATE_STAMP_TX_FIELD);
189             txIndex.setModelEntity(this);
190             indexes.add(txIndex);
191         }
192
193         if (utilTimer != null) utilTimer.timerString(" createModelEntity: before prim-keys");
194         NodeList JavaDoc pkList = entityElement.getElementsByTagName("prim-key");
195         for (int i = 0; i < pkList.getLength(); i++) {
196             ModelField field = reader.findModelField(this, ((Element JavaDoc) pkList.item(i)).getAttribute("field"));
197             if (field != null) {
198                 this.pks.add(field);
199                 field.isPk = true;
200             } else {
201                 Debug.logError("[ModelReader.createModelEntity] ERROR: Could not find field \"" +
202                     ((Element JavaDoc) pkList.item(i)).getAttribute("field") + "\" specified in a prim-key", module);
203             }
204         }
205
206         // now that we have the pks and the fields, make the nopks vector
207
this.nopks = FastList.newInstance();
208         for (int ind = 0; ind < this.fields.size(); ind++) {
209             ModelField field = (ModelField) this.fields.get(ind);
210             if (!field.isPk) this.nopks.add(field);
211         }
212
213         if (utilTimer != null) utilTimer.timerString(" createModelEntity: before relations");
214         this.populateRelated(reader, entityElement);
215         this.populateIndexes(entityElement);
216     }
217
218     /** DB Names Constructor */
219     public ModelEntity(String JavaDoc tableName, Map JavaDoc colMap, ModelFieldTypeReader modelFieldTypeReader, boolean isCaseSensitive) {
220         // if there is a dot in the name, remove it and everything before it, should be the schema name
221
this.tableName = tableName;
222         int dotIndex = this.tableName.indexOf(".");
223         if (dotIndex >= 0) {
224             this.tableName = this.tableName.substring(dotIndex + 1);
225         }
226         this.entityName = ModelUtil.dbNameToClassName(this.tableName);
227         Iterator JavaDoc columnEntryIter = colMap.entrySet().iterator();
228         while (columnEntryIter.hasNext()) {
229             Map.Entry JavaDoc columnEntry = (Map.Entry JavaDoc) columnEntryIter.next();
230             DatabaseUtil.ColumnCheckInfo ccInfo = (DatabaseUtil.ColumnCheckInfo) columnEntry.getValue();
231             ModelField newField = new ModelField(ccInfo, modelFieldTypeReader);
232             this.fields.add(newField);
233         }
234         this.updatePkLists();
235     }
236
237     protected void populateBasicInfo(Element JavaDoc entityElement) {
238         this.entityName = UtilXml.checkEmpty(entityElement.getAttribute("entity-name"));
239         this.tableName = UtilXml.checkEmpty(entityElement.getAttribute("table-name"), ModelUtil.javaNameToDbName(this.entityName));
240         this.packageName = UtilXml.checkEmpty(entityElement.getAttribute("package-name"));
241         this.defaultResourceName = UtilXml.checkEmpty(entityElement.getAttribute("default-resource-name"));
242         this.dependentOn = UtilXml.checkEmpty(entityElement.getAttribute("dependent-on"));
243         this.doLock = UtilXml.checkBoolean(entityElement.getAttribute("enable-lock"), false);
244         this.noAutoStamp = UtilXml.checkBoolean(entityElement.getAttribute("no-auto-stamp"), false);
245         this.neverCache = UtilXml.checkBoolean(entityElement.getAttribute("never-cache"), false);
246         this.autoClearCache = UtilXml.checkBoolean(entityElement.getAttribute("auto-clear-cache"), true);
247     }
248
249     protected void populateRelated(ModelReader reader, Element JavaDoc entityElement) {
250         NodeList JavaDoc relationList = entityElement.getElementsByTagName("relation");
251         for (int i = 0; i < relationList.getLength(); i++) {
252             Element JavaDoc relationElement = (Element JavaDoc) relationList.item(i);
253             if (relationElement.getParentNode() == entityElement) {
254                 ModelRelation relation = reader.createRelation(this, relationElement);
255                 if (relation != null) {
256                     relation.setModelEntity(this);
257                     this.relations.add(relation);
258                 }
259             }
260         }
261     }
262
263     protected void populateIndexes(Element JavaDoc entityElement) {
264         NodeList JavaDoc indexList = entityElement.getElementsByTagName("index");
265         for (int i = 0; i < indexList.getLength(); i++) {
266             Element JavaDoc indexElement = (Element JavaDoc) indexList.item(i);
267             if (indexElement.getParentNode() == entityElement) {
268                 ModelIndex index = new ModelIndex(this, indexElement);
269                 index.setModelEntity(this);
270                 this.indexes.add(index);
271             }
272         }
273     }
274
275     public boolean containsAllPkFieldNames(Set JavaDoc fieldNames) {
276         Iterator JavaDoc pksIter = this.getPksIterator();
277         while (pksIter.hasNext()) {
278             ModelField pkField = (ModelField) pksIter.next();
279             if (!fieldNames.contains(pkField.getName())) {
280                 return false;
281             }
282         }
283         return true;
284     }
285
286     // ===== GETTERS/SETTERS =====
287

288     public ModelReader getModelReader() {
289         return modelReader;
290     }
291
292     /** The entity-name of the Entity */
293     public String JavaDoc getEntityName() {
294         return this.entityName;
295     }
296
297     public void setEntityName(String JavaDoc entityName) {
298         this.entityName = entityName;
299     }
300
301     /** The plain table-name of the Entity without a schema name prefix */
302     public String JavaDoc getPlainTableName() {
303         return this.tableName;
304     }
305
306     /** The table-name of the Entity including a Schema name if specified in the datasource config */
307     public String JavaDoc getTableName(String JavaDoc helperName) {
308         return getTableName(EntityConfigUtil.getDatasourceInfo(helperName));
309     }
310
311     /** The table-name of the Entity including a Schema name if specified in the datasource config */
312     public String JavaDoc getTableName(DatasourceInfo datasourceInfo) {
313         if (datasourceInfo != null && datasourceInfo.schemaName != null && datasourceInfo.schemaName.length() > 0) {
314             return datasourceInfo.schemaName + "." + this.tableName;
315         } else {
316             return this.tableName;
317         }
318     }
319
320     public void setTableName(String JavaDoc tableName) {
321         this.tableName = tableName;
322     }
323
324     /** The package-name of the Entity */
325     public String JavaDoc getPackageName() {
326         return this.packageName;
327     }
328
329     public void setPackageName(String JavaDoc packageName) {
330         this.packageName = packageName;
331     }
332
333     /** The default-resource-name of the Entity */
334     public String JavaDoc getDefaultResourceName() {
335         return this.defaultResourceName;
336     }
337
338     public void setDefaultResourceName(String JavaDoc defaultResourceName) {
339         this.defaultResourceName = defaultResourceName;
340     }
341
342     /** The entity-name of the Entity that this Entity is dependent on, if empty then no dependency */
343     public String JavaDoc getDependentOn() {
344         return this.dependentOn;
345     }
346
347     public void setDependentOn(String JavaDoc dependentOn) {
348         this.dependentOn = dependentOn;
349     }
350
351     /** An indicator to specify if this entity is never cached.
352      * If true causes the delegator to not clear caches on write and to not get
353      * from cache on read showing a warning messages to that effect
354      */

355     public boolean getNeverCache() {
356         return this.neverCache;
357     }
358
359     public void setNeverCache(boolean neverCache) {
360         this.neverCache = neverCache;
361     }
362
363     public boolean getAutoClearCache() {
364         return this.autoClearCache;
365     }
366
367     public void setAutoClearCache(boolean autoClearCache) {
368         this.autoClearCache = autoClearCache;
369     }
370
371     /** An indicator to specify if this entity requires locking for updates */
372     public boolean getDoLock() {
373         return this.doLock;
374     }
375
376     public void setDoLock(boolean doLock) {
377         this.doLock = doLock;
378     }
379
380     public boolean lock() {
381         if (doLock && isField(STAMP_FIELD)) {
382             return true;
383         } else {
384             doLock = false;
385             return false;
386         }
387     }
388
389     public void updatePkLists() {
390         pks = FastList.newInstance();
391         nopks = FastList.newInstance();
392         for (int i = 0; i < fields.size(); i++) {
393             ModelField field = (ModelField) fields.get(i);
394
395             if (field.isPk)
396                 pks.add(field);
397             else
398                 nopks.add(field);
399         }
400     }
401
402     public boolean isField(String JavaDoc fieldName) {
403         if (fieldName == null) return false;
404         for (int i = 0; i < fields.size(); i++) {
405             ModelField field = (ModelField) fields.get(i);
406
407             if (field.name.equals(fieldName)) return true;
408         }
409         return false;
410     }
411
412     public boolean areFields(Collection JavaDoc fieldNames) {
413         if (fieldNames == null) return false;
414         Iterator JavaDoc iter = fieldNames.iterator();
415
416         while (iter.hasNext()) {
417             String JavaDoc fieldName = (String JavaDoc) iter.next();
418
419             if (!isField(fieldName)) return false;
420         }
421         return true;
422     }
423
424     public int getPksSize() {
425         return this.pks.size();
426     }
427
428     /**
429      * @deprecated
430      */

431     public ModelField getPk(int index) {
432         return (ModelField) this.pks.get(index);
433     }
434
435     public ModelField getOnlyPk() {
436         if (this.pks.size() == 1) {
437             return (ModelField) this.pks.get(0);
438         } else {
439             throw new IllegalArgumentException JavaDoc("Error in getOnlyPk, the [" + this.getEntityName() + "] entity has more than one pk!");
440         }
441     }
442
443     public Iterator JavaDoc getPksIterator() {
444         return this.pks.iterator();
445     }
446
447     public List JavaDoc getPksCopy() {
448         List JavaDoc newList = FastList.newInstance();
449         newList.addAll(this.pks);
450         return newList;
451     }
452
453     public String JavaDoc getFirstPkFieldName() {
454         List JavaDoc pkFieldNames = this.getPkFieldNames();
455         String JavaDoc idFieldName = null;
456         if (pkFieldNames != null && pkFieldNames.size() > 0) {
457             idFieldName = (String JavaDoc) pkFieldNames.get(0);
458         }
459         return idFieldName;
460     }
461
462     public int getNopksSize() {
463         return this.nopks.size();
464     }
465
466     /**
467      * @deprecated
468      */

469     public ModelField getNopk(int index) {
470         return (ModelField) this.nopks.get(index);
471     }
472
473     public Iterator JavaDoc getNopksIterator() {
474         return this.nopks.iterator();
475     }
476
477     public List JavaDoc getNopksCopy() {
478         List JavaDoc newList = FastList.newInstance();
479         newList.addAll(this.nopks);
480         return newList;
481     }
482
483     public int getFieldsSize() {
484         return this.fields.size();
485     }
486
487     /**
488      * @deprecated
489      */

490     public ModelField getField(int index) {
491         return (ModelField) this.fields.get(index);
492     }
493
494     public Iterator JavaDoc getFieldsIterator() {
495         return this.fields.iterator();
496     }
497
498     public List JavaDoc getFieldsCopy() {
499         List JavaDoc newList = FastList.newInstance();
500         newList.addAll(this.fields);
501         return newList;
502     }
503
504     /** The col-name of the Field, the alias of the field if this is on a view-entity */
505     public String JavaDoc getColNameOrAlias(String JavaDoc fieldName) {
506         ModelField modelField = this.getField(fieldName);
507         String JavaDoc fieldString = modelField.getColName();
508         return fieldString;
509     }
510
511     public ModelField getField(String JavaDoc fieldName) {
512         if (fieldName == null) return null;
513         if (fieldsMap == null) {
514             createFieldsMap();
515         }
516         ModelField modelField = (ModelField) fieldsMap.get(fieldName);
517         if (modelField == null) {
518             // sometimes weird things happen and this getField method is called before the fields are all populated, so before moving on just re-create the fieldsMap again real quick...
519
// the purpose of the fieldsMap is for speed, but if failures are a little slower, no biggie
520
createFieldsMap();
521             modelField = (ModelField) fieldsMap.get(fieldName);
522         }
523         return modelField;
524     }
525
526     protected synchronized void createFieldsMap() {
527         Map JavaDoc tempMap = FastMap.newInstance();
528         for (int i = 0; i < fields.size(); i++) {
529             ModelField field = (ModelField) fields.get(i);
530             tempMap.put(field.name, field);
531         }
532         fieldsMap = tempMap;
533     }
534
535     public void addField(ModelField field) {
536         if (field == null) return;
537         field.setModelEntity(this);
538         this.fields.add(field);
539
540         if (field.isPk) {
541             pks.add(field);
542         } else {
543             nopks.add(field);
544         }
545     }
546
547     public ModelField removeField(int index) {
548         ModelField field = null;
549
550         field = (ModelField) fields.remove(index);
551         if (field == null) return null;
552
553         if (field.isPk) {
554             pks.remove(field);
555         } else {
556             nopks.remove(field);
557         }
558         return field;
559     }
560
561     public ModelField removeField(String JavaDoc fieldName) {
562         if (fieldName == null) return null;
563         ModelField field = null;
564
565         for (int i = 0; i < fields.size(); i++) {
566             field = (ModelField) fields.get(i);
567             if (field.name.equals(fieldName)) {
568                 fields.remove(i);
569                 if (field.isPk) {
570                     pks.remove(field);
571                 } else {
572                     nopks.remove(field);
573                 }
574             }
575             field = null;
576         }
577         return field;
578     }
579
580     public List JavaDoc getAllFieldNames() {
581         return getFieldNamesFromFieldVector(fields);
582     }
583
584     public List JavaDoc getPkFieldNames() {
585         return getFieldNamesFromFieldVector(pks);
586     }
587
588     public List JavaDoc getNoPkFieldNames() {
589         return getFieldNamesFromFieldVector(nopks);
590     }
591
592     public List JavaDoc getFieldNamesFromFieldVector(List JavaDoc modelFields) {
593         List JavaDoc nameList = FastList.newInstance();
594
595         if (modelFields == null || modelFields.size() <= 0) return nameList;
596         for (int i = 0; i < modelFields.size(); i++) {
597             ModelField field = (ModelField) modelFields.get(i);
598
599             nameList.add(field.name);
600         }
601         return nameList;
602     }
603
604     public int getRelationsSize() {
605         return this.relations.size();
606     }
607
608     public int getRelationsOneSize() {
609         int numRels = 0;
610         Iterator JavaDoc relationsIter = this.getRelationsIterator();
611         while (relationsIter.hasNext()) {
612             ModelRelation modelRelation = (ModelRelation) relationsIter.next();
613             if ("one".equals(modelRelation.getType())) {
614                 numRels++;
615             }
616         }
617         return numRels;
618     }
619
620     public ModelRelation getRelation(int index) {
621         return (ModelRelation) this.relations.get(index);
622     }
623
624     public Iterator JavaDoc getRelationsIterator() {
625         return this.relations.iterator();
626     }
627
628     public ModelRelation getRelation(String JavaDoc relationName) {
629         if (relationName == null) return null;
630         for (int i = 0; i < relations.size(); i++) {
631             ModelRelation relation = (ModelRelation) relations.get(i);
632             if (relationName.equals(relation.title + relation.relEntityName)) return relation;
633         }
634         return null;
635     }
636
637     public void addRelation(ModelRelation relation) {
638         relation.setModelEntity(this);
639         this.relations.add(relation);
640     }
641
642     public ModelRelation removeRelation(int index) {
643         return (ModelRelation) this.relations.remove(index);
644     }
645
646     public int getIndexesSize() {
647         return this.indexes.size();
648     }
649
650     public ModelIndex getIndex(int index) {
651         return (ModelIndex) this.indexes.get(index);
652     }
653
654     public Iterator JavaDoc getIndexesIterator() {
655         return this.indexes.iterator();
656     }
657
658     public ModelIndex getIndex(String JavaDoc indexName) {
659         if (indexName == null) return null;
660         for (int i = 0; i < indexes.size(); i++) {
661             ModelIndex index = (ModelIndex) indexes.get(i);
662             if (indexName.equals(index.getName())) return index;
663         }
664         return null;
665     }
666
667     public void addIndex(ModelIndex index) {
668         index.setModelEntity(this);
669         this.indexes.add(index);
670     }
671
672     public ModelIndex removeIndex(int index) {
673         return (ModelIndex) this.indexes.remove(index);
674     }
675
676     public int getViewEntitiesSize() {
677         return this.viewEntities.size();
678     }
679
680     public ModelViewEntity getViewEntity(String JavaDoc viewEntityName) {
681         return (ModelViewEntity) this.viewEntities.get(viewEntityName);
682     }
683
684     public Iterator JavaDoc getViewConvertorsIterator() {
685         return this.viewEntities.entrySet().iterator();
686     }
687
688     public void addViewEntity(ModelViewEntity view) {
689         this.viewEntities.put(view.getEntityName(), view);
690     }
691
692     public List JavaDoc convertToViewValues(String JavaDoc viewEntityName, GenericEntity entity) {
693         if (entity == null || entity == GenericEntity.NULL_ENTITY || entity == GenericValue.NULL_VALUE) return UtilMisc.toList(entity);
694         ModelViewEntity view = (ModelViewEntity) this.viewEntities.get(viewEntityName);
695         return view.convert(getEntityName(), entity);
696     }
697
698     public ModelViewEntity removeViewEntity(String JavaDoc viewEntityName) {
699         return (ModelViewEntity) this.viewEntities.remove(viewEntityName);
700     }
701
702     public ModelViewEntity removeViewEntity(ModelViewEntity viewEntity) {
703        return removeViewEntity(viewEntity.getEntityName());
704     }
705
706     public String JavaDoc nameString(List JavaDoc flds) {
707         return nameString(flds, ", ", "");
708     }
709
710     public String JavaDoc nameString(List JavaDoc flds, String JavaDoc separator, String JavaDoc afterLast) {
711         StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
712
713         if (flds.size() < 1) {
714             return "";
715         }
716
717         int i = 0;
718
719         for (; i < flds.size() - 1; i++) {
720             returnString.append(((ModelField) flds.get(i)).name);
721             returnString.append(separator);
722         }
723         returnString.append(((ModelField) flds.get(i)).name);
724         returnString.append(afterLast);
725         return returnString.toString();
726     }
727
728     public String JavaDoc typeNameString(List JavaDoc flds) {
729         StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
730
731         if (flds.size() < 1) {
732             return "";
733         }
734
735         int i = 0;
736
737         for (; i < flds.size() - 1; i++) {
738             ModelField curField = (ModelField) flds.get(i);
739             returnString.append(curField.type);
740             returnString.append(" ");
741             returnString.append(curField.name);
742             returnString.append(", ");
743         }
744         ModelField curField = (ModelField) flds.get(i);
745         returnString.append(curField.type);
746         returnString.append(" ");
747         returnString.append(curField.name);
748         return returnString.toString();
749     }
750
751     public String JavaDoc fieldNameString() {
752         return fieldNameString(", ", "");
753     }
754
755     public String JavaDoc fieldNameString(String JavaDoc separator, String JavaDoc afterLast) {
756         return nameString(fields, separator, afterLast);
757     }
758
759     public String JavaDoc fieldTypeNameString() {
760         return typeNameString(fields);
761     }
762
763     public String JavaDoc primKeyClassNameString() {
764         return typeNameString(pks);
765     }
766
767     public String JavaDoc pkNameString() {
768         return pkNameString(", ", "");
769     }
770
771     public String JavaDoc pkNameString(String JavaDoc separator, String JavaDoc afterLast) {
772         return nameString(pks, separator, afterLast);
773     }
774
775     public String JavaDoc nonPkNullList() {
776         return fieldsStringList(fields, "null", ", ", false, true);
777     }
778
779     public String JavaDoc fieldsStringList(List JavaDoc flds, String JavaDoc eachString, String JavaDoc separator) {
780         return fieldsStringList(flds, eachString, separator, false, false);
781     }
782
783     public String JavaDoc fieldsStringList(List JavaDoc flds, String JavaDoc eachString, String JavaDoc separator, boolean appendIndex) {
784         return fieldsStringList(flds, eachString, separator, appendIndex, false);
785     }
786
787     public String JavaDoc fieldsStringList(List JavaDoc flds, String JavaDoc eachString, String JavaDoc separator, boolean appendIndex, boolean onlyNonPK) {
788         StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
789
790         if (flds.size() < 1) {
791             return "";
792         }
793
794         int i = 0;
795
796         for (; i < flds.size(); i++) {
797             if (onlyNonPK && ((ModelField) flds.get(i)).isPk) continue;
798             returnString.append(eachString);
799             if (appendIndex) returnString.append(i + 1);
800             if (i < flds.size() - 1) returnString.append(separator);
801         }
802         return returnString.toString();
803     }
804
805     public String JavaDoc colNameString(List JavaDoc flds) {
806         return colNameString(flds, ", ", "", false);
807     }
808
809     public String JavaDoc colNameString(List JavaDoc flds, String JavaDoc separator, String JavaDoc afterLast, boolean alias) {
810         StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
811
812         if (flds.size() < 1) {
813             return "";
814         }
815
816         Iterator JavaDoc fldsIt = flds.iterator();
817         while(fldsIt.hasNext()) {
818             ModelField field = (ModelField) fldsIt.next();
819             returnString.append(field.colName);
820             if (fldsIt.hasNext()) {
821                 returnString.append(separator);
822             }
823         }
824
825         returnString.append(afterLast);
826         return returnString.toString();
827     }
828
829     public String JavaDoc classNameString(List JavaDoc flds) {
830         return classNameString(flds, ", ", "");
831     }
832
833     public String JavaDoc classNameString(List JavaDoc flds, String JavaDoc separator, String JavaDoc afterLast) {
834         StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
835
836         if (flds.size() < 1) {
837             return "";
838         }
839
840         int i = 0;
841
842         for (; i < flds.size() - 1; i++) {
843             returnString.append(ModelUtil.upperFirstChar(((ModelField) flds.get(i)).name));
844             returnString.append(separator);
845         }
846         returnString.append(ModelUtil.upperFirstChar(((ModelField) flds.get(i)).name));
847         returnString.append(afterLast);
848         return returnString.toString();
849     }
850
851     public String JavaDoc finderQueryString(List JavaDoc flds) {
852         StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
853
854         if (flds.size() < 1) {
855             return "";
856         }
857         int i = 0;
858
859         for (; i < flds.size() - 1; i++) {
860             returnString.append(((ModelField) flds.get(i)).colName);
861             returnString.append(" like {");
862             returnString.append(i);
863             returnString.append("} AND ");
864         }
865         returnString.append(((ModelField) flds.get(i)).colName);
866         returnString.append(" like {");
867         returnString.append(i);
868         returnString.append("}");
869         return returnString.toString();
870     }
871
872     public String JavaDoc httpArgList(List JavaDoc flds) {
873         StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
874
875         if (flds.size() < 1) {
876             return "";
877         }
878         int i = 0;
879
880         for (; i < flds.size() - 1; i++) {
881             returnString.append("\"");
882             returnString.append(tableName);
883             returnString.append("_");
884             returnString.append(((ModelField) flds.get(i)).colName);
885             returnString.append("=\" + ");
886             returnString.append(((ModelField) flds.get(i)).name);
887             returnString.append(" + \"&\" + ");
888         }
889         returnString.append("\"");
890         returnString.append(tableName);
891         returnString.append("_");
892         returnString.append(((ModelField) flds.get(i)).colName);
893         returnString.append("=\" + ");
894         returnString.append(((ModelField) flds.get(i)).name);
895         return returnString.toString();
896     }
897
898     public String JavaDoc httpArgListFromClass(List JavaDoc flds) {
899         StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
900
901         if (flds.size() < 1) {
902             return "";
903         }
904
905         int i = 0;
906
907         for (; i < flds.size() - 1; i++) {
908             returnString.append("\"");
909             returnString.append(tableName);
910             returnString.append("_");
911             returnString.append(((ModelField) flds.get(i)).colName);
912             returnString.append("=\" + ");
913             returnString.append(ModelUtil.lowerFirstChar(entityName));
914             returnString.append(".get");
915             returnString.append(ModelUtil.upperFirstChar(((ModelField) flds.get(i)).name));
916             returnString.append("() + \"&\" + ");
917         }
918         returnString.append("\"");
919         returnString.append(tableName);
920         returnString.append("_");
921         returnString.append(((ModelField) flds.get(i)).colName);
922         returnString.append("=\" + ");
923         returnString.append(ModelUtil.lowerFirstChar(entityName));
924         returnString.append(".get");
925         returnString.append(ModelUtil.upperFirstChar(((ModelField) flds.get(i)).name));
926         returnString.append("()");
927         return returnString.toString();
928     }
929
930     public String JavaDoc httpArgListFromClass(List JavaDoc flds, String JavaDoc entityNameSuffix) {
931         StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
932
933         if (flds.size() < 1) {
934             return "";
935         }
936
937         int i = 0;
938
939         for (; i < flds.size() - 1; i++) {
940             returnString.append("\"");
941             returnString.append(tableName);
942             returnString.append("_");
943             returnString.append(((ModelField) flds.get(i)).colName);
944             returnString.append("=\" + ");
945             returnString.append(ModelUtil.lowerFirstChar(entityName));
946             returnString.append(entityNameSuffix);
947             returnString.append(".get");
948             returnString.append(ModelUtil.upperFirstChar(((ModelField) flds.get(i)).name));
949             returnString.append("() + \"&\" + ");
950         }
951         returnString.append("\"");
952         returnString.append(tableName);
953         returnString.append("_");
954         returnString.append(((ModelField) flds.get(i)).colName);
955         returnString.append("=\" + ");
956         returnString.append(ModelUtil.lowerFirstChar(entityName));
957         returnString.append(entityNameSuffix);
958         returnString.append(".get");
959         returnString.append(ModelUtil.upperFirstChar(((ModelField) flds.get(i)).name));
960         returnString.append("()");
961         return returnString.toString();
962     }
963
964     public String JavaDoc httpRelationArgList(List JavaDoc flds, ModelRelation relation) {
965         StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
966
967         if (flds.size() < 1) {
968             return "";
969         }
970
971         int i = 0;
972
973         for (; i < flds.size() - 1; i++) {
974             ModelKeyMap keyMap = relation.findKeyMapByRelated(((ModelField) flds.get(i)).name);
975
976             if (keyMap != null) {
977                 returnString.append("\"");
978                 returnString.append(tableName);
979                 returnString.append("_");
980                 returnString.append(((ModelField) flds.get(i)).colName);
981                 returnString.append("=\" + ");
982                 returnString.append(ModelUtil.lowerFirstChar(relation.mainEntity.entityName));
983                 returnString.append(".get");
984                 returnString.append(ModelUtil.upperFirstChar(keyMap.fieldName));
985                 returnString.append("() + \"&\" + ");
986             } else {
987                 Debug.logWarning("-- -- ENTITYGEN ERROR:httpRelationArgList: Related Key in Key Map not found for name: " + ((ModelField) flds.get(i)).name + " related entity: " + relation.relEntityName + " main entity: " + relation.mainEntity.entityName + " type: " + relation.type, module);
988             }
989         }
990         ModelKeyMap keyMap = relation.findKeyMapByRelated(((ModelField) flds.get(i)).name);
991
992         if (keyMap != null) {
993             returnString.append("\"");
994             returnString.append(tableName);
995             returnString.append("_");
996             returnString.append(((ModelField) flds.get(i)).colName);
997             returnString.append("=\" + ");
998             returnString.append(ModelUtil.lowerFirstChar(relation.mainEntity.entityName));
999             returnString.append(".get");
1000            returnString.append(ModelUtil.upperFirstChar(keyMap.fieldName));
1001            returnString.append("()");
1002        } else {
1003            Debug.logWarning("-- -- ENTITYGEN ERROR:httpRelationArgList: Related Key in Key Map not found for name: " + ((ModelField) flds.get(i)).name + " related entity: " + relation.relEntityName + " main entity: " + relation.mainEntity.entityName + " type: " + relation.type, module);
1004        }
1005        return returnString.toString();
1006    }
1007
1008    /*
1009     public String httpRelationArgList(ModelRelation relation) {
1010     String returnString = "";
1011     if(relation.keyMaps.size() < 1) { return ""; }
1012
1013     int i = 0;
1014     for(; i < relation.keyMaps.size() - 1; i++) {
1015     ModelKeyMap keyMap = (ModelKeyMap)relation.keyMaps.get(i);
1016     if(keyMap != null)
1017     returnString = returnString + "\"" + tableName + "_" + keyMap.relColName + "=\" + " + ModelUtil.lowerFirstChar(relation.mainEntity.entityName) + ".get" + ModelUtil.upperFirstChar(keyMap.fieldName) + "() + \"&\" + ";
1018     }
1019     ModelKeyMap keyMap = (ModelKeyMap)relation.keyMaps.get(i);
1020     returnString = returnString + "\"" + tableName + "_" + keyMap.relColName + "=\" + " + ModelUtil.lowerFirstChar(relation.mainEntity.entityName) + ".get" + ModelUtil.upperFirstChar(keyMap.fieldName) + "()";
1021     return returnString;
1022     }
1023     */

1024    public String JavaDoc typeNameStringRelatedNoMapped(List JavaDoc flds, ModelRelation relation) {
1025        StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
1026
1027        if (flds.size() < 1) {
1028            return "";
1029        }
1030
1031        int i = 0;
1032
1033        if (relation.findKeyMapByRelated(((ModelField) flds.get(i)).name) == null) {
1034            returnString.append(((ModelField) flds.get(i)).type);
1035            returnString.append(" ");
1036            returnString.append(((ModelField) flds.get(i)).name);
1037        }
1038        i++;
1039        for (; i < flds.size(); i++) {
1040            if (relation.findKeyMapByRelated(((ModelField) flds.get(i)).name) == null) {
1041                if (returnString.length() > 0) returnString.append(", ");
1042                returnString.append(((ModelField) flds.get(i)).type);
1043                returnString.append(" ");
1044                returnString.append(((ModelField) flds.get(i)).name);
1045            }
1046        }
1047        return returnString.toString();
1048    }
1049
1050    public String JavaDoc typeNameStringRelatedAndMain(List JavaDoc flds, ModelRelation relation) {
1051        StringBuffer JavaDoc returnString = new StringBuffer JavaDoc();
1052
1053        if (flds.size() < 1) {
1054            return "";
1055        }
1056
1057        int i = 0;
1058
1059        for (; i < flds.size() - 1; i++) {
1060            ModelKeyMap keyMap = relation.findKeyMapByRelated(((ModelField) flds.get(i)).name);
1061
1062            if (keyMap != null) {
1063                returnString.append(keyMap.fieldName);
1064                returnString.append(", ");
1065            } else {
1066                returnString.append(((ModelField) flds.get(i)).name);
1067                returnString.append(", ");
1068            }
1069        }
1070        ModelKeyMap keyMap = relation.findKeyMapByRelated(((ModelField) flds.get(i)).name);
1071
1072        if (keyMap != null) returnString.append(keyMap.fieldName);
1073        else returnString.append(((ModelField) flds.get(i)).name);
1074        return returnString.toString();
1075    }
1076
1077    public int compareTo(Object JavaDoc obj) {
1078        ModelEntity otherModelEntity = (ModelEntity) obj;
1079
1080        /* This DOESN'T WORK, so forget it... using two passes
1081         //sort list by fk dependencies
1082         
1083         if (this.getEntityName().equals(otherModelEntity.getEntityName())) {
1084         return 0;
1085         }
1086
1087         //look through relations for dependencies from this entity to the other
1088         Iterator relationsIter = this.getRelationsIterator();
1089         while (relationsIter.hasNext()) {
1090         ModelRelation modelRelation = (ModelRelation) relationsIter.next();
1091
1092         if ("one".equals(modelRelation.getType()) && modelRelation.getRelEntityName().equals(otherModelEntity.getEntityName())) {
1093         //this entity is dependent on the other entity, so put that entity earlier in the list
1094         return -1;
1095         }
1096         }
1097         
1098         //look through relations for dependencies from the other to this entity
1099         Iterator otherRelationsIter = otherModelEntity.getRelationsIterator();
1100         while (otherRelationsIter.hasNext()) {
1101         ModelRelation modelRelation = (ModelRelation) otherRelationsIter.next();
1102
1103         if ("one".equals(modelRelation.getType()) && modelRelation.getRelEntityName().equals(this.getEntityName())) {
1104         //the other entity is dependent on this entity, so put that entity later in the list
1105         return 1;
1106         }
1107         }
1108         
1109         return 0;
1110         */

1111
1112        return this.getEntityName().compareTo(otherModelEntity.getEntityName());
1113    }
1114
1115    public void convertFieldMapInPlace(Map JavaDoc inContext, GenericDelegator delegator) {
1116        Iterator JavaDoc modelFields = this.getFieldsIterator();
1117        while (modelFields.hasNext()) {
1118            ModelField modelField = (ModelField) modelFields.next();
1119            String JavaDoc fieldName = modelField.getName();
1120            Object JavaDoc oldValue = inContext.get(fieldName);
1121            if (oldValue != null) {
1122                inContext.put(fieldName, this.convertFieldValue(modelField, oldValue, delegator));
1123            }
1124        }
1125    }
1126
1127    public Object JavaDoc convertFieldValue(String JavaDoc fieldName, Object JavaDoc value, GenericDelegator delegator) {
1128        ModelField modelField = this.getField(fieldName);
1129        if (modelField == null) {
1130            String JavaDoc errMsg = "Could not convert field value: could not find an entity field for the name: [" + fieldName + "] on the [" + this.getEntityName() + "] entity.";
1131            throw new IllegalArgumentException JavaDoc(errMsg);
1132        }
1133        return convertFieldValue(modelField, value, delegator);
1134    }
1135
1136    public Object JavaDoc convertFieldValue(ModelField modelField, Object JavaDoc value, GenericDelegator delegator) {
1137        if (value == null || value == GenericEntity.NULL_FIELD) {
1138            return null;
1139        }
1140        String JavaDoc fieldJavaType = null;
1141        try {
1142            fieldJavaType = delegator.getEntityFieldType(this, modelField.getType()).getJavaType();
1143        } catch (GenericEntityException e) {
1144            String JavaDoc errMsg = "Could not convert field value: could not find Java type for the field: [" + modelField.getName() + "] on the [" + this.getEntityName() + "] entity: " + e.toString();
1145            Debug.logError(e, errMsg, module);
1146            throw new IllegalArgumentException JavaDoc(errMsg);
1147        }
1148        try {
1149            return ObjectType.simpleTypeConvert(value, fieldJavaType, null, null, false);
1150        } catch (GeneralException e) {
1151            String JavaDoc errMsg = "Could not convert field value for the field: [" + modelField.getName() + "] on the [" + this.getEntityName() + "] entity to the [" + fieldJavaType + "] type for the value [" + value + "]: " + e.toString();
1152            Debug.logError(e, errMsg, module);
1153            throw new IllegalArgumentException JavaDoc(errMsg);
1154        }
1155    }
1156
1157    /**
1158     * @return Returns the noAutoStamp.
1159     */

1160    public boolean getNoAutoStamp() {
1161        return this.noAutoStamp;
1162    }
1163
1164    /**
1165     * @param noAutoStamp The noAutoStamp to set.
1166     */

1167    public void setNoAutoStamp(boolean noAutoStamp) {
1168        this.noAutoStamp = noAutoStamp;
1169    }
1170
1171    public String JavaDoc toString() {
1172        return "ModelEntity[" + getEntityName() + "]";
1173    }
1174
1175    public Element JavaDoc toXmlElement(Document JavaDoc document, String JavaDoc packageName) {
1176        if (UtilValidate.isNotEmpty(this.getPackageName()) && !packageName.equals(this.getPackageName())) {
1177            Debug.logWarning("Export EntityModel XML Element [" + this.getEntityName() + "] with a NEW package - " + packageName, module);
1178        }
1179
1180        Element JavaDoc root = document.createElement("entity");
1181        root.setAttribute("entity-name", this.getEntityName());
1182        if (!this.getEntityName().equals(ModelUtil.dbNameToClassName(this.getPlainTableName())) ||
1183                !ModelUtil.javaNameToDbName(this.getEntityName()).equals(this.getPlainTableName())) {
1184                root.setAttribute("table-name", this.getPlainTableName());
1185        }
1186        root.setAttribute("package-name", packageName);
1187
1188        // additional elements
1189
if (UtilValidate.isNotEmpty(this.getDefaultResourceName())) {
1190            root.setAttribute("default-resource-name", this.getDefaultResourceName());
1191        }
1192
1193        if (UtilValidate.isNotEmpty(this.getDependentOn())) {
1194            root.setAttribute("dependent-on", this.getDependentOn());
1195        }
1196
1197        if (this.getDoLock()) {
1198            root.setAttribute("enable-lock", "true");
1199        }
1200
1201        if (this.getNoAutoStamp()) {
1202            root.setAttribute("no-auto-stamp", "true");
1203        }
1204
1205        if (this.getNeverCache()) {
1206            root.setAttribute("never-cache", "true");
1207        }
1208
1209        if (!this.getAutoClearCache()) {
1210            root.setAttribute("auto-clear-cache", "false");
1211        }
1212
1213        if (UtilValidate.isNotEmpty(this.getTitle())) {
1214            root.setAttribute("title", this.getTitle());
1215        }
1216
1217        if (UtilValidate.isNotEmpty(this.getCopyright())) {
1218            root.setAttribute("copyright", this.getCopyright());
1219        }
1220
1221        if (UtilValidate.isNotEmpty(this.getAuthor())) {
1222            root.setAttribute("author", this.getAuthor());
1223        }
1224
1225        if (UtilValidate.isNotEmpty(this.getVersion())) {
1226            root.setAttribute("version", this.getVersion());
1227        }
1228
1229        // description element
1230
if (UtilValidate.isNotEmpty(this.getDescription())) {
1231            UtilXml.addChildElementValue(root, "description", this.getDescription(), document);
1232        }
1233
1234        // append field elements
1235
Iterator JavaDoc fieldIter = this.getFieldsIterator();
1236        while (fieldIter != null && fieldIter.hasNext()) {
1237            ModelField field = (ModelField) fieldIter.next();
1238            if (!field.getIsAutoCreatedInternal()) {
1239                root.appendChild(field.toXmlElement(document));
1240            }
1241        }
1242
1243        // append PK elements
1244
Iterator JavaDoc pkIter = this.getPksIterator();
1245        while (pkIter != null && pkIter.hasNext()) {
1246            ModelField pk = (ModelField) pkIter.next();
1247            Element JavaDoc pkey = document.createElement("prim-key");
1248            pkey.setAttribute("field", pk.getName());
1249            root.appendChild(pkey);
1250        }
1251
1252        // append relation elements
1253
Iterator JavaDoc relIter = this.getRelationsIterator();
1254        while (relIter != null && relIter.hasNext()) {
1255            ModelRelation rel = (ModelRelation) relIter.next();
1256
1257        }
1258
1259        // append index elements
1260
Iterator JavaDoc idxIter = this.getIndexesIterator();
1261        while (idxIter != null && idxIter.hasNext()) {
1262            ModelIndex idx = (ModelIndex) idxIter.next();
1263            root.appendChild(idx.toXmlElement(document));
1264
1265        }
1266
1267        return root;
1268    }
1269
1270    public Element JavaDoc toXmlElement(Document JavaDoc document) {
1271        return this.toXmlElement(document, this.getPackageName());
1272    }
1273}
1274
1275
Popular Tags