KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > speedo > generation > generator > home > HomeGenerator


1 /**
2  * Copyright (C) 2001-2004 France Telecom R&D
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library 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 GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */

18 package org.objectweb.speedo.generation.generator.home;
19
20 import org.apache.velocity.app.Velocity;
21 import org.apache.velocity.context.Context;
22 import org.objectweb.asm.Type;
23 import org.objectweb.jorm.lib.JormPathHelper;
24 import org.objectweb.jorm.metainfo.api.Class;
25 import org.objectweb.jorm.metainfo.api.ClassRef;
26 import org.objectweb.jorm.metainfo.api.GenClassMapping;
27 import org.objectweb.jorm.metainfo.api.GenClassRef;
28 import org.objectweb.jorm.metainfo.api.MetaObject;
29 import org.objectweb.jorm.metainfo.api.NameDef;
30 import org.objectweb.jorm.metainfo.api.ReferenceMapping;
31 import org.objectweb.speedo.api.SpeedoException;
32 import org.objectweb.speedo.api.SpeedoProperties;
33 import org.objectweb.speedo.generation.enhancer.Util;
34 import org.objectweb.speedo.generation.generator.lib.SpeedoGenerator;
35 import org.objectweb.speedo.generation.generator.api.SpeedoGenerationException;
36 import org.objectweb.speedo.mapper.lib.Object2StringSerializer;
37 import org.objectweb.speedo.metadata.SpeedoClass;
38 import org.objectweb.speedo.metadata.SpeedoField;
39 import org.objectweb.speedo.metadata.SpeedoXMLDescriptor;
40 import org.objectweb.speedo.tools.StringReplace;
41 import org.objectweb.util.monolog.wrapper.velocity.VelocityLogger;
42
43 import java.io.FileWriter JavaDoc;
44 import java.util.ArrayList JavaDoc;
45 import java.util.Collection JavaDoc;
46 import java.util.Iterator JavaDoc;
47 import java.util.List JavaDoc;
48 import java.util.Map JavaDoc;
49 import java.util.Properties JavaDoc;
50
51 /**
52  *
53  * @author S.Chassande-Barrioz
54  */

55 public class HomeGenerator extends SpeedoGenerator {
56
57     public final static String JavaDoc LOGGER_NAME = SpeedoProperties.LOGGER_NAME
58             + ".generation.generator.homes";
59
60     public final static String JavaDoc TEMPLATE_NAME = TEMPLATE_DIR + ".home.Home";
61
62     // IMPLEMENTATION OF THE GeneratorComponent INTERFACE //
63
//----------------------------------------------------//
64

65     public boolean init() throws SpeedoException {
66         logger = scp.loggerFactory.getLogger(LOGGER_NAME);
67         return !scp.getXmldescriptor().isEmpty();
68     }
69
70     /**
71      * This method generates the a file since a SpeedoClass meta object.
72      *
73      * @param sClass
74      * is the speedo meta object.
75      * @param fileName
76      * name of the new file.
77      * @exception
78      * org.objectweb.speedo.generation.generator.api.SpeedoGenerationException
79      * If there is a problem during writing the new file.
80      */

81     public void generate(SpeedoClass sClass, String JavaDoc fileName)
82             throws SpeedoException {
83         computeTemplate(TEMPLATE_NAME.replace('.', '/') + ".vm");
84         try {
85             Context ctx = getContext(sClass);
86             FileWriter JavaDoc fw = new FileWriter JavaDoc(fileName);
87             ve.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM,
88                     new VelocityLogger(logger));
89             template.merge(ctx, fw);
90             fw.flush();
91             fw.close();
92         } catch (Exception JavaDoc e) {
93             throw new SpeedoGenerationException(
94                     "Error during the generation of the file " + fileName, e);
95         }
96     }
97
98     /**
99      * This method initialises the Velocity context.
100      *
101      * @param jdoClass :
102      * the jdoClass which represents the class to generate.
103      * @return a Velocity context.
104      */

105     protected Context getContext(SpeedoClass jdoClass) throws SpeedoException {
106         Context ctx = super.getContext(jdoClass);
107
108         // Jorm config
109
Properties classProperties = new Properties();
110         getJormConfig(jdoClass, classProperties);
111         String JavaDoc xmlFileName = jdoClass.jdoPackage.jdoXMLDescriptor.xmlFile;
112         xmlFileName = StringReplace.replaceChar('/', '.', xmlFileName);
113         xmlFileName = StringReplace.replaceChar(fs, '.', xmlFileName);
114         classProperties.setProperty(Object2StringSerializer.JDO_FILE_NAME_PROP,
115                 xmlFileName);
116         //Build the array of String with the calculated Map
117
String JavaDoc[] jormconfigInit = new String JavaDoc[classProperties.size()];
118         int i = 0;
119         for (Iterator JavaDoc it = classProperties.entrySet().iterator(); it.hasNext();) {
120             Map.Entry JavaDoc me = (Map.Entry JavaDoc) it.next();
121             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
122             sb.append("classProperties.setProperty(\"");
123             sb.append((String JavaDoc) me.getKey());
124             sb.append("\", \"");
125             sb.append((String JavaDoc) me.getValue());
126             sb.append("\");");
127             jormconfigInit[i] = sb.toString();
128             i++;
129         }
130         ctx.put("jormconfig", jormconfigInit);
131
132         //Define the 'pnameHints' attribute.
133
String JavaDoc pnamehints = scp.nmf.getNamingManager(jdoClass).getPNameHints(
134                 jdoClass, getClassNameDef(jdoClass.jormclass));
135         ctx.put("pnameHints", pnamehints);
136         ctx.put("nqds", jdoClass.name2query.values());
137         
138         StringBuffer JavaDoc fieldNames = new StringBuffer JavaDoc("new String[]{");
139         StringBuffer JavaDoc fieldTyes = new StringBuffer JavaDoc("new Class[]{");
140         String JavaDoc sep = "\n\t\t";
141         for(Iterator JavaDoc it = jdoClass.jdoField.values().iterator(); it.hasNext();) {
142             SpeedoField sf = (SpeedoField) it.next();
143             fieldNames.append(sep);
144             fieldNames.append("\"").append(sf.name).append("\"");
145             fieldTyes.append(sep);
146             fieldTyes.append(Util.getClassName(Type.getType(sf.desc)));
147             sep = ",\n\t\t";
148         }
149         fieldNames.append("\n\t}");
150         fieldTyes.append("\n\t}");
151         ctx.put("fieldsNamesArray", fieldNames);
152         ctx.put("fieldsTypesArray", fieldTyes);
153         
154         //Compute user caches
155
Map JavaDoc userCaches = computeUserCaches(jdoClass);
156         ctx.put("hasUserCache", Boolean.valueOf(!userCaches.isEmpty()));
157         if (!userCaches.isEmpty()) {
158             List JavaDoc l = new ArrayList JavaDoc(userCaches.keySet());
159             ctx.put("userCacheNames", l);
160             StringBuffer JavaDoc sb = new StringBuffer JavaDoc("new String[] {");
161             sep = "";
162             for (Iterator JavaDoc iter = l.iterator(); iter.hasNext();) {
163                 sb.append(sep).append("\"").append((String JavaDoc) iter.next()).append("\"");
164                 sep = ",\n\t\t\t";
165             }
166             sb.append("}");
167             ctx.put("userCacheNamesSTR", sb.toString());
168             ArrayList JavaDoc userCacheFields = new ArrayList JavaDoc();
169             ctx.put("userCacheFields", userCacheFields);
170             for (Iterator JavaDoc iter = userCaches.entrySet().iterator(); iter.hasNext();) {
171                 Map.Entry JavaDoc me = (Map.Entry JavaDoc) iter.next();
172                 List JavaDoc fields = (List JavaDoc) me.getValue();
173                 sb = new StringBuffer JavaDoc("new String[]{");
174                 sep = "";
175                 for (int j = 0; j < fields.size(); j++) {
176                     SpeedoField sf = (SpeedoField) fields.get(j);
177                     sb.append(sep).append("\"");
178                     sb.append(sf.name).append("\"");
179                     sep = ",\n\t\t\t";
180                     
181                     Field f = new Field();
182                     fillFieldInfo(f, sf, sf.jdoClass.computeFieldNumbers(), ctx);
183                     userCacheFields.add(f);
184                 }
185                 sb.append("}");
186                 userCaches.put(me.getKey(), sb.toString());
187             }
188             
189             ctx.put("userCacheFieldNames", userCaches);
190         }
191         return ctx;
192     }
193
194     private void getJormConfig(SpeedoClass jdoClass, Properties classProperties)
195             throws SpeedoException {
196         //Build the map
197
// Put the binder class name of the current persistent class
198
String JavaDoc id = JormPathHelper.getPath(jdoClass.jormclass);
199         NameDef nd = getClassNameDef(jdoClass.jormclass);
200         jormConfigs(nd, jdoClass, jdoClass.jormclass, id, classProperties);
201
202         //Put the binder class name for each reference field
203
SpeedoXMLDescriptor xml = jdoClass.jdoPackage.jdoXMLDescriptor;
204         for (Iterator JavaDoc it = jdoClass.jormclass.getAllFields().iterator(); it
205                 .hasNext();) {
206             Object JavaDoc o = it.next();
207             if (o instanceof ClassRef) {
208                 nd = getRefNameDef((ClassRef) o, jdoClass.jormclass);
209                 id = JormPathHelper.getPath(((ClassRef) o));
210                 SpeedoClass tsc = xml.getSpeedoClass(((ClassRef) o)
211                         .getMOClass().getFQName(), true);
212                 jormConfigs(nd, tsc, jdoClass.jormclass, id, classProperties);
213             } else if (o instanceof GenClassRef) {
214                 GenClassRef gcr = (GenClassRef) o;
215                 nd = getRefNameDef(gcr, jdoClass.jormclass);
216                 id = JormPathHelper.getPath((GenClassRef) o, false);
217                 jormConfigs(nd, jdoClass, gcr, id, classProperties);
218                 while (gcr.isGenClassRef()) {
219                     gcr = gcr.getGenClassRef();
220                     nd = getElemNameDef(gcr, jdoClass.jormclass);
221                     id = JormPathHelper.getPath(gcr, false);
222                     jormConfigs(nd, jdoClass, gcr, id, classProperties);
223                 }
224                 if (gcr.isClassRef()) {
225                     ClassRef cr = gcr.getClassRef();
226                     nd = getElemNameDef(gcr, jdoClass.jormclass);
227                     id = JormPathHelper.getPath(cr);
228                     SpeedoClass tsc = xml.getSpeedoClass(cr.getMOClass()
229                             .getFQName(), true);
230                     jormConfigs(nd, tsc, cr, id, classProperties);
231                 }
232             }
233         }
234     }
235
236     private void jormConfigs(NameDef nd, SpeedoClass targetClass,
237             MetaObject sourceMO, String JavaDoc key, Properties jormProp)
238             throws SpeedoException {
239         scp.nmf.getNamingManager(targetClass).getJormNamingConfig(nd,
240                 targetClass, sourceMO, key, jormProp);
241     }
242
243     private GenClassMapping getGenClassMapping(GenClassRef gcr, Class JavaDoc clazz)
244             throws SpeedoException {
245         String JavaDoc gcid = gcr.getGenClassId();
246         GenClassMapping gcm = getMapping(clazz).getGenClassMapping(gcid);
247         if (gcm == null) {
248             Class JavaDoc _clazz = clazz;
249             Collection JavaDoc superclasses = _clazz.getSuperClasses();
250             while (gcm == null && !superclasses.isEmpty()) {
251                 _clazz = (Class JavaDoc) superclasses.iterator().next();
252                 gcm = getMapping(_clazz).getGenClassMapping(gcid);
253                 superclasses = _clazz.getSuperClasses();
254             }
255         }
256         if (gcm == null) {
257             throw new SpeedoException("No GenClassMapping found for the field "
258                     + gcid);
259         }
260         return gcm;
261     }
262
263     private NameDef getRefNameDef(GenClassRef gcr, Class JavaDoc clazz)
264             throws SpeedoException {
265         return (NameDef) getGenClassMapping(gcr, clazz).getIdentifierMapping()
266                 .getLinkedMO();
267     }
268
269     private NameDef getElemNameDef(GenClassRef gcr, Class JavaDoc clazz)
270             throws SpeedoException {
271         return (NameDef) getGenClassMapping(gcr, clazz).getReferenceMapping()
272                 .getLinkedMO();
273     }
274
275     private ReferenceMapping getReferenceMapping(ClassRef cr, Class JavaDoc clazz)
276             throws SpeedoException {
277         String JavaDoc rid = cr.getName();
278         ReferenceMapping rm = getMapping(clazz).getClassMapping()
279                 .getReferenceMapping(rid);
280         if (rm == null) {
281             Class JavaDoc _clazz = clazz;
282             Collection JavaDoc superclasses = _clazz.getSuperClasses();
283             while (rm == null && !superclasses.isEmpty()) {
284                 _clazz = (Class JavaDoc) superclasses.iterator().next();
285                 rm = getMapping(_clazz).getClassMapping().getReferenceMapping(
286                         rid);
287                 superclasses = _clazz.getSuperClasses();
288             }
289         }
290         if (rm == null) {
291             throw new SpeedoException(
292                     "No ReferenceMapping found for the field " + rid);
293         }
294         return rm;
295
296     }
297
298     private NameDef getRefNameDef(ClassRef cr, Class JavaDoc clazz)
299             throws SpeedoException {
300         return (NameDef) getReferenceMapping(cr, clazz).getLinkedMO();
301     }
302
303 }
Popular Tags