KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jacorb > poa > POA


1 package org.jacorb.poa;
2
3 /*
4  * JacORB - a free Java ORB
5  *
6  * Copyright (C) 1997-2004 Gerald Brose.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the Free
20  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */

22
23 import org.jacorb.poa.util.*;
24 import org.jacorb.poa.except.*;
25
26 import org.jacorb.orb.dsi.ServerRequest;
27 import org.jacorb.ssl.SSLPolicy;
28 import org.jacorb.ssl.SSLPolicyValue;
29 import org.jacorb.ssl.SSL_POLICY_TYPE;
30
31 import org.omg.PortableServer.*;
32 import org.omg.PortableServer.POAPackage.*;
33 import org.omg.PortableServer.POAManagerPackage.State JavaDoc;
34
35 import org.omg.BiDirPolicy.*;
36
37 import org.apache.avalon.framework.logger.Logger;
38 import org.apache.avalon.framework.configuration.*;
39
40 import java.util.*;
41
42 /**
43  * The main POA class, an implementation of
44  * <code>org.omg.PortableServer.POA</code>
45  *
46  * @author Reimo Tiedemann, FU Berlin
47  * @version $Id: POA.java,v 1.50 2004/10/21 14:48:59 francisco Exp $
48  */

49
50 public class POA
51     extends _POALocalBase
52     implements Configurable
53 {
54     // my orb instance
55
private org.jacorb.orb.ORB orb;
56
57     /** the configuration object for this POA instance */
58     private org.jacorb.config.Configuration configuration = null;
59
60     /** the POA logger instance */
61     private Logger logger = null;
62     private byte[] implName = null;
63     private byte[] serverId = null;
64
65     /** used to hold the POA name for logging */
66     private String JavaDoc logPrefix = "<unset>";
67
68     // for listening POA Events
69
private POAListener poaListener;
70     // for monitoring
71
private POAMonitor monitor;
72
73     private POAManager poaManager;
74     private POA parent;
75     private String JavaDoc name;
76     private String JavaDoc qualifiedName;
77
78     // name -> child POA's
79
private Hashtable childs = new Hashtable();
80
81     Servant defaultServant;
82     ServantManager servantManager;
83     private AdapterActivator adapterActivator;
84
85     private AOM aom;
86     // thread for handle Requests
87
private RequestController requestController;
88
89     // poa identity and a counter for oid generation
90
private byte[] poaId;
91     private byte[] watermark;
92     private long objectIdCount;
93
94     /* policies */
95
96     // default: ORB_CTRL_MODEL
97
protected ThreadPolicy threadPolicy;
98
99     // default: TRANSIENT
100
protected LifespanPolicy lifespanPolicy;
101
102     // default: UNIQUE_ID
103
protected IdUniquenessPolicy idUniquenessPolicy;
104
105     // default: SYSTEM_ID
106
protected IdAssignmentPolicy idAssignmentPolicy;
107
108     // default: RETAIN
109
protected ServantRetentionPolicy servantRetentionPolicy;
110
111     // default: USE_ACTIVE_OBJECT_MAP_ONLY
112
protected RequestProcessingPolicy requestProcessingPolicy;
113
114     // default: NO_IMPLICIT_ACTIVATION
115
protected ImplicitActivationPolicy implicitActivationPolicy;
116
117     // default: NORMAL
118
protected BidirectionalPolicy bidirectionalPolicy;
119
120     // default: SSL_NOT_REQUIRED
121
protected SSLPolicy sslPolicy;
122
123     private Hashtable all_policies = null;
124
125     /** key: , value: CORBA.Object */
126     private Hashtable createdReferences;
127
128     // stores the etherealize_objects value from the first call of destroy
129
private boolean etherealize;
130
131     // synchronisation stuff
132
private int shutdownState = POAConstants.NOT_CALLED;
133     private java.lang.Object JavaDoc poaCreationLog = new java.lang.Object JavaDoc();
134     private java.lang.Object JavaDoc poaDestructionLog = new java.lang.Object JavaDoc();
135     private java.lang.Object JavaDoc unknownAdapterLog = new java.lang.Object JavaDoc();
136     private boolean unknownAdapterCalled;
137
138     private boolean configured = false;
139
140 // private POA()
141
// {
142
// }
143

144     private POA(org.jacorb.orb.ORB _orb,
145                 String JavaDoc _name,
146                 POA _parent,
147                 POAManager _poaManager,
148                 org.omg.CORBA.Policy JavaDoc[] policies)
149     {
150         orb = _orb;
151         name = _name;
152         parent = _parent;
153         poaManager = _poaManager;
154         logPrefix = "POA " + name;
155
156         all_policies = new Hashtable();
157         createdReferences = new Hashtable();
158
159         if (policies != null)
160         {
161             for (int i=0; i<policies.length; i++)
162             {
163                 all_policies.put( new Integer JavaDoc( policies[i].policy_type() ),
164                                   policies[i]);
165
166                 switch (policies[i].policy_type())
167                 {
168                     case THREAD_POLICY_ID.value :
169                     threadPolicy =
170                         (org.omg.PortableServer.ThreadPolicy JavaDoc) policies[i];
171                     break;
172                     case LIFESPAN_POLICY_ID.value :
173                     lifespanPolicy =
174                         (org.omg.PortableServer.LifespanPolicy JavaDoc) policies[i];
175                     break;
176                     case ID_UNIQUENESS_POLICY_ID.value :
177                     idUniquenessPolicy =
178                         (org.omg.PortableServer.IdUniquenessPolicy JavaDoc) policies[i];
179                     break;
180                     case ID_ASSIGNMENT_POLICY_ID.value :
181                     idAssignmentPolicy =
182                         (org.omg.PortableServer.IdAssignmentPolicy JavaDoc) policies[i];
183                     break;
184                     case SERVANT_RETENTION_POLICY_ID.value :
185                     servantRetentionPolicy =
186                         (org.omg.PortableServer.ServantRetentionPolicy JavaDoc) policies[i];
187                     break;
188                     case REQUEST_PROCESSING_POLICY_ID.value :
189                     requestProcessingPolicy =
190                         (org.omg.PortableServer.RequestProcessingPolicy JavaDoc) policies[i];
191                     break;
192                     case IMPLICIT_ACTIVATION_POLICY_ID.value :
193                     implicitActivationPolicy =
194                         (org.omg.PortableServer.ImplicitActivationPolicy JavaDoc) policies[i];
195                     break;
196                     case BIDIRECTIONAL_POLICY_TYPE.value :
197                     bidirectionalPolicy =
198                         (org.omg.BiDirPolicy.BidirectionalPolicy) policies[i];
199                     break;
200                     case SSL_POLICY_TYPE.value :
201                     sslPolicy = (SSLPolicy) policies[i];
202                     break;
203                 }
204             }
205         }
206
207         //check if BiDir policy tell us to use BiDirGIOP (for the
208
//whole ORB)
209
if( bidirectionalPolicy != null )
210         {
211             org.jacorb.orb.giop.BiDirPolicy bdp =
212                 (org.jacorb.orb.giop.BiDirPolicy) bidirectionalPolicy;
213
214             if( bdp.useBiDirGIOP() )
215             {
216                 _orb.turnOnBiDirGIOP();
217             }
218         }
219
220 // watermark = generateWatermark();
221

222 // aom = isRetain() ? new AOM( isUniqueId(), isSingleThreadModel(), logger) : null;
223

224 // // GB: modified
225
// requestController = new RequestController(this, orb, aom);
226
// poaManager.registerPOA(this);
227
// monitor = new POAMonitorLightImpl();
228

229 // monitor.init( this, aom,
230
// requestController.getRequestQueue(),
231
// requestController.getPoolManager(),
232
// "POA " + name );
233

234 // monitor.openMonitor();
235
// if (poaListener != null)
236
// poaListener.poaCreated(this);
237
}
238
239
240     public void configure(Configuration myConfiguration)
241         throws ConfigurationException
242     {
243         this.configuration = (org.jacorb.config.Configuration)myConfiguration;
244         logger = configuration.getNamedLogger("jacorb.poa");
245
246         implName =
247             configuration.getAttribute("jacorb.implname","standardImplName").getBytes();
248         serverId =
249             String.valueOf((long)(Math.random()*9999999999L)).getBytes();
250
251         watermark = generateWatermark();
252
253         aom = isRetain() ? new AOM( isUniqueId(), isSingleThreadModel(), logger) : null;
254
255         // GB: modified
256
requestController = new RequestController(this, orb, aom);
257         requestController.configure(configuration);
258
259         poaManager.registerPOA(this);
260         monitor = new POAMonitorLightImpl();
261         monitor.init( this, aom,
262                       requestController.getRequestQueue(),
263                       requestController.getPoolManager(),
264                       "POA " + name );
265
266         monitor.openMonitor();
267         if (poaListener != null)
268             poaListener.poaCreated(this);
269
270         monitor.configure(configuration);
271
272         if (logger.isDebugEnabled())
273         {
274             logger.debug("POA " + name + " ready");
275         }
276         configured = true;
277     }
278
279
280     /**
281      * Everybody who is interested in poa events can use this method
282      * to register an event listener. The poa will pass the register calls
283      * to the right components
284      */

285
286     public void _addPOAEventListener(EventListener listener)
287     {
288         if (!configured)
289             throw new Error JavaDoc("POA: not configured!");
290
291         if (listener instanceof POAListener)
292             addPOAListener((POAListener)listener);
293
294         if (listener instanceof AOMListener && aom != null)
295             aom.addAOMListener((AOMListener)listener);
296
297         if (listener instanceof RequestQueueListener)
298             requestController.getRequestQueue().addRequestQueueListener((RequestQueueListener)listener);
299
300         if (listener instanceof RPPoolManagerListener)
301             requestController.getPoolManager().addRPPoolManagerListener((RPPoolManagerListener)listener);
302     }
303
304     /**
305      * called from orb, returns a registered child poa,
306      * if no child poa exists a adapter activator will used
307      * to create a new poa unter this name
308      */

309
310     public org.jacorb.poa.POA _getChildPOA( String JavaDoc adapter_name )
311         throws ParentIsHolding
312     {
313         if (!configured)
314             throw new Error JavaDoc("POA: not configured!");
315
316         checkDestructionApparent();
317
318         POA child = (POA) childs.get(adapter_name);
319
320         if (child == null || child.isDestructionApparent())
321         {
322
323             if (adapterActivator == null)
324                 throw new org.omg.CORBA.OBJECT_NOT_EXIST JavaDoc("no adapter activator exists for " +
325                                                          adapter_name);
326
327             if (isHolding())
328                 throw new ParentIsHolding();
329
330             if (isDiscarding())
331                 throw new org.omg.CORBA.TRANSIENT JavaDoc("a parent poa is in discarding state");
332
333             if (isInactive())
334                 throw new org.omg.CORBA.OBJ_ADAPTER JavaDoc("a parent poa is in inactive state");
335
336             /* poa should be active */
337
338             boolean successful = false;
339
340             if (isSingleThreadModel())
341             {
342                 /* all invocations an adapter activator are serialized
343                    if the single thread model is in use */

344                 synchronized (unknownAdapterLog)
345                 {
346                     while (unknownAdapterCalled)
347                     {
348                         try
349                         {
350                             unknownAdapterLog.wait();
351                         }
352                         catch (InterruptedException JavaDoc e) {
353                         }
354                     }
355                     unknownAdapterCalled = true;
356                     try
357                     {
358                         successful =
359                         the_activator().unknown_adapter(this, POAUtil.unmaskStr(adapter_name));
360                     }
361                     finally
362                     {
363                         unknownAdapterCalled = false;
364                         unknownAdapterLog.notifyAll();
365                     }
366                 }
367             }
368             else
369             {
370                 /* ORB_CTRL_MODEL */
371                 successful = the_activator().unknown_adapter(this, POAUtil.unmaskStr(adapter_name));
372             }
373
374             /* unknown_adapter doesn't return until the
375                poa is created and initialized */

376             if (successful)
377             {
378                 if ((child = (POA) childs.get(adapter_name)) == null)
379                 {
380                     throw new POAInternalError("error: unknown_adapter returns true, but the child poa doesn't extist");
381                 }
382
383             }
384             else
385             {
386                 throw new org.omg.CORBA.OBJECT_NOT_EXIST JavaDoc("poa activation is failed");
387             }
388         }
389         return child;
390     }
391
392     /**
393      * returns the complete poa name
394      */

395
396     public String JavaDoc _getQualifiedName()
397     {
398         if (qualifiedName == null)
399         {
400             if (parent == null)
401             {
402                 qualifiedName = "";
403             }
404             else if (parent.the_parent() == null)
405             {
406                 qualifiedName = name;
407             }
408             else
409             {
410                 qualifiedName = parent._getQualifiedName() +
411                 POAConstants.OBJECT_KEY_SEPARATOR + name;
412             }
413         }
414         return qualifiedName;
415     }
416
417     /**
418      * called from orb for handing over a request
419      */

420
421     public void _invoke(ServerRequest request)
422         throws WrongAdapter
423     {
424         if (!configured)
425             throw new Error JavaDoc("POA: not configured!");
426
427         synchronized(poaDestructionLog)
428         {
429             checkDestructionApparent ();
430
431             // if the request is for this poa check whether the object
432
// key is generated from him
433
if (request.remainingPOAName() == null)
434             {
435                 if (!previouslyGeneratedObjectKey(request.objectKey()))
436                 {
437                     if (logger.isWarnEnabled())
438                     {
439                         logger.warn(logPrefix +
440                                     " rid: " + request.requestId() +
441                                     " opname: " + request.operation() +
442                                     " _invoke: object key not previously generated!");
443                         if (logger.isDebugEnabled())
444                         {
445                             logger.debug(logPrefix +
446                                          " ObjectKey : " + org.jacorb.orb.util.CorbaLoc.parseKey(request.objectKey()) +
447                                          " to POA Id : " + org.jacorb.orb.util.CorbaLoc.parseKey(getPOAId()) + " mismatch.");
448                         }
449                     }
450                     throw new WrongAdapter();
451                 }
452                 if (isSystemId() && !previouslyGeneratedObjectId(request.objectId()) )
453                 {
454                     if (logger.isWarnEnabled())
455                     {
456                         logger.warn(logPrefix +
457                                     " rid: " + request.requestId() +
458                                     " opname: " + request.operation() +
459                                     " _invoke: object id not previously generated!");
460                         if (logger.isDebugEnabled())
461                         {
462                             logger.debug(logPrefix +
463                                          " ObjectId : " + org.jacorb.orb.util.CorbaLoc.parseKey(request.objectId()) +
464                                          " to POA watermark : " + org.jacorb.orb.util.CorbaLoc.parseKey(watermark) + " mismatch.");
465                         }
466                     }
467                     throw new WrongAdapter();
468                 }
469             }
470
471
472             try
473             {
474                 // pass the request to the request controller the
475
// operation returns immediately after the request is
476
// queued
477
if (logger.isDebugEnabled())
478                 {
479                     logger.debug(logPrefix +
480                                  " rid: " + request.requestId() +
481                                  " opname: " + request.operation() +
482                                  " _invoke: queuing request");
483                 }
484                 requestController.queueRequest(request);
485             }
486             catch (ResourceLimitReachedException e)
487             {
488                 throw new org.omg.CORBA.TRANSIENT JavaDoc("resource limit reached");
489             }
490         }
491     }
492
493     /**
494      * called from orb to obtain the RootPOA
495      */

496
497     static public POA _POA_init(org.jacorb.orb.ORB orb)
498     {
499         POAManager poaMgr = new POAManager(orb);
500
501         /* the only policy value that differs from default */
502         org.omg.CORBA.Policy JavaDoc [] policies= null;
503
504         policies = new org.omg.CORBA.Policy JavaDoc[1];
505
506         policies[0] =
507             new org.jacorb.poa.policy.ImplicitActivationPolicy(ImplicitActivationPolicyValue.IMPLICIT_ACTIVATION);
508
509         POA rootPOA =
510             new POA(orb, POAConstants.ROOT_POA_NAME, null, poaMgr, policies);
511
512         return rootPOA;
513     }
514
515
516     /**
517      * Unregister an event listener. The poa will pass the
518      * unregister calls to the right components
519      */

520
521     public void _removePOAEventListener(EventListener listener)
522     {
523         if (listener instanceof POAListener)
524             removePOAListener((POAListener)listener);
525         if (listener instanceof AOMListener && aom != null)
526             aom.removeAOMListener((AOMListener)listener);
527         if (listener instanceof RequestQueueListener)
528             requestController.getRequestQueue().removeRequestQueueListener((RequestQueueListener)listener);
529         if (listener instanceof RPPoolManagerListener)
530             requestController.getPoolManager().removeRPPoolManagerListener((RPPoolManagerListener)listener);
531     }
532
533
534     public byte[] activate_object(Servant servant)
535         throws ServantAlreadyActive, WrongPolicy
536     {
537         if (!configured)
538             throw new Error JavaDoc("POA: not configured!");
539
540         checkDestructionApparent ();
541
542         if (!isRetain() || !isSystemId())
543             throw new WrongPolicy();
544
545         byte[] objectId = generateObjectId();
546
547         try
548         {
549             aom.add(objectId, servant);
550
551             orb.set_delegate( servant );
552         }
553         catch (ObjectAlreadyActive e)
554         {
555             throw new POAInternalError("error: object already active (activate_object)");
556         }
557
558         return objectId;
559     }
560
561     public void activate_object_with_id( byte[] oid, Servant servant )
562         throws ServantAlreadyActive, ObjectAlreadyActive, WrongPolicy
563     {
564         if (!configured)
565             throw new Error JavaDoc("POA: not configured!");
566
567         checkDestructionApparent ();
568
569         if( oid == null )
570         {
571             throw new org.omg.CORBA.BAD_PARAM JavaDoc( "Cannot activate_object_with_id with null ID." );
572         }
573
574         if ( !isRetain() )
575             throw new WrongPolicy();
576
577         if ( isSystemId() && !previouslyGeneratedObjectId(oid) )
578         {
579             if (logger.isWarnEnabled())
580             {
581                 logger.warn(logPrefix + "oid: " + POAUtil.convert(oid) +
582                             " - activate_object_with_id: oid not previously generated!");
583             }
584             throw new org.omg.CORBA.BAD_PARAM JavaDoc();
585         }
586
587         aom.add( oid, servant );
588
589         orb.set_delegate( servant );
590     }
591
592     protected synchronized void addPOAListener( POAListener listener )
593     {
594         poaListener = EventMulticaster.add(poaListener, listener);
595     }
596
597     protected void changeToActive()
598     {
599         if (poaListener != null)
600             poaListener.poaStateChanged(this, POAConstants.ACTIVE);
601         monitor.changeState("changed to active...");
602
603         // notify everybody who is waiting for request completion
604
requestController.resetPreviousCompletionCall();
605         // continue the request dispatching
606
requestController.continueToWork();
607
608         monitor.changeState("active");
609     }
610
611     protected void changeToDiscarding() {
612
613         if (poaListener != null) poaListener.poaStateChanged(this, POAConstants.DISCARDING);
614         monitor.changeState("changed to discarding ...");
615
616         // notify everybody who is waiting for request completion
617
requestController.resetPreviousCompletionCall();
618         // continue the request dispatching
619
requestController.continueToWork();
620         // wait for completion of all active requests
621
requestController.waitForCompletion();
622
623         monitor.changeState("discarding");
624     }
625
626     protected void changeToHolding()
627     {
628         if (poaListener != null)
629             poaListener.poaStateChanged(this, POAConstants.HOLDING);
630         monitor.changeState("changed to holding ...");
631
632         // notify everybody who is waiting for request completion
633
requestController.resetPreviousCompletionCall();
634         // wait for completion of all active requests
635
requestController.waitForCompletion();
636
637         monitor.changeState("holding");
638     }
639
640
641     protected void changeToInactive(boolean etherealize_objects)
642     {
643         if (poaListener != null)
644             poaListener.poaStateChanged(this, POAConstants.INACTIVE);
645
646         monitor.changeState("changed to inactive ...");
647
648         // notify everybody who is waiting for request completion
649
requestController.resetPreviousCompletionCall();
650
651         // continue the request dispatching
652
requestController.continueToWork();
653
654         // wait for completion of all active requests
655
requestController.waitForCompletion();
656
657         /* etherialize all active objects */
658         if (etherealize && isRetain() && useServantManager())
659         {
660             if (logger.isInfoEnabled())
661                 logger.info(logPrefix + "etherialize all servants ...");
662
663             aom.removeAll((ServantActivator) servantManager, this, true);
664
665             if (logger.isInfoEnabled())
666                 logger.info(logPrefix + "etherialize all servants ...");
667
668             if (monitor != null)
669                 monitor.changeState("inactive (etherialization completed)");
670
671         }
672         else
673         {
674             if (monitor != null)
675                 monitor.changeState("inactive (no etherialization)");
676         }
677     }
678
679
680     public IdAssignmentPolicy create_id_assignment_policy (IdAssignmentPolicyValue value)
681     {
682         checkDestructionApparent ();
683         return new org.jacorb.poa.policy.IdAssignmentPolicy (value);
684     }
685
686     public IdUniquenessPolicy create_id_uniqueness_policy (IdUniquenessPolicyValue value)
687     {
688         checkDestructionApparent ();
689         return new org.jacorb.poa.policy.IdUniquenessPolicy (value);
690     }
691
692     public ImplicitActivationPolicy create_implicit_activation_policy
693         (ImplicitActivationPolicyValue value)
694     {
695         checkDestructionApparent ();
696         return new org.jacorb.poa.policy.ImplicitActivationPolicy (value);
697     }
698
699     public LifespanPolicy create_lifespan_policy (LifespanPolicyValue value)
700     {
701         checkDestructionApparent ();
702         return new org.jacorb.poa.policy.LifespanPolicy (value);
703     }
704
705     /**
706      * additionally raises an org.omg.CORBA.BAD_INV_ORDER exception if the poa
707      * goes shutdown and this method will called (not spec.)
708      */

709
710     public org.omg.PortableServer.POA JavaDoc create_POA( String JavaDoc adapter_name,
711                                                   org.omg.PortableServer.POAManager JavaDoc a_POAManager,
712                                                   org.omg.CORBA.Policy JavaDoc[] policies)
713         throws AdapterAlreadyExists, InvalidPolicy
714     {
715         if (!configured)
716             throw new Error JavaDoc("POA: not configured!");
717
718         checkDestructionApparent();
719
720         String JavaDoc poa_name = POAUtil.maskStr(adapter_name);
721
722         /* this implementation works only with a instance of org.jacorb.poa.POAManager */
723         if (a_POAManager != null &&
724             !(a_POAManager instanceof org.jacorb.poa.POAManager))
725             throw new ApplicationError("error: the POAManager is incompatible with type \"jacorb.poa.POAManager\"!" );
726
727         org.omg.CORBA.Policy JavaDoc[] policyList = null;
728         if (policies != null)
729         {
730             // check the policy list for inconstancies
731
short index = verifyPolicyList(policies);
732
733             if (index != -1)
734                 throw new InvalidPolicy(index);
735
736             // copy the policy list
737
policyList = new org.omg.CORBA.Policy JavaDoc[policies.length];
738
739             for (int i=0; i<policies.length; i++)
740             {
741                 policyList[i] = policies[i].copy();
742             }
743         }
744
745         POA child;
746
747         synchronized (poaCreationLog)
748         {
749             if ((child = (POA)childs.get(poa_name)) != null &&
750                 !child.isDestructionApparent())
751             {
752                 throw new AdapterAlreadyExists();
753             }
754             // wait for completion of a concurrent destruction process
755
if (child != null)
756             {
757                 POA aChild;
758                 while ((aChild = (POA)childs.get(poa_name)) != null)
759                 {
760                     try
761                     {
762                         poaCreationLog.wait(); // notification is in unregisterChild
763
}
764                     catch (InterruptedException JavaDoc e) {
765                     }
766                     // anyone else has won the race
767
if (child != aChild)
768                         throw new AdapterAlreadyExists();
769                 }
770             }
771
772             if (isShutdownInProgress())
773                 throw new org.omg.CORBA.BAD_INV_ORDER JavaDoc();
774
775             POAManager aPOAManager =
776                 a_POAManager == null ? new POAManager(orb) : (POAManager) a_POAManager;
777
778             child =
779                 new POA(orb, poa_name, this, aPOAManager, policyList);
780
781             try
782             {
783                 child.configure(configuration);
784             }
785             catch (ConfigurationException e)
786             {
787                 throw new org.omg.CORBA.INTERNAL JavaDoc(e.getMessage());
788             }
789
790             // notify a poa listener
791
try
792             {
793                 if (poaListener != null)
794                     poaListener.poaCreated(child);
795             }
796             catch (org.omg.CORBA.INTERNAL JavaDoc e)
797             {
798                 aPOAManager.poaCreationFailed = true;
799                 throw e;
800             }
801             // register the child poa
802
childs.put(poa_name, child);
803         }
804         return child;
805     }
806
807
808     /**
809      * The specified repository id, which may be a null string, will become the
810      * type_id of the generated object reference
811      */

812
813     public org.omg.CORBA.Object JavaDoc create_reference (String JavaDoc intf_rep_id)
814         throws WrongPolicy
815     {
816         if (!configured)
817             throw new Error JavaDoc("POA: not configured!");
818
819         checkDestructionApparent();
820
821         if (!isSystemId())
822         {
823             throw new WrongPolicy();
824         }
825
826         return (getReference (generateObjectId (), intf_rep_id, false));
827     }
828
829
830     /**
831      * The specified repository id, which may be a null string, will become the
832      * type_id of the generated object reference
833      */

834
835     public org.omg.CORBA.Object JavaDoc create_reference_with_id(byte[] oid,
836                                                          String JavaDoc intf_rep_id)
837         throws WrongPolicy
838     {
839         if (!configured)
840             throw new Error JavaDoc("POA: not configured!");
841
842         checkDestructionApparent();
843
844         if (isSystemId() && !previouslyGeneratedObjectId (oid))
845         {
846             if (logger.isWarnEnabled())
847             {
848                 logger.warn(logPrefix + "oid: " + POAUtil.convert(oid) +
849                             "create_reference_with_id : object key not previously generated!");
850             }
851
852             throw new org.omg.CORBA.BAD_PARAM JavaDoc ();
853         }
854
855         return getReference (oid, intf_rep_id, false);
856     }
857
858
859     public RequestProcessingPolicy create_request_processing_policy(RequestProcessingPolicyValue value)
860     {
861         checkDestructionApparent();
862         return new org.jacorb.poa.policy.RequestProcessingPolicy (value);
863     }
864
865
866     public ServantRetentionPolicy create_servant_retention_policy(ServantRetentionPolicyValue value)
867     {
868         checkDestructionApparent();
869         return new org.jacorb.poa.policy.ServantRetentionPolicy(value);
870     }
871
872
873     public ThreadPolicy create_thread_policy(ThreadPolicyValue value)
874     {
875         checkDestructionApparent();
876         return new org.jacorb.poa.policy.ThreadPolicy(value);
877     }
878
879
880     /**
881      * The operation does not wait for requests or etherealization to complete
882      * and always returns immediately (after deactivating the oid?)
883      */

884
885
886     public synchronized void deactivate_object(byte[] oid)
887         throws ObjectNotActive, WrongPolicy
888     {
889         if (!configured)
890             throw new Error JavaDoc("POA: not configured!");
891
892         if (!isRetain())
893             throw new WrongPolicy();
894
895         aom.remove(
896             oid,
897             requestController,
898             useServantManager() ? (ServantActivator)servantManager : null,
899             this,
900             false
901                   );
902
903         createdReferences.remove( new ByteArrayKey(oid));
904     }
905
906
907     public void destroy( boolean etherealize_objects,
908                          boolean wait_for_completion )
909     {
910         if (!configured)
911             throw new Error JavaDoc("POA: not configured!");
912
913         if (wait_for_completion && isInInvocationContext())
914             throw new org.omg.CORBA.BAD_INV_ORDER JavaDoc();
915
916         makeShutdownInProgress(etherealize_objects);
917
918         /* synchronized with creationLog */
919         /* child poa creations are impossible now */
920         // destroy all childs first
921

922         Enumeration en = childs.elements();
923         while (en.hasMoreElements())
924         {
925             POA child = (POA) en.nextElement();
926             child.destroy(etherealize, wait_for_completion);
927         }
928
929         Thread JavaDoc thread = new Thread JavaDoc()
930         {
931             public void run()
932             {
933                 /* The apparent destruction of the POA
934                    occurs only after all executing
935                    requests in the POA have completed,
936                    but before any calls to etherealize
937                    are made. */

938                 requestController.waitForShutdown();
939                 /* poa behaves as if he is in the
940                     holding state now and blocks until
941                     all active request have comleted */

942                 makeDestructionApparent();
943                 /* unregister poa from the POAManager,
944                    any calls on the poa are impossible
945                    now especially you cannot activate
946                    or deactivate objects (raises a
947                    OBJ_NOT_EXIST exception), but you
948                    have a race condition with
949                    currently running object
950                    (de)activation processes */

951                 makeDestructionComplete();
952             }
953         };
954         thread.start();
955         if (wait_for_completion)
956         {
957             try
958             {
959                 thread.join();
960             } catch (InterruptedException JavaDoc e) {}
961         }
962     }
963
964
965     private byte[] extractWatermark(byte[] id)
966     {
967         if( id.length < watermark.length )
968             return new byte[0];
969         else
970             return IdUtil.extract(id, id.length-watermark.length, watermark.length);
971     }
972
973
974     /**
975      * If the intended child poa is not found and activate_it is TRUE,
976      * it is possible for another thread to create the same poa with
977      * create_POA at the same time in a race condition. Applications
978      * should be prepared to deal with failures from the manual
979      * (create_POA) or automatic (findPOA or unknown_adapter from
980      * AdapterActivator) POA creation. Another possible situation is
981      * that the poa returned goes shutdown but the orb will notice
982      * this situation if he will proceed with request processing.
983      */

984     public org.omg.PortableServer.POA JavaDoc find_POA( String JavaDoc adapter_name,
985                                                 boolean activate_it)
986         throws AdapterNonExistent
987     {
988         checkDestructionApparent();
989
990         String JavaDoc poa_name = POAUtil.maskStr(adapter_name);
991
992         POA child = (POA)childs.get(poa_name);
993
994         if (child == null || child.isDestructionApparent())
995         {
996
997             boolean successful = false;
998
999             if (activate_it && the_activator() != null) {
1000                /* all invocations an adapter activator are serialized
1001                   if the single thread model is in use */

1002                if (isSingleThreadModel()) {
1003                    synchronized (unknownAdapterLog) {
1004                        while (unknownAdapterCalled) {
1005                            try {
1006                                unknownAdapterLog.wait();
1007                            } catch (InterruptedException JavaDoc e) {
1008                            }
1009                        }
1010                        unknownAdapterCalled = true;
1011                        try
1012                        {
1013                            successful =
1014                            the_activator().unknown_adapter(this, adapter_name);
1015                        }
1016                        finally {
1017                            unknownAdapterCalled = false;
1018                            unknownAdapterLog.notifyAll();
1019                        }
1020                    }
1021
1022                } else { /* ORB_CTRL_MODEL */
1023                    successful = the_activator().unknown_adapter(this, adapter_name);
1024                }
1025            }
1026
1027            /* unknown_adapter returns not until the poa is created and initialized */
1028            if (successful)
1029            {
1030                if ((child = (POA) childs.get(poa_name)) == null)
1031                {
1032                    throw new POAInternalError("error: unknown_adapter returns true, but the child poa does'n extist");
1033                }
1034
1035            }
1036            else
1037            {
1038                throw new AdapterNonExistent();
1039            }
1040        }
1041        return child;
1042    }
1043
1044
1045    /**
1046     * <code>generateObjectId</code> creates a new ObjectId for an object.
1047     *
1048     * @return a <code>byte[]</code> value.
1049     */

1050    private synchronized byte[] generateObjectId()
1051    {
1052        if (isPersistent())
1053        {
1054            return IdUtil.concat(IdUtil.createId(4), watermark);
1055        }
1056        else
1057        {
1058            // Synchonize as the increment is not an atomic operation.
1059
return IdUtil.concat(IdUtil.toId(objectIdCount++), watermark);
1060        }
1061    }
1062
1063
1064    private byte[] generateWatermark()
1065    {
1066        if (watermark == null)
1067        {
1068            if (isPersistent())
1069                watermark = IdUtil.toId(new String JavaDoc(getPOAId()).hashCode());
1070            else
1071                watermark = IdUtil.createId(4);
1072        }
1073        return watermark;
1074    }
1075
1076
1077    public Servant get_servant()
1078        throws NoServant, WrongPolicy
1079    {
1080        if (!configured)
1081            throw new Error JavaDoc("POA: not configured!");
1082
1083        checkDestructionApparent();
1084
1085        if (!isUseDefaultServant())
1086            throw new WrongPolicy();
1087
1088        if (defaultServant == null)
1089            throw new NoServant();
1090        return defaultServant;
1091    }
1092
1093
1094    public org.omg.PortableServer.ServantManager JavaDoc get_servant_manager()
1095        throws WrongPolicy
1096    {
1097        if (!configured)
1098            throw new Error JavaDoc("POA: not configured!");
1099
1100        checkDestructionApparent();
1101
1102        if (!isUseServantManager())
1103            throw new WrongPolicy();
1104
1105        return servantManager;
1106    }
1107
1108
1109    protected POAMonitor getMonitor()
1110    {
1111        return monitor;
1112    }
1113
1114    protected org.jacorb.orb.ORB getORB()
1115    {
1116        return orb;
1117    }
1118
1119    public byte[] getPOAId()
1120    {
1121        if (poaId == null)
1122        {
1123            byte[] impl_name =
1124                POAUtil.maskId( (implName != null) ?
1125                                implName :
1126                                serverId );
1127            int in_length = impl_name.length;
1128
1129            byte[] poa_name = _getQualifiedName().getBytes();
1130            int pn_length = poa_name.length;
1131
1132            int offset = 0;
1133            if (pn_length == 0)
1134            {
1135                poaId = new byte[in_length];
1136                System.arraycopy (impl_name, 0, poaId, 0, in_length);
1137            }
1138            else
1139            {
1140                poaId = new byte[in_length + pn_length + 1];
1141                System.arraycopy (impl_name, 0, poaId, 0, in_length);
1142                offset += in_length;
1143                poaId[offset] = POAConstants.OBJECT_KEY_SEP_BYTE;
1144                offset++;
1145                System.arraycopy (poa_name, 0, poaId, offset, pn_length);
1146            }
1147        }
1148        return poaId;
1149    }
1150
1151    protected org.omg.CORBA.Object JavaDoc getReference
1152        (byte[] oid, String JavaDoc intf_rep_id, boolean cache)
1153    {
1154        byte[] object_id = POAUtil.maskId (oid);
1155        int pid_length = getPOAId().length;
1156        int oid_length = object_id.length;
1157        byte [] object_key = new byte[pid_length + oid_length + 1];
1158        int offset = 0;
1159
1160        System.arraycopy (getPOAId(), 0, object_key, offset, pid_length);
1161        offset += pid_length;
1162        object_key[offset] = POAConstants.OBJECT_KEY_SEP_BYTE;
1163        offset++;
1164        System.arraycopy (object_id, 0, object_key, offset, oid_length);
1165
1166        ByteArrayKey key = new ByteArrayKey (oid);
1167
1168        org.omg.CORBA.Object JavaDoc result =
1169            (org.omg.CORBA.Object JavaDoc) createdReferences.get (key);
1170
1171        if (result == null)
1172        {
1173            result = ((org.jacorb.orb.ORB)orb).getReference
1174                (this, object_key, intf_rep_id, !isPersistent());
1175
1176            if (cache)
1177            {
1178                createdReferences.put (key, result);
1179            }
1180
1181            if ( poaListener != null )
1182                poaListener.referenceCreated( result );
1183        }
1184
1185        return result;
1186    }
1187
1188    protected RequestController getRequestController()
1189    {
1190        return requestController;
1191    }
1192
1193    protected State JavaDoc getState()
1194    {
1195        return poaManager.get_state();
1196    }
1197
1198    public org.omg.CORBA.Object JavaDoc id_to_reference (byte[] oid)
1199        throws ObjectNotActive, WrongPolicy
1200    {
1201        checkDestructionApparent ();
1202
1203        if ( !isRetain() )
1204            throw new WrongPolicy();
1205
1206        Servant servant = null;
1207        /* objectId is not active */
1208        if ((servant = aom.getServant(oid)) == null)
1209            throw new ObjectNotActive();
1210
1211        /* If the object with the specified ObjectId currently active,
1212           a reference encapsulating the information used to activate
1213           the object is returned. */

1214        return getReference (oid, servant._all_interfaces (this, oid)[0], true);
1215    }
1216
1217
1218    public Servant id_to_servant(byte[] oid)
1219        throws ObjectNotActive, WrongPolicy
1220    {
1221        checkDestructionApparent ();
1222
1223        if (!isRetain() && !isUseDefaultServant()) throw new WrongPolicy();
1224
1225        Servant servant = null;
1226        /* servant is active */
1227        if (isRetain() && (servant = aom.getServant(oid)) != null) {
1228            return servant;
1229        }
1230        if (useDefaultServant()) {
1231            return defaultServant;
1232        }
1233
1234        throw new ObjectNotActive();
1235    }
1236
1237
1238    protected boolean isActive()
1239    {
1240        return poaManager.get_state().value() ==
1241        org.omg.PortableServer.POAManagerPackage.State._ACTIVE ? true : false;
1242    }
1243
1244    protected void checkDestructionApparent()
1245    {
1246        if (isDestructionApparent())
1247        {
1248            throw new org.omg.CORBA.OBJECT_NOT_EXIST JavaDoc ("POA destroyed");
1249        }
1250    }
1251
1252    protected static void checkNotLocal(org.omg.CORBA.Object JavaDoc obj)
1253        throws WrongAdapter
1254    {
1255        if (obj instanceof org.omg.CORBA.LocalObject JavaDoc)
1256        {
1257            throw new WrongAdapter ("Local object");
1258        }
1259    }
1260
1261    protected boolean isDestructionApparent()
1262    {
1263        return shutdownState >= POAConstants.DESTRUCTION_APPARENT;
1264    }
1265
1266    protected boolean isDestructionComplete()
1267    {
1268        return shutdownState >= POAConstants.DESTRUCTION_COMPLETE;
1269    }
1270
1271    protected boolean isDiscarding()
1272    {
1273        return poaManager.get_state().value() ==
1274            org.omg.PortableServer.POAManagerPackage.State._DISCARDING ? true : false;
1275    }
1276
1277    protected boolean isHolding()
1278    {
1279        return poaManager.get_state().value() ==
1280            org.omg.PortableServer.POAManagerPackage.State._HOLDING ? true : false;
1281    }
1282
1283    protected boolean isImplicitActivation()
1284    {
1285        return implicitActivationPolicy != null &&
1286            implicitActivationPolicy.value() == ImplicitActivationPolicyValue.IMPLICIT_ACTIVATION;
1287    }
1288
1289    protected boolean isInactive()
1290    {
1291        return poaManager.get_state().value() ==
1292            org.omg.PortableServer.POAManagerPackage.State._INACTIVE ? true : false;
1293
1294    }
1295
1296    /**
1297     * returns true if the current thread is in the context of
1298     * executing a request from some POA belonging to the same ORB as
1299     * this POA */

1300
1301    private boolean isInInvocationContext()
1302    {
1303        try
1304        {
1305            if (orb.getPOACurrent().getORB() == orb)
1306                return true;
1307        }
1308        catch (org.omg.PortableServer.CurrentPackage.NoContext JavaDoc e)
1309        {
1310        }
1311        return false;
1312    }
1313
1314    /**
1315     * returns true if the current thread is in the context of executing
1316     * a request on the specified servant from this POA,
1317     * if the specified servant is null, it returns true if the current
1318     * thread is in an invocation context from this POA.
1319     */

1320
1321    private boolean isInInvocationContext(Servant servant)
1322    {
1323        try
1324        {
1325            if( orb.getPOACurrent().get_POA() == this &&
1326                (servant == null || orb.getPOACurrent().getServant() == servant))
1327            {
1328                return true;
1329            }
1330        }
1331        catch (org.omg.PortableServer.CurrentPackage.NoContext JavaDoc e)
1332        {
1333        }
1334        return false;
1335    }
1336
1337    protected boolean isMultipleId()
1338    {
1339        return idUniquenessPolicy != null &&
1340        idUniquenessPolicy.value() == IdUniquenessPolicyValue.MULTIPLE_ID;
1341    }
1342
1343    public boolean isPersistent()
1344    {
1345        return lifespanPolicy != null &&
1346        lifespanPolicy.value() == LifespanPolicyValue.PERSISTENT;
1347    }
1348
1349    /**
1350     * also called from Delegate
1351     */

1352
1353    public boolean isRetain()
1354    {
1355        return servantRetentionPolicy == null ||
1356        servantRetentionPolicy.value() == ServantRetentionPolicyValue.RETAIN;
1357    }
1358
1359    protected boolean isShutdownInProgress()
1360    {
1361        return shutdownState >= POAConstants.SHUTDOWN_IN_PROGRESS;
1362    }
1363
1364    protected boolean isSingleThreadModel()
1365    {
1366        return threadPolicy != null &&
1367        threadPolicy.value() == ThreadPolicyValue.SINGLE_THREAD_MODEL;
1368    }
1369
1370    public boolean isSystemId()
1371    {
1372        return idAssignmentPolicy == null ||
1373        idAssignmentPolicy.value() == IdAssignmentPolicyValue.SYSTEM_ID;
1374    }
1375
1376    protected boolean isUniqueId()
1377    {
1378        return idUniquenessPolicy == null ||
1379        idUniquenessPolicy.value() == IdUniquenessPolicyValue.UNIQUE_ID;
1380    }
1381
1382    /**
1383     */

1384
1385    protected boolean isUseDefaultServant()
1386    {
1387        return requestProcessingPolicy != null &&
1388        requestProcessingPolicy.value() == RequestProcessingPolicyValue.USE_DEFAULT_SERVANT;
1389    }
1390
1391    public boolean isUseServantManager()
1392    {
1393        return requestProcessingPolicy != null &&
1394        requestProcessingPolicy.value() == RequestProcessingPolicyValue.USE_SERVANT_MANAGER;
1395    }
1396
1397    public boolean isSSLRequired()
1398    {
1399        return sslPolicy != null &&
1400        sslPolicy.value() == SSLPolicyValue.SSL_REQUIRED;
1401    }
1402
1403    /**
1404     * Any calls on the poa are impossible now, especially you cannot
1405     * activate or deactivate objects (raises a OBJ_NOT_EXIST
1406     * exception). The poa will unregistered with the POAManager.
1407     * After destruction has become apparent, the POA may be
1408     * re-created via either the AdapterActivator or a call to
1409     * create_POA
1410     */

1411
1412    private void makeDestructionApparent()
1413    {
1414        synchronized (poaDestructionLog)
1415        {
1416            if (shutdownState < POAConstants.DESTRUCTION_APPARENT)
1417            {
1418                /* do */
1419                poaManager.unregisterPOA(this);
1420
1421                /* set */
1422                shutdownState = POAConstants.DESTRUCTION_APPARENT;
1423
1424                /* announce */
1425                if (poaListener != null)
1426                    poaListener.poaStateChanged(this, POAConstants.DESTROYED);
1427
1428                if (logger.isDebugEnabled())
1429                    logger.debug(logPrefix + "destruction is apparent");
1430
1431                monitor.changeState("destruction is apparent ...");
1432            }
1433        }
1434    }
1435
1436    /**
1437     * After destruction has become complete, a poa creation process
1438     * under the same poa name can continue now.
1439     */

1440
1441    private void makeDestructionComplete()
1442    {
1443        if (shutdownState < POAConstants.DESTRUCTION_COMPLETE)
1444        {
1445            /* do */
1446            /* clear up the queue */
1447            if (logger.isDebugEnabled())
1448                logger.debug(logPrefix + "clear up the queue ...");
1449
1450            requestController.clearUpQueue(new org.omg.CORBA.OBJECT_NOT_EXIST JavaDoc("adapter destroyed"));
1451
1452            if (logger.isDebugEnabled())
1453                logger.debug(logPrefix + "... done");
1454
1455            /* etherialize all active objects */
1456            if (etherealize && isRetain() && useServantManager())
1457            {
1458                if (logger.isDebugEnabled())
1459                    logger.debug(logPrefix + "etherialize all servants ...");
1460
1461                aom.removeAll((ServantActivator) servantManager, this, true);
1462
1463                if (logger.isDebugEnabled())
1464                    logger.debug(logPrefix + "... done");
1465            }
1466
1467            /* stop the request processor threads */
1468            if (!isSingleThreadModel())
1469            {
1470                if (logger.isDebugEnabled())
1471                    logger.debug(logPrefix + "remove all processors from the pool ...");
1472                requestController.clearUpPool();
1473
1474                if (logger.isDebugEnabled())
1475                    logger.debug(logPrefix + "... done");
1476            }
1477
1478            /* stop the request controller */
1479            if (logger.isDebugEnabled())
1480                logger.debug(logPrefix + "stop the request controller ...");
1481
1482            requestController.end();
1483
1484            if (logger.isDebugEnabled())
1485                logger.debug(logPrefix + "... done");
1486
1487            /* set */
1488            shutdownState = POAConstants.DESTRUCTION_COMPLETE;
1489            if (parent != null)
1490            {
1491                // I am not the RootPOA
1492
// unregister the poa with the parent and
1493
// notify a concurrent creation process
1494
parent.unregisterChild(name);
1495            }
1496
1497            /* annouce */
1498            if (logger.isInfoEnabled())
1499                logger.info(logPrefix + " destroyed");
1500
1501            monitor.changeState("destroyed");
1502
1503            /* clear tables */
1504            createdReferences.clear();
1505            all_policies.clear();
1506        }
1507    }
1508
1509    /**
1510     * The etherealize_objects parameter from the destroy method will
1511     * saved in the field etherealize because the etherealize_objects
1512     * parameter applies only the first call of destroy. Subsequent
1513     * calls use the field etherealize. Any calls to create_POA are
1514     * impossible now (receives a BAD_INV_ORDER exception).
1515     */

1516
1517    private void makeShutdownInProgress(boolean etherealize_objects)
1518    {
1519        synchronized (poaCreationLog)
1520        {
1521            if (shutdownState < POAConstants.SHUTDOWN_IN_PROGRESS)
1522            {
1523                /* do */
1524                etherealize = etherealize_objects;
1525
1526                /* set */
1527                shutdownState = POAConstants.SHUTDOWN_IN_PROGRESS;
1528
1529                /* annouce */
1530                if (logger.isDebugEnabled())
1531                    logger.debug(logPrefix + "shutdown is in progress");
1532
1533                monitor.changeState("shutdown is in progress ...");
1534            }
1535        }
1536    }
1537
1538    public boolean previouslyGeneratedObjectId(byte[] oid)
1539    {
1540        return IdUtil.equals(watermark, extractWatermark(oid));
1541    }
1542
1543    public boolean previouslyGeneratedObjectKey(byte[] object_key)
1544    {
1545        return IdUtil.equals(object_key, getPOAId(), getPOAId().length);
1546    }
1547
1548    public byte[] reference_to_id (org.omg.CORBA.Object JavaDoc reference)
1549        throws WrongAdapter, WrongPolicy
1550    {
1551        checkDestructionApparent ();
1552        checkNotLocal (reference);
1553
1554        byte[] objectId = POAUtil.extractOID(reference);
1555
1556        /* not spec (isSystemId) */
1557        if (isSystemId() && !previouslyGeneratedObjectId(objectId))
1558        {
1559            if (logger.isWarnEnabled())
1560                logger.warn(logPrefix + "oid: " + POAUtil.convert(objectId) +
1561                            "reference_to_id: oid not previously generated!");
1562            throw new WrongAdapter();
1563        }
1564
1565        return objectId;
1566    }
1567
1568    public Servant reference_to_servant(org.omg.CORBA.Object JavaDoc reference)
1569        throws ObjectNotActive, WrongAdapter, WrongPolicy
1570    {
1571        checkDestructionApparent();
1572        checkNotLocal(reference);
1573
1574        if (!isRetain() && !isUseDefaultServant())
1575            throw new WrongPolicy();
1576
1577        byte[] objectId = POAUtil.extractOID(reference);
1578
1579        /* not spec (isSystemId) */
1580        if (isSystemId() && !previouslyGeneratedObjectId(objectId))
1581        {
1582            if (logger.isWarnEnabled())
1583                logger.warn(logPrefix + "oid: " + POAUtil.convert(objectId) +
1584                            "reference_to_servant: oid not previously generated!");
1585            throw new WrongAdapter();
1586        }
1587
1588        ByteArrayKey oid = new ByteArrayKey (objectId);
1589
1590        if ( ( aom != null && aom.isDeactivating (oid) )
1591             || requestController.isDeactivating (oid))
1592        {
1593            if (logger.isWarnEnabled())
1594                logger.warn(logPrefix + "oid: " + POAUtil.convert(objectId) +
1595                            "cannot process request, because object is already in the deactivation process");
1596
1597            throw new org.omg.CORBA.OBJECT_NOT_EXIST JavaDoc();
1598        }
1599
1600        Servant servant = null;
1601
1602        /* is active servant */
1603        if (isRetain() && (servant = aom.getServant(objectId)) != null)
1604        {
1605            return servant;
1606        }
1607        else if (useDefaultServant())
1608        {
1609            return defaultServant;
1610        }
1611
1612        throw new ObjectNotActive();
1613    }
1614
1615    protected synchronized void removePOAListener(POAListener listener)
1616    {
1617        poaListener = EventMulticaster.remove(poaListener, listener);
1618    }
1619
1620
1621    public byte[] servant_to_id(Servant servant)
1622        throws ServantNotActive, WrongPolicy
1623    {
1624        checkDestructionApparent ();
1625
1626        if ((!isUseDefaultServant()) &&
1627            (!isRetain() || !isUniqueId()) &&
1628            (!isRetain() || !isImplicitActivation()))
1629            throw new WrongPolicy();
1630
1631        byte[] objectId = null;
1632
1633        if (isRetain())
1634        {
1635            if (isUniqueId() && (objectId = aom.getObjectId(servant)) != null)
1636            {
1637                return objectId;
1638            }
1639
1640            if ( isImplicitActivation() &&
1641                 ( isMultipleId() || !aom.contains(servant)) )
1642            {
1643                objectId = generateObjectId();
1644                /* activate the servant using the generated objectId and the
1645                   intfRepId associated with the servant */

1646                try
1647                {
1648                    aom.add(objectId, servant);
1649                }
1650                catch (ObjectAlreadyActive e)
1651                {
1652                    throw new POAInternalError("error: object already active (servant_to_id)");
1653                }
1654                catch (ServantAlreadyActive e)
1655                {
1656                    /* it's ok, a nother one was faster with
1657                        activation (only occurs if unique_id is set) */

1658                    objectId = aom.getObjectId(servant);
1659                }
1660                return objectId;
1661            }
1662        }
1663        if (isUseDefaultServant() && servant == defaultServant &&
1664            isInInvocationContext(servant))
1665        {
1666            /* objectId associated with the current invocation */
1667            try
1668            {
1669                objectId = orb.getPOACurrent().get_object_id();
1670            }
1671            catch (org.omg.PortableServer.CurrentPackage.NoContext JavaDoc e)
1672            {
1673                throw new POAInternalError("error: not in invocation context (servant_to_id)");
1674            }
1675            return objectId;
1676        }
1677
1678        throw new ServantNotActive();
1679    }
1680
1681    /**
1682     */

1683
1684    public org.omg.CORBA.Object JavaDoc servant_to_reference(Servant servant)
1685        throws ServantNotActive, WrongPolicy
1686    {
1687        checkDestructionApparent ();
1688
1689        boolean isInInvocationContext = isInInvocationContext(servant);
1690
1691        if ( (!isRetain() || !isUniqueId()) &&
1692             (!isRetain() || !isImplicitActivation()) &&
1693             !isInInvocationContext )
1694            throw new WrongPolicy();
1695
1696        byte[] objectId = null;
1697
1698        if (isInInvocationContext)
1699        {
1700            /* reference = Reference associated with the current invocation */
1701            try
1702            {
1703                objectId = orb.getPOACurrent().get_object_id();
1704            }
1705            catch (org.omg.PortableServer.CurrentPackage.NoContext JavaDoc e)
1706            {
1707                throw new POAInternalError("error: not in invocation context (servant_to_reference)");
1708            }
1709            return getReference(objectId,
1710                                servant._all_interfaces(this, objectId)[0],
1711                                true);
1712        }
1713
1714        if (isRetain())
1715        {
1716            if (isUniqueId())
1717            {
1718                /* the object reference encapsulating the information
1719                   used to activate the servant is returned */

1720
1721                if ((objectId = aom.getObjectId(servant)) != null)
1722                {
1723                    return getReference(objectId, servant._all_interfaces(this, objectId)[0], true);
1724                }
1725            }
1726
1727            if (isImplicitActivation() && (isMultipleId() || !aom.contains(servant)) )
1728            {
1729                objectId = generateObjectId();
1730
1731                /* activate the servant using a generated objectId and
1732                   the intfRepId associated with the servant
1733                   and a corresponding object reference is returned */

1734
1735                try
1736                {
1737                    aom.add(objectId, servant);
1738                }
1739                catch (ObjectAlreadyActive e)
1740                {
1741                    throw new POAInternalError("error: object already active (servant_to_reference)");
1742                }
1743                catch (ServantAlreadyActive e)
1744                {
1745                    /* it's ok, another one was faster with activation
1746                       (only occurs if unique_id is set) */

1747                    objectId = aom.getObjectId(servant);
1748                }
1749
1750                orb.set_delegate(servant);
1751
1752                return getReference(objectId,
1753                                    servant._all_interfaces(this, objectId)[0],
1754                                    true);
1755            }
1756        }
1757        throw new ServantNotActive();
1758    }
1759
1760
1761    public void set_servant(Servant _defaultServant)
1762        throws WrongPolicy
1763    {
1764        checkDestructionApparent();
1765
1766        if (!isUseDefaultServant())
1767            throw new WrongPolicy();
1768
1769        defaultServant = _defaultServant;
1770
1771        if (defaultServant != null)
1772            orb.set_delegate(defaultServant); // set the orb
1773
}
1774
1775    /**
1776     * this method makes a additional check: if the POA has the RETAIN
1777     * policy and _servantManager is not a instance of
1778     * ServantActivator or if the POA has the NON_RETAIN policy and
1779     * _servantManager is not a instance of ServantLocator this method
1780     * raises also the WrongPolicy Exception (not spec.)
1781     */

1782
1783    public void set_servant_manager(org.omg.PortableServer.ServantManager JavaDoc servant_manager)
1784        throws WrongPolicy
1785    {
1786        checkDestructionApparent ();
1787
1788        if (!isUseServantManager())
1789            throw new WrongPolicy();
1790
1791        if (servantManager != null)
1792            throw new org.omg.CORBA.BAD_INV_ORDER JavaDoc();
1793
1794        /* not spec. */
1795        if( isRetain() &&
1796            !(servant_manager instanceof org.omg.PortableServer.ServantActivator JavaDoc))
1797            throw new WrongPolicy();
1798
1799        if (!isRetain() &&
1800            !(servant_manager instanceof org.omg.PortableServer.ServantLocator JavaDoc))
1801            throw new WrongPolicy();
1802
1803        servantManager = servant_manager;
1804    }
1805
1806
1807    protected void setMonitor(POAMonitor _monitor)
1808    {
1809        monitor = _monitor;
1810    }
1811
1812    /**
1813     * it is system-dependent whether the root POA initially has an adapter
1814     * activator. a newly created POA has not an adapter activator (null)
1815     */

1816
1817    public org.omg.PortableServer.AdapterActivator JavaDoc the_activator()
1818    {
1819        checkDestructionApparent ();
1820        return adapterActivator;
1821    }
1822
1823    public void the_activator(org.omg.PortableServer.AdapterActivator JavaDoc adapter_activator)
1824    {
1825        checkDestructionApparent();
1826        adapterActivator = adapter_activator;
1827    }
1828
1829    public String JavaDoc the_name()
1830    {
1831        checkDestructionApparent();
1832        return POAUtil.unmaskStr(name);
1833    }
1834
1835    public org.omg.PortableServer.POA JavaDoc the_parent()
1836    {
1837        checkDestructionApparent();
1838        return parent;
1839    }
1840
1841    public org.omg.PortableServer.POA JavaDoc[] the_children()
1842    {
1843        checkDestructionApparent();
1844
1845        int i = 0;
1846        Enumeration enumeration;
1847        org.omg.PortableServer.POA JavaDoc[] children;
1848
1849        synchronized (poaCreationLog)
1850        {
1851            children = new org.omg.PortableServer.POA JavaDoc[childs.size()];
1852            enumeration = childs.elements();
1853            while (enumeration.hasMoreElements())
1854            {
1855                children[i] = (org.omg.PortableServer.POA JavaDoc) enumeration.nextElement();
1856                i++;
1857            }
1858        }
1859
1860        return children;
1861    }
1862
1863    public org.omg.PortableServer.POAManager JavaDoc the_POAManager()
1864    {
1865        checkDestructionApparent();
1866        return poaManager;
1867    }
1868
1869    /**
1870     * notified the completion of a child destruction
1871     */

1872
1873    protected void unregisterChild(String JavaDoc name)
1874    {
1875        synchronized (poaCreationLog)
1876        {
1877            childs.remove(name);
1878            poaCreationLog.notifyAll();
1879        }
1880    }
1881
1882    /**
1883     * called from Delegate
1884     */

1885
1886    public boolean useDefaultServant()
1887    {
1888        return isUseDefaultServant() && defaultServant != null;
1889    }
1890
1891    protected boolean useServantManager()
1892    {
1893        return isUseServantManager() && servantManager != null;
1894    }
1895
1896
1897    /**
1898     * If any of the policies specified are not valid, or if conflicting
1899     * policies are specified, or if any of the specified policies require
1900     * prior administrative action that has not been performed, or if the
1901     * policy type is unknown, this method returns the index in the policy list
1902     * of the first offending policy object. By the creation of a new POA object
1903     * this lead to an InvalidPolicy exception being raised containing this index.
1904     *
1905     * If everything's fine, this method returns -1;
1906     */

1907
1908    private short verifyPolicyList(org.omg.CORBA.Policy JavaDoc[] policies)
1909    {
1910        org.omg.CORBA.Policy JavaDoc policy;
1911        org.omg.CORBA.Policy JavaDoc policy2;
1912
1913        for (short i = 0; i < policies.length; i++)
1914        {
1915            switch (policies[i].policy_type())
1916            {
1917                case THREAD_POLICY_ID.value :
1918                /* no dependencies */
1919                break;
1920                case LIFESPAN_POLICY_ID.value :
1921                // PERSISTENT -> ImplName is set
1922
if (((LifespanPolicy) policies[i]).value() ==
1923                    LifespanPolicyValue.PERSISTENT)
1924                {
1925                    if ( implName == null )
1926                    {
1927                        logger.fatalError("cannot create a persistent poa! (implname property is not used)");
1928                        return i;
1929                    }
1930                }
1931
1932                /* no dependencies */
1933                break;
1934                case ID_UNIQUENESS_POLICY_ID.value :
1935                /* no dependencies */
1936                /* if you set NON_RETAIN the poa doesn't take any
1937                   notice of the IdUniquenesPolicyValue */

1938                break;
1939                case ID_ASSIGNMENT_POLICY_ID.value :
1940                // SYSTEM_ID -> no dependencies USER_ID ->
1941
// NO_IMPLICIT_ACTIVATION, but an error will detected
1942
// if we have considered the IMPLICIT_ACTIVATION
1943
// policy
1944
break;
1945
1946                case SERVANT_RETENTION_POLICY_ID.value :
1947                // RETAIN -> no dependencies
1948
// NON_RETAIN -> (USE_DEFAULT_SERVANT || USE_SERVANT_MANAGER)
1949
if (((ServantRetentionPolicy) policies[i]).value() ==
1950                    ServantRetentionPolicyValue.NON_RETAIN) {
1951
1952                    policy =
1953                    POAUtil.getPolicy(policies, REQUEST_PROCESSING_POLICY_ID.value);
1954                    if (policy != null)
1955                    {
1956                        if ( ((RequestProcessingPolicy) policy).value() !=
1957                             RequestProcessingPolicyValue.USE_DEFAULT_SERVANT &&
1958                             ((RequestProcessingPolicy) policy).value() !=
1959                             RequestProcessingPolicyValue.USE_SERVANT_MANAGER)
1960                        {
1961                            return i;
1962                        }
1963                    }
1964                    else
1965                    {
1966                        return i; // default (USE_ACTIVE_OBJECT_MAP_ONLY) is forbidden
1967
}
1968                    // NON_RETAIN -> NO_IMPLICIT_ACTIVATION, but an error will
1969
// be detected if we have considered the IMPLICIT_ACTIVATION policy
1970
}
1971                break;
1972
1973                case REQUEST_PROCESSING_POLICY_ID.value :
1974                // USE_SERVANT_MANAGER -> no dependencies
1975
// USE_ACTIVE_OBJECT_MAP_ONLY -> RETAIN
1976
if (((RequestProcessingPolicy) policies[i]).value() ==
1977                    RequestProcessingPolicyValue.USE_ACTIVE_OBJECT_MAP_ONLY)
1978                {
1979
1980                    policy = POAUtil.getPolicy( policies,
1981                                                SERVANT_RETENTION_POLICY_ID.value);
1982                    if (policy != null)
1983                    {
1984                        if (((ServantRetentionPolicy) policy).value() !=
1985                            ServantRetentionPolicyValue.RETAIN)
1986                        {
1987                            return i;
1988                        }
1989                    }
1990                    else
1991                    {
1992                        // do nothing, because default (RETAIN) is ok
1993
}
1994                    // USE_DEFAULT_SERVANT -> (MULTIPLE_ID || NON_RETAIN) /* not spec. (NON_RETAIN) */
1995
}
1996                else if (((RequestProcessingPolicy) policies[i]).value() == RequestProcessingPolicyValue.USE_DEFAULT_SERVANT)
1997                {
1998                    policy =
1999                    POAUtil.getPolicy(policies, ID_UNIQUENESS_POLICY_ID.value);
2000                    policy2 =
2001                    POAUtil.getPolicy(policies, SERVANT_RETENTION_POLICY_ID.value);
2002                    if (policy == null && policy2 == null)
2003                    {
2004                        return i; // default (UNIQUE_ID && RETAIN) is forbidden
2005
}
2006                    else if (policy != null && policy2 == null)
2007                    {
2008                        if (((IdUniquenessPolicy) policy).value() !=
2009                            IdUniquenessPolicyValue.MULTIPLE_ID )
2010                            return i;
2011                    }
2012                    else if (policy == null && policy2 != null)
2013                    {
2014                        if (((ServantRetentionPolicy) policy2).value() !=
2015                            ServantRetentionPolicyValue.NON_RETAIN )
2016                            return i;
2017                    }
2018                    else if (policy != null && policy2 != null)
2019                    {
2020                        if (((IdUniquenessPolicy) policy).value() !=
2021                            IdUniquenessPolicyValue.MULTIPLE_ID &&
2022                            ((ServantRetentionPolicy) policy2).value() !=
2023                            ServantRetentionPolicyValue.NON_RETAIN )
2024                            return i;
2025                    }
2026                }
2027                break;
2028
2029                case IMPLICIT_ACTIVATION_POLICY_ID.value :
2030                // NO_IMPLICIT_ACTIVATION -> no dependencies
2031
// IMPLICIT_ACTIVATION -> (SYSTEM_ID && RETAIN)
2032
if (((ImplicitActivationPolicy) policies[i]).value() ==
2033                    ImplicitActivationPolicyValue.IMPLICIT_ACTIVATION)
2034                {
2035                    policy = POAUtil.getPolicy(policies,
2036                                               SERVANT_RETENTION_POLICY_ID.value);
2037                    if (policy != null)
2038                    {
2039                        if (((ServantRetentionPolicy) policy).value() !=
2040                            ServantRetentionPolicyValue.RETAIN)
2041                        {
2042                            return i;
2043                        }
2044                    }
2045                    else
2046                    {
2047                        // do nothing, because default (RETAIN) is ok
2048
}
2049
2050                    policy = POAUtil.getPolicy(policies, ID_ASSIGNMENT_POLICY_ID.value);
2051                    if (policy != null)
2052                    {
2053                        if (((IdAssignmentPolicy) policy).value() !=
2054                            IdAssignmentPolicyValue.SYSTEM_ID)
2055                        {
2056                            return i;
2057                        }
2058                    }
2059                    else
2060                    {
2061                        // do nothing, because default (SYSTEM_ID) is ok
2062
}
2063                }
2064                break;
2065                case BIDIRECTIONAL_POLICY_TYPE.value :
2066                // nothing to do
2067
break;
2068                //ignore unknown policies
2069

2070                // // unknown policy type -> return i
2071
// default :
2072
// return i;
2073
}
2074        }
2075        return -1;
2076    }
2077
2078    public org.omg.CORBA.Policy JavaDoc getPolicy(int type)
2079    {
2080        return (org.omg.CORBA.Policy JavaDoc) all_policies.get(new Integer JavaDoc(type));
2081    }
2082
2083    public void addLocalRequest()
2084    {
2085        requestController.addLocalRequest();
2086    }
2087
2088    public void removeLocalRequest()
2089    {
2090        requestController.removeLocalRequest();
2091    }
2092
2093    public int getNumberOfObjects()
2094    {
2095        return aom.size ();
2096    }
2097}
2098
Popular Tags