KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > amber > field > KeyPropertyField


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  * Free Software Foundation, Inc.
23  * 59 Temple Place, Suite 330
24  * Boston, MA 02111-1307 USA
25  *
26  * @author Scott Ferguson
27  */

28
29 package com.caucho.amber.field;
30
31 import com.caucho.amber.expr.AmberExpr;
32 import com.caucho.amber.expr.KeyColumnExpr;
33 import com.caucho.amber.expr.PathExpr;
34 import com.caucho.amber.query.QueryParser;
35 import com.caucho.amber.table.Column;
36 import com.caucho.amber.type.RelatedType;
37 import com.caucho.amber.type.Type;
38 import com.caucho.bytecode.JClassWrapper;
39 import com.caucho.config.ConfigException;
40 import com.caucho.java.JavaWriter;
41 import com.caucho.log.Log;
42 import com.caucho.util.L10N;
43
44 import java.io.IOException JavaDoc;
45 import java.lang.reflect.Method JavaDoc;
46 import java.util.ArrayList JavaDoc;
47 import java.util.HashSet JavaDoc;
48 import java.util.logging.Logger JavaDoc;
49
50 /**
51  * Configuration for a bean's field
52  */

53 public class KeyPropertyField extends PropertyField implements IdField {
54   private static final L10N L = new L10N(KeyPropertyField.class);
55   protected static final Logger JavaDoc log = Log.open(KeyPropertyField.class);
56
57   private Column _column;
58   private boolean _isKeyField;
59   private String JavaDoc _generator;
60
61   public KeyPropertyField(RelatedType tableType)
62   {
63     super(tableType);
64   }
65
66   public KeyPropertyField(RelatedType tableType,
67                           String JavaDoc name)
68     throws ConfigException
69   {
70     super(tableType, name);
71   }
72
73   public KeyPropertyField(RelatedType entityType,
74                           String JavaDoc name,
75                           Column column)
76     throws ConfigException
77   {
78     super(entityType, name);
79
80     _column = column;
81     _column.setPrimaryKey(true);
82   }
83
84   /**
85    * Returns true if key fields are accessed through fields.
86    */

87   public boolean isKeyField()
88   {
89     return _isKeyField;
90   }
91
92   /**
93    * Set true if key fields are accessed through fields.
94    */

95   public void setKeyField(boolean isKeyField)
96   {
97     _isKeyField = isKeyField;
98   }
99
100   /**
101    * Sets the generator.
102    */

103   public void setGenerator(String JavaDoc generator)
104   {
105     _generator = generator;
106
107     if (_column != null)
108       _column.setGeneratorType(generator);
109   }
110
111   /**
112    * Gets the generator.
113    */

114   public String JavaDoc getGenerator()
115   {
116     return _generator;
117   }
118
119   /**
120    * Returns true for a generator.
121    */

122   public boolean isAutoGenerate()
123   {
124     return _generator != null;
125   }
126
127   /**
128    * Sets the column
129    */

130   public void setColumn(Column column)
131   {
132     _column = column;
133     _column.setPrimaryKey(true);
134   }
135
136   /**
137    * Returns column
138    */

139   public Column getColumn()
140   {
141     return _column;
142   }
143
144   /**
145    * Returns columns
146    */

147   public ArrayList JavaDoc<Column> getColumns()
148   {
149     ArrayList JavaDoc<Column> columns = new ArrayList JavaDoc<Column>();
150
151     columns.add(_column);
152
153     return columns;
154   }
155
156   /**
157    * Returns the component count.
158    */

159   public int getComponentCount()
160   {
161     return 1;
162   }
163
164   /**
165    * Returns type
166    */

167   public Type getType()
168   {
169     return _column.getType();
170   }
171
172   /**
173    * Returns the foreign type.
174    */

175   public String JavaDoc getForeignTypeName()
176   {
177     return _column.getType().getForeignTypeName();
178   }
179
180   /**
181    * Generates any prologue.
182    */

183   public void generatePrologue(JavaWriter out, HashSet JavaDoc<Object JavaDoc> completedSet)
184     throws IOException JavaDoc
185   {
186     super.generatePrologue(out, completedSet);
187
188     if (isAbstract()) {
189       out.println();
190
191       out.println();
192       out.println("public " + getJavaTypeName() + " " + getGetterName() + "()");
193       out.println("{");
194       out.println(" return " + getFieldName() + ";");
195       out.println("}");
196
197       out.println();
198       out.println("public void " + getSetterName() + "(" + getJavaTypeName() + " v)");
199       out.println("{");
200       out.println(" " + getFieldName() + " = v;");
201       out.println("}");
202     }
203   }
204
205   /**
206    * Returns the actual data.
207    */

208   public String JavaDoc generateSuperGetter()
209   {
210     if (isAbstract() || getGetterMethod() == null)
211       return getFieldName();
212     else
213       return getGetterMethod().getName() + "()";
214   }
215
216   /**
217    * Sets the actual data.
218    */

219   public String JavaDoc generateSuperSetter(String JavaDoc value)
220   {
221     if (isAbstract() || getGetterMethod() == null || getSetterMethod() == null)
222       return(getFieldName() + " = " + value + ";");
223     else
224       return getSetterMethod().getName() + "(" + value + ")";
225   }
226
227   /**
228    * Returns the select code
229    */

230   public String JavaDoc generateSelect(String JavaDoc id)
231   {
232     return _column.generateSelect(id);
233   }
234
235   /**
236    * Returns the JPA QL select code
237    */

238   public String JavaDoc generateJavaSelect(String JavaDoc id)
239   {
240     String JavaDoc select = getName();
241
242     if (id != null)
243       select = id + "." + select;
244
245     return select;
246   }
247
248   /**
249    * Returns the where code
250    */

251   public String JavaDoc generateMatchArgWhere(String JavaDoc id)
252   {
253     return _column.generateMatchArgWhere(id);
254   }
255
256   /**
257    * Returns the where code
258    */

259   public String JavaDoc generateRawWhere(String JavaDoc id)
260   {
261     return id + "." + getName() + "=?";
262   }
263
264   /**
265    * Returns the foreign type.
266    */

267   public int generateLoadForeign(JavaWriter out, String JavaDoc rs,
268                                  String JavaDoc indexVar, int index)
269     throws IOException JavaDoc
270   {
271     return generateLoadForeign(out, rs, indexVar, index,
272                                getForeignTypeName().replace('.', '_'));
273   }
274
275   /**
276    * Generates loading cache
277    */

278   public void generateLoadFromObject(JavaWriter out, String JavaDoc obj)
279     throws IOException JavaDoc
280   {
281     out.println(generateSuperSetter(generateGet(obj)) + ";");
282   }
283
284   /**
285    * Generates loading cache
286    */

287   public String JavaDoc generateSetNull(String JavaDoc obj)
288     throws IOException JavaDoc
289   {
290     return generateSet(obj, getColumn().getType().generateNull());
291   }
292
293   /**
294    * Returns a test for null.
295    */

296   public String JavaDoc generateIsNull(String JavaDoc value)
297   {
298     return "(" + getType().generateIsNull(generateSuperGetter()) + ")";
299   }
300
301   /**
302    * Returns the foreign type.
303    */

304   public int generateLoadForeign(JavaWriter out, String JavaDoc rs,
305                                  String JavaDoc indexVar, int index,
306                                  String JavaDoc name)
307     throws IOException JavaDoc
308   {
309     // XXX: 0 == null
310
return _column.getType().generateLoadForeign(out, rs, indexVar, index);
311   }
312
313   /**
314    * Generates the set clause.
315    */

316   public void generateSet(JavaWriter out, String JavaDoc pstmt,
317                           String JavaDoc index, String JavaDoc value)
318     throws IOException JavaDoc
319   {
320     if (value == null)
321       _column.getType().generateSetNull(out, pstmt, index);
322     else
323       _column.getType().generateSet(out, pstmt, index,
324                                     generateGet(value));
325   }
326
327   /**
328    * Generates code for a match.
329    */

330   public void generateMatch(JavaWriter out, String JavaDoc key)
331     throws IOException JavaDoc
332   {
333     out.println("return " + generateEquals("super", key) + ";");
334   }
335
336   /**
337    * Generates code to test the equals.
338    */

339   public String JavaDoc generateEquals(String JavaDoc left, String JavaDoc right)
340   {
341     return _column.getType().generateEquals(left, right);
342   }
343
344   /**
345    * Generates the set clause.
346    */

347   public void generateSetInsert(JavaWriter out, String JavaDoc pstmt, String JavaDoc index)
348     throws IOException JavaDoc
349   {
350     String JavaDoc value = generateSuperGetter();
351
352     if (isAutoGenerate()) {
353       out.println("if (" + getType().generateIsNull(value) + ") {");
354       out.pushDepth();
355
356       getType().generateSetNull(out, pstmt, index);
357
358       out.popDepth();
359       out.println("} else {");
360       out.pushDepth();
361
362       generateSet(out, pstmt, index);
363
364       out.popDepth();
365       out.println("}");
366     }
367     else
368       generateSet(out, pstmt, index);
369   }
370
371   /**
372    * Generates the set clause.
373    */

374   public void generateCheckCreateKey(JavaWriter out)
375     throws IOException JavaDoc
376   {
377     /*
378       out.println("insertSql.append(\"" + getName() + "\");");
379       out.println("insertValues.append(\"?\");");
380     */

381
382     if ("identity".equals(_generator))
383       return;
384     else if (_generator != null) {
385       if (getEntitySourceType().getGenerator(getName()) == null)
386         throw new IllegalStateException JavaDoc("no sequence generator for " + getName());
387
388       out.println("if (" + getType().generateIsNull(generateSuperGetter()) + ") {");
389       out.pushDepth();
390
391       String JavaDoc id = "home.nextGeneratorId(aConn, \"" + getName() + "\")";
392
393       String JavaDoc javaType = getType().getJavaTypeName();
394
395       if ("long".equals(javaType))
396         id = "(" + javaType + ") " + id;
397       else if ("int".equals(javaType))
398         id = "(" + javaType + ") " + id;
399       else if ("short".equals(javaType))
400         id = "(" + javaType + ") " + id;
401       else if ("java.lang.Long".equals(javaType))
402         id = "new Long(" + id + ")";
403       else if ("java.lang.Integer".equals(javaType))
404         id = "new Integer((int) " + id + ")";
405       else if ("java.lang.Short".equals(javaType))
406         id = "new Short((short) " + id + ")";
407       else if ("java.lang.Byte".equals(javaType))
408         id = "new Byte((byte) " + id + ")";
409       else
410         throw new UnsupportedOperationException JavaDoc(L.l("{0} is an unsupported generated key type.",
411                                                     javaType));
412
413       out.println(generateSuperSetter(id) + ";");
414
415       out.popDepth();
416       out.println("}");
417
418       return;
419     }
420
421     if (! getJavaType().isPrimitive()) {
422       out.println("if (" + getType().generateIsNull(generateSuperGetter()) + ")");
423       out.println(" throw new com.caucho.amber.AmberException(\"primary key must not be null on creation. " + getGetterName() + "() must not return null.\");");
424     }
425   }
426
427   /**
428    * Generates the set clause.
429    */

430   public void generateSetGeneratedKeys(JavaWriter out, String JavaDoc pstmt)
431     throws IOException JavaDoc
432   {
433     if (! "identity".equals(_generator))
434       return;
435
436     out.print("if (");
437     out.print(getType().generateIsNull(generateSuperGetter()));
438     out.println(") {");
439     out.pushDepth();
440
441     String JavaDoc var = "__caucho_rs_" + out.generateId();
442
443     out.println("java.sql.ResultSet " + var + " = " + pstmt + ".getGeneratedKeys();");
444     out.println("if (" + var + ".next()) {");
445     out.pushDepth();
446
447     out.print(getType().getName() + " v1 = ");
448     getType().generateLoad(out, var, "", 1);
449     out.println(";");
450
451     out.println(generateSuperSetter("v1") + ";");
452
453     out.println("if (__caucho_log.isLoggable(java.util.logging.Level.FINER))");
454     out.println(" __caucho_log.finer(\"create with new primaryKey \" + " + generateSuperGetter() + ");");
455
456     out.popDepth();
457     out.println("}");
458     out.println("else throw new java.sql.SQLException();");
459
460     out.popDepth();
461     out.println("}");
462   }
463
464   /**
465    * Generates the setter for a key property
466    */

467   public String JavaDoc generateSetKeyProperty(String JavaDoc key, String JavaDoc value)
468     throws IOException JavaDoc
469   {
470     if (_isKeyField)
471       return key + "." + getName() + " = " + value;
472     else
473       return generateSet(key, value);
474   }
475
476   /**
477    * Generates the getter for a key property
478    */

479   public String JavaDoc generateGetKeyProperty(String JavaDoc key)
480   {
481     if (_isKeyField)
482       return key + "." + getName();
483     else
484       return generateGet(key);
485   }
486
487   /**
488    * Generates the property getter for an EJB proxy
489    *
490    * @param value the non-null value
491    */

492   public String JavaDoc generateGetProxyProperty(String JavaDoc value)
493   {
494     // XXX: better solution
495
Class JavaDoc proxyClass = ((JClassWrapper) getEntitySourceType().getProxyClass()).getWrappedClass();
496
497     try {
498       Method JavaDoc method = proxyClass.getMethod(getGetterName(), new Class JavaDoc[0]);
499
500       if (method != null)
501         return generateGet(value);
502     } catch (Throwable JavaDoc e) {
503     }
504
505     Id id = getEntitySourceType().getId();
506
507     return generateGetKeyProperty("((" + id.getForeignTypeName() + ") " + value + ".getPrimaryKey())");
508   }
509
510   /**
511    * Creates the expression for the field.
512    */

513   public AmberExpr createExpr(QueryParser parser, PathExpr parent)
514   {
515     return new KeyColumnExpr(parent, getColumn());
516   }
517
518   /**
519    * Converts to an object.
520    */

521   public String JavaDoc toObject(String JavaDoc value)
522   {
523     return getColumn().getType().toObject(value);
524   }
525
526   /**
527    * Converts from an object.
528    */

529   public String JavaDoc toValue(String JavaDoc value)
530   {
531     return getColumn().getType().generateCastFromObject(value);
532   }
533 }
534
Popular Tags