KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > finalist > jaggenerator > modules > Field


1 /* Copyright (C) 2003 Finalist IT Group
2  *
3  * This file is part of JAG - the Java J2EE Application Generator
4  *
5  * JAG is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * JAG is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  * You should have received a copy of the GNU General Public License
14  * along with JAG; if not, write to the Free Software
15  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16  */

17
18 package com.finalist.jaggenerator.modules;
19
20 import com.finalist.jag.util.TemplateString;
21 import com.finalist.jaggenerator.Column;
22 import com.finalist.jaggenerator.JagGenerator;
23 import com.finalist.jaggenerator.Utils;
24 import com.finalist.jaggenerator.validation.StrutsValidation;
25 import org.w3c.dom.Document JavaDoc;
26 import org.w3c.dom.Element JavaDoc;
27 import org.w3c.dom.NodeList JavaDoc;
28
29 import javax.swing.*;
30 import javax.swing.tree.DefaultMutableTreeNode JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.HashSet JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.List JavaDoc;
35
36 /**
37  * @author hillie
38  */

39 public class Field extends DefaultMutableTreeNode JavaDoc implements JagBean {
40     private StrutsValidation validations = new StrutsValidation();
41     private Relation relation;
42     private Entity parentEntity;
43     private boolean previousRequiredState;
44     private String JavaDoc oldName;
45     private static final ArrayList JavaDoc jdbcTypes = new ArrayList JavaDoc();
46     private boolean nullable = true;
47
48     /**
49      * Static set of classes for which the UniqueIdGenerator is able to generate primary keys.
50      */

51     private final static HashSet JavaDoc autogeneratablePrimaryKeyClasses = new HashSet JavaDoc();
52
53     static {
54         autogeneratablePrimaryKeyClasses.add("java.lang.Byte");
55         autogeneratablePrimaryKeyClasses.add("java.lang.Double");
56         autogeneratablePrimaryKeyClasses.add("java.lang.Integer");
57         autogeneratablePrimaryKeyClasses.add("java.lang.Long");
58         autogeneratablePrimaryKeyClasses.add("java.lang.Short");
59         autogeneratablePrimaryKeyClasses.add("java.lang.String");
60
61         java.lang.reflect.Field JavaDoc[] fields = java.sql.Types JavaDoc.class.getDeclaredFields();
62         for (int i = 0; i < fields.length; i++) {
63             jdbcTypes.add(fields[i].getName());
64         }
65     }
66
67
68     /**
69      * Creates new form BeanForm
70      */

71     public Field(Entity parent, Column column) {
72         parentEntity = parent;
73         try {
74             init();
75             String JavaDoc name = Utils.format(column.getName());
76             nullable = column.isNullable();
77             nameText.setText(name);
78             oldName = name;
79             typeText.setText(getType(column));
80             columnNameText.setText(column.getName());
81             sqlTypeText.setText(getSqlType(column));
82             jdbcTypeComboBox.setSelectedItem(getJdbcType(column));
83             if (column.isPrimaryKey()) {
84                 setPrimaryKey(column.isPrimaryKey());
85             }
86             if (primaryKeyCheckBox.isSelected()) {
87                 autoGeneratedCheckBox.setSelected(isPkClassIsAutogeneratable());
88             }
89             requiredCheckBox.setSelected(!nullable);
90             regenerateValidations();
91
92         } catch (Exception JavaDoc e) {
93             e.printStackTrace();
94         }
95     }
96
97
98     /**
99      * Use for building up the entity field gui component
100      */

101     public Field(Entity parent, Element JavaDoc el) {
102         parentEntity = parent;
103         try {
104             init();
105             NodeList JavaDoc nl = el.getElementsByTagName("module-data");
106
107             for (int i = 0; i < nl.getLength(); i++) {
108                 Element JavaDoc child = (Element JavaDoc) nl.item(i);
109                 String JavaDoc attName = child.getAttribute("name");
110                 String JavaDoc value = null;
111                 if (child.getFirstChild() != null)
112                     value = child.getFirstChild().getNodeValue();
113                 if (value != null) {
114                     if (attName.equalsIgnoreCase("name")) {
115                         nameText.setText(value);
116                         oldName = value;
117                         continue;
118                     }
119                     if (attName.equalsIgnoreCase("type")) {
120                         typeText.setText(value);
121                         continue;
122                     }
123                     if (attName.equalsIgnoreCase("column-name")) {
124                         columnNameText.setText(value);
125                         continue;
126                     }
127                     if (attName.equalsIgnoreCase("required")) {
128                         boolean required = "true".equalsIgnoreCase(value);
129                         nullable = !required;
130                         requiredCheckBox.setSelected(required);
131                         continue;
132                     }
133                     if (attName.equalsIgnoreCase("sql-type")) {
134                         sqlTypeText.setText(value);
135                         continue;
136                     }
137                     if (attName.equalsIgnoreCase("jdbc-type")) {
138                         jdbcTypeComboBox.setSelectedItem(value);
139                         continue;
140                     }
141                     if (attName.equalsIgnoreCase("primary-key")) {
142                         // Don't use the setPrimaryKey method for non-primary keys,
143
// since it will overrule the required and auto-primary key settings.
144
if ("true".equalsIgnoreCase(value)) {
145                             setPrimaryKey(true);
146                         } else {
147                             primaryKeyCheckBox.setSelected(false);
148                         }
149                         continue;
150                     }
151                     if (attName.equalsIgnoreCase("auto-primary-key")) {
152                         autoGeneratedCheckBox.setSelected("true".equalsIgnoreCase(value)
153                                 && isPkClassIsAutogeneratable());
154                         continue;
155                     }
156                     if (attName.equalsIgnoreCase("foreign-key")) {
157                         setForeignKey("true".equalsIgnoreCase(value.trim()));
158                         continue;
159                     }
160                     if (attName.equalsIgnoreCase("validation-depends")) {
161                         if (value != null) {
162                             validations.setDependsList(value);
163                             validationDependsText.setText(value);
164                         } else {
165                             validationDependsText.setText("");
166                         }
167                         continue;
168                     }
169                     if (attName.equalsIgnoreCase("validation-xml")) {
170                         if (value != null) {
171                             validations.setXml(value);
172                             validationXMLTextArea.setText(value);
173                         } else {
174                             validationXMLTextArea.setText("");
175                         }
176                         continue;
177                     }
178                 }
179             }
180
181         } catch (Exception JavaDoc e) {
182             e.printStackTrace();
183         }
184     }
185
186
187     public String JavaDoc toString() {
188         return nameText.getText();
189     }
190
191     public JPanel getPanel() {
192         return panel;
193     }
194
195     public void getXML(Element JavaDoc el) {
196         Document JavaDoc doc = el.getOwnerDocument();
197         Element JavaDoc module = doc.createElement("module-data");
198         module.setAttribute("name", "field");
199
200         Element JavaDoc name = doc.createElement("module-data");
201         name.setAttribute("name", "name");
202         if (nameText.getText() != null) {
203             if (nameText.getText() != null) {
204                 name.appendChild(doc.createTextNode(nameText.getText()));
205             }
206         }
207         module.appendChild(name);
208
209         Element JavaDoc type = doc.createElement("module-data");
210         type.setAttribute("name", "type");
211         if (typeText.getText() != null) {
212             type.appendChild(doc.createTextNode(typeText.getText()));
213         }
214         module.appendChild(type);
215
216         Element JavaDoc columnName = doc.createElement("module-data");
217         columnName.setAttribute("name", "column-name");
218         if (columnNameText.getText() != null) {
219             columnName.appendChild(doc.createTextNode(columnNameText.getText()));
220         }
221         module.appendChild(columnName);
222
223
224         Element JavaDoc required = doc.createElement("module-data");
225         required.setAttribute("name", "required");
226         required.appendChild(doc.createTextNode(Boolean.toString(requiredCheckBox.isSelected())));
227         module.appendChild(required);
228
229
230         Element JavaDoc sqlType = doc.createElement("module-data");
231         sqlType.setAttribute("name", "sql-type");
232         if (sqlTypeText.getText() != null) {
233             sqlType.appendChild(doc.createTextNode(sqlTypeText.getText()));
234         }
235         module.appendChild(sqlType);
236
237         Element JavaDoc jdbcType = doc.createElement("module-data");
238         jdbcType.setAttribute("name", "jdbc-type");
239         jdbcType.appendChild(doc.createTextNode(jdbcTypeComboBox.getSelectedItem().toString()));
240         module.appendChild(jdbcType);
241
242         Element JavaDoc primaryKey = doc.createElement("module-data");
243         primaryKey.setAttribute("name", "primary-key");
244         primaryKey.appendChild(doc.createTextNode(Boolean.toString(primaryKeyCheckBox.isSelected())));
245         module.appendChild(primaryKey);
246
247         Element JavaDoc autoPrimary = doc.createElement("module-data");
248         autoPrimary.setAttribute("name", "auto-primary-key");
249         autoPrimary.appendChild(doc.createTextNode(Boolean.toString(autoGeneratedCheckBox.isSelected())));
250         module.appendChild(autoPrimary);
251
252         Element JavaDoc foreignKey = doc.createElement("module-data");
253         foreignKey.setAttribute("name", "foreign-key");
254         foreignKey.appendChild(doc.createTextNode("" + isForeignKey()));
255         module.appendChild(foreignKey);
256
257         Element JavaDoc validationDepends = doc.createElement("module-data");
258         validationDepends.setAttribute("name", "validation-depends");
259         if (validationDependsText.getText() != null) {
260             validationDepends.appendChild(doc.createTextNode(validationDependsText.getText()));
261         }
262         module.appendChild(validationDepends);
263
264         Element JavaDoc validationXml = doc.createElement("module-data");
265         validationXml.setAttribute("name", "validation-xml");
266         if (validationXMLTextArea.getText() != null) {
267             validationXml.appendChild(doc.createTextNode(validationXMLTextArea.getText()));
268         }
269         module.appendChild(validationXml);
270
271         el.appendChild(module);
272     }
273
274     public TemplateString getSqlType() {
275         return new TemplateString(sqlTypeText.getText());
276     }
277
278     public void setSqlType(String JavaDoc text) {
279         sqlTypeText.setText(text);
280     }
281
282     public TemplateString getJdbcType() {
283         return new TemplateString(jdbcTypeComboBox.getSelectedItem().toString());
284     }
285
286     public void setJdbcType(String JavaDoc text) {
287         jdbcTypeComboBox.setSelectedItem(text);
288     }
289
290     public TemplateString getPrimaryKey() {
291         return new TemplateString(Boolean.toString(primaryKeyCheckBox.isSelected()));
292     }
293
294     public TemplateString getForeignKey() {
295         return new TemplateString(Boolean.toString(isForeignKey()));
296     }
297
298     public String JavaDoc getValidationDepends() {
299         if (validationDependsText.getText() == null) {
300             return "";
301         } else {
302             return validationDependsText.getText();
303         }
304     }
305
306     public String JavaDoc getValidationXml() {
307         return validationXMLTextArea.getText();
308     }
309
310     /**
311      * Check if the field is a date field.
312      *
313      * @return true if the field is a date field
314      */

315     public String JavaDoc isDate() {
316         if ("java.sql.Date".equals(getType())) {
317             return "true";
318         }
319         if ("java.util.Date".equals(getType())) {
320             return "true";
321         }
322         return "false";
323     }
324
325     /**
326      * Check if the field is a time field.
327      *
328      * @return true if the field is a time field
329      */

330     public String JavaDoc isTime() {
331         if ("java.sql.Time".equals(getType())) {
332             return "true";
333         }
334         if ("java.sql.Timestamp".equals(getType())) {
335             return "true";
336         }
337         return "false";
338     }
339
340     public String JavaDoc getType(Column column) {
341         if (column.getSqlType() == null) {
342             return "";
343         }
344         String JavaDoc sqlType = column.getSqlType().toUpperCase();
345         int scale = column.getScale();
346         int precision = column.getPrecision();
347         if (sqlType == null)
348             return "";
349         if (sqlType.equals("DATE"))
350             return "java.sql.Date";
351         if (sqlType.equals("BOOL"))
352             return "java.lang.Boolean";
353         if (sqlType.equals("FLOAT"))
354             return "java.lang.Float";
355         if (sqlType.equals("DOUBLE"))
356             return "java.lang.Double";
357         if (sqlType.equals("FLOAT(7)"))
358             return "java.lang.Float";
359         if (sqlType.equals("FLOAT8"))
360             return "java.lang.Double";
361         if (contains(sqlType, "NUMERIC") || contains(sqlType, "NUMERIC"))
362             return "java.math.BigDecimal";
363         if (sqlType.equals("BYTEA")) {
364             System.out.println("Mapping the BYTEA binary type to java.sql.Blob. JAG has no support for binary fields.");
365             return "java.sql.Blob";
366         }
367         if ((sqlType.indexOf("TIMESTAMP") != -1) || (sqlType.indexOf("DATETIME") != -1))
368             return "java.sql.Timestamp";
369         if (sqlType.equals("TIME"))
370             return "java.sql.Time";
371         if (contains(sqlType, "TINYINT"))
372             return "java.lang.Byte";
373         if (contains(sqlType, "SMALLINT"))
374             return "java.lang.Short";
375         if (contains(sqlType, "BIGINT"))
376             return "java.lang.Long";
377         if (contains(sqlType, "DECIMAL"))
378             return "java.math.BigDecimal";
379         if (contains(sqlType, "BLOB"))
380             return "java.sql.Blob";
381         if (contains(sqlType, "SERIAL"))
382             return "java.lang.Long";
383        if (contains(sqlType, "IDENTITY"))
384            return "java.lang.Long";
385         if (sqlType.equals("NUMBER") || sqlType.equals("INT") ||
386                 sqlType.equals("YEAR") ||
387                 sqlType.indexOf("INT") > -1) {
388             if (scale == 0) {
389                 if (precision == 0) {
390                     // this is the case for pseudo columns
391
// like sequences, count(*) etc.
392
// by convention, let's convert them to Integer
393
return "java.lang.Integer";
394                 }
395                 if (precision <= 2) {
396                     //let it be a byte
397
//
398
return "java.lang.Integer";
399                 }
400                 if (precision <= 5) {
401                     return "java.lang.Integer";
402                 }
403                 if (precision <= 9) {
404                     //let it be an int
405
return "java.lang.Integer";
406                 }
407                 if (precision <= 18) {
408                     if (sqlType.indexOf("INT") != -1) {
409                         return "java.lang.Integer";
410                     }
411                     //let it be a long
412
return "java.lang.Long";
413                 } else {
414                     return "java.math.BigDecimal";
415                 }
416             }
417             if (precision + scale <= 12) {
418                 //return "java.lang.Float";
419
return "java.math.BigDecimal";
420             }
421             if (precision + scale <= 64) {
422                 return "java.lang.Double";
423             } else {
424                 return "java.math.BigDecimal";
425             }
426         }
427
428         if (sqlType.indexOf("CHAR") > -1) {
429             return "java.lang.String";
430         }
431         if (sqlType.indexOf("TEXT") > -1) {
432             return "java.lang.String";
433         }
434         System.out.println("unknown sql type: " + sqlType + " Map it to a String.");
435         return "java.lang.String";
436     }
437
438     public String JavaDoc getJdbcType(Column column) {
439         if (column.getSqlType() == null) {
440             return "";
441         }
442         String JavaDoc sqlType = column.getSqlType().toUpperCase();
443         int scale = column.getScale();
444         int precision = column.getPrecision();
445         if (sqlType == null)
446             return "";
447
448         if (sqlType.equals("NUMERIC") || sqlType.equals("TINYINT") || sqlType.equals("SMALLINT") ||
449                 sqlType.equals("DOUBLE") || sqlType.equals("TIMESTAMP") || sqlType.equals("FLOAT") ||
450                 sqlType.equals("DATE") || sqlType.equals("TIME") || contains(sqlType, "BIGINT") ||
451                 sqlType.equals("DECIMAL"))
452             return sqlType;
453
454         if (contains(sqlType, "CHAR")) {
455             return "VARCHAR";
456         }
457         if (contains(sqlType, "TEXT")) {
458             return "VARCHAR";
459         }
460         if (sqlType.equals("DATETIME"))
461             return "TIMESTAMP";
462         // Postgress specific:
463
if (sqlType.equals("FLOAT(7)"))
464             return "FLOAT";
465         // Postgress specific:
466
if (sqlType.equals("FLOAT8"))
467             return "DOUBLE";
468         if (sqlType.equals("BYTEA"))
469             return "VARBINARY";
470         if (contains(sqlType, "BLOB")) {
471             return "BLOB";
472         }
473        if (contains(sqlType, "SERIAL"))
474            return "INTEGER";
475        if (contains(sqlType, "IDENTITY"))
476            return "INTEGER";
477         if (sqlType.equals("NUMBER") || contains(sqlType, "INT") || sqlType.equals("YEAR")) {
478             if (scale == 0) {
479                 if (precision == 0) {
480                     // this is the case for pseudo columns
481
// like sequences, count(*) etc.
482
// by convention, let's convert them to Integer
483
return "INTEGER";
484                 }
485                 if (precision <= 5) {
486                     //let it be a byte
487
return "INTEGER";
488                 }
489                 if (precision <= 9) {
490                     //let it be an int
491
return "INTEGER";
492                 }
493                 if (precision <= 18) {
494                     if (sqlType.indexOf("INT") != -1) {
495                         return "INTEGER";
496                     }
497                     //let it be a long
498
return "BIGINT";
499                 }
500             }
501             if (precision + scale <= 12) {
502                 return "DECIMAL";
503             }
504             if (precision + scale <= 64) {
505                 return "DOUBLE";
506             }
507         }
508
509         return "JAVA_OBJECT";
510     }
511
512     public String JavaDoc getSqlType(Column column) {
513         if (column.getSqlType() == null) {
514             return "";
515         }
516         String JavaDoc sqlType = column.getSqlType().toUpperCase();
517         int scale = column.getScale();
518         int precision = column.getPrecision();
519         int length = column.getLength();
520         if (sqlType == null)
521             return "";
522         if (sqlType.equals("NUMBER") || sqlType.equals("DOUBLE") || contains(sqlType, "INT") ||
523                 sqlType.equals("YEAR") || sqlType.equals("FLOAT") || sqlType.equals("DECIMAL")) {
524             if (precision > 0) {
525                 sqlType = sqlType + "(" + precision;
526                 if (scale != 0) {
527                     sqlType = sqlType + ", " + scale;
528                 }
529                 sqlType = sqlType + ")";
530             }
531             return sqlType;
532         }
533         if (sqlType.indexOf("CHAR") > -1) {
534             if (length > 0) {
535                 return sqlType + "(" + length + ")";
536             }
537         }
538         return sqlType;
539     }
540
541
542     /**
543      * Helper method to determine the max size of a field.
544      * -1 will be returned fields without a size specification.
545      *
546      * @return max size of a field.
547      */

548     public int getMaxSize() {
549         String JavaDoc jdbcType = getJdbcType().toString();
550         int size;
551         if ("VARCHAR".equals(jdbcType) || "CHAR".equals(jdbcType) || "LONGVARCHAR".equals(jdbcType)) {
552             size = -1;
553         } else {
554             return -1;
555         }
556         String JavaDoc sqlType = getSqlType().toString();
557         if (sqlType == null) {
558             return size;
559         }
560         int beginIndex = sqlType.indexOf("(");
561         int endIndex = sqlType.indexOf(",");
562         if (endIndex == -1) {
563             endIndex = sqlType.indexOf(")");
564         }
565         if (beginIndex == -1 || endIndex == -1) {
566             return size;
567         }
568         String JavaDoc strSize = sqlType.substring(beginIndex + 1, endIndex);
569         try {
570             size = Integer.parseInt(strSize);
571             return size;
572         } catch (Exception JavaDoc e) {
573             return size;
574         }
575     }
576
577     public String JavaDoc getRefName() {
578         return null;
579     }
580
581
582     /**
583      * Return true if the field is a numeric field,
584      * like Integer, Short etc..
585      *
586      * @return true if numeric
587      */

588     public boolean isNumeric() {
589         return ("java.lang.Integer".equals(getType())) ||
590                 ("java.lang.Byte".equals(getType())) ||
591                 ("java.lang.Long".equals(getType())) ||
592                 ("java.lang.Short".equals(getType()));
593     }
594
595
596    /**
597     * Determine if the field can be used with a sequence.
598     * For this the following must apply:
599     * - the field needs to be a primary key
600     * - the autogenerate primary key checkbox should be on.
601     * - the database should be oracle or postgresql with a Serial field.
602     *
603     * @return true if sequence is allowed
604     */

605    public boolean isSequenceField() {
606    if (isPrimaryKey() && getHasAutoGenPrimaryKey() ) {
607       Datasource d = getDatasource();
608       String JavaDoc mapping = d.getTypeMapping().getLower();
609       if (mapping.startsWith("mysql")) {
610          return false;
611       }
612       // For Oracle there is no autoincrement field. Always use true.
613
if (mapping.startsWith("oracle")) {
614          return true;
615       }
616       if (mapping.startsWith("postgresql")) {
617          // Postgresql supporst sequence, but if the field is a Serial field, we don't want to use them.
618
if (getSqlType().getLower().startsWith("serial")) {
619             return false;
620          } else {
621             return true;
622          }
623       }
624       if (mapping.startsWith("hypersonic")) {
625          if (getSqlType().getLower().startsWith("identity")) {
626             return false;
627          } else {
628             return true;
629          }
630       }
631    }
632    // By default, return false.
633
return false;
634    }
635
636
637    private Config getConfig() {
638       List JavaDoc services = JagGenerator.getObjectsFromTree(Config.class);
639       for (int i=0; i<services.size(); i++) {
640          Config c = (Config) services.get(i);
641          return c;
642       }
643       return null;
644    }
645
646    private Datasource getDatasource() {
647       List JavaDoc services = JagGenerator.getObjectsFromTree(Datasource.class);
648       for (int i=0; i<services.size(); i++) {
649          Datasource d = (Datasource) services.get(i);
650          return d;
651       }
652       return null;
653    }
654
655     /**
656      * Indicates whether the field is part of the primary key.
657      *
658      * @return <code>true</code> if the field is part of the primary key
659      */

660     public boolean isPrimaryKey() {
661         return primaryKeyCheckBox.isSelected();
662     }
663
664
665     public boolean getHasAutoGenPrimaryKey() {
666         return autoGeneratedCheckBox.isSelected();
667     }
668
669     public void setHasAutoGenPrimaryKey(boolean value) {
670         autoGeneratedCheckBox.setSelected(value);
671     }
672
673     /**
674      * Setter for this field, which specifies whether or not this Field is a foreign key field within its table.
675      *
676      * @param foreignKey
677      */

678     public void setForeignKey(boolean foreignKey) {
679         foreignKeyCheckBox.setSelected(foreignKey);
680     }
681
682     public boolean isForeignKey() {
683         return foreignKeyCheckBox.isSelected();
684     }
685
686     /**
687      * Returns the class that represents the primary key type
688      *
689      * @return the class that represents the primary key type
690      */

691     public String JavaDoc getType() {
692         return typeText.getText();
693     }
694
695     /**
696      * Set the field type
697      *
698      * @param text type.
699      */

700     public void setType(String JavaDoc text) {
701         typeText.setText(text);
702     }
703
704     /**
705      * Returns the name of the field
706      *
707      * @return the name of the field.
708      */

709     public TemplateString getName() {
710         return new TemplateString(nameText.getText());
711     }
712
713     /**
714      * Sets the name of the field
715      *
716      * @param name the name of the field.
717      */

718     public void setName(String JavaDoc name) {
719         oldName = nameText.getText();
720         nameText.setText(name);
721     }
722
723     public String JavaDoc getColumnName() {
724         return columnNameText.getText();
725     }
726
727     /**
728      * Gets the relation, if this field represents a container-managed relation field in its parent entity bean.
729      *
730      * @return the Relation object, or <code>null</code> if this field doesn't represent a relation.
731      */

732     public Relation getRelation() {
733         return relation;
734     }
735
736     public void setRelation(Relation relation) {
737         this.relation = relation;
738     }
739
740     public boolean isRelation() {
741         return relation != null;
742     }
743
744     /**
745      * Make the nullable field available.
746      *
747      * @return true if the field is nullable.
748      */

749     public boolean isNullable() {
750         return nullable;
751     }
752
753     /**
754      * Return true if the field is required, so nullable is true.
755      *
756      * @return true if the field is required.
757      */

758     public boolean isRequired() {
759         return !nullable;
760     }
761
762
763     /**
764      * Return the size of a sql type in case it is a string type. Otherwise return null.
765      *
766      * @return get the size.
767      */

768     public String JavaDoc getSize() {
769         TemplateString theType = getSqlType();
770         if (theType == null) {
771             return null;
772         }
773         List JavaDoc parameters = StrutsValidation.getParams(getSqlType().toString());
774         if (getSqlType().toString().indexOf("CHAR") != -1 && !parameters.isEmpty()) {
775             return (String JavaDoc) parameters.get(0);
776         }
777         return null;
778     }
779
780
781     /**
782      * Regenerates the Struts validations for this field.
783      */

784     public void regenerateValidations() {
785         validations = new StrutsValidation(sqlTypeText.getText(),
786                 jdbcTypeComboBox.getSelectedItem().toString(), enforceRequiredValidation());
787         if (validations.getDependsList() != null) {
788             validationDependsText.setText(validations.getDependsList());
789         } else {
790             validationDependsText.setText("");
791         }
792         if (validations.getXml() != null) {
793             validationXMLTextArea.setText(validations.getXml());
794         } else {
795             validationXMLTextArea.setText("");
796         }
797     }
798
799
800     private boolean enforceRequiredValidation() {
801         //primary key fields are always 'required' (can't be null), but in the webapp we only validate this
802
//if the pk field isn't auto-generated.
803
return getHasAutoGenPrimaryKey() ? false : requiredCheckBox.isSelected();
804     }
805
806     /**
807      * A heap of things happen when you set a field as primary key - keep them all here!
808      *
809      * @param value
810      */

811     public void setPrimaryKey(boolean value) {
812         primaryKeyCheckBox.setSelected(value);
813         autoGeneratedCheckBox.setEnabled(value);
814         requiredCheckBox.setEnabled(!value);
815         if (value) {
816             previousRequiredState = requiredCheckBox.isSelected();
817             requiredCheckBox.setSelected(true);
818         } else {
819             requiredCheckBox.setSelected(previousRequiredState);
820         }
821     }
822
823     public boolean isPkClassIsAutogeneratable() {
824         String JavaDoc primaryKeyClass = typeText.getText();
825         return autogeneratablePrimaryKeyClasses.contains(primaryKeyClass);
826     }
827
828     private void init() {
829         initComponents();
830         Iterator JavaDoc types = jdbcTypes.iterator();
831         while (types.hasNext()) {
832             String JavaDoc jdbcType = (String JavaDoc) types.next();
833             jdbcTypeComboBox.addItem(jdbcType);
834         }
835     }
836
837     /**
838      * This method is called from within the constructor to
839      * initialize the form.
840      * WARNING: Do NOT modify this code. The content of this method is
841      * always regenerated by the Form Editor.
842      */

843     // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
844
private void initComponents() {
845         panel = new javax.swing.JPanel JavaDoc();
846         nameLabel = new javax.swing.JLabel JavaDoc();
847         typeLabel = new javax.swing.JLabel JavaDoc();
848         columnNameLabel = new javax.swing.JLabel JavaDoc();
849         sqlTypeLabel = new javax.swing.JLabel JavaDoc();
850         jdbcTypeLabel = new javax.swing.JLabel JavaDoc();
851         nameText = new javax.swing.JTextField JavaDoc();
852         typeText = new javax.swing.JTextField JavaDoc();
853         columnNameText = new javax.swing.JTextField JavaDoc();
854         sqlTypeText = new javax.swing.JTextField JavaDoc();
855         jPanel1 = new javax.swing.JPanel JavaDoc();
856         validationDependsText = new javax.swing.JTextField JavaDoc();
857         validationXMLScrollPane = new javax.swing.JScrollPane JavaDoc();
858         validationXMLTextArea = new javax.swing.JTextArea JavaDoc();
859         validationXMLLabel = new javax.swing.JLabel JavaDoc();
860         validationDependsLabel = new javax.swing.JLabel JavaDoc();
861         regenerateButton = new javax.swing.JButton JavaDoc();
862         jdbcTypeComboBox = new javax.swing.JComboBox JavaDoc();
863         checkboxPanel2 = new javax.swing.JPanel JavaDoc();
864         autoGeneratedCheckBox = new javax.swing.JCheckBox JavaDoc();
865         requiredCheckBox = new javax.swing.JCheckBox JavaDoc();
866         checkboxPanel1 = new javax.swing.JPanel JavaDoc();
867         primaryKeyCheckBox = new javax.swing.JCheckBox JavaDoc();
868         foreignKeyCheckBox = new javax.swing.JCheckBox JavaDoc();
869
870         panel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
871
872         nameLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
873         nameLabel.setText("Name: ");
874         panel.add(nameLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 90, -1));
875
876         typeLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
877         typeLabel.setText("Type: ");
878         panel.add(typeLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, 90, -1));
879
880         columnNameLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
881         columnNameLabel.setText("Column name: ");
882         panel.add(columnNameLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, 90, -1));
883
884         sqlTypeLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
885         sqlTypeLabel.setText("SQL-type: ");
886         panel.add(sqlTypeLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, 90, -1));
887
888         jdbcTypeLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
889         jdbcTypeLabel.setText("JDBC-type: ");
890         panel.add(jdbcTypeLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 130, 90, -1));
891
892         nameText.addFocusListener(new java.awt.event.FocusAdapter JavaDoc() {
893             public void focusLost(java.awt.event.FocusEvent JavaDoc evt) {
894                 nameTextFocusLost(evt);
895             }
896         });
897
898         panel.add(nameText, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 10, 260, -1));
899
900         typeText.addFocusListener(new java.awt.event.FocusAdapter JavaDoc() {
901             public void focusLost(java.awt.event.FocusEvent JavaDoc evt) {
902                 typeTextFocusLost(evt);
903             }
904         });
905
906         panel.add(typeText, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 40, 260, -1));
907
908         columnNameText.addFocusListener(new java.awt.event.FocusAdapter JavaDoc() {
909             public void focusLost(java.awt.event.FocusEvent JavaDoc evt) {
910                 columnNameTextFocusLost(evt);
911             }
912         });
913
914         panel.add(columnNameText, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 70, 260, -1));
915
916         sqlTypeText.addFocusListener(new java.awt.event.FocusAdapter JavaDoc() {
917             public void focusLost(java.awt.event.FocusEvent JavaDoc evt) {
918                 sqlTypeTextFocusLost(evt);
919             }
920         });
921
922         panel.add(sqlTypeText, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 100, 260, -1));
923
924         jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
925
926         jPanel1.setBorder(new javax.swing.border.TitledBorder JavaDoc("Struts validations:"));
927         validationDependsText.setColumns(46);
928         validationDependsText.addFocusListener(new java.awt.event.FocusAdapter JavaDoc() {
929             public void focusLost(java.awt.event.FocusEvent JavaDoc evt) {
930                 validationDependsTextFocusLost(evt);
931             }
932         });
933
934         jPanel1.add(validationDependsText, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 30, 290, -1));
935
936         validationXMLTextArea.setColumns(48);
937         validationXMLTextArea.setFont(new java.awt.Font JavaDoc("Lucida Console", 0, 10));
938         validationXMLTextArea.setRows(6);
939         validationXMLTextArea.addFocusListener(new java.awt.event.FocusAdapter JavaDoc() {
940             public void focusLost(java.awt.event.FocusEvent JavaDoc evt) {
941                 validationXMLTextAreaFocusLost(evt);
942             }
943         });
944
945         validationXMLScrollPane.setViewportView(validationXMLTextArea);
946
947         jPanel1.add(validationXMLScrollPane, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 59, -1, 90));
948
949         validationXMLLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
950         validationXMLLabel.setText("Validation XML: ");
951         jPanel1.add(validationXMLLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(-20, 60, 110, 20));
952
953         validationDependsLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
954         validationDependsLabel.setText("Validations: ");
955         jPanel1.add(validationDependsLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(-20, 30, 110, -1));
956
957         regenerateButton.setText("Regenerate validations");
958         regenerateButton.setEnabled(false);
959         regenerateButton.addActionListener(new java.awt.event.ActionListener JavaDoc() {
960             public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
961                 regenerateButtonActionPerformed(evt);
962             }
963         });
964
965         jPanel1.add(regenerateButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 170, -1, -1));
966
967         panel.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 240, 400, 200));
968
969         jdbcTypeComboBox.addActionListener(new java.awt.event.ActionListener JavaDoc() {
970             public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
971                 jdbcTypeComboBoxActionPerformed(evt);
972             }
973         });
974
975         panel.add(jdbcTypeComboBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 130, 260, -1));
976
977         checkboxPanel2.setLayout(new java.awt.BorderLayout JavaDoc());
978
979         autoGeneratedCheckBox.setText("Auto-generated primary key:");
980         autoGeneratedCheckBox.setEnabled(false);
981         autoGeneratedCheckBox.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
982         autoGeneratedCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
983         autoGeneratedCheckBox.addActionListener(new java.awt.event.ActionListener JavaDoc() {
984             public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
985                 autoGeneratedCheckBoxActionPerformed(evt);
986             }
987         });
988
989         checkboxPanel2.add(autoGeneratedCheckBox, java.awt.BorderLayout.SOUTH);
990
991         requiredCheckBox.setText("Required (not nullable):");
992         requiredCheckBox.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
993         requiredCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
994         requiredCheckBox.setMaximumSize(new java.awt.Dimension JavaDoc(186, 24));
995         requiredCheckBox.setMinimumSize(new java.awt.Dimension JavaDoc(186, 24));
996         requiredCheckBox.setPreferredSize(new java.awt.Dimension JavaDoc(186, 24));
997         requiredCheckBox.addActionListener(new java.awt.event.ActionListener JavaDoc() {
998             public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
999                 requiredCheckBoxActionPerformed(evt);
1000            }
1001        });
1002
1003        checkboxPanel2.add(requiredCheckBox, java.awt.BorderLayout.NORTH);
1004
1005        panel.add(checkboxPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 170, 190, 50));
1006
1007        checkboxPanel1.setLayout(new java.awt.BorderLayout JavaDoc());
1008
1009        primaryKeyCheckBox.setText("Primary key:");
1010        primaryKeyCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
1011        primaryKeyCheckBox.addActionListener(new java.awt.event.ActionListener JavaDoc() {
1012            public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
1013                primaryKeyCheckBoxActionPerformed(evt);
1014            }
1015        });
1016
1017        checkboxPanel1.add(primaryKeyCheckBox, java.awt.BorderLayout.NORTH);
1018
1019        foreignKeyCheckBox.setText("Foreign key:");
1020        foreignKeyCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
1021        foreignKeyCheckBox.addActionListener(new java.awt.event.ActionListener JavaDoc() {
1022            public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
1023                foreignKeyCheckBoxActionPerformed(evt);
1024            }
1025        });
1026
1027        checkboxPanel1.add(foreignKeyCheckBox, java.awt.BorderLayout.SOUTH);
1028
1029        panel.add(checkboxPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 170, 160, 50));
1030
1031    }
1032    // </editor-fold>//GEN-END:initComponents
1033

1034    private void jdbcTypeComboBoxActionPerformed(java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_jdbcTypeComboBoxActionPerformed
1035
JagGenerator.stateChanged(false);
1036        regenerateButton.setEnabled(true);
1037    }//GEN-LAST:event_jdbcTypeComboBoxActionPerformed
1038

1039    private void autoGeneratedCheckBoxActionPerformed(java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_autoGeneratedCheckBoxActionPerformed
1040
if (autoGeneratedCheckBox.isSelected() && !isPkClassIsAutogeneratable()) {
1041            JagGenerator.logToConsole("Can't autogenerate primary keys with class type '" + typeText.getText() + "'!");
1042            autoGeneratedCheckBox.setSelected(false);
1043        }
1044    }//GEN-LAST:event_autoGeneratedCheckBoxActionPerformed
1045

1046    private void regenerateButtonActionPerformed(java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_regenerateButtonActionPerformed
1047
regenerateValidations();
1048        regenerateButton.setEnabled(false);
1049    }//GEN-LAST:event_regenerateButtonActionPerformed
1050

1051    private void requiredCheckBoxActionPerformed(java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_requiredCheckBoxActionPerformed
1052
JagGenerator.stateChanged(false);
1053        regenerateButton.setEnabled(true);
1054    }//GEN-LAST:event_requiredCheckBoxActionPerformed
1055

1056    private void validationXMLTextAreaFocusLost(java.awt.event.FocusEvent JavaDoc evt) {//GEN-FIRST:event_validationXMLTextAreaFocusLost
1057
JagGenerator.stateChanged(false);
1058    }//GEN-LAST:event_validationXMLTextAreaFocusLost
1059

1060    private void validationDependsTextFocusLost(java.awt.event.FocusEvent JavaDoc evt) {//GEN-FIRST:event_validationDependsTextFocusLost
1061
JagGenerator.stateChanged(false);
1062    }//GEN-LAST:event_validationDependsTextFocusLost
1063

1064    private void foreignKeyCheckBoxActionPerformed(java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_foreignKeyCheckBoxActionPerformed
1065
JagGenerator.stateChanged(false);
1066        regenerateButton.setEnabled(true);
1067    }//GEN-LAST:event_foreignKeyCheckBoxActionPerformed
1068

1069    private void primaryKeyCheckBoxActionPerformed(java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_primaryKeyCheckBoxActionPerformed
1070
boolean checked = primaryKeyCheckBox.isSelected();
1071        setPrimaryKey(checked);
1072
1073        //tell the parent entity bean that its primary key status has changed..
1074
if (checked) {
1075            parentEntity.setPrimaryKey(this);
1076        } else {
1077            parentEntity.unsetPrimaryKey(this);
1078        }
1079
1080        JagGenerator.stateChanged(false);
1081        regenerateButton.setEnabled(true);
1082    }//GEN-LAST:event_primaryKeyCheckBoxActionPerformed
1083

1084    private void sqlTypeTextFocusLost(java.awt.event.FocusEvent JavaDoc evt) {//GEN-FIRST:event_sqlTypeTextFocusLost
1085
JagGenerator.stateChanged(false);
1086        regenerateButton.setEnabled(true);
1087    }//GEN-LAST:event_sqlTypeTextFocusLost
1088

1089    private void columnNameTextFocusLost(java.awt.event.FocusEvent JavaDoc evt) {//GEN-FIRST:event_columnNameTextFocusLost
1090
JagGenerator.stateChanged(false);
1091    }//GEN-LAST:event_columnNameTextFocusLost
1092

1093    private void typeTextFocusLost(java.awt.event.FocusEvent JavaDoc evt) {//GEN-FIRST:event_typeTextFocusLost
1094
JagGenerator.stateChanged(false);
1095    }//GEN-LAST:event_typeTextFocusLost
1096

1097    private void nameTextFocusLost(java.awt.event.FocusEvent JavaDoc evt) {//GEN-FIRST:event_nameTextFocusLost
1098
if (!nameText.getText().equals(oldName)) {
1099            parentEntity.notifyRelationsThatFieldNameChanged(oldName, nameText.getText());
1100            oldName = nameText.getText();
1101        }
1102        JagGenerator.stateChanged(true);
1103    }//GEN-LAST:event_nameTextFocusLost
1104

1105    private boolean contains(String JavaDoc s, String JavaDoc sub) {
1106        return s.indexOf(sub) > -1;
1107    }
1108
1109    // Variables declaration - do not modify//GEN-BEGIN:variables
1110
public javax.swing.JCheckBox JavaDoc autoGeneratedCheckBox;
1111    private javax.swing.JPanel JavaDoc checkboxPanel1;
1112    private javax.swing.JPanel JavaDoc checkboxPanel2;
1113    private javax.swing.JLabel JavaDoc columnNameLabel;
1114    private javax.swing.JTextField JavaDoc columnNameText;
1115    public javax.swing.JCheckBox JavaDoc foreignKeyCheckBox;
1116    private javax.swing.JPanel JavaDoc jPanel1;
1117    private javax.swing.JComboBox JavaDoc jdbcTypeComboBox;
1118    private javax.swing.JLabel JavaDoc jdbcTypeLabel;
1119    private javax.swing.JLabel JavaDoc nameLabel;
1120    private javax.swing.JTextField JavaDoc nameText;
1121    private javax.swing.JPanel JavaDoc panel;
1122    public javax.swing.JCheckBox JavaDoc primaryKeyCheckBox;
1123    private javax.swing.JButton JavaDoc regenerateButton;
1124    public javax.swing.JCheckBox JavaDoc requiredCheckBox;
1125    private javax.swing.JLabel JavaDoc sqlTypeLabel;
1126    private javax.swing.JTextField JavaDoc sqlTypeText;
1127    private javax.swing.JLabel JavaDoc typeLabel;
1128    private javax.swing.JTextField JavaDoc typeText;
1129    private javax.swing.JLabel JavaDoc validationDependsLabel;
1130    public javax.swing.JTextField JavaDoc validationDependsText;
1131    private javax.swing.JLabel JavaDoc validationXMLLabel;
1132    private javax.swing.JScrollPane JavaDoc validationXMLScrollPane;
1133    private javax.swing.JTextArea JavaDoc validationXMLTextArea;
1134    // End of variables declaration//GEN-END:variables
1135
}
1136
1137
Popular Tags