KickJava   Java API By Example, From Geeks To Geeks.

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


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.KeyManyToOneExpr;
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.table.ForeignColumn;
37 import com.caucho.amber.table.LinkColumns;
38 import com.caucho.amber.type.EntityType;
39 import com.caucho.amber.type.RelatedType;
40 import com.caucho.amber.type.Type;
41 import com.caucho.config.ConfigException;
42 import com.caucho.java.JavaWriter;
43 import com.caucho.log.Log;
44 import com.caucho.util.CharBuffer;
45 import com.caucho.util.L10N;
46
47 import java.io.IOException JavaDoc;
48 import java.util.ArrayList JavaDoc;
49 import java.util.HashSet JavaDoc;
50 import java.util.logging.Logger JavaDoc;
51
52 /**
53  * Configuration for a bean's field
54  */

55 public class KeyManyToOneField extends EntityManyToOneField implements IdField {
56   private static final L10N L = new L10N(KeyManyToOneField.class);
57   protected static final Logger JavaDoc log = Log.open(KeyManyToOneField.class);
58
59   // fields
60
private ArrayList JavaDoc<KeyPropertyField> _idFields =
61     new ArrayList JavaDoc<KeyPropertyField>();
62
63   // use field accessors to get key values.
64
private boolean _isKeyField;
65
66   public KeyManyToOneField(RelatedType entityType, String JavaDoc name)
67     throws ConfigException
68   {
69     super(entityType, name);
70   }
71
72   public KeyManyToOneField(RelatedType entityType,
73                            String JavaDoc name,
74                            LinkColumns columns)
75     throws ConfigException
76   {
77     super(entityType, name);
78
79     setLinkColumns(columns);
80
81     setSourceCascadeDelete(true);
82   }
83
84   /**
85    * Gets the generator.
86    */

87   public String JavaDoc getGenerator()
88   {
89     return null;
90   }
91
92   /**
93    * Returns the target type as entity (ejb 2.1)
94    * See com.caucho.ejb.ql.Expr
95    */

96   public EntityType getEntityType()
97   {
98     return (EntityType) getEntityTargetType();
99   }
100
101   public Type getType()
102   {
103     return getEntityTargetType();
104   }
105
106   public Column getColumn()
107   {
108     throw new UnsupportedOperationException JavaDoc();
109   }
110
111   /**
112    * Set true if key fields are accessed through fields.
113    */

114   public void setKeyField(boolean isKeyField)
115   {
116     _isKeyField = isKeyField;
117   }
118
119   /**
120    * Returns the foreign type name.
121    */

122   public String JavaDoc getForeignTypeName()
123   {
124     return getJavaTypeName();
125   }
126
127   /**
128    * Set true if deletes cascade to the target.
129    */

130   public boolean isTargetCascadeDelete()
131   {
132     return false;
133   }
134
135   /**
136    * Set true if deletes cascade to the source.
137    */

138   public boolean isSourceCascadeDelete()
139   {
140     return true;
141   }
142
143   /**
144    * Initialize the field.
145    */

146   public void init()
147     throws ConfigException
148   {
149     super.init();
150
151     ArrayList JavaDoc<IdField> keys = getEntityTargetType().getId().getKeys();
152
153     ArrayList JavaDoc<ForeignColumn> columns = getLinkColumns().getColumns();
154
155     for (int i = 0; i < keys.size(); i++) {
156       IdField key = keys.get(i);
157       ForeignColumn column = columns.get(i);
158
159       KeyPropertyField field;
160       field = new IdentifyingKeyPropertyField(getEntitySourceType(), column);
161
162       _idFields.add(field);
163     }
164   }
165
166   /**
167    * Returns the component count.
168    */

169   public int getComponentCount()
170   {
171     return getEntityTargetType().getId().getKeyCount();
172   }
173
174   /**
175    * Returns columns
176    */

177   public ArrayList JavaDoc<Column> getColumns()
178   {
179     ArrayList JavaDoc<Column> columns = new ArrayList JavaDoc<Column>();
180
181     columns.addAll(getLinkColumns().getColumns());
182
183     return columns;
184   }
185
186   /**
187    * Returns the identifying field matching the target's id.
188    */

189   public KeyPropertyField getIdField(IdField field)
190   {
191     ArrayList JavaDoc<IdField> keys = getEntityTargetType().getId().getKeys();
192
193     if (_idFields.size() != keys.size()) {
194       try {
195         init();
196       } catch (Exception JavaDoc e) {
197         throw new RuntimeException JavaDoc(e);
198       }
199     }
200
201     for (int i = 0; i < keys.size(); i++) {
202       if (keys.get(i) == field)
203         return _idFields.get(i);
204     }
205
206     throw new IllegalStateException JavaDoc(field.toString());
207   }
208
209   /**
210    * Creates the expression for the field.
211    */

212   public AmberExpr createExpr(QueryParser parser, PathExpr parent)
213   {
214     return new KeyManyToOneExpr(parent, this);
215   }
216
217   /**
218    * Returns the where code
219    */

220   public String JavaDoc generateMatchArgWhere(String JavaDoc id)
221   {
222     return getLinkColumns().generateMatchArgSQL(id);
223   }
224
225   /**
226    * Returns the where code
227    */

228   public String JavaDoc generateRawWhere(String JavaDoc id)
229   {
230     CharBuffer cb = new CharBuffer();
231
232     String JavaDoc prefix = id + "." + getName();
233
234     ArrayList JavaDoc<IdField> keys = getEntityTargetType().getId().getKeys();
235
236     for (int i = 0; i < keys.size(); i++) {
237       if (i != 0)
238         cb.append(" and ");
239
240       cb.append(keys.get(i).generateRawWhere(prefix));
241     }
242
243     return cb.toString();
244   }
245
246   /**
247    * Generates the property getter for an EJB proxy
248    *
249    * @param value the non-null value
250    */

251   public String JavaDoc generateGetProxyProperty(String JavaDoc value)
252   {
253     throw new UnsupportedOperationException JavaDoc();
254   }
255
256   /**
257    * Generates the linking for a join
258    */

259   public void generateJoin(CharBuffer cb, String JavaDoc table1, String JavaDoc table2)
260   {
261     cb.append(getLinkColumns().generateJoin(table1, table2));
262   }
263
264   /**
265    * Gets the column corresponding to the target field.
266    */

267   public ForeignColumn getColumn(Column key)
268   {
269     return getLinkColumns().getSourceColumn(key);
270   }
271
272   /**
273    * Returns the foreign type.
274    */

275   public int generateLoadForeign(JavaWriter out, String JavaDoc rs,
276                                  String JavaDoc indexVar, int index)
277     throws IOException JavaDoc
278   {
279     return generateLoadForeign(out, rs, indexVar, index,
280                                getForeignTypeName().replace('.', '_'));
281   }
282
283   /**
284    * Returns the actual data.
285    */

286   public String JavaDoc generateSuperGetter()
287   {
288     if (isAbstract() || getGetterMethod() == null)
289       return getFieldName();
290     else
291       return getGetterMethod().getName() + "()";
292   }
293
294   /**
295    * Sets the actual data.
296    */

297   public String JavaDoc generateSuperSetter(String JavaDoc value)
298   {
299     if (isAbstract() || getGetterMethod() == null || getSetterMethod() == null)
300       return(getFieldName() + " = " + value + ";");
301     else
302       return getSetterMethod().getName() + "(" + value + ")";
303   }
304
305   /**
306    * Returns the foreign type.
307    */

308   public int generateLoadForeign(JavaWriter out, String JavaDoc rs,
309                                  String JavaDoc indexVar, int index,
310                                  String JavaDoc name)
311     throws IOException JavaDoc
312   {
313     out.print("(" + getForeignTypeName() + ") ");
314
315     out.print("aConn.loadProxy(\"" + getEntityTargetType().getName() + "\", ");
316     index = getEntityTargetType().getId().generateLoadForeign(out, rs, indexVar, index,
317                                                               getName());
318
319     out.println(");");
320
321     return index;
322   }
323
324   /**
325    * Generates any prologue.
326    */

327   public void generatePrologue(JavaWriter out, HashSet JavaDoc<Object JavaDoc> completedSet)
328     throws IOException JavaDoc
329   {
330     super.generatePrologue(out, completedSet);
331
332     if (isAbstract()) {
333       out.println();
334
335       out.println();
336       out.println("public " + getJavaTypeName() + " " + getGetterName() + "()");
337       out.println("{");
338       out.println(" return " + getFieldName() + ";");
339       out.println("}");
340
341       out.println();
342       out.println("public void " + getSetterName() + "(" + getJavaTypeName() + " v)");
343       out.println("{");
344       out.println(" " + getFieldName() + " = v;");
345       out.println("}");
346     }
347   }
348
349   /**
350    * Generates the set clause.
351    */

352   public void generateSet(JavaWriter out, String JavaDoc pstmt,
353                           String JavaDoc index, String JavaDoc value)
354     throws IOException JavaDoc
355   {
356     ArrayList JavaDoc<ForeignColumn> columns = getLinkColumns().getColumns();
357
358     Id id = getEntityTargetType().getId();
359     ArrayList JavaDoc<IdField> keys = id.getKeys();
360
361     String JavaDoc prop = value != null ? generateGet(value) : null;
362     for (int i = 0; i < columns.size(); i++ ){
363       IdField key = keys.get(i);
364       ForeignColumn column = columns.get(i);
365
366       column.generateSet(out, pstmt, index, key.generateGet(prop));
367     }
368   }
369
370   /**
371    * Generates the set clause.
372    */

373   public void generateSet(JavaWriter out, String JavaDoc pstmt, String JavaDoc index)
374     throws IOException JavaDoc
375   {
376     String JavaDoc var = getFieldName();
377
378     Id id = getEntityTargetType().getId();
379     ArrayList JavaDoc<IdField> keys = id.getKeys();
380
381     for (int i = 0; i < keys.size(); i++) {
382       IdField key = keys.get(i);
383
384       key.getType().generateSet(out, pstmt, index, key.generateGet(var));
385     }
386   }
387
388   /**
389    * Generates the set clause.
390    */

391   public void generateSetInsert(JavaWriter out, String JavaDoc pstmt, String JavaDoc index)
392     throws IOException JavaDoc
393   {
394     String JavaDoc value = generateSuperGetter();
395
396     out.println("if (" + getEntityTargetType().generateIsNull(value) + ") {");
397     out.pushDepth();
398
399     getEntityTargetType().generateSetNull(out, pstmt, index);
400
401     out.popDepth();
402     out.println("} else {");
403     out.pushDepth();
404
405     generateSet(out, pstmt, index);
406
407     out.popDepth();
408     out.println("}");
409   }
410
411   /**
412    * Generates the setter for a key property
413    */

414   public String JavaDoc generateSetKeyProperty(String JavaDoc key, String JavaDoc value)
415     throws IOException JavaDoc
416   {
417     if (_isKeyField)
418       return key + "." + getName() + " = " + value;
419     else
420       return generateSet(key, value);
421   }
422
423   /**
424    * Generates the getter for a key property
425    */

426   public String JavaDoc generateGetKeyProperty(String JavaDoc key)
427     throws IOException JavaDoc
428   {
429     if (_isKeyField)
430       return key + "." + getName();
431     else
432       return generateGet(key);
433   }
434
435   /**
436    * Generates the set clause.
437    */

438   public void generateSetGeneratedKeys(JavaWriter out, String JavaDoc pstmt)
439     throws IOException JavaDoc
440   {
441   }
442
443   /**
444    * Generates the set clause.
445    */

446   public void generateCheckCreateKey(JavaWriter out)
447     throws IOException JavaDoc
448   {
449     out.println("if (" + generateSuperGetter() + " == null)");
450     out.println(" throw new com.caucho.amber.AmberException(\"primary key must not be null on creation. " + getGetterName() + "() must not return null.\");");
451   }
452
453   /**
454    * Returns a test for null.
455    */

456   public String JavaDoc generateIsNull(String JavaDoc value)
457   {
458     return "(" + value + " == null)";
459   }
460
461   /**
462    * Converts from an object.
463    */

464   public String JavaDoc toValue(String JavaDoc value)
465   {
466     return "((" + getJavaTypeName() + ") " + value + ")";
467   }
468 }
469
Popular Tags