KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > db4o > Platform4


1 /* Copyright (C) 2004 - 2006 db4objects Inc. http://www.db4o.com
2
3 This file is part of the db4o open source object database.
4
5 db4o is free software; you can redistribute it and/or modify it under
6 the terms of version 2 of the GNU General Public License as published
7 by the Free Software Foundation and as clarified by db4objects' GPL
8 interpretation policy, available at
9 http://www.db4o.com/about/company/legalpolicies/gplinterpretation/
10 Alternatively you can write to db4objects, Inc., 1900 S Norfolk Street,
11 Suite 350, San Mateo, CA 94403, USA.
12
13 db4o is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */

21 package com.db4o;
22
23 import java.net.*;
24 import java.util.Date JavaDoc;
25
26 import com.db4o.config.*;
27 import com.db4o.foundation.*;
28 import com.db4o.handlers.*;
29 import com.db4o.inside.*;
30 import com.db4o.query.*;
31 import com.db4o.reflect.*;
32 import com.db4o.reflect.generic.*;
33 import com.db4o.types.*;
34
35 /**
36  * @exclude
37  * @sharpen.ignore
38  */

39 public final class Platform4 {
40     
41
42     static private int collectionCheck;
43
44     static private JDK jdkWrapper;
45     static private int nioCheck;
46
47     static private int setAccessibleCheck;
48     static private int shutDownHookCheck;
49     static int callConstructorCheck;
50     static ShutDownRunnable shutDownRunnable;
51
52     static Thread JavaDoc shutDownThread;
53     
54     static final String JavaDoc ACCESSIBLEOBJECT = "java.lang.reflect.AccessibleObject";
55     static final String JavaDoc GETCONSTRUCTOR = "newConstructorForSerialization";
56     static final String JavaDoc REFERENCEQUEUE = "java.lang.ref.ReferenceQueue";
57     static final String JavaDoc REFLECTIONFACTORY = "sun.reflect.ReflectionFactory";
58     static final String JavaDoc RUNFINALIZERSONEXIT = "runFinalizersOnExit";
59     
60     static final String JavaDoc UTIL = "java.util.";
61     static final String JavaDoc DB4O_PACKAGE = "com.db4o.";
62     static final String JavaDoc DB4O_CONFIG = DB4O_PACKAGE + "config.";
63     static final String JavaDoc DB4O_ASSEMBLY = ", db4o";
64     
65     
66     // static private int cCreateNewFile;
67
static private int weakReferenceCheck;
68     
69     private static final Class JavaDoc[] SIMPLE_CLASSES = {
70         Integer JavaDoc.class,
71         Long JavaDoc.class,
72         Float JavaDoc.class,
73         Boolean JavaDoc.class,
74         Double JavaDoc.class,
75         Byte JavaDoc.class,
76         Character JavaDoc.class,
77         Short JavaDoc.class,
78         String JavaDoc.class,
79         java.util.Date JavaDoc.class
80     };
81
82
83     static final void addShutDownHook(Object JavaDoc a_stream, Object JavaDoc a_lock) {
84         synchronized (a_lock) {
85             if (hasShutDownHook()) {
86                 if (shutDownThread == null) {
87                     shutDownRunnable = new ShutDownRunnable();
88                     shutDownThread = jdk().addShutdownHook(shutDownRunnable);
89                 }
90                 shutDownRunnable.ensure(a_stream);
91             }
92         }
93     }
94
95     public static final boolean canSetAccessible() {
96         if (Deploy.csharp) {
97             return true;
98         }
99         if (setAccessibleCheck == YapConst.UNCHECKED) {
100             if (Deploy.csharp) {
101                 setAccessibleCheck = YapConst.NO;
102             } else {
103                 if (jdk().ver() >= 2) {
104                     setAccessibleCheck = YapConst.YES;
105                 } else {
106                     setAccessibleCheck = YapConst.NO;
107                     if (Db4o.i_config.messageLevel() >= 0) {
108                         Messages.logErr(Db4o.i_config, 47, null, null);
109                     }
110                 }
111             }
112         }
113         return setAccessibleCheck == YapConst.YES;
114     }
115     
116     /**
117      * use for system classes only, since not ClassLoader
118      * or Reflector-aware
119      */

120     static final boolean classIsAvailable(String JavaDoc className) {
121         try {
122             return Class.forName(className) != null;
123         } catch (Throwable JavaDoc t) {
124             return false;
125         }
126     }
127     
128     static Db4oCollections collections(Object JavaDoc a_object){
129         return jdk().collections((YapStream)a_object);
130     }
131     
132     static final Reflector createReflector(Object JavaDoc classLoader){
133         return jdk().createReflector(classLoader);
134     }
135
136     static final Object JavaDoc createReferenceQueue() {
137         return jdk().createReferenceQueue();
138     }
139     
140     public static Object JavaDoc createWeakReference(Object JavaDoc obj){
141         return jdk().createWeakReference(obj);
142     }
143
144     static final Object JavaDoc createYapRef(Object JavaDoc a_queue, Object JavaDoc a_yapObject, Object JavaDoc a_object) {
145         return jdk().createYapRef(a_queue, (YapObject) a_yapObject, a_object);
146     }
147     
148     static Object JavaDoc deserialize(byte[] bytes) {
149         return jdk().deserialize(bytes);
150     }
151     
152     static final long doubleToLong(double a_double) {
153         return Double.doubleToLongBits(a_double);
154     }
155
156     static final QConEvaluation evaluationCreate(Transaction a_trans, Object JavaDoc example){
157         if(example instanceof Evaluation){
158             return new QConEvaluation(a_trans, example);
159         }
160         return null;
161     }
162     
163     static final void evaluationEvaluate(Object JavaDoc a_evaluation, Candidate a_candidate){
164         ((Evaluation)a_evaluation).evaluate(a_candidate);
165     }
166
167     /** may be needed for YapConfig processID() at a later date */
168     /*
169     static boolean createNewFile(File file) throws IOException{
170         return file.createNewFile();
171     }
172     */

173     
174     public static Object JavaDoc[] collectionToArray(YapStream stream, Object JavaDoc obj){
175         Collection4 col = flattenCollection(stream, obj);
176         Object JavaDoc[] ret = new Object JavaDoc[col.size()];
177         col.toArray(ret);
178         return ret;
179     }
180
181     static final Collection4 flattenCollection(YapStream stream, Object JavaDoc obj) {
182         Collection4 col = new Collection4();
183         flattenCollection1(stream, obj, col);
184         return col;
185     }
186
187     /**
188      * Should create additional configuration, for example through reflection
189      * on annotations.
190      *
191      * - If a valid configuration is passed as classConfig, any additional
192      * configuration, if available, should be applied to this object, and
193      * this object should be returned.
194      * - If classConfig is null and there is no additional configuration,
195      * null should be returned.
196      * - If classConfig is null and there is additional configuration, this code
197      * should create and register a new configuration via config.objectClass(),
198      * apply additional configuration there and return this new instance.
199      *
200      * The reason for this dispatch is to avoid creation of a configuration
201      * for a class that doesn't need configuration at all.
202      *
203      * @param clazz The class to be searched for additional configuration information
204      * @param config The global database configuration
205      * @param classConfig A class configuration, if one already exists
206      * @return classConfig, if not null, a newly created ObjectClass otherwise.
207      */

208     public static Config4Class extendConfiguration(ReflectClass clazz,Configuration config,Config4Class classConfig) {
209         return jdk().extendConfiguration(clazz, config, classConfig);
210     }
211     
212     static final void flattenCollection1(YapStream stream, Object JavaDoc obj, Collection4 col) {
213         if (obj == null) {
214             col.add(null);
215         } else {
216             ReflectClass claxx = stream.reflector().forObject(obj);
217             if (claxx.isArray()) {
218                 Object JavaDoc[] objects;
219                 if (claxx.getComponentType().isArray()) {
220                     objects = new YapArrayN(stream, null, false).allElements(obj);
221                 } else {
222                     objects = new YapArray(stream, null, false).allElements(obj);
223                 }
224                 for (int i = 0; i < objects.length; i++) {
225                     flattenCollection1(stream, objects[i], col);
226                 }
227             } else {
228                 flattenCollection2(stream, obj, col);
229             }
230         }
231     }
232
233     static final void flattenCollection2(final YapStream a_stream, Object JavaDoc a_object, final com.db4o.foundation.Collection4 col) {
234         Reflector reflector = a_stream.reflector();
235         if (reflector.forObject(a_object).isCollection()) {
236             forEachCollectionElement(a_object, new Visitor4() {
237                 public void visit(Object JavaDoc obj) {
238                     flattenCollection1(a_stream, obj, col);
239                 }
240             });
241         } else {
242             col.add(a_object);
243         }
244     }
245
246     static final void forEachCollectionElement(Object JavaDoc a_object, Visitor4 a_visitor) {
247         jdk().forEachCollectionElement(a_object, a_visitor);
248     }
249
250     static final String JavaDoc format(Date JavaDoc date, boolean showTime) {
251         return jdk().format(date, showTime);
252     }
253
254     public static Object JavaDoc getClassForType(Object JavaDoc obj) {
255         return obj;
256     }
257
258     static final void getDefaultConfiguration(Config4Impl config) {
259         
260         // Initialize all JDK stuff first, before doing ClassLoader stuff
261
jdk();
262         hasWeakReferences();
263         hasNio();
264         hasCollections();
265         hasShutDownHook();
266         
267         if(config.reflector()==null) {
268             config.reflectWith(jdk().createReflector(null));
269         }
270         
271         config.objectClass("java.lang.StringBuffer").compare(new ObjectAttribute() {
272             public Object JavaDoc attribute(Object JavaDoc original) {
273                 if (original instanceof StringBuffer JavaDoc) {
274                     return ((StringBuffer JavaDoc) original).toString();
275                 }
276                 return original;
277             }
278         });
279         
280         translate(config.objectClass("java.lang.Class"), "TClass");
281         translateCollection(config, "Hashtable", "THashtable", true);
282         if (jdk().ver() >= 2) {
283             try {
284                 translateCollection(config, "AbstractCollection", "TCollection", false);
285                 translateUtilNull(config, "AbstractList");
286                 translateUtilNull(config, "AbstractSequentialList");
287                 translateUtilNull(config, "LinkedList");
288                 translateUtilNull(config, "ArrayList");
289                 translateUtilNull(config, "Vector");
290                 translateUtilNull(config, "Stack");
291                 translateUtilNull(config, "AbstractSet");
292                 translateUtilNull(config, "HashSet");
293                 translate(config, UTIL + "TreeSet", "TTreeSet");
294                 translateCollection(config, "AbstractMap", "TMap", true);
295                 translateUtilNull(config, "HashMap");
296                 translateUtilNull(config, "WeakHashMap");
297                 translate(config, UTIL + "TreeMap", "TTreeMap");
298             } catch (Exception JavaDoc e) {
299             }
300         } else {
301             translateCollection(config, "Vector", "TVector", false);
302         }
303         netReadAsJava(config, "ext.Db4oDatabase");
304         netReadAsJava(config, "P1Object");
305         netReadAsJava(config, "P1Collection");
306         netReadAsJava(config, "P1HashElement");
307         netReadAsJava(config, "P1ListElement");
308         netReadAsJava(config, "P2HashMap");
309         netReadAsJava(config, "P2LinkedList");
310         netReadAsJava(config, "StaticClass");
311         netReadAsJava(config, "StaticField");
312     }
313     
314     public static Object JavaDoc getTypeForClass(Object JavaDoc obj){
315         return obj;
316     }
317
318     static final Object JavaDoc getYapRefObject(Object JavaDoc a_object) {
319         return jdk().getYapRefObject(a_object);
320     }
321
322     static final synchronized boolean hasCollections() {
323         if (collectionCheck == YapConst.UNCHECKED) {
324             if (!Deploy.csharp) {
325                 if (classIsAvailable(UTIL + "Collection")) {
326                     collectionCheck = YapConst.YES;
327                     return true;
328                 }
329             }
330             collectionCheck = YapConst.NO;
331         }
332         return collectionCheck == YapConst.YES;
333     }
334
335     static final boolean hasLockFileThread() {
336         return !Deploy.csharp;
337     }
338
339     static final boolean hasNio() {
340         if (!Debug.nio) {
341             return false;
342         }
343         if (nioCheck == YapConst.UNCHECKED) {
344             if ((jdk().ver() >= 4)
345                 && (!noNIO())) {
346                 nioCheck = YapConst.YES;
347                 return true;
348             }
349             nioCheck = YapConst.NO;
350         }
351         return nioCheck == YapConst.YES;
352
353     }
354
355     static final boolean hasShutDownHook() {
356         if (shutDownHookCheck == YapConst.UNCHECKED) {
357             if (!Deploy.csharp) {
358                 if (jdk().ver() >= 3){
359                     shutDownHookCheck = YapConst.YES;
360                     return true;
361                 }
362                 JDKReflect.invoke(System JavaDoc.class, RUNFINALIZERSONEXIT, new Class JavaDoc[] {boolean.class}, new Object JavaDoc[]{new Boolean JavaDoc(true)});
363             }
364             shutDownHookCheck = YapConst.NO;
365         }
366         return shutDownHookCheck == YapConst.YES;
367     }
368
369     static final boolean hasWeakReferences() {
370         if (!Debug.weakReferences) {
371             return false;
372         }
373         if (weakReferenceCheck == YapConst.UNCHECKED) {
374             if (!Deploy.csharp) {
375                 if (classIsAvailable(ACCESSIBLEOBJECT)
376                     && classIsAvailable(REFERENCEQUEUE)
377                     && jdk().ver() >= 2) {
378                     weakReferenceCheck = YapConst.YES;
379                     return true;
380                 }
381             }
382             weakReferenceCheck = YapConst.NO;
383         }
384         return weakReferenceCheck == YapConst.YES;
385     }
386     
387     static final boolean ignoreAsConstraint(Object JavaDoc obj){
388         return false;
389     }
390
391     static final boolean isCollectionTranslator(Config4Class a_config) {
392         return jdk().isCollectionTranslator(a_config);
393     }
394     
395     public static boolean isConnected(Socket socket) {
396         return jdk().isConnected(socket);
397     }
398     
399     public static final boolean isValueType(ReflectClass claxx){
400         return false;
401     }
402     
403     public static JDK jdk() {
404         if (jdkWrapper == null) {
405             createJdk();
406         }
407         return jdkWrapper;
408     }
409     
410     private static void createJdk() {
411         
412         if (classIsAvailable("java.lang.reflect.Method")){
413             jdkWrapper = (JDK)createInstance("com.db4o.JDKReflect");
414         }
415
416         if (classIsAvailable(Platform4.ACCESSIBLEOBJECT)){
417             jdkWrapper = createJDKWrapper("1_2");
418         }
419         
420         if (jdk().methodIsAvailable("java.lang.Runtime","addShutdownHook",
421                 new Class JavaDoc[] { Thread JavaDoc.class })){
422             jdkWrapper = createJDKWrapper("1_3");
423         }
424
425         if(classIsAvailable("java.nio.channels.FileLock")){
426             jdkWrapper = createJDKWrapper("1_4");
427         }
428         
429         if(classIsAvailable("java.lang.Enum")){
430             jdkWrapper = createJDKWrapper("5");
431         }
432         
433     }
434     
435     private static JDK createJDKWrapper(String JavaDoc name){
436         JDK newWrapper = (JDK)createInstance("com.db4o.JDK_" + name);
437         if(newWrapper != null){
438             return newWrapper;
439         }
440         return jdkWrapper;
441     }
442     
443     /**
444      * use for system classes only, since not ClassLoader
445      * or Reflector-aware
446      */

447     private static final Object JavaDoc createInstance(String JavaDoc name) {
448         try {
449             Class JavaDoc clazz = Class.forName(name);
450             if(clazz != null){
451                 return clazz.newInstance();
452             }
453         } catch (Exception JavaDoc e) {
454         }
455         return null;
456     }
457     
458     public static boolean isSimple(Class JavaDoc a_class){
459         for (int i = 0; i < SIMPLE_CLASSES.length; i++) {
460             if(a_class == SIMPLE_CLASSES[i]){
461                 return true;
462             }
463         }
464         return false;
465     }
466     
467     static final void killYapRef(Object JavaDoc a_object){
468         jdk().killYapRef(a_object);
469     }
470     
471     public static void link(){
472         if (!Deploy.csharp) {
473             
474             // link standard translators, so they won't get deleted
475
// by deployment
476

477             new TClass();
478             new TVector();
479             new THashtable();
480             new TNull();
481         }
482     }
483
484     // FIXME: functionality should really be in IoAdapter
485
public static final void lockFile(Object JavaDoc file) {
486         if (!hasNio()) {
487             return;
488         }
489
490         // FIXME: libgcj 3.x isn't able to properly lock the database file
491
String JavaDoc fullversion = System.getProperty("java.fullversion");
492         if (fullversion != null && fullversion.indexOf("GNU libgcj") >= 0) {
493             System.err.println("Warning: Running in libgcj 3.x--not locking database file!");
494             return;
495         }
496         
497         jdk().lockFile(file);
498     }
499     
500     public static final void unlockFile(Object JavaDoc file) {
501         if (hasNio()) {
502             jdk().unlockFile(file);
503         }
504     }
505
506     static final double longToDouble(long a_long) {
507         return Double.longBitsToDouble(a_long);
508     }
509
510     static void markTransient(String JavaDoc a_marker) {
511         // do nothing
512
}
513
514     static boolean callConstructor() {
515         if (callConstructorCheck == YapConst.UNCHECKED) {
516             
517             if(jdk().methodIsAvailable(
518                 REFLECTIONFACTORY,
519                 GETCONSTRUCTOR,
520                 new Class JavaDoc[]{Class JavaDoc.class, jdk().constructorClass()}
521                 )){
522                 
523                 callConstructorCheck = YapConst.NO;
524                 return false;
525             }
526             callConstructorCheck = YapConst.YES;
527         }
528         return callConstructorCheck == YapConst.YES;
529     }
530     
531     private static final void netReadAsJava(Config4Impl config, String JavaDoc className){
532         Config4Class classConfig = (Config4Class)config.objectClass(DB4O_PACKAGE + className + DB4O_ASSEMBLY);
533         if(classConfig == null){
534             return;
535         }
536         classConfig.maintainMetaClass(false);
537         classConfig.readAs(DB4O_PACKAGE + className);
538     }
539
540     private static final boolean noNIO() {
541         try {
542             if (propertyIs("java.vendor", "Sun")
543                 && propertyIs("java.version", "1.4.0")
544                 && (propertyIs("os.name", "Linux")
545                     || propertyIs("os.name", "Windows 95")
546                     || propertyIs("os.name", "Windows 98"))) {
547                 return true;
548             }
549             return false;
550         } catch (Exception JavaDoc e) {
551             return true;
552         }
553     }
554
555     static final void pollReferenceQueue(Object JavaDoc a_stream, Object JavaDoc a_referenceQueue) {
556         jdk().pollReferenceQueue((YapStream) a_stream, a_referenceQueue);
557     }
558
559     public static void postOpen(ObjectContainer a_oc) {
560         // do nothing
561
}
562     
563     static void preClose(ObjectContainer a_oc) {
564         // do nothing
565
}
566
567     private static final boolean propertyIs(String JavaDoc propertyName, String JavaDoc propertyValue) {
568         String JavaDoc property = System.getProperty(propertyName);
569         return (property != null) && (property.indexOf(propertyValue) == 0);
570     }
571     
572     public static void registerCollections(GenericReflector reflector) {
573         if(!Deploy.csharp){
574             reflector.registerCollection(P1Collection.class);
575             jdk().registerCollections(reflector);
576         }
577     }
578
579
580     static final void removeShutDownHook(Object JavaDoc a_stream, Object JavaDoc a_lock) {
581         synchronized (a_lock) {
582             if (hasShutDownHook()) {
583                 if (shutDownRunnable != null) {
584                     shutDownRunnable.remove(a_stream);
585                 }
586                 if (shutDownRunnable.size() == 0) {
587                     if (!shutDownRunnable.dontRemove) {
588                         try {
589                             jdk().removeShutdownHook(shutDownThread);
590                         } catch (Exception JavaDoc e) {
591                             // this is safer than attempting perfect
592
// synchronisation
593
}
594                     }
595                     shutDownThread = null;
596                     shutDownRunnable = null;
597                 }
598             }
599         }
600     }
601     
602     static final byte[] serialize(Object JavaDoc obj) throws Exception JavaDoc{
603         return jdk().serialize(obj);
604     }
605
606     public static final void setAccessible(Object JavaDoc a_accessible) {
607         if (!Deploy.csharp) {
608             if (setAccessibleCheck == YapConst.UNCHECKED) {
609                 canSetAccessible();
610             }
611             if (setAccessibleCheck == YapConst.YES) {
612                 jdk().setAccessible(a_accessible);
613             }
614         }
615     }
616     
617     public static boolean storeStaticFieldValues(Reflector reflector, ReflectClass claxx) {
618         return jdk().isEnum(reflector, claxx);
619     }
620
621     private static final void translate(ObjectClass oc, String JavaDoc to) {
622         ((Config4Class)oc).translateOnDemand(DB4O_CONFIG + to);
623     }
624
625     private static final void translate(Config4Impl config, String JavaDoc from, String JavaDoc to) {
626         translate(config.objectClass(from), to);
627     }
628
629     private static final void translateCollection(
630         Config4Impl config,
631         String JavaDoc from,
632         String JavaDoc to,
633         boolean cascadeOnDelete) {
634         ObjectClass oc = config.objectClass(UTIL + from);
635         oc.updateDepth(3);
636         if (cascadeOnDelete) {
637             oc.cascadeOnDelete(true);
638         }
639         translate(oc, to);
640     }
641
642     private static final void translateUtilNull(Config4Impl config, String JavaDoc className) {
643         translate(config, UTIL + className, "TNull");
644     }
645
646     static final YapTypeAbstract[] types(YapStream stream) {
647         return new YapTypeAbstract[] {
648                 new NetDateTime(stream),
649                 new NetDecimal(stream),
650                 new NetSByte(stream),
651                 new NetUInt(stream),
652                 new NetULong(stream),
653                 new NetUShort(stream)
654         };
655     }
656     
657     public static byte[] updateClassName(byte[] bytes) {
658         // needed for .NET only: update assembly names if necessary
659
return bytes;
660     }
661     
662     public static Object JavaDoc weakReferenceTarget(Object JavaDoc weakRef){
663         return jdk().weakReferenceTarget(weakRef);
664     }
665
666     public static Object JavaDoc wrapEvaluation(Object JavaDoc evaluation) {
667         throw Exceptions4.virtualException();
668     }
669
670     public static boolean isTransient(ReflectClass a_class) {
671         return false;
672     }
673
674     public static boolean isDb4oClass(String JavaDoc className) {
675         if (className.indexOf("com.db4o.test") == 0) {
676             return false;
677         }
678         return className.indexOf("com.db4o") == 0;
679     }
680 }
Popular Tags