KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jorm > generator > lib > BinderGenerator


1 /**
2  * JORM: an implementation of a generic mapping system for persistent Java
3  * objects. Two mapping are supported: to RDBMS and to binary files.
4  * Copyright (C) 2001-2003 France Telecom R&D - INRIA
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * Contact: jorm-team@objectweb.org
21  *
22  */

23
24 package org.objectweb.jorm.generator.lib;
25
26 import org.apache.velocity.VelocityContext;
27 import org.apache.velocity.context.Context;
28 import org.objectweb.jorm.api.PException;
29 import org.objectweb.jorm.compiler.api.PExceptionCompiler;
30 import org.objectweb.jorm.compiler.api.JormCompilerParameter;
31 import org.objectweb.jorm.metainfo.api.CompositeName;
32 import org.objectweb.jorm.metainfo.api.ScalarField;
33 import org.objectweb.jorm.metainfo.api.Package;
34 import org.objectweb.jorm.metainfo.api.PrimitiveElement;
35 import org.objectweb.jorm.type.api.PType;
36 import org.objectweb.jorm.util.io.api.TargetHolder;
37 import org.objectweb.util.monolog.api.BasicLevel;
38
39 import java.io.File JavaDoc;
40 import java.io.FileWriter JavaDoc;
41 import java.util.Iterator JavaDoc;
42 import java.util.Collection JavaDoc;
43 import java.util.HashMap JavaDoc;
44 import java.util.ArrayList JavaDoc;
45
46 /**
47  * This class is a generator of XXXBinder objects. It is generic either the
48  * mapper type. This generator use the velocity tools. The used template is
49  * Binder.vm . Associated to this template this generator builds a velocity
50  * context which contains the following information:<br/>
51  * <table border=1>
52  * <tr><td>Key</td><td>Value</td></tr>
53  * <tr><td>"compositename"</td><td>The reference to the compositename meta object</td></tr>
54  * <tr>
55  * <td>"tools"</td>
56  * <td>The reference to the <a HREF="CommonHelper.html">CommonHelper<a/></td>
57  * </tr>
58  * <tr>
59  * <td>"header"</td>
60  * <td>The file name of the common template which contains the header of
61  * the generate files.</td>
62  * </tr>
63  * </table>
64  */

65 public class BinderGenerator extends CommonGenerator {
66
67     HashMap JavaDoc autoCalculatedFieldInfos;
68
69     /**
70      * This method generates a XPBinder file corresponding to the co
71      * parameter in the directory parameter.
72      * @param co The meta object interface.
73      * @param holder The target holder which allows to create files.
74      * @param cp This parameter permits to reach the compilation parameters.
75      */

76     public void generate(CompositeName co,
77                          TargetHolder holder,
78                          JormCompilerParameter cp) throws PException {
79         // Calculate fileName
80
String JavaDoc packName = ((Package JavaDoc) co.getParent()).getName();
81         String JavaDoc fileName = co.getName() + "Binder";
82         if (packName != null && packName.length() > 0) {
83             fileName = packName + "." + fileName;
84             fileName = fileName.replace('.', File.separatorChar);
85         }
86         logger.log(BasicLevel.DEBUG, "Generate the " + fileName + " Binder");
87         // Fetch a block with the fileName
88
Context ctx = new VelocityContext();
89         ctx.put("compositename", co);
90         ctx.put("tools", this);
91         ctx.put("bindertools", this);
92         ctx.put("header", GEN_TEMPLATE_DIR + "Header.vm");
93         Collection JavaDoc allFields = co.getAllFields();
94         Iterator JavaDoc it = allFields.iterator();
95         PrimitiveElement firstField = (PrimitiveElement) it.next();
96         //If the composite name is composed by an unique field that the type is
97
// different to String, specify a uniqueField in order to support the
98
// direct coding. The String coding is always supported !!
99
if (!it.hasNext()) {
100             ctx.put("uniqueField", firstField);
101             if (firstField.getType().getTypeCode() != PType.TYPECODE_STRING) {
102                 ctx.put("defaultStringEncoding", "toto");
103             }
104         } else {
105             ctx.put("defaultStringEncoding", "toto");
106         }
107
108         //Auto calculated field.
109
it = allFields.iterator();
110         boolean allAutoCalculated = true;
111         while (it.hasNext()) {
112             PrimitiveElement pe = (PrimitiveElement) it.next();
113             if (pe.isAutoCalculated()) {
114                 if (autoCalculatedFieldInfos == null) {
115                     autoCalculatedFieldInfos = new HashMap JavaDoc();
116                 }
117                 AutoCalculatedFieldInfo acfi = new AutoCalculatedFieldInfo();
118                 autoCalculatedFieldInfos.put(pe.getName(), acfi);
119                 acfi.pe = pe;
120                 acfi.name = pe.getName() + "JormLongGen";
121                 acfi.type = "org.objectweb.jorm.facility.naming.generator.LongGen";
122                 acfi.value = pe.getName() + "JormLongGen.genId($)";
123                 acfi.getter = "getACF" + upperFL(pe.getName());
124                 acfi.setter = "setACF" + upperFL(pe.getName());
125                 switch (pe.getType().getTypeCode()) {
126                 case PType.TYPECODE_INT:
127                     acfi.value = "(int) " + acfi.value;
128                     break;
129                 case PType.TYPECODE_OBJINT:
130                     acfi.value = "new Integer((int)" + acfi.value + ")";
131                     break;
132                 case PType.TYPECODE_LONG:
133                     //nothing more to do
134
break;
135                 case PType.TYPECODE_OBJLONG:
136                     acfi.value = "new Long(" + acfi.value + ")";
137                     break;
138                 default:
139                     throw new PException(
140                         "Auto calculated field not supported for the field type: "
141                         + pe.getType().getJavaName());
142                 }
143             } else {
144                 allAutoCalculated = false;
145             }
146         }
147         if (autoCalculatedFieldInfos != null) {
148             ctx.put("autoCalculatedFieldInfos", autoCalculatedFieldInfos.values());
149         }
150         ctx.put("allAutoCalculated", Boolean.valueOf(allAutoCalculated));
151
152         try {
153             FileWriter JavaDoc fw = holder.getFileWriter(fileName + ".java");
154             if (template == null) {
155                 template = velocityEngine.getTemplate(GEN_TEMPLATE_DIR + "Binder.vm");
156             }
157             template.merge(ctx, fw);
158             fw.flush();
159             fw.close();
160         } catch (Exception JavaDoc e) {
161             throw new PExceptionCompiler(e, "Problem while generating PBinder.");
162         }
163     }
164
165     public boolean containsObject(CompositeName cn) throws PException {
166         for (Iterator JavaDoc it = cn.getAllFields().iterator(); it.hasNext();) {
167             if (canBeNullValue(
168                     ((ScalarField) it.next()).getType())) {
169                 return true;
170             }
171         }
172         return false;
173     }
174
175     public boolean containsPrimitive(CompositeName cn) throws PException {
176         for (Iterator JavaDoc it = cn.getAllFields().iterator(); it.hasNext();) {
177             if (!canBeNullValue(
178                     ((ScalarField) it.next()).getType())) {
179                 return true;
180             }
181         }
182         return false;
183     }
184
185     public String JavaDoc getNullValue(PrimitiveElement pe) {
186         if (isObjectType(pe.getType())) {
187             return "null";
188         } else if (pe.getType().getTypeCode() == PType.TYPECODE_CHAR) {
189             return "'0'";
190         } else {
191             return "(" + pe.getType().getJavaName() + ") -1";
192         }
193     }
194
195     public String JavaDoc getPNameFromSpecificPNG(CompositeName cn,
196                                           String JavaDoc pngVar,
197                                           String JavaDoc ctxVar) throws PException {
198         return getPNameFromSpecificPNG(cn, pngVar, ctxVar, null);
199     }
200     public String JavaDoc getPNameFromSpecificPNG(CompositeName cn,
201                                           String JavaDoc pngVar,
202                                           String JavaDoc ctxVar,
203                                           String JavaDoc connVar) throws PException {
204         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
205         result.append("new ");
206         result.append(cn.getName());
207         result.append("PName(");
208         Iterator JavaDoc fs = cn.getAllFields().iterator();
209         while (fs.hasNext()) {
210             ScalarField f = (ScalarField) fs.next();
211             if (connVar!= null && f.isAutoCalculated()) {
212                 result.append(((AutoCalculatedFieldInfo)
213                     autoCalculatedFieldInfos.get(f.getName()))
214                     .getValue(connVar));
215                 result.append(", ");
216             } else {
217                 result.append("((");
218                 result.append(cn.getName());
219                 result.append("PNG)");
220                 result.append(pngVar);
221                 result.append(").pnGet");
222                 result.append(upperFL(f.getName()));
223                 result.append("(");
224                 result.append(ctxVar);
225                 result.append("), ");
226             }
227         }
228         result.append(" this)");
229         return result.toString();
230     }
231
232     public String JavaDoc getPNameFromGenericPNG(CompositeName cn,
233                                          String JavaDoc pngVar,
234                                          String JavaDoc ctxVar) throws PException {
235         return getPNameFromGenericPNG(cn, pngVar, ctxVar, null);
236     }
237
238     public String JavaDoc getPNameFromGenericPNG(CompositeName cn,
239                                          String JavaDoc pngVar,
240                                          String JavaDoc ctxVar,
241                                          String JavaDoc connVar) throws PException {
242         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
243         result.append("new ");
244         result.append(cn.getName());
245         result.append("PName(");
246         Iterator JavaDoc fs = cn.getAllFields().iterator();
247         while (fs.hasNext()) {
248             ScalarField f = (ScalarField) fs.next();
249             if (connVar!= null && f.isAutoCalculated()) {
250                 result.append(((AutoCalculatedFieldInfo)
251                     autoCalculatedFieldInfos.get(f.getName()))
252                     .getValue(connVar));
253                 result.append(", ");
254             } else {
255                 result.append("((PNameGetter)");
256                 result.append(pngVar);
257                 result.append(").");
258                 result.append(getPNameGetterGetFunction(f.getType()));
259                 result.append("(\"");
260                 result.append(f.getName());
261                 result.append("\", ");
262                 result.append(ctxVar);
263                 result.append("), ");
264             }
265         }
266         result.append(" this)");
267         return result.toString();
268     }
269
270     public String JavaDoc getTestNullValues(CompositeName cn, boolean generic, String JavaDoc ctx)
271             throws PException {
272         StringBuffer JavaDoc res = new StringBuffer JavaDoc("");
273         String JavaDoc sep = "";
274         Iterator JavaDoc fs = cn.getAllFields().iterator();
275         while (fs.hasNext()) {
276             ScalarField f = (ScalarField) fs.next();
277             res.append(sep);
278             sep = " && ";
279             res.append("(");
280             String JavaDoc v1;
281             if (generic) {
282                 v1 = "png." + getPNameGetterGetFunction(f.getType()) + "(\""
283                     + f.getName() + "\", " + ctx + ")";
284             } else {
285                 v1 = "png.pnGet" + upperFL(f.getName() + "(" + ctx + ")");
286             }
287             res.append(comparePE(v1, "jorm" + f.getName(), f.getType()));
288             res.append(")");
289         }
290         return res.toString();
291     }
292
293     public String JavaDoc getCoderSetter(PType t) {
294         if (t.getTypeCode() == PType.TYPECODE_BYTEARRAY) {
295             return "putByteArray(";
296         } else {
297             return "put" + getCoderName(t) + "(";
298         }
299     }
300
301     public String JavaDoc getCoderGetter(PType t) {
302         if (t.getTypeCode() == PType.TYPECODE_BYTEARRAY) {
303             return "getByteArray()";
304         } else {
305             return "get" + getCoderName(t) + "()";
306         }
307     }
308
309     public class AutoCalculatedFieldInfo {
310         public PrimitiveElement pe;
311         public String JavaDoc type;
312         public String JavaDoc name;
313         private String JavaDoc value;
314         public String JavaDoc getter;
315         public String JavaDoc setter;
316
317         public String JavaDoc getType() {
318             return type;
319         }
320
321         public String JavaDoc getName() {
322             return name;
323         }
324
325         public String JavaDoc getGetter() {
326             return getter;
327         }
328
329         public String JavaDoc getSetter() {
330             return setter;
331         }
332
333         public String JavaDoc getValue(String JavaDoc connVar) {
334             int idx = value.indexOf('$');
335             if (idx == -1) {
336                 return value;
337             } else {
338                 return value.substring(0, idx) + connVar
339                     + value.substring(idx + 1);
340             }
341         }
342     }
343 }
344
Popular Tags