KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > corba > se > impl > util > Utility


1 /*
2  * @(#)Utility.java 1.41 04/06/21
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 /*
9  * Licensed Materials - Property of IBM
10  * RMI-IIOP v1.0
11  * Copyright IBM Corp. 1998 1999 All Rights Reserved
12  *
13  * US Government Users Restricted Rights - Use, duplication or
14  * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
15  */

16
17 package com.sun.corba.se.impl.util;
18
19 import org.omg.CORBA.SystemException JavaDoc;
20 import org.omg.CORBA.CompletionStatus JavaDoc;
21 import org.omg.CORBA.BAD_OPERATION JavaDoc;
22 import org.omg.CORBA.BAD_INV_ORDER JavaDoc;
23 import org.omg.CORBA.BAD_PARAM JavaDoc;
24 import org.omg.CORBA.ORB JavaDoc;
25 import org.omg.CORBA.Any JavaDoc;
26 import org.omg.CORBA.TypeCode JavaDoc;
27 import org.omg.CORBA.Principal JavaDoc;
28 import org.omg.CORBA.portable.InputStream JavaDoc;
29 import org.omg.CORBA.portable.OutputStream JavaDoc;
30 import org.omg.CORBA.portable.BoxedValueHelper JavaDoc;
31 import org.omg.CORBA.portable.ValueFactory JavaDoc;
32 import org.omg.CORBA.portable.Streamable JavaDoc;
33 import org.omg.CORBA.portable.Delegate JavaDoc;
34
35
36 import java.util.Hashtable JavaDoc;
37 import java.util.NoSuchElementException JavaDoc;
38
39 import java.rmi.Remote JavaDoc;
40 import java.rmi.NoSuchObjectException JavaDoc;
41 import java.rmi.RemoteException JavaDoc;
42 import java.rmi.server.RemoteStub JavaDoc;
43
44 import javax.rmi.PortableRemoteObject JavaDoc;
45 import javax.rmi.CORBA.Stub JavaDoc;
46 import javax.rmi.CORBA.Tie JavaDoc;
47 import javax.rmi.CORBA.Util JavaDoc;
48
49 import java.io.Serializable JavaDoc;
50 import java.io.File JavaDoc;
51 import java.io.FileInputStream JavaDoc;
52
53 import org.omg.PortableServer.POA JavaDoc;
54
55 import com.sun.org.omg.SendingContext.CodeBase;
56
57 import com.sun.corba.se.spi.logging.CORBALogDomains ;
58 import com.sun.corba.se.spi.presentation.rmi.PresentationManager;
59 import com.sun.corba.se.spi.presentation.rmi.StubAdapter ;
60
61 import com.sun.corba.se.impl.logging.UtilSystemException ;
62 import com.sun.corba.se.impl.logging.OMGSystemException ;
63
64 /**
65  * Handy class full of static functions.
66  */

67 public final class Utility {
68
69     public static final String JavaDoc STUB_PREFIX = "_";
70     public static final String JavaDoc RMI_STUB_SUFFIX = "_Stub";
71     public static final String JavaDoc DYNAMIC_STUB_SUFFIX = "_DynamicStub" ;
72     public static final String JavaDoc IDL_STUB_SUFFIX = "Stub";
73     public static final String JavaDoc TIE_SUFIX = "_Tie";
74     private static IdentityHashtable tieCache = new IdentityHashtable();
75     private static IdentityHashtable tieToStubCache = new IdentityHashtable();
76     private static IdentityHashtable stubToTieCache = new IdentityHashtable();
77     private static Object JavaDoc CACHE_MISS = new Object JavaDoc();
78     private static UtilSystemException wrapper = UtilSystemException.get(
79     CORBALogDomains.UTIL ) ;
80     private static OMGSystemException omgWrapper = OMGSystemException.get(
81     CORBALogDomains.UTIL ) ;
82
83     /**
84      * Ensure that stubs, ties, and implementation objects
85      * are 'connected' to the runtime. Converts implementation
86      * objects to a type suitable for sending on the wire.
87      * @param obj the object to connect.
88      * @param orb the ORB to connect to if obj is exported to IIOP.
89      * @param convertToStub true if implementation types should be
90      * converted to Stubs rather than just org.omg.CORBA.Object.
91      * @return the connected object.
92      * @exception NoSuchObjectException if obj is an implementation
93      * which has not been exported.
94      */

95     public static Object JavaDoc autoConnect(Object JavaDoc obj, ORB JavaDoc orb, boolean convertToStub)
96     {
97         if (obj == null) {
98             return obj;
99         }
100         
101         if (StubAdapter.isStub(obj)) {
102             try {
103         StubAdapter.getDelegate(obj) ;
104             } catch (BAD_OPERATION JavaDoc okay) {
105                 try {
106             StubAdapter.connect( obj, orb ) ;
107                 } catch (RemoteException JavaDoc e) {
108                     // The stub could not be connected because it
109
// has an invalid IOR...
110
throw wrapper.objectNotConnected( e,
111             obj.getClass().getName() ) ;
112                 }
113             }
114             
115             return obj;
116         }
117         
118         if (obj instanceof Remote JavaDoc) {
119         Remote JavaDoc remoteObj = (Remote JavaDoc)obj;
120             Tie JavaDoc theTie = Util.getTie(remoteObj);
121             if (theTie != null) {
122                 try {
123                     theTie.orb();
124                 } catch (SystemException JavaDoc okay) {
125                     theTie.orb(orb);
126                 }
127                
128                 if (convertToStub) {
129                     Object JavaDoc result = loadStub(theTie,null,null,true);
130                     if (result != null) {
131                         return result;
132                     } else {
133             throw wrapper.couldNotLoadStub(obj.getClass().getName());
134                     }
135                 } else {
136             return StubAdapter.activateTie( theTie );
137                 }
138             } else {
139                 // This is an implementation object which has not been
140
// exported to IIOP OR is a JRMP stub or implementation
141
// object which cannot be marshalled into an ORB stream...
142
throw wrapper.objectNotExported( obj.getClass().getName() ) ;
143             }
144         }
145         
146         // Didn't need to do anything, just return the input...
147

148         return obj;
149     }
150                                             
151     /*
152      * Get a new instance of an RMI-IIOP Tie for the
153      * given server object.
154      */

155     public static Tie JavaDoc loadTie(Remote JavaDoc obj) {
156         Tie JavaDoc result = null;
157         Class JavaDoc objClass = obj.getClass();
158         
159         // Have we tried to find this guy before?
160

161         synchronized (tieCache) {
162             
163             Object JavaDoc it = tieCache.get(obj);
164             
165             if (it == null) {
166                 
167                 // No, so try it...
168

169                 try {
170
171                     // First try the classname...
172

173                     result = loadTie(objClass);
174                         
175                     // If we don't have a valid tie at this point,
176
// walk up the parent chain until we either
177
// load a tie or encounter PortableRemoteObject
178
// or java.lang.Object...
179

180                     while (result == null &&
181                            (objClass = objClass.getSuperclass()) != null &&
182                            objClass != PortableRemoteObject JavaDoc.class &&
183                            objClass != Object JavaDoc.class) {
184                                 
185                         result = loadTie(objClass);
186                     }
187                 } catch (Exception JavaDoc ex) {
188             wrapper.loadTieFailed( ex, objClass.getName() ) ;
189         }
190             
191                 // Did we get it?
192

193                 if (result == null) {
194                     
195                     // Nope, so cache that fact...
196

197                     tieCache.put(obj,CACHE_MISS);
198                     
199                 } else {
200                     
201                     // Yes, so cache it...
202

203                     tieCache.put(obj,result);
204                 }
205             } else {
206                 
207                 // Yes, return a new instance or fail again if
208
// it was a miss last time...
209

210                 if (it != CACHE_MISS) {
211                     try {
212                         result = (Tie JavaDoc) it.getClass().newInstance();
213                     } catch (Exception JavaDoc e) {
214                     }
215                 }
216             }
217         }
218         
219         return result;
220     }
221     
222     /*
223      * Load an RMI-IIOP Tie
224      */

225     private static Tie JavaDoc loadTie(Class JavaDoc theClass)
226     {
227     return com.sun.corba.se.spi.orb.ORB.getStubFactoryFactory().
228         getTie( theClass ) ;
229     }
230  
231     /*
232      * Clear the stub/tie caches. Intended for use by
233      * test code.
234      */

235     public static void clearCaches() {
236         synchronized (tieToStubCache) {
237             tieToStubCache.clear();
238         }
239         synchronized (tieCache) {
240             tieCache.clear();
241         }
242         synchronized (stubToTieCache) {
243             stubToTieCache.clear();
244         }
245     }
246     
247     /*
248      * Load a class and check that it is assignable to a given type.
249      * @param className the class name.
250      * @param remoteCodebase the codebase to use. May be null.
251      * @param loader the class loader of last resort. May be null.
252      * @param expectedType the expected type. May be null.
253      * @return the loaded class.
254      */

255     static Class JavaDoc loadClassOfType(String JavaDoc className, String JavaDoc remoteCodebase,
256     ClassLoader JavaDoc loader, Class JavaDoc expectedType,
257     ClassLoader JavaDoc expectedTypeClassLoader) throws ClassNotFoundException JavaDoc
258     {
259     Class JavaDoc loadedClass = null;
260
261     try {
262             //Sequence finding of the stubs according to spec
263
try{
264                 //If-else is put here for speed up of J2EE.
265
//According to the OMG spec, the if clause is not dead code.
266
//It can occur if some compiler has allowed generation
267
//into org.omg.stub hierarchy for non-offending
268
//classes. This will encourage people to
269
//produce non-offending class stubs in their own hierarchy.
270
if (!PackagePrefixChecker.hasOffendingPrefix(
271             PackagePrefixChecker.withoutPackagePrefix(className))){
272                     loadedClass = Util.loadClass(
273             PackagePrefixChecker.withoutPackagePrefix(className),
274                         remoteCodebase,
275                         loader);
276                 } else {
277                     loadedClass = Util.loadClass(className, remoteCodebase,
278                         loader);
279                 }
280             } catch (ClassNotFoundException JavaDoc cnfe) {
281                 loadedClass = Util.loadClass(className, remoteCodebase,
282                     loader);
283             }
284             if (expectedType == null)
285             return loadedClass;
286     } catch (ClassNotFoundException JavaDoc cnfe) {
287         if (expectedType == null)
288             throw cnfe;
289     }
290     
291         // If no class was loaded, or if the loaded class is not of the
292
// correct type, make a further attempt to load the correct class
293
// using the classloader of the expected type.
294
// _REVISIT_ Is this step necessary, or should the Util,loadClass
295
// algorithm always produce a valid class if the setup is correct?
296
// Does the OMG standard algorithm need to be changed to include
297
// this step?
298
if (loadedClass == null || !expectedType.isAssignableFrom(loadedClass)){
299             if (expectedType.getClassLoader() != expectedTypeClassLoader)
300                 throw new IllegalArgumentException JavaDoc(
301                     "expectedTypeClassLoader not class loader of " +
302                     "expected Type.");
303
304             if (expectedTypeClassLoader != null)
305         loadedClass = expectedTypeClassLoader.loadClass(className);
306             else {
307                 ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
308                 if (cl == null)
309                     cl = ClassLoader.getSystemClassLoader();
310
311                 loadedClass = cl.loadClass(className);
312             }
313         }
314
315     return loadedClass;
316     }
317
318     /*
319      * Load a class and check that it is compatible with a given type.
320      * @param className the class name.
321      * @param remoteCodebase the codebase to use. May be null.
322      * @param loadingContext the loading context. May be null.
323      * @param relatedType the related type. May be null.
324      * @return the loaded class.
325      */

326     public static Class JavaDoc loadClassForClass (String JavaDoc className,
327                                            String JavaDoc remoteCodebase,
328                                            ClassLoader JavaDoc loader,
329                        Class JavaDoc relatedType,
330                                            ClassLoader JavaDoc relatedTypeClassLoader)
331         throws ClassNotFoundException JavaDoc
332     {
333         if (relatedType == null)
334         return Util.loadClass(className, remoteCodebase, loader);
335
336     Class JavaDoc loadedClass = null;
337     try {
338         loadedClass = Util.loadClass(className, remoteCodebase, loader);
339     } catch (ClassNotFoundException JavaDoc cnfe) {
340         if (relatedType.getClassLoader() == null)
341             throw cnfe;
342     }
343     
344         // If no class was not loaded, or if the loaded class is not of the
345
// correct type, make a further attempt to load the correct class
346
// using the classloader of the related type.
347
// _REVISIT_ Is this step necessary, or should the Util,loadClass
348
// algorithm always produce a valid class if the setup is correct?
349
// Does the OMG standard algorithm need to be changed to include
350
// this step?
351
if (loadedClass == null ||
352         (loadedClass.getClassLoader() != null &&
353          loadedClass.getClassLoader().loadClass(relatedType.getName()) !=
354                  relatedType))
355         {
356             if (relatedType.getClassLoader() != relatedTypeClassLoader)
357                 throw new IllegalArgumentException JavaDoc(
358                     "relatedTypeClassLoader not class loader of relatedType.");
359
360             if (relatedTypeClassLoader != null)
361         loadedClass = relatedTypeClassLoader.loadClass(className);
362         }
363     
364     return loadedClass;
365     }
366
367     /**
368      * Get the helper for an IDLValue
369      *
370      * Throws MARSHAL exception if no helper found.
371      */

372     public static BoxedValueHelper JavaDoc getHelper(Class JavaDoc clazz, String JavaDoc codebase,
373         String JavaDoc repId)
374     {
375     String JavaDoc className = null;
376         if (clazz != null) {
377         className = clazz.getName();
378         if (codebase == null)
379             codebase = Util.getCodebase(clazz);
380     } else {
381         if (repId != null)
382                 className = RepositoryId.cache.getId(repId).getClassName();
383         if (className == null) // no repId or unrecognized repId
384
throw wrapper.unableLocateValueHelper(
385             CompletionStatus.COMPLETED_MAYBE);
386     }
387
388         try {
389             ClassLoader JavaDoc clazzLoader =
390                 (clazz == null ? null : clazz.getClassLoader());
391             Class JavaDoc helperClass =
392                 loadClassForClass(className+"Helper", codebase, clazzLoader,
393                 clazz, clazzLoader);
394         return (BoxedValueHelper JavaDoc)helperClass.newInstance();
395
396         } catch (ClassNotFoundException JavaDoc cnfe) {
397         throw wrapper.unableLocateValueHelper( CompletionStatus.COMPLETED_MAYBE,
398         cnfe );
399         } catch (IllegalAccessException JavaDoc iae) {
400         throw wrapper.unableLocateValueHelper( CompletionStatus.COMPLETED_MAYBE,
401         iae );
402         } catch (InstantiationException JavaDoc ie) {
403         throw wrapper.unableLocateValueHelper( CompletionStatus.COMPLETED_MAYBE,
404         ie );
405         } catch (ClassCastException JavaDoc cce) {
406         throw wrapper.unableLocateValueHelper( CompletionStatus.COMPLETED_MAYBE,
407         cce );
408         }
409     }
410
411     /**
412      * Get the factory for an IDLValue
413      *
414      * Throws MARSHAL exception if no factory found.
415      */

416     public static ValueFactory JavaDoc getFactory(Class JavaDoc clazz, String JavaDoc codebase,
417                                ORB JavaDoc orb, String JavaDoc repId)
418     {
419     ValueFactory JavaDoc factory = null;
420     if ((orb != null) && (repId != null)) {
421         try {
422                 factory = ((org.omg.CORBA_2_3.ORB JavaDoc)orb).lookup_value_factory(
423                     repId);
424         } catch (org.omg.CORBA.BAD_PARAM JavaDoc ex) {
425             // Try other way
426
}
427     }
428
429     String JavaDoc className = null;
430         if (clazz != null) {
431         className = clazz.getName();
432         if (codebase == null)
433             codebase = Util.getCodebase(clazz);
434     } else {
435         if (repId != null)
436                 className = RepositoryId.cache.getId(repId).getClassName();
437         if (className == null) // no repId or unrecognized repId
438
throw omgWrapper.unableLocateValueFactory(
439             CompletionStatus.COMPLETED_MAYBE);
440     }
441
442     // if earlier search found a non-default factory, or the same default
443
// factory that loadClassForClass would return, bale out now...
444
if (factory != null &&
445         (!factory.getClass().getName().equals(className+"DefaultFactory") ||
446          (clazz == null && codebase == null)))
447         return factory;
448
449         try {
450             ClassLoader JavaDoc clazzLoader =
451                 (clazz == null ? null : clazz.getClassLoader());
452         Class JavaDoc factoryClass =
453                 loadClassForClass(className+"DefaultFactory", codebase,
454                 clazzLoader, clazz, clazzLoader);
455         return (ValueFactory JavaDoc)factoryClass.newInstance();
456
457         } catch (ClassNotFoundException JavaDoc cnfe) {
458         throw omgWrapper.unableLocateValueFactory(
459         CompletionStatus.COMPLETED_MAYBE, cnfe);
460         } catch (IllegalAccessException JavaDoc iae) {
461         throw omgWrapper.unableLocateValueFactory(
462         CompletionStatus.COMPLETED_MAYBE, iae);
463         } catch (InstantiationException JavaDoc ie) {
464         throw omgWrapper.unableLocateValueFactory(
465         CompletionStatus.COMPLETED_MAYBE, ie);
466         } catch (ClassCastException JavaDoc cce) {
467         throw omgWrapper.unableLocateValueFactory(
468         CompletionStatus.COMPLETED_MAYBE, cce);
469         }
470     }
471
472     /*
473      * Load an RMI-IIOP Stub given a Tie.
474      * @param tie the tie.
475      * @param stubClass the stub class. May be null.
476      * @param remoteCodebase the codebase to use. May be null.
477      * @param onlyMostDerived if true, will fail if cannot load a stub for the
478      * first repID in the tie. If false, will walk all repIDs.
479      * @return the stub or null if not found.
480      */

481
482     public static Remote JavaDoc loadStub(Tie JavaDoc tie,
483                   PresentationManager.StubFactory stubFactory,
484                   String JavaDoc remoteCodebase,
485                   boolean onlyMostDerived)
486     {
487         StubEntry entry = null;
488
489         // Do we already have it cached?
490
synchronized (tieToStubCache) {
491             Object JavaDoc cached = tieToStubCache.get(tie);
492             if (cached == null) {
493                 // No, so go try to load it...
494
entry = loadStubAndUpdateCache(
495                         tie, stubFactory, remoteCodebase, onlyMostDerived);
496             } else {
497                 // Yes, is it a stub? If not, it was a miss last
498
// time, so return null again...
499
if (cached != CACHE_MISS) {
500                     // It's a stub.
501
entry = (StubEntry) cached;
502                     
503                     // Does the cached stub meet the requirements
504
// of the caller? If the caller does not require
505
// the most derived stub and does not require
506
// a specific stub type, we don't have to check
507
// any further because the cached type is good
508
// enough...
509
if (!entry.mostDerived && onlyMostDerived) {
510                         // We must reload because we do not have
511
// the most derived cached already...
512
// The stubFactory arg must be null here
513
// to force onlyMostDerived=true to work
514
// correctly.
515
entry = loadStubAndUpdateCache(tie,null,
516                 remoteCodebase,true);
517                     } else if (stubFactory != null &&
518             !StubAdapter.getTypeIds(entry.stub)[0].equals(
519                 stubFactory.getTypeIds()[0]) )
520                     {
521                         // We do not have exactly the right stub. First, try to
522
// upgrade the cached stub by forcing it to the most
523
// derived stub...
524
entry = loadStubAndUpdateCache(tie,null,
525                 remoteCodebase,true);
526
527                         // If that failed, try again with the exact type
528
// we need...
529
if (entry == null) {
530                             entry = loadStubAndUpdateCache(tie,stubFactory,
531                                     remoteCodebase,onlyMostDerived);
532                         }
533                     } else {
534                         // Use the cached stub. Is the delegate set?
535
try {
536                             Delegate JavaDoc stubDel = StubAdapter.getDelegate(
537                 entry.stub ) ;
538                         } catch (Exception JavaDoc e2) {
539                             // No, so set it if we can...
540
try {
541                                 Delegate JavaDoc del = StubAdapter.getDelegate(
542                     tie ) ;
543                 StubAdapter.setDelegate( entry.stub,
544                     del ) ;
545                             } catch (Exception JavaDoc e) {}
546                         }
547                     }
548                 }
549             }
550         }
551         
552         if (entry != null) {
553             return (Remote JavaDoc)entry.stub;
554         } else {
555             return null;
556         }
557     }
558     
559     /*
560      * Load an RMI-IIOP Stub given a Tie, but do not look in the cache.
561      * This method must be called with the lock held for tieToStubCache.
562      * @param tie the tie.
563      * @param stubFactory the stub factory. May be null.
564      * @param remoteCodebase the codebase to use. May be null.
565      * @param onlyMostDerived if true, will fail if cannot load a stub for the
566      * first repID in the tie. If false, will walk all repIDs.
567      * @return the StubEntry or null if not found.
568      */

569     private static StubEntry loadStubAndUpdateCache (
570         Tie JavaDoc tie, PresentationManager.StubFactory stubFactory,
571     String JavaDoc remoteCodebase, boolean onlyMostDerived)
572     {
573         org.omg.CORBA.Object JavaDoc stub = null;
574         StubEntry entry = null;
575         boolean tieIsStub = StubAdapter.isStub( tie ) ;
576
577         if (stubFactory != null) {
578             try {
579                 stub = stubFactory.makeStub();
580             } catch (Throwable JavaDoc e) {
581         wrapper.stubFactoryCouldNotMakeStub( e ) ;
582                 if (e instanceof ThreadDeath JavaDoc) {
583                     throw (ThreadDeath JavaDoc) e;
584                 }
585             }
586         } else {
587             String JavaDoc[] ids = null;
588             if (tieIsStub) {
589         ids = StubAdapter.getTypeIds( tie ) ;
590             } else {
591         // This will throw an exception if the tie
592
// is not a Servant. XXX Handle this better?
593
ids = ((org.omg.PortableServer.Servant JavaDoc)tie).
594                       _all_interfaces( null, null );
595             }
596                                 
597             if (remoteCodebase == null) {
598                 remoteCodebase = Util.getCodebase(tie.getClass());
599             }
600                     
601         if (ids.length == 0) {
602         stub = new org.omg.stub.java.rmi._Remote_Stub JavaDoc();
603         } else {
604         // Now walk all the RepIDs till we find a stub or fail...
605
for (int i = 0; i < ids.length; i++) {
606             if (ids[i].length() == 0) {
607             stub = new org.omg.stub.java.rmi._Remote_Stub JavaDoc();
608             break;
609             }
610                 
611             try {
612             PresentationManager.StubFactoryFactory stubFactoryFactory =
613                 com.sun.corba.se.spi.orb.ORB.getStubFactoryFactory();
614             RepositoryId rid = RepositoryId.cache.getId( ids[i] ) ;
615             String JavaDoc className = rid.getClassName() ;
616             boolean isIDLInterface = rid.isIDLType() ;
617             stubFactory = stubFactoryFactory.createStubFactory(
618                 className, isIDLInterface, remoteCodebase, null,
619                 tie.getClass().getClassLoader() ) ;
620             stub = stubFactory.makeStub();
621             break;
622             } catch (Exception JavaDoc e) {
623             wrapper.errorInMakeStubFromRepositoryId( e ) ;
624             }
625                 
626             if (onlyMostDerived)
627             break;
628         }
629         }
630     }
631                 
632         if (stub == null) {
633             // Stub == null, so cache the miss...
634
tieToStubCache.put(tie,CACHE_MISS);
635     } else {
636             if (tieIsStub) {
637                 try {
638             Delegate JavaDoc del = StubAdapter.getDelegate( tie ) ;
639             StubAdapter.setDelegate( stub, del ) ;
640                 } catch( Exception JavaDoc e1 ) {
641                     // The tie does not have a delegate set, so stash
642
// this tie away using the stub as a key so that
643
// later, when the stub is connected, we can find
644
// and connect the tie as well...
645

646                     synchronized (stubToTieCache) {
647                         stubToTieCache.put(stub,tie);
648                     }
649                 }
650             } else {
651                 // Tie extends Servant
652
try {
653             Delegate JavaDoc delegate = StubAdapter.getDelegate( tie ) ;
654             StubAdapter.setDelegate( stub, delegate ) ;
655                 } catch( org.omg.CORBA.BAD_INV_ORDER JavaDoc bad) {
656                     synchronized (stubToTieCache) {
657                         stubToTieCache.put(stub,tie);
658                     }
659                 } catch( Exception JavaDoc e ) {
660                     // Exception is caught because of any of the
661
// following reasons
662
// 1) POA is not associated with the TIE
663
// 2) POA Policies for the tie-associated POA
664
// does not support _this_object() call.
665
throw wrapper.noPoa( e ) ;
666                 }
667             }
668             // Update the cache...
669
entry = new StubEntry(stub,onlyMostDerived);
670             tieToStubCache.put(tie,entry);
671         }
672             
673         return entry;
674     }
675                                    
676     /*
677      * If we loadStub(Tie,...) stashed away a tie which was
678      * not connected, remove it from the cache and return
679      * it.
680      */

681     public static Tie JavaDoc getAndForgetTie (org.omg.CORBA.Object JavaDoc stub) {
682         synchronized (stubToTieCache) {
683             return (Tie JavaDoc) stubToTieCache.remove(stub);
684         }
685     }
686     
687     /*
688      * Remove any cached Stub for the given tie.
689      */

690     public static void purgeStubForTie (Tie JavaDoc tie) {
691         StubEntry entry;
692         synchronized (tieToStubCache) {
693             entry = (StubEntry)tieToStubCache.remove(tie);
694         }
695     if (entry != null) {
696             synchronized (stubToTieCache) {
697                 stubToTieCache.remove(entry.stub);
698             }
699     }
700     }
701     
702     /*
703      * Remove cached tie/servant pair.
704      */

705     public static void purgeTieAndServant (Tie JavaDoc tie) {
706     synchronized (tieCache) {
707         Object JavaDoc target = tie.getTarget();
708         if (target != null)
709         tieCache.remove(target);
710     }
711     }
712
713     /*
714      * Convert a RepId to a stubName...
715      */

716     public static String JavaDoc stubNameFromRepID (String JavaDoc repID) {
717         
718         // Convert the typeid to a RepositoryId instance, get
719
// the className and mangle it as needed...
720

721         RepositoryId id = RepositoryId.cache.getId(repID);
722         String JavaDoc className = id.getClassName();
723         
724         if (id.isIDLType()) {
725             className = idlStubName(className);
726         } else {
727             className = stubName(className);
728         }
729         return className;
730     }
731   
732     
733     /*
734      * Load an RMI-IIOP Stub. This is used in PortableRemoteObject.narrow.
735      */

736     public static Remote JavaDoc loadStub (org.omg.CORBA.Object JavaDoc narrowFrom,
737                                    Class JavaDoc narrowTo)
738     {
739         Remote JavaDoc result = null;
740             
741     try {
742             // Get the codebase from the delegate to use when loading
743
// the new stub, if possible...
744
String JavaDoc codebase = null;
745             try {
746                 // We can't assume that narrowFrom is a CORBA_2_3 stub, yet
747
// it may have a 2_3 Delegate that provides a codebase. Swallow
748
// the ClassCastException otherwise.
749
Delegate JavaDoc delegate = StubAdapter.getDelegate( narrowFrom ) ;
750                 codebase = ((org.omg.CORBA_2_3.portable.Delegate JavaDoc)delegate).
751             get_codebase(narrowFrom);
752
753             } catch (ClassCastException JavaDoc e) {
754         wrapper.classCastExceptionInLoadStub( e ) ;
755             }
756
757         PresentationManager.StubFactoryFactory sff =
758         com.sun.corba.se.spi.orb.ORB.getStubFactoryFactory() ;
759         PresentationManager.StubFactory sf = sff.createStubFactory(
760         narrowTo.getName(), false, codebase, narrowTo,
761         narrowTo.getClassLoader() ) ;
762         result = (Remote JavaDoc)sf.makeStub() ;
763         StubAdapter.setDelegate( result,
764         StubAdapter.getDelegate( narrowFrom ) ) ;
765         } catch (Exception JavaDoc err) {
766         wrapper.exceptionInLoadStub( err ) ;
767         }
768         
769         return result;
770     }
771         
772     /*
773      * Load an RMI-IIOP Stub class. This is used in the
774      * StaticStubFactoryFactory code.
775      */

776     public static Class JavaDoc loadStubClass(String JavaDoc repID,
777                                       String JavaDoc remoteCodebase,
778                       Class JavaDoc expectedType)
779     throws ClassNotFoundException JavaDoc
780     {
781         // Get the repID and check for "" special case.
782
// We should never be called with it (See CDRInputStream
783
// and the loadStub() method)...
784

785         if (repID.length() == 0) {
786             throw new ClassNotFoundException JavaDoc();
787         }
788         
789         // Get the stubname from the repID and load
790
// the class. If we have a valid 'sender', fall
791
// back to using its codebase if we need to...
792
String JavaDoc className = Utility.stubNameFromRepID(repID);
793         ClassLoader JavaDoc expectedTypeClassLoader = (expectedType == null ? null :
794         expectedType.getClassLoader());
795
796         try {
797               return loadClassOfType(className,
798                                        remoteCodebase,
799                                        expectedTypeClassLoader,
800                                        expectedType,
801                                        expectedTypeClassLoader);
802         } catch (ClassNotFoundException JavaDoc e) {
803         return loadClassOfType(PackagePrefixChecker.packagePrefix() + className,
804                                    remoteCodebase,
805                                    expectedTypeClassLoader,
806                                    expectedType,
807                                    expectedTypeClassLoader);
808         }
809     }
810
811     /**
812      * Create an RMI stub name.
813      */

814     public static String JavaDoc stubName (String JavaDoc className)
815     {
816     return stubName( className, false ) ;
817     }
818
819     public static String JavaDoc dynamicStubName( String JavaDoc className )
820     {
821     return stubName( className, true ) ;
822     }
823
824     private static String JavaDoc stubName( String JavaDoc className,
825     boolean isDynamic )
826     {
827     String JavaDoc name = stubNameForCompiler( className, isDynamic ) ;
828     if (PackagePrefixChecker.hasOffendingPrefix( name ))
829         name = PackagePrefixChecker.packagePrefix() + name ;
830     return name ;
831     }
832
833     public static String JavaDoc stubNameForCompiler (String JavaDoc className)
834     {
835     return stubNameForCompiler( className, false ) ;
836     }
837
838     private static String JavaDoc stubNameForCompiler( String JavaDoc className,
839     boolean isDynamic )
840     {
841         int index = className.indexOf('$');
842         if (index < 0) {
843             index = className.lastIndexOf('.');
844         }
845
846     String JavaDoc suffix = isDynamic ? DYNAMIC_STUB_SUFFIX :
847         RMI_STUB_SUFFIX ;
848     
849         if (index > 0) {
850             return className.substring(0,index+1) + STUB_PREFIX +
851         className.substring(index+1) + suffix;
852         } else {
853             return STUB_PREFIX + className + suffix;
854         }
855     }
856
857     /**
858      * Create an RMI tie name.
859      */

860     public static String JavaDoc tieName (String JavaDoc className)
861     {
862         return
863             PackagePrefixChecker.hasOffendingPrefix(tieNameForCompiler(className)) ?
864             PackagePrefixChecker.packagePrefix() + tieNameForCompiler(className) :
865             tieNameForCompiler(className);
866     }
867
868     public static String JavaDoc tieNameForCompiler (String JavaDoc className)
869     {
870         int index = className.indexOf('$');
871         if (index < 0) {
872             index = className.lastIndexOf('.');
873         }
874         if (index > 0) {
875             return className.substring(0,index+1) +
876         STUB_PREFIX +
877         className.substring(index+1) +
878         TIE_SUFIX;
879         } else {
880             return STUB_PREFIX +
881         className +
882         TIE_SUFIX;
883         }
884     }
885
886     /**
887      * Throws the CORBA equivalent of a java.io.NotSerializableException
888      */

889     public static void throwNotSerializableForCorba(String JavaDoc className) {
890     throw omgWrapper.notSerializable( CompletionStatus.COMPLETED_MAYBE,
891         className ) ;
892     }
893
894     /**
895      * Create an IDL stub name.
896      */

897     public static String JavaDoc idlStubName(String JavaDoc className)
898     {
899         String JavaDoc result = null;
900         int index = className.lastIndexOf('.');
901         if (index > 0) {
902             result = className.substring(0,index+1) +
903         STUB_PREFIX +
904         className.substring(index+1) +
905         IDL_STUB_SUFFIX;
906         } else {
907             result = STUB_PREFIX +
908         className +
909         IDL_STUB_SUFFIX;
910         }
911         return result;
912     }
913     
914     public static void printStackTrace()
915     {
916     Throwable JavaDoc thr = new Throwable JavaDoc( "Printing stack trace:" ) ;
917     thr.fillInStackTrace() ;
918     thr.printStackTrace() ;
919     }
920
921     /**
922      * Read an object reference from the input stream and narrow
923      * it to the desired type.
924      * @param in the stream to read from.
925      * @throws ClassCastException if narrowFrom cannot be cast to narrowTo.
926      */

927     public static Object JavaDoc readObjectAndNarrow(InputStream JavaDoc in,
928                                              Class JavaDoc narrowTo)
929     throws ClassCastException JavaDoc
930     {
931         Object JavaDoc result = in.read_Object();
932     if (result != null)
933             return PortableRemoteObject.narrow(result, narrowTo);
934     else
935         return null;
936     }
937
938     /**
939      * Read an abstract interface type from the input stream and narrow
940      * it to the desired type.
941      * @param in the stream to read from.
942      * @throws ClassCastException if narrowFrom cannot be cast to narrowTo.
943      */

944     public static Object JavaDoc readAbstractAndNarrow(
945     org.omg.CORBA_2_3.portable.InputStream JavaDoc in, Class JavaDoc narrowTo)
946     throws ClassCastException JavaDoc
947     {
948         Object JavaDoc result = in.read_abstract_interface();
949     if (result != null)
950             return PortableRemoteObject.narrow(result, narrowTo);
951     else
952         return null;
953     }
954
955
956     /** Converts an Ascii Character into Hexadecimal digit
957      */

958     static int hexOf( char x )
959     {
960     int val;
961
962         val = x - '0';
963         if (val >=0 && val <= 9)
964             return val;
965
966         val = (x - 'a') + 10;
967         if (val >= 10 && val <= 15)
968             return val;
969
970         val = (x - 'A') + 10;
971         if (val >= 10 && val <= 15)
972             return val;
973
974     throw wrapper.badHexDigit() ;
975     }
976 }
977
978 class StubEntry {
979     org.omg.CORBA.Object JavaDoc stub;
980     boolean mostDerived;
981     
982     StubEntry(org.omg.CORBA.Object JavaDoc stub, boolean mostDerived) {
983         this.stub = stub;
984         this.mostDerived = mostDerived;
985     }
986 }
987
Popular Tags