KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > mdr > handlers > BaseObjectHandler


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19 package org.netbeans.mdr.handlers;
20
21 import org.netbeans.api.mdr.MDRObject;
22 import org.netbeans.api.mdr.MDRepository;
23 import org.netbeans.mdr.NBMDRepositoryImpl;
24 import org.netbeans.mdr.handlers.gen.HandlerGenerator;
25 import org.netbeans.mdr.persistence.MOFID;
26 import org.netbeans.mdr.persistence.StorageBadRequestException;
27 import org.netbeans.mdr.persistence.StorageException;
28 import org.netbeans.mdr.storagemodel.MdrStorage;
29 import org.netbeans.mdr.storagemodel.StorableBaseObject;
30 import org.netbeans.mdr.storagemodel.StorableObject;
31 import org.netbeans.mdr.storagemodel.Transient;
32 import org.netbeans.mdr.util.DebugException;
33 import org.netbeans.mdr.util.ImplClass;
34 import org.netbeans.mdr.util.Logger;
35 import javax.jmi.reflect.InvalidObjectException;
36 import javax.jmi.reflect.RefBaseObject;
37 import javax.jmi.reflect.RefObject;
38 import javax.jmi.reflect.RefPackage;
39 import java.util.*;
40
41 /** Handles RefBaseObjectCalls
42  *
43  * @author Petr Hrebejk, Martin Matula
44  * @version
45  */

46 public abstract class BaseObjectHandler extends ImplClass implements MDRObject/*, OclAny*/ {
47     
48     private static MDRClassLoader defaultLoader = null;
49     private static ClassLoaderProvider provider = null;
50     
51     static Map deletedInstances = new WeakHashMap();
52     
53     /* --------------------------------------------------------------------- */
54     /* -- Static setters/getters ------------------------------------------- */
55     /* --------------------------------------------------------------------- */
56     
57     public static synchronized void setClassLoaderProvider(ClassLoaderProvider provider) {
58         BaseObjectHandler.provider = provider;
59     }
60     
61     public static synchronized MDRClassLoader getDefaultClassLoader() {
62         if (defaultLoader == null) {
63             defaultLoader = new MDRClassLoader(provider);
64         }
65 // Logger.getDefault().log(defaultLoader.toString() + " : " + defaultLoader.getClass().getName());
66
return defaultLoader;
67     }
68     
69     /* --------------------------------------------------------------------- */
70     /* -- Private attributes ----------------------------------------------- */
71     /* --------------------------------------------------------------------- */
72
73 // /** The object in strorage to delegate to
74
// */
75
// private final StorableBaseObject storableDelegate;
76
private MOFID mofId;
77     private final MdrStorage mdrStorage;
78     // The storable hard reference is used only by transient objects
79
// to prevent garbage collection.
80
// For non transient objects it is null during the whole life cycle.
81
private StorableBaseObject storable;
82     
83     /* --------------------------------------------------------------------- */
84     /* -- Static helper methods -------------------------------------------- */
85     /* --------------------------------------------------------------------- */
86
87     /**
88      * Returns the handler class for JMI interface <code>ifc</code> and storage object <code>s</code>.
89      *
90      * @param ifc JMI interface to be implemented by the class
91      * @param s storage object to be wrapped by an instances of the class
92      * @return class implementing <code>ifc</code>
93      */

94     public static Class JavaDoc getHandlerClass(Class JavaDoc ifc, StorableBaseObject s) throws IllegalArgumentException JavaDoc {
95         MDRClassLoader loader = getDefaultClassLoader();
96         
97         /* check if the loader may load the interface */
98         check(loader, ifc);
99         /* try to load from cache */
100         Map cache = getLoaderCache(loader);
101         String JavaDoc className = getName(ifc);
102         Class JavaDoc result = getFromCache(cache, ifc, className);
103         
104         if (result == null) {
105             try {
106                 byte[] handlerClassFile;
107                 StorableObject metaObject = s.getMetaObject();
108                 if (s instanceof StorableObject) {
109                     handlerClassFile = metaObject.getInstanceClassFile();
110                 } else {
111                     handlerClassFile = metaObject.getClassFile();
112                 }
113                 
114                 if (handlerClassFile == null) {
115                     /* generate and define handler class */
116                     handlerClassFile = HandlerGenerator.generateHandler(className, ifc, s);
117                     if (s instanceof StorableObject) {
118                         metaObject.setInstanceClassFile(handlerClassFile);
119                     } else {
120                         metaObject.setClassFile(handlerClassFile);
121                     }
122                 }
123                 
124                 /* [XXX] Allow the use of a system property org.netbeans.mdr.byteCodeDir, write class
125                  * files to that directory, if the system property is set.
126                  */

127 // try {
128
// java.io.FileOutputStream file = new java.io.FileOutputStream("/mnt/work/mdrclasses/" + className.substring(className.lastIndexOf('.') + 1) + ".class");
129
// file.write(handlerClassFile);
130
// file.close();
131
// } catch (Exception e) {
132
// Logger.getDefault().notify(Logger.INFORMATIONAL, e);
133
// }
134

135                 result = loader.defineClass(className, handlerClassFile);
136             } catch (StorageException e) {
137                 throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
138             } finally {
139                 releaseCache(cache, result, className);
140             }
141         }
142         
143         return result;
144     }
145
146     /**
147      * Returns the JMI interface to be implemented by the handler of <code>s</code>.
148      *
149      * @param s a storage object
150      * @return the JMI interface for <code>s</code>
151      */

152     public static Class JavaDoc resolveClass(StorableBaseObject s) {
153         try {
154             StorableObject metaObject = s.getMetaObject();
155             return getDefaultClassLoader().resolveInterface(metaObject, !(s instanceof StorableObject));
156         } catch (StorageException e) {
157             throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
158         }
159     }
160     
161     /**
162      * Returns interface <code>ifcName</code>. The interface is not generated on the
163      * fly, but must be available for loading by the default class-loader
164      * (see {@link BaseObjectHandler#getDefaultClassLoader()}).
165      *
166      * @param ifcName name of the interface to be loaded
167      * @return the interface named <code>ifcName</code>
168      */

169     public static Class JavaDoc resolveInterface(String JavaDoc ifcName) throws ClassNotFoundException JavaDoc {
170         try {
171             return Class.forName(ifcName, true, BaseObjectHandler.getDefaultClassLoader());
172         } catch (RuntimeException JavaDoc e) {
173             Logger.getDefault().annotate(e, "ClassLoader: " + BaseObjectHandler.getDefaultClassLoader());
174             Logger.getDefault().annotate(e, "ClassName: " + ifcName);
175             throw e;
176         } catch (Error JavaDoc e) {
177             Logger.getDefault().annotate(e, "ClassLoader: " + BaseObjectHandler.getDefaultClassLoader());
178             Logger.getDefault().annotate(e, "ClassName: " + ifcName);
179             throw e;
180     }
181     }
182         
183     /**
184      * Loads the class <code>implName</code> from the default class loader.
185      *
186      * @param implName class name
187      * @return the class
188      */

189     public static Class JavaDoc resolveImplementation(String JavaDoc implName) throws ClassNotFoundException JavaDoc {
190         try {
191             return Class.forName(implName, true, BaseObjectHandler.getDefaultClassLoader());
192         } catch (ClassNotFoundException JavaDoc e) {
193             // Logger.getDefault().annotate(e, "Implementation of derived element not found. ClassName: " + implName);
194
throw e;
195         } catch (Error JavaDoc e) {
196             Logger.getDefault().annotate(e, "ClassLoader: " + BaseObjectHandler.getDefaultClassLoader());
197             Logger.getDefault().annotate(e, "ClassName: " + implName);
198             throw e;
199     } catch (RuntimeException JavaDoc e) {
200             Logger.getDefault().annotate(e, "ClassLoader: " + BaseObjectHandler.getDefaultClassLoader());
201             Logger.getDefault().annotate(e, "ClassName: " + implName);
202             throw e;
203         }
204     }
205     
206     /* --------------------------------------------------------------------- */
207     /* -- Constructor(s) --------------------------------------------------- */
208     /* --------------------------------------------------------------------- */
209
210     /** Creates new RefBaseObjectHandler */
211     protected BaseObjectHandler(StorableBaseObject storable) {
212         _setDelegate(storable);
213         this.mdrStorage = storable.getMdrStorage();
214     }
215     
216     /* --------------------------------------------------------------------- */
217     /* -- Transaction related methods -------------------------------------- */
218     /* --------------------------------------------------------------------- */
219     
220     protected final void _lock() {
221         _lock(false);
222     }
223     
224     protected final void _lock(boolean write) {
225         _getRepository().beginTrans(write);
226     }
227     
228     protected final void _unlock() {
229         _getRepository().endTrans();
230     }
231
232     protected final void _unlock(boolean fail) {
233         _getRepository().endTrans(fail);
234     }
235     
236     /* --------------------------------------------------------------------- */
237     /* -- Implements org.netbeans.api.mdr.MDRObject ------------------------ */
238     /* --------------------------------------------------------------------- */
239     
240     public final MDRepository repository() {
241         return _getRepository();
242     }
243     
244     /* --------------------------------------------------------------------- */
245     /* -- Extends java.lang.Object ----------------------------------------- */
246     /* --------------------------------------------------------------------- */
247
248     /** Tests this object with other object for identity.
249      * The object is identical if it is of RefBaseObject type
250      * and its mofid equals to this object mofid.
251      * This equals method and hashCode method are the only two
252      * methods guaranteed to work after the object was deleted.
253      * This allows developer to safely remove the deleted object from a container.
254      * @param obj other object
255      * @return true if objects are identical
256      */

257     public final boolean equals(Object JavaDoc obj) {
258         if (obj instanceof BaseObjectHandler) {
259             return this == obj;
260         } else return (obj instanceof RefBaseObject) && ((RefBaseObject) obj).refMofId().equals(refMofId());
261     }
262
263     public String JavaDoc toString() {
264         String JavaDoc className = getClass().getName();
265         className = className.substring( className.lastIndexOf( "." ) + 1 );
266         String JavaDoc metaId;
267         try {
268             metaId = _getDelegate().getMetaObject().getMofId().toString();
269         } catch (Exception JavaDoc e) {
270             metaId = "(not available)";
271         }
272         String JavaDoc outP;
273
274         try {
275             outP = _getDelegate().getOutermostPackage().getMofId().toString();
276         } catch (Exception JavaDoc e) {
277             outP = "(not available)";
278         }
279         
280         return className + " ID: " + refMofId() + " MID: " + metaId + " OPCKG: " + outP;
281     }
282
283     /** Returns hash code of this object.
284      * This hashCode method and equals method are the only two
285      * methods guaranteed to work after the object was deleted.
286      * This allows developer to safely remove the deleted object from a container.
287      * @return int the hash code
288      */

289     public final int hashCode() {
290         return this.mofId.hashCode();
291     }
292     
293     /* --------------------------------------------------------------------- */
294     /* -- Implements javax.jmi.reflect.RefBaseObject ----------------------- */
295     /* --------------------------------------------------------------------- */
296
297     public final RefObject refMetaObject() {
298         _lock(false);
299         try {
300             return (RefObject) _getRepository().getHandler(_getDelegate().getMetaObject());
301         } catch (StorageException e) {
302             throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
303         } finally {
304             _unlock();
305         }
306     }
307
308     public final RefPackage refImmediatePackage() {
309         _lock(false);
310         try {
311             return (RefPackage) _getRepository().getHandler(_getDelegate().getImmediatePackage());
312         } catch (StorageException e) {
313             throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
314         } finally {
315             _unlock();
316         }
317     }
318
319     public final RefPackage refOutermostPackage() {
320         _lock(false);
321         try {
322             StorableBaseObject pkg = _getDelegate().getOutermostPackage();
323             if (pkg.getMofId().equals(_getDelegate().getMofId())) {
324                 return (RefPackage) this;
325             } else {
326                 return (RefPackage) _getRepository().getHandler(pkg);
327             }
328         } catch (StorageException e) {
329             throw (DebugException) Logger.getDefault().annotate(new DebugException(), e);
330         } finally {
331             _unlock();
332         }
333     }
334
335     public final String JavaDoc refMofId() {
336         return mofId.toString();
337     }
338     
339     public final Collection refVerifyConstraints(boolean deepVerify) {
340         _lock(false);
341         try {
342             if (deepVerify) return _recursiveVerify(new ArrayList(), new HashSet());
343             else return _verify(new ArrayList());
344         } finally {
345             _unlock();
346         }
347     }
348     
349     /* --------------------------------------------------------------------- */
350     /* -- --------------------------------------------------- */
351     /* --------------------------------------------------------------------- */
352
353     public final StorableBaseObject _getDelegate() {
354         try {
355             StorableBaseObject result;
356             if (this.storable != null)
357                 result = this.storable; // Transient object
358
else
359                 result = mdrStorage.getObject(mofId); // Persistent object
360
if (result == null) {
361                 Exception JavaDoc exc = (Exception JavaDoc)deletedInstances.get(this);
362                 if (exc != null) {
363                     Logger.getDefault().notify(Logger.INFORMATIONAL, exc);
364                 }
365                 throw new InvalidObjectException(null, "Object with MOFID " + mofId + " no longer exists, class: " + getClass().getName());
366             }
367             return result;
368         } catch (StorageBadRequestException e) {
369             Exception JavaDoc exc = (Exception JavaDoc)deletedInstances.get(this);
370             if (exc != null) {
371                 Logger.getDefault().notify(Logger.INFORMATIONAL, exc);
372             }
373             throw new InvalidObjectException(null, "Object with MOFID " + mofId + " no longer exists, class: " + getClass().getName());
374         } catch (StorageException e) {
375             throw new DebugException(e.toString());
376         }
377         
378         //return storableDelegate;
379
}
380     
381     public final MOFID _getMofId() {
382         return mofId;
383     }
384
385     protected final void _setDelegate(StorableBaseObject storable) {
386         boolean register = false;
387         MOFID newMofId = storable.getMofId();
388         if (this.mofId != null && !this.mofId.equals(newMofId)) {
389             _getRepository().removeHandler(this.mofId);
390             register = true;
391         }
392         this.mofId = newMofId;
393         if (storable instanceof StorableObject && storable instanceof Transient) {
394             this.storable = storable;
395         } else {
396             this.storable = null;
397         }
398         if (register) {
399             _getRepository().addHandler(this);
400         }
401     }
402
403     protected final MdrStorage _getMdrStorage() {
404         return mdrStorage;
405     }
406     
407     protected final NBMDRepositoryImpl _getRepository() {
408         return mdrStorage.getRepository();
409     }
410     
411     /* --------------------------------------------------------------------- */
412     /* -- Methods to be overridden by sub-classes -------------------------- */
413     /* --------------------------------------------------------------------- */
414
415     protected abstract Collection _recursiveVerify(Collection violations, Set visited);
416     protected abstract Collection _verify(Collection violations);
417 }
418
Popular Tags