KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > speedo > naming > lib > UserIdCompositeNamingManager


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.naming.lib;
19
20 import org.objectweb.asm.Type;
21 import org.objectweb.jorm.api.PException;
22 import org.objectweb.jorm.metainfo.api.CompositeName;
23 import org.objectweb.jorm.metainfo.api.GenClassRef;
24 import org.objectweb.jorm.metainfo.api.CommonClassMapping;
25 import org.objectweb.jorm.metainfo.api.Manager;
26 import org.objectweb.jorm.metainfo.api.MetaObject;
27 import org.objectweb.jorm.metainfo.api.NameDef;
28 import org.objectweb.jorm.metainfo.api.NameRef;
29 import org.objectweb.jorm.metainfo.api.Reference;
30 import org.objectweb.jorm.naming.api.PName;
31 import org.objectweb.jorm.naming.api.PNameCoder;
32 import org.objectweb.jorm.type.api.PType;
33 import org.objectweb.medor.filter.lib.ExpressionPrinter;
34 import org.objectweb.speedo.api.SpeedoException;
35 import org.objectweb.speedo.api.SpeedoProperties;
36 import org.objectweb.speedo.generation.jorm.JormMIMappingBuilder;
37 import org.objectweb.speedo.generation.lib.NamingRules;
38 import org.objectweb.speedo.mapper.api.JormFactory;
39 import org.objectweb.speedo.metadata.SpeedoClass;
40 import org.objectweb.speedo.metadata.SpeedoExtension;
41 import org.objectweb.speedo.metadata.SpeedoField;
42 import org.objectweb.speedo.metadata.SpeedoIdentity;
43 import org.objectweb.speedo.naming.api.MIBuilderHelper;
44 import org.objectweb.speedo.naming.api.NamingManager;
45 import org.objectweb.speedo.naming.api.UserId;
46 import org.objectweb.speedo.naming.api.UserIdFactory;
47 import org.objectweb.util.monolog.api.BasicLevel;
48
49 import java.util.ArrayList JavaDoc;
50 import java.util.Collection JavaDoc;
51 import java.util.Iterator JavaDoc;
52 import java.util.Properties JavaDoc;
53
54 import javax.jdo.JDOUserException;
55
56 /**
57  *
58  * @author S.Chassande-Barrioz
59  */

60 public class UserIdCompositeNamingManager
61     extends NamingManagerHelper
62     implements NamingManager {
63
64     private final static String JavaDoc COMPOSITE_USER_ID = "cuid";
65
66     protected String JavaDoc getName() {
67         return COMPOSITE_USER_ID;
68     }
69
70     // IMPLEMENTATION OF THE METHOD FROM THE NamingManager INTERFACE //
71
//---------------------------------------------------------------//
72
public boolean canManage(SpeedoClass sc) {
73         if (sc.identityType == SpeedoIdentity.USER_ID && sc.datastoreSequence == null) {
74             ArrayList JavaDoc idFields = new ArrayList JavaDoc();
75             Iterator JavaDoc fieldsIt = sc.jdoField.values().iterator();
76             while (fieldsIt.hasNext()) {
77                 SpeedoField sp = (SpeedoField) fieldsIt.next();
78                 if (sp.primaryKey) {
79                     idFields.add(sp);
80                 }
81             }
82             String JavaDoc objectidClass = sc.objectidClass;
83             if (sc.generateObjectId()) {
84                 objectidClass = NamingRules.generatedObjectIdName(sc.getFQName());
85             }
86             return objectidClass != null && objectidClass.length() > 0;
87         }
88         return false;
89     }
90
91     public Object JavaDoc encode(PName pn) throws PException {
92         if (pn instanceof UserIdFactory) {
93             return ((UserIdFactory) pn).getNewUserId();
94         }
95         return null;
96     }
97
98     public PName decode(PNameCoder pnc,
99                         Object JavaDoc oid,
100                         Class JavaDoc clazz,
101                         JormFactory jf) throws PException {
102         if (oid instanceof UserId) {
103             //the oid is a UserId
104
if (pnc != null) {
105                 //Use the pnc found by the clazz
106
return pnc.decodeAbstract(oid, null);
107             } else if (((UserId) oid).jdoGetPersistentClassName() != null) {
108                 //No pnc but the class name is inside the UserId
109
ClassLoader JavaDoc cl = oid.getClass().getClassLoader();
110                 if (cl == null) {
111                     cl = jf.getClass().getClassLoader();
112                 }
113                 if (cl == null) {
114                     cl = ClassLoader.getSystemClassLoader();
115                 }
116                 return jf.getPNamingContext(
117                         ((UserId) oid).jdoGetPersistentClassName(), cl)
118                         .decodeAbstract(oid, null);
119             }
120         } else if (pnc != null
121                 && (oid instanceof String JavaDoc)
122                 && (pnc.getNull() instanceof UserIdFactory)) {
123             //The oid is a String which must be the parameter of the constructor
124
Class JavaDoc idclass = ((UserIdFactory) pnc.getNull())
125                     .getNewUserId().getClass();
126             Object JavaDoc o = null;
127             try {
128                 o = idclass.getConstructor(new Class JavaDoc[]{String JavaDoc.class})
129                         .newInstance(new Object JavaDoc[]{(String JavaDoc) oid});
130             } catch (Exception JavaDoc e) {
131                 throw new JDOUserException("No constructor with a String " +
132                         "parameter available on the identifier class: "
133                         + idclass.getName());
134             }
135             //recall with the UserId
136
return decode(pnc, o, clazz, jf);
137         }
138
139         return null;
140     }
141
142     public boolean canProvidePBinder(Object JavaDoc hints, ClassLoader JavaDoc classLoader) {
143         if(!super.canProvidePBinder(hints, classLoader)) {
144             return false;
145         }
146         String JavaDoc cn = getBinderClassNameFromHints(hints, COMPOSITE_USER_ID);
147         if (cn == null) {
148             return false;
149         }
150         try {
151             classLoader.loadClass(cn);
152             return true;
153         } catch (ClassNotFoundException JavaDoc e) {
154             return false;
155         }
156     }
157
158     public boolean canProvidePNamingContext(Object JavaDoc hints, ClassLoader JavaDoc classLoader) {
159         if(!super.canProvidePNamingContext(hints, classLoader)) {
160             return false;
161         }
162         String JavaDoc cn = getPNCClassNameFromHints(hints, COMPOSITE_USER_ID);
163         if (cn == null) {
164             return false;
165         }
166         try {
167             classLoader.loadClass(getPNCClassNameFromHints(hints, COMPOSITE_USER_ID));
168             return true;
169         } catch (ClassNotFoundException JavaDoc e) {
170             return false;
171         }
172     }
173
174     public void fillNameDef(MIBuilderHelper mibh,
175                             Manager manager,
176                             NameDef nd,
177                             SpeedoClass tsc,
178                             SpeedoClass ssc,
179                             MetaObject mo,
180                             Reference ref,
181                             CommonClassMapping hcm,
182                             JormMIMappingBuilder mb,
183                             boolean isIdentifier,
184                             boolean isInGenClass,
185                             boolean createField,
186                             Collection JavaDoc createdMOs) throws SpeedoException, PException {
187         boolean debug = logger.isLoggable(BasicLevel.DEBUG);
188         if (debug) {
189             logger.log(BasicLevel.DEBUG, "CompositeUserId: Filling the name def: "
190                 + "\n\tsource class=" + (ssc == null ? null : ssc.getFQName())
191                 + "\n\ttarget class=" + (tsc == null ? null : tsc.getFQName())
192                 + "\n\tmo=" + mo
193                 + "\n\treference=" + ref
194                 + "\n\tisIdentifier=" + isIdentifier
195                 + "\n\tisInGenClass=" + isInGenClass
196                 + "\n\tcreateField=" + createField);
197         }
198         SpeedoClass clazzWithIdField = tsc;
199         while(clazzWithIdField.superClassName != null) {
200             clazzWithIdField = clazzWithIdField.getSpeedoClassFromContext(
201                 clazzWithIdField.superClassName);
202         }
203         ArrayList JavaDoc idFields = new ArrayList JavaDoc();
204         Iterator JavaDoc fieldsIt = clazzWithIdField.jdoField.values().iterator();
205         while (fieldsIt.hasNext()) {
206             SpeedoField sf = (SpeedoField) fieldsIt.next();
207             if (sf.primaryKey) {
208                 idFields.add(sf);
209             }
210         }
211         String JavaDoc objectidClass = clazzWithIdField.objectidClass;
212         if (objectidClass == null && tsc.generateObjectId()) {
213             objectidClass = NamingRules.generatedObjectIdName(clazzWithIdField.getFQName());
214         }
215         //The user has specified an object id ==> use it for the namedef
216
CompositeName cn = manager.getCompositeName(objectidClass);
217         boolean cnnotdefined = (cn == null);
218         if (cnnotdefined) {
219             if (debug) {
220                 logger.log(BasicLevel.DEBUG, "\tCreate the composite name " + objectidClass);
221             }
222             cn = manager.createCompositeName(objectidClass);
223             createdMOs.add(cn);
224         }
225         NameRef nr = nd.createNameRef(cn);
226         for (int i = 0; i < idFields.size(); i++) {
227             SpeedoField sf = (SpeedoField) idFields.get(i);
228             int size = PType.NOSIZE;
229             SpeedoExtension se = sf.getExtension(SpeedoProperties.VENDOR_NAME, SpeedoProperties.SIZE);
230             if (se != null) {
231                 try {
232                     size = Integer.parseInt(se.value);
233                 } catch (NumberFormatException JavaDoc e) {
234                     //The error will occur during the parsing of the primitive
235
// field in the referenced class
236
}
237             }
238             int scale = PType.NOSIZE;
239             se = sf.getExtension(SpeedoProperties.VENDOR_NAME, SpeedoProperties.SCALE);
240             if (se != null) {
241                 try {
242                     scale = Integer.parseInt(se.value);
243                 } catch (NumberFormatException JavaDoc e) {
244                     //The error will occur during the parsing of the primitive
245
// field in the referenced class
246
}
247             }
248             if (cnnotdefined) {
249                 cn.createCompositeNameField(sf.name,
250                         mibh.getPrimitivePType(Type.getType(sf.desc)),
251                         size, scale);
252             }
253             String JavaDoc fn = mibh.getNameDefFieldPrefix(
254                     ref, isIdentifier, isInGenClass) + sf.name;
255             if (debug) {
256                 logger.log(BasicLevel.DEBUG, "\tField name " + fn);
257             }
258             if (createField) {
259                 fn = mibh.createNameDefField(mo, fn,
260                         mibh.getPrimitivePType(Type.getType(sf.desc)), size, scale).getName();
261             }
262             nr.addProjection(sf.name, fn);
263         }
264         if (createField && (mb != null)) {
265             mb.createNameDefMapping(hcm, nd, ssc, isIdentifier, isInGenClass);
266         }
267     }
268
269     public String JavaDoc getPNameHints(SpeedoClass sc, NameDef nd) {
270         return "this.jdoReferenceState";
271     }
272
273     public String JavaDoc getGCPNameHints(SpeedoClass sc, NameDef nd) {
274         return "proxy.getPName()";
275     }
276
277     /**
278      * Build a property value compsed such as this pattern
279      * userid,binder_class_name,pnc_class_name,class_name
280      * @param nd
281      * @param targetClass
282      * @param sourceMO
283      * @param key
284      * @param result
285      */

286     public void getJormNamingConfig(NameDef nd,
287                                     SpeedoClass targetClass,
288                                     MetaObject sourceMO,
289                                     String JavaDoc key,
290                                     Properties result) throws SpeedoException {
291         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
292         sb.append(COMPOSITE_USER_ID);
293         sb.append(HINTS_SEP);
294         String JavaDoc binderClassName = NamingRules.binderName(
295             nd.getNameRef().getCompositeName().getFQName());
296         sb.append(binderClassName);
297         sb.append(HINTS_SEP);
298         String JavaDoc className = targetClass.getFQName();
299         SpeedoClass ancestor = targetClass.getAncestor();
300         if (sourceMO instanceof GenClassRef //For a Genclass ref or identifier
301
|| (ancestor == null //No inheritance
302
&& targetClass.jormclass.getSubClasses().isEmpty())) {
303             sb.append(binderClassName);
304         } else {
305             if (ancestor == null) {
306                 ancestor = targetClass;
307             }
308             try {
309                 logger.log(BasicLevel.DEBUG, "Class " + targetClass.jormclass.getFQName() + "\n"
310                                         + " NamedDef " + nd.toString() + "\n"
311                                         + " Filter " + ExpressionPrinter.e2str(targetClass.jormclass.getInheritanceFilter(nd)) );
312                 if (targetClass.jormclass.getSubClasses().isEmpty()) {
313                     sb.append(binderClassName);
314                 } else if (targetClass.jormclass.detectFilterElementNotInPK(targetClass.jormclass.getInheritanceFilter(nd), nd)) {
315                     //if has child(ren)
316
//and one of the fields of the filter is not in the primary key,
317
//use a PolymorphicPNC
318
logger.log(BasicLevel.DEBUG, "Composite PName : assign a polymorphic PNC for the class" + targetClass.jormclass.getFQName() + ".");
319                     sb.append(POLYMORPHIC_PNC);
320                 } else {
321                     //use a kfpnc
322
logger.log(BasicLevel.DEBUG, "Composite PName : assign a KFPNC for the class" + targetClass.jormclass.getFQName() + ".");
323                     sb.append(NamingRules.kfpncName(ancestor.getFQName()));
324                 }
325             } catch (Exception JavaDoc e) {
326                 logger.log(BasicLevel.ERROR, "Error while retrieving the inheritance filter of the namedef:" + nd.toString());
327                 throw new SpeedoException("Error while retrieving the inheritance filter of the namedef:" + nd.toString(), e);
328             }
329             className = ancestor.getFQName();
330         }
331         sb.append(HINTS_SEP);
332         sb.append(className);
333         result.setProperty(key, sb.toString());
334     }
335
336 }
337
Popular Tags