1 //
2 // Copyright (c) ZeroC, Inc. All rights reserved.
3 //
4 
5 package IceInternal;
6 
7 import java.util.concurrent.TimeUnit;
8 
9 public final class Instance implements Ice.ClassResolver
10 {
11     static private class ThreadObserverHelper
12     {
ThreadObserverHelper(String threadName)13         ThreadObserverHelper(String threadName)
14         {
15             _threadName = threadName;
16         }
17 
updateObserver(Ice.Instrumentation.CommunicatorObserver obsv)18         synchronized public void updateObserver(Ice.Instrumentation.CommunicatorObserver obsv)
19         {
20             assert(obsv != null);
21 
22             _observer = obsv.getThreadObserver("Communicator",
23                                                _threadName,
24                                                Ice.Instrumentation.ThreadState.ThreadStateIdle,
25                                                _observer);
26             if(_observer != null)
27             {
28                 _observer.attach();
29             }
30         }
31 
beforeExecute()32         protected void beforeExecute()
33         {
34             _threadObserver = _observer;
35             if(_threadObserver != null)
36             {
37                 _threadObserver.stateChanged(Ice.Instrumentation.ThreadState.ThreadStateIdle,
38                                              Ice.Instrumentation.ThreadState.ThreadStateInUseForOther);
39             }
40         }
41 
afterExecute()42         protected void afterExecute()
43         {
44             if(_threadObserver != null)
45             {
46                 _threadObserver.stateChanged(Ice.Instrumentation.ThreadState.ThreadStateInUseForOther,
47                                              Ice.Instrumentation.ThreadState.ThreadStateIdle);
48                 _threadObserver = null;
49             }
50         }
51 
52         final private String _threadName;
53         //
54         // We use a volatile to avoid synchronization when reading
55         // _observer. Reference assignement is atomic in Java so it
56         // also doesn't need to be synchronized.
57         //
58         private volatile Ice.Instrumentation.ThreadObserver _observer;
59         private Ice.Instrumentation.ThreadObserver _threadObserver;
60     }
61 
62     static private class Timer extends java.util.concurrent.ScheduledThreadPoolExecutor
63     {
Timer(Ice.Properties props, String threadName)64         Timer(Ice.Properties props, String threadName)
65         {
66             super(1, Util.createThreadFactory(props, threadName)); // Single thread executor
67             setRemoveOnCancelPolicy(true);
68             setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
69             _observerHelper = new ThreadObserverHelper(threadName);
70         }
71 
updateObserver(Ice.Instrumentation.CommunicatorObserver obsv)72         public void updateObserver(Ice.Instrumentation.CommunicatorObserver obsv)
73         {
74             _observerHelper.updateObserver(obsv);
75         }
76 
77         @Override
beforeExecute(Thread t, Runnable r)78         protected void beforeExecute(Thread t, Runnable r)
79         {
80             _observerHelper.beforeExecute();
81         }
82 
83         @Override
afterExecute(Runnable t, Throwable e)84         protected void afterExecute(Runnable t, Throwable e)
85         {
86             _observerHelper.afterExecute();
87         }
88 
89         private final ThreadObserverHelper _observerHelper;
90     }
91 
92     static private class QueueExecutor extends java.util.concurrent.ThreadPoolExecutor
93     {
QueueExecutor(Ice.Properties props, String threadName)94         QueueExecutor(Ice.Properties props, String threadName)
95         {
96             super(1, 1, 0, TimeUnit.MILLISECONDS, new java.util.concurrent.LinkedBlockingQueue<Runnable>(),
97                   Util.createThreadFactory(props, threadName));
98             _observerHelper = new ThreadObserverHelper(threadName);
99         }
100 
updateObserver(Ice.Instrumentation.CommunicatorObserver obsv)101         public void updateObserver(Ice.Instrumentation.CommunicatorObserver obsv)
102         {
103             _observerHelper.updateObserver(obsv);
104         }
105 
106         @Override
beforeExecute(Thread t, Runnable r)107         protected void beforeExecute(Thread t, Runnable r)
108         {
109             _observerHelper.beforeExecute();
110         }
111 
112         @Override
afterExecute(Runnable t, Throwable e)113         protected void afterExecute(Runnable t, Throwable e)
114         {
115             _observerHelper.afterExecute();
116         }
117 
destroy()118         public void destroy()
119             throws InterruptedException
120         {
121             shutdown();
122             while(!isTerminated())
123             {
124                 // A very long time.
125                 awaitTermination(100000, java.util.concurrent.TimeUnit.SECONDS);
126             }
127         }
128 
129         private final ThreadObserverHelper _observerHelper;
130     }
131 
132     private class ObserverUpdaterI implements Ice.Instrumentation.ObserverUpdater
133     {
134         @Override
135         public void
updateConnectionObservers()136         updateConnectionObservers()
137         {
138             Instance.this.updateConnectionObservers();
139         }
140 
141         @Override
142         public void
updateThreadObservers()143         updateThreadObservers()
144         {
145             Instance.this.updateThreadObservers();
146         }
147     }
148 
149     public Ice.InitializationData
initializationData()150     initializationData()
151     {
152         //
153         // No check for destruction. It must be possible to access the
154         // initialization data after destruction.
155         //
156         // No mutex lock, immutable.
157         //
158         return _initData;
159     }
160 
161     public TraceLevels
traceLevels()162     traceLevels()
163     {
164         // No mutex lock, immutable.
165         assert(_traceLevels != null);
166         return _traceLevels;
167     }
168 
169     public DefaultsAndOverrides
defaultsAndOverrides()170     defaultsAndOverrides()
171     {
172         // No mutex lock, immutable.
173         assert(_defaultsAndOverrides != null);
174         return _defaultsAndOverrides;
175     }
176 
177     public synchronized RouterManager
routerManager()178     routerManager()
179     {
180         if(_state == StateDestroyed)
181         {
182             throw new Ice.CommunicatorDestroyedException();
183         }
184 
185         assert(_routerManager != null);
186         return _routerManager;
187     }
188 
189     public synchronized LocatorManager
locatorManager()190     locatorManager()
191     {
192         if(_state == StateDestroyed)
193         {
194             throw new Ice.CommunicatorDestroyedException();
195         }
196 
197         assert(_locatorManager != null);
198         return _locatorManager;
199     }
200 
201     public synchronized ReferenceFactory
referenceFactory()202     referenceFactory()
203     {
204         if(_state == StateDestroyed)
205         {
206             throw new Ice.CommunicatorDestroyedException();
207         }
208 
209         assert(_referenceFactory != null);
210         return _referenceFactory;
211     }
212 
213     public synchronized RequestHandlerFactory
requestHandlerFactory()214     requestHandlerFactory()
215     {
216         if(_state == StateDestroyed)
217         {
218             throw new Ice.CommunicatorDestroyedException();
219         }
220 
221         assert(_requestHandlerFactory != null);
222         return _requestHandlerFactory;
223     }
224 
225     public synchronized ProxyFactory
proxyFactory()226     proxyFactory()
227     {
228         if(_state == StateDestroyed)
229         {
230             throw new Ice.CommunicatorDestroyedException();
231         }
232 
233         assert(_proxyFactory != null);
234         return _proxyFactory;
235     }
236 
237     public synchronized OutgoingConnectionFactory
outgoingConnectionFactory()238     outgoingConnectionFactory()
239     {
240         if(_state == StateDestroyed)
241         {
242             throw new Ice.CommunicatorDestroyedException();
243         }
244 
245         assert(_outgoingConnectionFactory != null);
246         return _outgoingConnectionFactory;
247     }
248 
249     public synchronized ObjectAdapterFactory
objectAdapterFactory()250     objectAdapterFactory()
251     {
252         if(_state == StateDestroyed)
253         {
254             throw new Ice.CommunicatorDestroyedException();
255         }
256 
257         assert(_objectAdapterFactory != null);
258         return _objectAdapterFactory;
259     }
260 
261     public int
protocolSupport()262     protocolSupport()
263     {
264         return _protocolSupport;
265     }
266 
267     public boolean
preferIPv6()268     preferIPv6()
269     {
270         return _preferIPv6;
271     }
272 
273     public NetworkProxy
networkProxy()274     networkProxy()
275     {
276         return _networkProxy;
277     }
278 
279     public synchronized ThreadPool
clientThreadPool()280     clientThreadPool()
281     {
282         if(_state == StateDestroyed)
283         {
284             throw new Ice.CommunicatorDestroyedException();
285         }
286 
287         assert(_clientThreadPool != null);
288         return _clientThreadPool;
289     }
290 
291     public synchronized ThreadPool
serverThreadPool()292     serverThreadPool()
293     {
294         if(_state == StateDestroyed)
295         {
296             throw new Ice.CommunicatorDestroyedException();
297         }
298 
299         if(_serverThreadPool == null) // Lazy initialization.
300         {
301             if(_state == StateDestroyInProgress)
302             {
303                 throw new Ice.CommunicatorDestroyedException();
304             }
305 
306             int timeout = _initData.properties.getPropertyAsInt("Ice.ServerIdleTime");
307             _serverThreadPool = new ThreadPool(this, "Ice.ThreadPool.Server", timeout);
308         }
309 
310         return _serverThreadPool;
311     }
312 
313     public synchronized EndpointHostResolver
endpointHostResolver()314     endpointHostResolver()
315     {
316         if(_state == StateDestroyed)
317         {
318             throw new Ice.CommunicatorDestroyedException();
319         }
320 
321         assert(_endpointHostResolver != null);
322         return _endpointHostResolver;
323     }
324 
325     synchronized public RetryQueue
retryQueue()326     retryQueue()
327     {
328         if(_state == StateDestroyed)
329         {
330             throw new Ice.CommunicatorDestroyedException();
331         }
332 
333         assert(_retryQueue != null);
334         return _retryQueue;
335     }
336 
337     synchronized public java.util.concurrent.ScheduledExecutorService
timer()338     timer()
339     {
340         if(_state == StateDestroyed)
341         {
342             throw new Ice.CommunicatorDestroyedException();
343         }
344 
345         assert(_timer != null);
346         return _timer;
347     }
348 
349     public synchronized EndpointFactoryManager
endpointFactoryManager()350     endpointFactoryManager()
351     {
352         if(_state == StateDestroyed)
353         {
354             throw new Ice.CommunicatorDestroyedException();
355         }
356 
357         assert(_endpointFactoryManager != null);
358         return _endpointFactoryManager;
359     }
360 
361     public synchronized Ice.PluginManager
pluginManager()362     pluginManager()
363     {
364         if(_state == StateDestroyed)
365         {
366             throw new Ice.CommunicatorDestroyedException();
367         }
368 
369         assert(_pluginManager != null);
370         return _pluginManager;
371     }
372 
373     public int
messageSizeMax()374     messageSizeMax()
375     {
376         // No mutex lock, immutable.
377         return _messageSizeMax;
378     }
379 
380     public int
batchAutoFlushSize()381     batchAutoFlushSize()
382     {
383         // No mutex lock, immutable.
384         return _batchAutoFlushSize;
385     }
386 
387     public Ice.ToStringMode
toStringMode()388     toStringMode()
389     {
390         // No mutex lock, immutable
391         return _toStringMode;
392     }
393 
394     public int
cacheMessageBuffers()395     cacheMessageBuffers()
396     {
397         // No mutex lock, immutable.
398         return _cacheMessageBuffers;
399     }
400 
401     public ACMConfig
clientACM()402     clientACM()
403     {
404         // No mutex lock, immutable.
405         return _clientACM;
406     }
407 
408     public ACMConfig
serverACM()409     serverACM()
410     {
411         // No mutex lock, immutable.
412         return _serverACM;
413     }
414 
415     public Ice.ImplicitContextI
getImplicitContext()416     getImplicitContext()
417     {
418         return _implicitContext;
419     }
420 
421     public synchronized Ice.ObjectPrx
createAdmin(Ice.ObjectAdapter adminAdapter, Ice.Identity adminIdentity)422     createAdmin(Ice.ObjectAdapter adminAdapter, Ice.Identity adminIdentity)
423     {
424         if(Thread.interrupted())
425         {
426             throw new Ice.OperationInterruptedException();
427         }
428 
429         boolean createAdapter = (adminAdapter == null);
430 
431         synchronized(this)
432         {
433             if(_state == StateDestroyed)
434             {
435                 throw new Ice.CommunicatorDestroyedException();
436             }
437 
438             if(adminIdentity == null || adminIdentity.name == null || adminIdentity.name.isEmpty())
439             {
440                 throw new Ice.IllegalIdentityException(adminIdentity);
441             }
442 
443             if(_adminAdapter != null)
444             {
445                 throw new Ice.InitializationException("Admin already created");
446             }
447 
448             if(!_adminEnabled)
449             {
450                 throw new Ice.InitializationException("Admin is disabled");
451             }
452 
453             if(createAdapter)
454             {
455                 if(!_initData.properties.getProperty("Ice.Admin.Endpoints").isEmpty())
456                 {
457                     adminAdapter = _objectAdapterFactory.createObjectAdapter("Ice.Admin", null);
458                 }
459                 else
460                 {
461                     throw new Ice.InitializationException("Ice.Admin.Endpoints is not set");
462                 }
463             }
464 
465             _adminIdentity = adminIdentity;
466             _adminAdapter = adminAdapter;
467             addAllAdminFacets();
468         }
469 
470         if(createAdapter)
471         {
472             try
473             {
474                 adminAdapter.activate();
475             }
476             catch(Ice.LocalException ex)
477             {
478                 //
479                 // We cleanup _adminAdapter, however this error is not recoverable
480                 // (can't call again getAdmin() after fixing the problem)
481                 // since all the facets (servants) in the adapter are lost
482                 //
483                 adminAdapter.destroy();
484                 synchronized(this)
485                 {
486                     _adminAdapter = null;
487                 }
488                 throw ex;
489             }
490         }
491         setServerProcessProxy(adminAdapter, adminIdentity);
492         return adminAdapter.createProxy(adminIdentity);
493     }
494 
495     public Ice.ObjectPrx
getAdmin()496     getAdmin()
497     {
498         if(Thread.interrupted())
499         {
500             throw new Ice.OperationInterruptedException();
501         }
502 
503         Ice.ObjectAdapter adminAdapter;
504         Ice.Identity adminIdentity;
505 
506         synchronized(this)
507         {
508             if(_state == StateDestroyed)
509             {
510                 throw new Ice.CommunicatorDestroyedException();
511             }
512 
513             if(_adminAdapter != null)
514             {
515                 return _adminAdapter.createProxy(_adminIdentity);
516             }
517             else if(_adminEnabled)
518             {
519                 if(!_initData.properties.getProperty("Ice.Admin.Endpoints").isEmpty())
520                 {
521                     adminAdapter = _objectAdapterFactory.createObjectAdapter("Ice.Admin", null);
522                 }
523                 else
524                 {
525                     return null;
526                 }
527                 adminIdentity = new Ice.Identity("admin", _initData.properties.getProperty("Ice.Admin.InstanceName"));
528                 if(adminIdentity.category.isEmpty())
529                 {
530                     adminIdentity.category = java.util.UUID.randomUUID().toString();
531                 }
532 
533                 _adminIdentity = adminIdentity;
534                 _adminAdapter = adminAdapter;
535                 addAllAdminFacets();
536                 // continue below outside synchronization
537             }
538             else
539             {
540                 return null;
541             }
542         }
543 
544         try
545         {
546             adminAdapter.activate();
547         }
548         catch(Ice.LocalException ex)
549         {
550             //
551             // We cleanup _adminAdapter, however this error is not recoverable
552             // (can't call again getAdmin() after fixing the problem)
553             // since all the facets (servants) in the adapter are lost
554             //
555             adminAdapter.destroy();
556             synchronized(this)
557             {
558                 _adminAdapter = null;
559             }
560             throw ex;
561         }
562 
563         setServerProcessProxy(adminAdapter, adminIdentity);
564         return adminAdapter.createProxy(adminIdentity);
565     }
566 
567     public synchronized void
addAdminFacet(Ice.Object servant, String facet)568     addAdminFacet(Ice.Object servant, String facet)
569     {
570         if(_state == StateDestroyed)
571         {
572             throw new Ice.CommunicatorDestroyedException();
573         }
574 
575         if(_adminAdapter == null || (!_adminFacetFilter.isEmpty() && !_adminFacetFilter.contains(facet)))
576         {
577             if(_adminFacets.get(facet) != null)
578             {
579                 throw new Ice.AlreadyRegisteredException("facet", facet);
580             }
581             _adminFacets.put(facet, servant);
582         }
583         else
584         {
585             _adminAdapter.addFacet(servant, _adminIdentity, facet);
586         }
587     }
588 
589     public synchronized Ice.Object
removeAdminFacet(String facet)590     removeAdminFacet(String facet)
591     {
592         if(_state == StateDestroyed)
593         {
594             throw new Ice.CommunicatorDestroyedException();
595         }
596 
597         Ice.Object result;
598 
599         if(_adminAdapter == null || (!_adminFacetFilter.isEmpty() && !_adminFacetFilter.contains(facet)))
600         {
601             result = _adminFacets.remove(facet);
602             if(result == null)
603             {
604                 throw new Ice.NotRegisteredException("facet", facet);
605             }
606         }
607         else
608         {
609             result = _adminAdapter.removeFacet(_adminIdentity, facet);
610         }
611 
612         return result;
613     }
614 
615     public synchronized Ice.Object
findAdminFacet(String facet)616     findAdminFacet(String facet)
617     {
618         if(_state == StateDestroyed)
619         {
620             throw new Ice.CommunicatorDestroyedException();
621         }
622 
623         Ice.Object result = null;
624 
625         if(_adminAdapter == null || (!_adminFacetFilter.isEmpty() && !_adminFacetFilter.contains(facet)))
626         {
627             result = _adminFacets.get(facet);
628         }
629         else
630         {
631             result = _adminAdapter.findFacet(_adminIdentity, facet);
632         }
633 
634         return result;
635     }
636 
637     public synchronized java.util.Map<String, Ice.Object>
findAllAdminFacets()638     findAllAdminFacets()
639     {
640         if(_state == StateDestroyed)
641         {
642             throw new Ice.CommunicatorDestroyedException();
643         }
644 
645         if(_adminAdapter == null)
646         {
647             return new java.util.HashMap<String, Ice.Object>(_adminFacets);
648         }
649         else
650         {
651             java.util.Map<String, Ice.Object> result = _adminAdapter.findAllFacets(_adminIdentity);
652             if(!_adminFacets.isEmpty())
653             {
654                 // Also returns filtered facets
655                 result.putAll(_adminFacets);
656             }
657             return result;
658         }
659     }
660 
661     public synchronized void
setDefaultLocator(Ice.LocatorPrx locator)662     setDefaultLocator(Ice.LocatorPrx locator)
663     {
664         if(_state == StateDestroyed)
665         {
666             throw new Ice.CommunicatorDestroyedException();
667         }
668 
669         _referenceFactory = _referenceFactory.setDefaultLocator(locator);
670     }
671 
672     public synchronized void
setDefaultRouter(Ice.RouterPrx router)673     setDefaultRouter(Ice.RouterPrx router)
674     {
675         if(_state == StateDestroyed)
676         {
677             throw new Ice.CommunicatorDestroyedException();
678         }
679 
680         _referenceFactory = _referenceFactory.setDefaultRouter(router);
681     }
682 
683     public void
setLogger(Ice.Logger logger)684     setLogger(Ice.Logger logger)
685     {
686         //
687         // No locking, as it can only be called during plug-in loading
688         //
689         _initData.logger = logger;
690     }
691 
692     public void
setThreadHook(Ice.ThreadNotification threadHook)693     setThreadHook(Ice.ThreadNotification threadHook)
694     {
695         //
696         // No locking, as it can only be called during plug-in loading
697         //
698         _initData.threadHook = threadHook;
699     }
700 
701     public Class<?>
findClass(String className)702     findClass(String className)
703     {
704         return Util.findClass(className, _initData.classLoader);
705     }
706 
707     public ClassLoader
getClassLoader()708     getClassLoader()
709     {
710         return _initData.classLoader;
711     }
712 
713     //
714     // From Ice.ClassResolver.
715     //
resolveClass(String typeId)716     public Class<?> resolveClass(String typeId)
717         throws LinkageError
718     {
719         Class<?> c = null;
720 
721         //
722         // To convert a Slice type id into a Java class, we do the following:
723         //
724         // 1. Convert the Slice type id into a classname (e.g., ::M::X -> M.X).
725         // 2. If that fails, extract the top-level module (if any) from the type id
726         //    and check for an Package property. If found, prepend the property
727         //    value to the classname.
728         // 3. If that fails, check for an Default.Package property. If found,
729         //    prepend the property value to the classname.
730         //
731         String className;
732         boolean addClass = false;
733 
734         synchronized(this)
735         {
736             className = _typeToClassMap.get(typeId);
737         }
738 
739         if(className == null)
740         {
741             className = Ice.Util.typeIdToClass(typeId);
742             addClass = true;
743         }
744 
745         c = getConcreteClass(className);
746 
747         if(c == null)
748         {
749             int pos = typeId.indexOf(':', 2);
750             if(pos != -1)
751             {
752                 String topLevelModule = typeId.substring(2, pos);
753                 String pkg = _initData.properties.getProperty("Ice.Package." + topLevelModule);
754                 if(pkg.length() > 0)
755                 {
756                     c = getConcreteClass(pkg + "." + className);
757                 }
758             }
759         }
760 
761         if(c == null)
762         {
763             String pkg = _initData.properties.getProperty("Ice.Default.Package");
764             if(pkg.length() > 0)
765             {
766                 c = getConcreteClass(pkg + "." + className);
767             }
768         }
769 
770         if(c != null && addClass)
771         {
772             synchronized(this)
773             {
774                 className = c.getName();
775                 if(_typeToClassMap.containsKey(typeId))
776                 {
777                     assert(_typeToClassMap.get(typeId).equals(className));
778                 }
779                 else
780                 {
781                     _typeToClassMap.put(typeId, className);
782                 }
783             }
784         }
785 
786         return c;
787     }
788 
resolveCompactId(int compactId)789     public String resolveCompactId(int compactId)
790     {
791         String className = "IceCompactId.TypeId_" + Integer.toString(compactId);
792         Class<?> c = getConcreteClass(className);
793         if(c == null)
794         {
795             for(String pkg : _packages)
796             {
797                 c = getConcreteClass(pkg + "." + className);
798                 if(c != null)
799                 {
800                     break;
801                 }
802             }
803         }
804         if(c != null)
805         {
806             try
807             {
808                 return (String)c.getField("typeId").get(null);
809             }
810             catch(Exception ex)
811             {
812                 assert(false);
813             }
814         }
815         return "";
816     }
817 
getConcreteClass(String className)818     public Class<?> getConcreteClass(String className)
819         throws LinkageError
820     {
821         Class<?> c = findClass(className);
822 
823         if(c != null)
824         {
825             //
826             // Ensure the class is instantiable. The constants are
827             // defined in the JVM specification (0x200 = interface,
828             // 0x400 = abstract).
829             //
830             final int modifiers = c.getModifiers();
831             if((modifiers & 0x200) == 0 && (modifiers & 0x400) == 0)
832             {
833                 return c;
834             }
835         }
836 
837         return null;
838     }
839 
840     public boolean
useApplicationClassLoader()841     useApplicationClassLoader()
842     {
843         return _useApplicationClassLoader;
844     }
845 
846     public boolean
queueRequests()847     queueRequests()
848     {
849         return _queueExecutorService != null;
850     }
851 
852     synchronized public QueueExecutorService
getQueueExecutor()853     getQueueExecutor()
854     {
855         if(_state == StateDestroyed)
856         {
857             throw new Ice.CommunicatorDestroyedException();
858         }
859         return _queueExecutorService;
860     }
861 
862     //
863     // Only for use by Ice.CommunicatorI
864     //
865     public
Instance(Ice.Communicator communicator, Ice.InitializationData initData)866     Instance(Ice.Communicator communicator, Ice.InitializationData initData)
867     {
868         _state = StateActive;
869         _initData = initData;
870 
871         try
872         {
873             if(_initData.properties == null)
874             {
875                 _initData.properties = Ice.Util.createProperties();
876             }
877 
878             synchronized(Instance.class)
879             {
880                 if(!_oneOffDone)
881                 {
882                     String stdOut = _initData.properties.getProperty("Ice.StdOut");
883                     String stdErr = _initData.properties.getProperty("Ice.StdErr");
884 
885                     java.io.PrintStream outStream = null;
886 
887                     if(stdOut.length() > 0)
888                     {
889                         //
890                         // We need to close the existing stdout for JVM thread dump to go
891                         // to the new file
892                         //
893                         System.out.close();
894 
895                         try
896                         {
897                             outStream = new java.io.PrintStream(new java.io.FileOutputStream(stdOut, true));
898                         }
899                         catch(java.io.FileNotFoundException ex)
900                         {
901                             throw new Ice.FileException(0, stdOut, ex);
902                         }
903 
904                         System.setOut(outStream);
905                     }
906                     if(stdErr.length() > 0)
907                     {
908                         //
909                         // close for consistency with stdout
910                         //
911                         System.err.close();
912 
913                         if(stdErr.equals(stdOut))
914                         {
915                             System.setErr(outStream);
916                         }
917                         else
918                         {
919                             try
920                             {
921                                 System.setErr(new java.io.PrintStream(new java.io.FileOutputStream(stdErr, true)));
922                             }
923                             catch(java.io.FileNotFoundException ex)
924                             {
925                                 throw new Ice.FileException(0, stdErr, ex);
926                             }
927 
928                         }
929                     }
930                     _oneOffDone = true;
931                 }
932             }
933 
934             if(_initData.logger == null)
935             {
936                 String logfile = _initData.properties.getProperty("Ice.LogFile");
937                 if(_initData.properties.getPropertyAsInt("Ice.UseSyslog") > 0 &&
938                    !System.getProperty("os.name").startsWith("Windows"))
939                 {
940                     if(logfile.length() != 0)
941                     {
942                         throw new Ice.InitializationException("Both syslog and file logger cannot be enabled.");
943                     }
944                     _initData.logger = new Ice.SysLoggerI(_initData.properties.getProperty("Ice.ProgramName"),
945                                 _initData.properties.getPropertyWithDefault("Ice.SyslogFacility", "LOG_USER"));
946                 }
947                 else if(logfile.length() != 0)
948                 {
949                     _initData.logger = new Ice.LoggerI(_initData.properties.getProperty("Ice.ProgramName"), logfile);
950                 }
951                 else
952                 {
953                     _initData.logger = Ice.Util.getProcessLogger();
954                 }
955             }
956 
957             _packages = validatePackages();
958 
959             _useApplicationClassLoader = _initData.properties.getPropertyAsInt("Ice.UseApplicationClassLoader") > 0;
960 
961             _traceLevels = new TraceLevels(_initData.properties);
962 
963             _defaultsAndOverrides = new DefaultsAndOverrides(_initData.properties, _initData.logger);
964 
965             _clientACM = new ACMConfig(_initData.properties,
966                                        _initData.logger,
967                                        "Ice.ACM.Client",
968                                        new ACMConfig(_initData.properties, _initData.logger, "Ice.ACM",
969                                                      new ACMConfig(false)));
970 
971             _serverACM = new ACMConfig(_initData.properties,
972                                        _initData.logger,
973                                        "Ice.ACM.Server",
974                                        new ACMConfig(_initData.properties, _initData.logger, "Ice.ACM",
975                                                      new ACMConfig(true)));
976 
977             {
978                 final int defaultMessageSizeMax = 1024;
979                 int num = _initData.properties.getPropertyAsIntWithDefault("Ice.MessageSizeMax", defaultMessageSizeMax);
980                 if(num < 1 || num > 0x7fffffff / 1024)
981                 {
982                     _messageSizeMax = 0x7fffffff;
983                 }
984                 else
985                 {
986                     _messageSizeMax = num * 1024; // Property is in kilobytes, _messageSizeMax in bytes
987                 }
988             }
989 
990             if(_initData.properties.getProperty("Ice.BatchAutoFlushSize").isEmpty() &&
991                !_initData.properties.getProperty("Ice.BatchAutoFlush").isEmpty())
992             {
993                 if(_initData.properties.getPropertyAsInt("Ice.BatchAutoFlush") > 0)
994                 {
995                     _batchAutoFlushSize = _messageSizeMax;
996                 }
997                 else
998                 {
999                     _batchAutoFlushSize = 0;
1000                 }
1001             }
1002             else
1003             {
1004                 int num = _initData.properties.getPropertyAsIntWithDefault("Ice.BatchAutoFlushSize", 1024); // 1MB
1005                 if(num < 1)
1006                 {
1007                     _batchAutoFlushSize = num;
1008                 }
1009                 else if(num > 0x7fffffff / 1024)
1010                 {
1011                     _batchAutoFlushSize = 0x7fffffff;
1012                 }
1013                 else
1014                 {
1015                     _batchAutoFlushSize = num * 1024; // Property is in kilobytes, _batchAutoFlushSize in bytes
1016                 }
1017             }
1018 
1019             String toStringModeStr = _initData.properties.getPropertyWithDefault("Ice.ToStringMode", "Unicode");
1020             if(toStringModeStr.equals("Unicode"))
1021             {
1022                 _toStringMode = Ice.ToStringMode.Unicode;
1023             }
1024             else if(toStringModeStr.equals("ASCII"))
1025             {
1026                 _toStringMode = Ice.ToStringMode.ASCII;
1027             }
1028             else if(toStringModeStr.equals("Compat"))
1029             {
1030                 _toStringMode = Ice.ToStringMode.Compat;
1031             }
1032             else
1033             {
1034                 throw new Ice.InitializationException("The value for Ice.ToStringMode must be Unicode, ASCII or Compat");
1035             }
1036 
1037             _implicitContext = Ice.ImplicitContextI.create(_initData.properties.getProperty("Ice.ImplicitContext"));
1038 
1039             _routerManager = new RouterManager();
1040 
1041             _locatorManager = new LocatorManager(_initData.properties);
1042 
1043             _referenceFactory = new ReferenceFactory(this, communicator);
1044 
1045             _requestHandlerFactory = new RequestHandlerFactory(this);
1046 
1047             _proxyFactory = new ProxyFactory(this);
1048 
1049             boolean isIPv6Supported = Network.isIPv6Supported();
1050             boolean ipv4 = _initData.properties.getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0;
1051             boolean ipv6 = _initData.properties.getPropertyAsIntWithDefault("Ice.IPv6", isIPv6Supported ? 1 : 0) > 0;
1052             if(!ipv4 && !ipv6)
1053             {
1054                 throw new Ice.InitializationException("Both IPV4 and IPv6 support cannot be disabled.");
1055             }
1056             else if(ipv4 && ipv6)
1057             {
1058                 _protocolSupport = Network.EnableBoth;
1059             }
1060             else if(ipv4)
1061             {
1062                 _protocolSupport = Network.EnableIPv4;
1063             }
1064             else
1065             {
1066                 _protocolSupport = Network.EnableIPv6;
1067             }
1068             _preferIPv6 = _initData.properties.getPropertyAsInt("Ice.PreferIPv6Address") > 0;
1069 
1070             _networkProxy = createNetworkProxy(_initData.properties, _protocolSupport);
1071 
1072             _endpointFactoryManager = new EndpointFactoryManager(this);
1073 
1074             ProtocolInstance tcpProtocolInstance = new ProtocolInstance(this, Ice.TCPEndpointType.value, "tcp", false);
1075             _endpointFactoryManager.add(new TcpEndpointFactory(tcpProtocolInstance));
1076 
1077             ProtocolInstance udpProtocolInstance = new ProtocolInstance(this, Ice.UDPEndpointType.value, "udp", false);
1078             _endpointFactoryManager.add(new UdpEndpointFactory(udpProtocolInstance));
1079 
1080             ProtocolInstance wsProtocolInstance = new ProtocolInstance(this, Ice.WSEndpointType.value, "ws", false);
1081             _endpointFactoryManager.add(new WSEndpointFactory(wsProtocolInstance, Ice.TCPEndpointType.value));
1082 
1083             ProtocolInstance wssProtocolInstance = new ProtocolInstance(this, Ice.WSSEndpointType.value, "wss", true);
1084             _endpointFactoryManager.add(new WSEndpointFactory(wssProtocolInstance, Ice.SSLEndpointType.value));
1085 
1086             _pluginManager = new Ice.PluginManagerI(communicator, this);
1087 
1088             if(_initData.valueFactoryManager == null)
1089             {
1090                 _initData.valueFactoryManager = new ValueFactoryManagerI();
1091             }
1092 
1093             _outgoingConnectionFactory = new OutgoingConnectionFactory(communicator, this);
1094 
1095             _objectAdapterFactory = new ObjectAdapterFactory(this, communicator);
1096 
1097             _retryQueue = new RetryQueue(this);
1098 
1099             //
1100             // If Ice.ThreadInterruptSafe is set or we're running on Android all
1101             // IO is done on the background thread. For Android we use the queue
1102             // executor as Android doesn't allow any network invocations on the main
1103             // thread even if the call is non-blocking.
1104             //
1105             if(_initData.properties.getPropertyAsInt("Ice.ThreadInterruptSafe") > 0 || Util.isAndroid())
1106             {
1107                 _queueExecutor = new QueueExecutor(_initData.properties,
1108                                                    Util.createThreadName(_initData.properties, "Ice.BackgroundIO"));
1109                 _queueExecutorService = new QueueExecutorService(_queueExecutor);
1110 
1111                 // Caching message buffers is not supported with background IO.
1112                 _cacheMessageBuffers = 0;
1113             }
1114             else
1115             {
1116                 _cacheMessageBuffers = _initData.properties.getPropertyAsIntWithDefault("Ice.CacheMessageBuffers", 2);
1117             }
1118         }
1119         catch(Ice.LocalException ex)
1120         {
1121             destroy(false);
1122             throw ex;
1123         }
1124     }
1125 
1126     @SuppressWarnings("deprecation")
1127     @Override
1128     protected synchronized void
finalize()1129     finalize()
1130         throws Throwable
1131     {
1132         try
1133         {
1134             IceUtilInternal.Assert.FinalizerAssert(_state == StateDestroyed);
1135             IceUtilInternal.Assert.FinalizerAssert(_referenceFactory == null);
1136             IceUtilInternal.Assert.FinalizerAssert(_requestHandlerFactory == null);
1137             IceUtilInternal.Assert.FinalizerAssert(_proxyFactory == null);
1138             IceUtilInternal.Assert.FinalizerAssert(_outgoingConnectionFactory == null);
1139             IceUtilInternal.Assert.FinalizerAssert(_objectAdapterFactory == null);
1140             IceUtilInternal.Assert.FinalizerAssert(_clientThreadPool == null);
1141             IceUtilInternal.Assert.FinalizerAssert(_serverThreadPool == null);
1142             IceUtilInternal.Assert.FinalizerAssert(_endpointHostResolver == null);
1143             IceUtilInternal.Assert.FinalizerAssert(_timer == null);
1144             IceUtilInternal.Assert.FinalizerAssert(_routerManager == null);
1145             IceUtilInternal.Assert.FinalizerAssert(_locatorManager == null);
1146             IceUtilInternal.Assert.FinalizerAssert(_endpointFactoryManager == null);
1147             IceUtilInternal.Assert.FinalizerAssert(_pluginManager == null);
1148             IceUtilInternal.Assert.FinalizerAssert(_retryQueue == null);
1149         }
1150         catch(java.lang.Exception ex)
1151         {
1152         }
1153         finally
1154         {
1155             super.finalize();
1156         }
1157     }
1158 
1159     public void
finishSetup(Ice.StringSeqHolder args, Ice.Communicator communicator)1160     finishSetup(Ice.StringSeqHolder args, Ice.Communicator communicator)
1161     {
1162         //
1163         // Load plug-ins.
1164         //
1165         assert(_serverThreadPool == null);
1166         Ice.PluginManagerI pluginManagerImpl = (Ice.PluginManagerI)_pluginManager;
1167         pluginManagerImpl.loadPlugins(args);
1168 
1169         //
1170         // Initialize the endpoint factories once all the plugins are loaded. This gives
1171         // the opportunity for the endpoint factories to find underyling factories.
1172         //
1173         _endpointFactoryManager.initialize();
1174 
1175         //
1176         // Create Admin facets, if enabled.
1177         //
1178         // Note that any logger-dependent admin facet must be created after we load all plugins,
1179         // since one of these plugins can be a Logger plugin that sets a new logger during loading
1180         //
1181 
1182         if(_initData.properties.getProperty("Ice.Admin.Enabled").isEmpty())
1183         {
1184             _adminEnabled = !_initData.properties.getProperty("Ice.Admin.Endpoints").isEmpty();
1185         }
1186         else
1187         {
1188             _adminEnabled = _initData.properties.getPropertyAsInt("Ice.Admin.Enabled") > 0;
1189         }
1190 
1191         String[] facetFilter = _initData.properties.getPropertyAsList("Ice.Admin.Facets");
1192         if(facetFilter.length > 0)
1193         {
1194             _adminFacetFilter.addAll(java.util.Arrays.asList(facetFilter));
1195         }
1196 
1197         if(_adminEnabled)
1198         {
1199             //
1200             // Process facet
1201             //
1202             String processFacetName = "Process";
1203             if(_adminFacetFilter.isEmpty() || _adminFacetFilter.contains(processFacetName))
1204             {
1205                 _adminFacets.put(processFacetName, new ProcessI(communicator));
1206             }
1207 
1208             //
1209             // Logger facet
1210             //
1211             String loggerFacetName = "Logger";
1212             if(_adminFacetFilter.isEmpty() || _adminFacetFilter.contains(loggerFacetName))
1213             {
1214                 LoggerAdminLogger logger = new LoggerAdminLoggerI(_initData.properties, _initData.logger);
1215                 setLogger(logger);
1216                 _adminFacets.put(loggerFacetName, logger.getFacet());
1217             }
1218 
1219             //
1220             // Properties facet
1221             //
1222             String propertiesFacetName = "Properties";
1223             PropertiesAdminI propsAdmin = null;
1224             if(_adminFacetFilter.isEmpty() || _adminFacetFilter.contains(propertiesFacetName))
1225             {
1226                 propsAdmin = new PropertiesAdminI(this);
1227                 _adminFacets.put(propertiesFacetName, propsAdmin);
1228             }
1229 
1230             //
1231             // Metrics facet
1232             //
1233             String metricsFacetName = "Metrics";
1234             if(_adminFacetFilter.isEmpty() || _adminFacetFilter.contains(metricsFacetName))
1235             {
1236                  CommunicatorObserverI observer = new CommunicatorObserverI(_initData);
1237                  _initData.observer = observer;
1238                  _adminFacets.put(metricsFacetName, observer.getFacet());
1239 
1240                  //
1241                  // Make sure the admin plugin receives property updates.
1242                  //
1243                  if(propsAdmin != null)
1244                  {
1245                      propsAdmin.addUpdateCallback(observer.getFacet());
1246                  }
1247             }
1248         }
1249 
1250         //
1251         // Set observer updater
1252         //
1253         if(_initData.observer != null)
1254         {
1255             _initData.observer.setObserverUpdater(new ObserverUpdaterI());
1256         }
1257 
1258         //
1259         // Create threads.
1260         //
1261         try
1262         {
1263             _timer = new Timer(_initData.properties, Util.createThreadName(_initData.properties, "Ice.Timer"));
1264         }
1265         catch(RuntimeException ex)
1266         {
1267             String s = "cannot create thread for timer:\n" + Ex.toString(ex);
1268             _initData.logger.error(s);
1269             throw ex;
1270         }
1271 
1272         try
1273         {
1274             _endpointHostResolver = new EndpointHostResolver(this);
1275         }
1276         catch(RuntimeException ex)
1277         {
1278             String s = "cannot create thread for endpoint host resolver:\n" + Ex.toString(ex);
1279             _initData.logger.error(s);
1280             throw ex;
1281         }
1282 
1283         _clientThreadPool = new ThreadPool(this, "Ice.ThreadPool.Client", 0);
1284 
1285         //
1286         // The default router/locator may have been set during the loading of plugins.
1287         // Therefore we make sure it is not already set before checking the property.
1288         //
1289         if(_referenceFactory.getDefaultRouter() == null)
1290         {
1291             Ice.RouterPrx router =
1292                 Ice.RouterPrxHelper.uncheckedCast(_proxyFactory.propertyToProxy("Ice.Default.Router"));
1293             if(router != null)
1294             {
1295                 _referenceFactory = _referenceFactory.setDefaultRouter(router);
1296             }
1297         }
1298 
1299         if(_referenceFactory.getDefaultLocator() == null)
1300         {
1301             Ice.LocatorPrx loc =
1302                 Ice.LocatorPrxHelper.uncheckedCast(_proxyFactory.propertyToProxy("Ice.Default.Locator"));
1303             if(loc != null)
1304             {
1305                 _referenceFactory = _referenceFactory.setDefaultLocator(loc);
1306             }
1307         }
1308 
1309         //
1310         // Server thread pool initialization is lazy in serverThreadPool().
1311         //
1312 
1313         //
1314         // An application can set Ice.InitPlugins=0 if it wants to postpone
1315         // initialization until after it has interacted directly with the
1316         // plug-ins.
1317         //
1318         if(_initData.properties.getPropertyAsIntWithDefault("Ice.InitPlugins", 1) > 0)
1319         {
1320             pluginManagerImpl.initializePlugins();
1321         }
1322 
1323         //
1324         // This must be done last as this call creates the Ice.Admin object adapter
1325         // and eventually registers a process proxy with the Ice locator (allowing
1326         // remote clients to invoke on Ice.Admin facets as soon as it's registered).
1327         //
1328         if(_initData.properties.getPropertyAsIntWithDefault("Ice.Admin.DelayCreation", 0) <= 0)
1329         {
1330             getAdmin();
1331         }
1332     }
1333 
1334     //
1335     // Only for use by Ice.CommunicatorI
1336     //
1337     @SuppressWarnings("deprecation")
1338     public void
destroy(boolean interruptible)1339     destroy(boolean interruptible)
1340     {
1341         if(interruptible && Thread.interrupted())
1342         {
1343             throw new Ice.OperationInterruptedException();
1344         }
1345 
1346         synchronized(this)
1347         {
1348             //
1349             // If destroy is in progress, wait for it to be done. This
1350             // is necessary in case destroy() is called concurrently
1351             // by multiple threads.
1352             //
1353             while(_state == StateDestroyInProgress)
1354             {
1355                 try
1356                 {
1357                     wait();
1358                 }
1359                 catch(InterruptedException ex)
1360                 {
1361                     if(interruptible)
1362                     {
1363                         throw new Ice.OperationInterruptedException();
1364                     }
1365                 }
1366             }
1367 
1368             if(_state == StateDestroyed)
1369             {
1370                 return;
1371             }
1372             _state = StateDestroyInProgress;
1373         }
1374 
1375         try
1376         {
1377             //
1378             // Shutdown and destroy all the incoming and outgoing Ice
1379             // connections and wait for the connections to be finished.
1380             //
1381             if(_objectAdapterFactory != null)
1382             {
1383                 _objectAdapterFactory.shutdown();
1384             }
1385 
1386             if(_outgoingConnectionFactory != null)
1387             {
1388                 _outgoingConnectionFactory.destroy();
1389             }
1390 
1391             if(_objectAdapterFactory != null)
1392             {
1393                 _objectAdapterFactory.destroy();
1394             }
1395 
1396             if(_outgoingConnectionFactory != null)
1397             {
1398                 _outgoingConnectionFactory.waitUntilFinished();
1399             }
1400 
1401             if(_retryQueue != null)
1402             {
1403                 _retryQueue.destroy(); // Must be called before destroying thread pools.
1404             }
1405 
1406             if(_initData.observer != null)
1407             {
1408                 _initData.observer.setObserverUpdater(null);
1409             }
1410 
1411             if(_initData.logger instanceof LoggerAdminLogger)
1412             {
1413                 //
1414                 // This only disables the remote logging; we don't set or reset _initData.logger
1415                 //
1416                 ((LoggerAdminLogger)_initData.logger).destroy();
1417             }
1418 
1419             //
1420             // Now, destroy the thread pools. This must be done *only* after
1421             // all the connections are finished (the connections destruction
1422             // can require invoking callbacks with the thread pools).
1423             //
1424             if(_serverThreadPool != null)
1425             {
1426                 _serverThreadPool.destroy();
1427             }
1428             if(_clientThreadPool != null)
1429             {
1430                 _clientThreadPool.destroy();
1431             }
1432             if(_endpointHostResolver != null)
1433             {
1434                 _endpointHostResolver.destroy();
1435             }
1436             if(_timer != null)
1437             {
1438                 _timer.shutdown(); // Don't use shutdownNow(), timers don't support interrupts
1439             }
1440 
1441             //
1442             // Wait for all the threads to be finished.
1443             //
1444             try
1445             {
1446                 if(_clientThreadPool != null)
1447                 {
1448                     _clientThreadPool.joinWithAllThreads();
1449                 }
1450                 if(_serverThreadPool != null)
1451                 {
1452                     _serverThreadPool.joinWithAllThreads();
1453                 }
1454                 if(_endpointHostResolver != null)
1455                 {
1456                     _endpointHostResolver.joinWithThread();
1457                 }
1458                 if(_queueExecutor != null)
1459                 {
1460                     _queueExecutor.destroy();
1461                 }
1462                 if(_timer != null)
1463                 {
1464                     while(!_timer.isTerminated())
1465                     {
1466                         // A very long time.
1467                         _timer.awaitTermination(100000, java.util.concurrent.TimeUnit.SECONDS);
1468                     }
1469                 }
1470             }
1471             catch(InterruptedException ex)
1472             {
1473                 if(interruptible)
1474                 {
1475                     throw new Ice.OperationInterruptedException();
1476                 }
1477             }
1478 
1479             //
1480             // NOTE: at this point destroy() can't be interrupted
1481             // anymore. The calls below are therefore guaranteed to be
1482             // called once.
1483             //
1484 
1485             for(Ice.ObjectFactory f : _objectFactoryMap.values())
1486             {
1487                 f.destroy();
1488             }
1489             _objectFactoryMap.clear();
1490 
1491             if(_routerManager != null)
1492             {
1493                 _routerManager.destroy();
1494             }
1495 
1496             if(_locatorManager != null)
1497             {
1498                 _locatorManager.destroy();
1499             }
1500 
1501             if(_endpointFactoryManager != null)
1502             {
1503                 _endpointFactoryManager.destroy();
1504             }
1505 
1506             if(_initData.properties.getPropertyAsInt("Ice.Warn.UnusedProperties") > 0)
1507             {
1508                 java.util.List<String> unusedProperties = ((Ice.PropertiesI)_initData.properties).getUnusedProperties();
1509                 if(unusedProperties.size() != 0)
1510                 {
1511                     StringBuilder message = new StringBuilder("The following properties were set but never read:");
1512                     for(String p : unusedProperties)
1513                     {
1514                         message.append("\n    ");
1515                         message.append(p);
1516                     }
1517                     _initData.logger.warning(message.toString());
1518                 }
1519             }
1520 
1521             //
1522             // Destroy last so that a Logger plugin can receive all log/traces before its destruction.
1523             //
1524             if(_pluginManager != null)
1525             {
1526                 _pluginManager.destroy();
1527             }
1528 
1529             if(_initData.logger instanceof Ice.LoggerI)
1530             {
1531                 Ice.LoggerI logger = (Ice.LoggerI)_initData.logger;
1532                 logger.destroy();
1533             }
1534 
1535             synchronized(this)
1536             {
1537                 _objectAdapterFactory = null;
1538                 _outgoingConnectionFactory = null;
1539                 _retryQueue = null;
1540 
1541                 _serverThreadPool = null;
1542                 _clientThreadPool = null;
1543                 _endpointHostResolver = null;
1544                 _timer = null;
1545 
1546                 _referenceFactory = null;
1547                 _requestHandlerFactory = null;
1548                 _proxyFactory = null;
1549                 _routerManager = null;
1550                 _locatorManager = null;
1551                 _endpointFactoryManager = null;
1552 
1553                 _pluginManager = null;
1554 
1555                 _adminAdapter = null;
1556                 _adminFacets.clear();
1557 
1558                 _queueExecutor = null;
1559                 _queueExecutorService = null;
1560 
1561                 _typeToClassMap.clear();
1562 
1563                 _state = StateDestroyed;
1564                 notifyAll();
1565             }
1566         }
1567         finally
1568         {
1569             synchronized(this)
1570             {
1571                 if(_state == StateDestroyInProgress)
1572                 {
1573                     assert(interruptible);
1574                     _state = StateActive;
1575                     notifyAll();
1576                 }
1577             }
1578         }
1579     }
1580 
getBufSizeWarn(short type)1581     public BufSizeWarnInfo getBufSizeWarn(short type)
1582     {
1583         synchronized(_setBufSizeWarn)
1584         {
1585             BufSizeWarnInfo info;
1586             if(!_setBufSizeWarn.containsKey(type))
1587             {
1588                 info = new BufSizeWarnInfo();
1589                 info.sndWarn = false;
1590                 info.sndSize = -1;
1591                 info.rcvWarn = false;
1592                 info.rcvSize = -1;
1593                 _setBufSizeWarn.put(type, info);
1594             }
1595             else
1596             {
1597                 info = _setBufSizeWarn.get(type);
1598             }
1599             return info;
1600         }
1601     }
1602 
setSndBufSizeWarn(short type, int size)1603     public void setSndBufSizeWarn(short type, int size)
1604     {
1605         synchronized(_setBufSizeWarn)
1606         {
1607             BufSizeWarnInfo info = getBufSizeWarn(type);
1608             info.sndWarn = true;
1609             info.sndSize = size;
1610             _setBufSizeWarn.put(type, info);
1611         }
1612     }
1613 
setRcvBufSizeWarn(short type, int size)1614     public void setRcvBufSizeWarn(short type, int size)
1615     {
1616         synchronized(_setBufSizeWarn)
1617         {
1618             BufSizeWarnInfo info = getBufSizeWarn(type);
1619             info.rcvWarn = true;
1620             info.rcvSize = size;
1621             _setBufSizeWarn.put(type, info);
1622         }
1623     }
1624 
1625     @SuppressWarnings("deprecation")
addObjectFactory(final Ice.ObjectFactory factory, String id)1626     public synchronized void addObjectFactory(final Ice.ObjectFactory factory, String id)
1627     {
1628         //
1629         // Create a ValueFactory wrapper around the given ObjectFactory and register the wrapper
1630         // with the value factory manager. This may raise AlreadyRegisteredException.
1631         //
1632         _initData.valueFactoryManager.add(
1633             new Ice.ValueFactory()
1634             {
1635                 public Ice.Object create(String id)
1636                 {
1637                     return factory.create(id);
1638                 }
1639             }, id);
1640 
1641         _objectFactoryMap.put(id, factory);
1642     }
1643 
1644     @SuppressWarnings("deprecation")
findObjectFactory(String id)1645     public synchronized Ice.ObjectFactory findObjectFactory(String id)
1646     {
1647         return _objectFactoryMap.get(id);
1648     }
1649 
1650     private void
updateConnectionObservers()1651     updateConnectionObservers()
1652     {
1653         try
1654         {
1655             assert(_outgoingConnectionFactory != null);
1656             _outgoingConnectionFactory.updateConnectionObservers();
1657             assert(_objectAdapterFactory != null);
1658             _objectAdapterFactory.updateConnectionObservers();
1659         }
1660         catch(Ice.CommunicatorDestroyedException ex)
1661         {
1662         }
1663     }
1664 
1665     private void
updateThreadObservers()1666     updateThreadObservers()
1667     {
1668         try
1669         {
1670             if(_clientThreadPool != null)
1671             {
1672                 _clientThreadPool.updateObservers();
1673             }
1674             if(_serverThreadPool != null)
1675             {
1676                 _serverThreadPool.updateObservers();
1677             }
1678             assert(_objectAdapterFactory != null);
1679             _objectAdapterFactory.updateThreadObservers();
1680             if(_endpointHostResolver != null)
1681             {
1682                 _endpointHostResolver.updateObserver();
1683             }
1684             if(_timer != null)
1685             {
1686                 _timer.updateObserver(_initData.observer);
1687             }
1688             if(_queueExecutor != null)
1689             {
1690                 _queueExecutor.updateObserver(_initData.observer);
1691             }
1692         }
1693         catch(Ice.CommunicatorDestroyedException ex)
1694         {
1695         }
1696     }
1697 
1698     private String[]
validatePackages()1699     validatePackages()
1700     {
1701         final String prefix = "Ice.Package.";
1702         java.util.Map<String, String> map = _initData.properties.getPropertiesForPrefix(prefix);
1703         java.util.List<String> packages = new java.util.ArrayList<String>();
1704         for(java.util.Map.Entry<String, String> p : map.entrySet())
1705         {
1706             String key = p.getKey();
1707             String pkg = p.getValue();
1708             if(key.length() == prefix.length())
1709             {
1710                 _initData.logger.warning("ignoring invalid property: " + key + "=" + pkg);
1711             }
1712             String module = key.substring(prefix.length());
1713             String className = pkg + "." + module + "._Marker";
1714             Class<?> cls = null;
1715             try
1716             {
1717                 cls = findClass(className);
1718             }
1719             catch(java.lang.Exception ex)
1720             {
1721             }
1722             if(cls == null)
1723             {
1724                 _initData.logger.warning("unable to validate package: " + key + "=" + pkg);
1725             }
1726             else
1727             {
1728                 packages.add(pkg);
1729             }
1730         }
1731 
1732         String pkg = _initData.properties.getProperty("Ice.Default.Package");
1733         if(pkg.length() > 0)
1734         {
1735             packages.add(pkg);
1736         }
1737         return packages.toArray(new String[packages.size()]);
1738     }
1739 
1740     private synchronized void
addAllAdminFacets()1741     addAllAdminFacets()
1742     {
1743         java.util.Map<String, Ice.Object> filteredFacets = new java.util.HashMap<String, Ice.Object>();
1744         for(java.util.Map.Entry<String, Ice.Object> p : _adminFacets.entrySet())
1745         {
1746             if(_adminFacetFilter.isEmpty() || _adminFacetFilter.contains(p.getKey()))
1747             {
1748                 _adminAdapter.addFacet(p.getValue(), _adminIdentity, p.getKey());
1749             }
1750             else
1751             {
1752                 filteredFacets.put(p.getKey(), p.getValue());
1753             }
1754         }
1755         _adminFacets = filteredFacets;
1756     }
1757 
1758     private void
setServerProcessProxy(Ice.ObjectAdapter adminAdapter, Ice.Identity adminIdentity)1759     setServerProcessProxy(Ice.ObjectAdapter adminAdapter, Ice.Identity adminIdentity)
1760     {
1761         Ice.ObjectPrx admin = adminAdapter.createProxy(adminIdentity);
1762         Ice.LocatorPrx locator = adminAdapter.getLocator();
1763         String serverId = _initData.properties.getProperty("Ice.Admin.ServerId");
1764 
1765         if(locator != null && !serverId.isEmpty())
1766         {
1767             Ice.ProcessPrx process = Ice.ProcessPrxHelper.uncheckedCast(admin.ice_facet("Process"));
1768             try
1769             {
1770                 //
1771                 // Note that as soon as the process proxy is registered, the communicator might be
1772                 // shutdown by a remote client and admin facets might start receiving calls.
1773                 //
1774                 locator.getRegistry().setServerProcessProxy(serverId, process);
1775             }
1776             catch(Ice.ServerNotFoundException ex)
1777             {
1778                 if(_traceLevels.location >= 1)
1779                 {
1780                     StringBuilder s = new StringBuilder(128);
1781                     s.append("couldn't register server `");
1782                     s.append(serverId);
1783                     s.append("' with the locator registry:\n");
1784                     s.append("the server is not known to the locator registry");
1785                     _initData.logger.trace(_traceLevels.locationCat, s.toString());
1786                 }
1787 
1788                 throw new Ice.InitializationException("Locator knows nothing about server `" + serverId + "'");
1789             }
1790             catch(Ice.LocalException ex)
1791             {
1792                 if(_traceLevels.location >= 1)
1793                 {
1794                     StringBuilder s = new StringBuilder(128);
1795                     s.append("couldn't register server `");
1796                     s.append(serverId);
1797                     s.append("' with the locator registry:\n");
1798                     s.append(ex.toString());
1799                     _initData.logger.trace(_traceLevels.locationCat, s.toString());
1800                 }
1801                 throw ex;
1802             }
1803 
1804             if(_traceLevels.location >= 1)
1805             {
1806                 StringBuilder s = new StringBuilder(128);
1807                 s.append("registered server `");
1808                 s.append(serverId);
1809                 s.append("' with the locator registry");
1810                 _initData.logger.trace(_traceLevels.locationCat, s.toString());
1811             }
1812         }
1813     }
1814 
createNetworkProxy(Ice.Properties properties, int protocolSupport)1815     private NetworkProxy createNetworkProxy(Ice.Properties properties, int protocolSupport)
1816     {
1817         String proxyHost;
1818 
1819         proxyHost = properties.getProperty("Ice.SOCKSProxyHost");
1820         if(!proxyHost.isEmpty())
1821         {
1822             if(protocolSupport == Network.EnableIPv6)
1823             {
1824                 throw new Ice.InitializationException("IPv6 only is not supported with SOCKS4 proxies");
1825             }
1826             int proxyPort = properties.getPropertyAsIntWithDefault("Ice.SOCKSProxyPort", 1080);
1827             return new SOCKSNetworkProxy(proxyHost, proxyPort);
1828         }
1829 
1830         proxyHost = properties.getProperty("Ice.HTTPProxyHost");
1831         if(!proxyHost.isEmpty())
1832         {
1833             return new HTTPNetworkProxy(proxyHost, properties.getPropertyAsIntWithDefault("Ice.HTTPProxyPort", 1080));
1834         }
1835 
1836         return null;
1837     }
1838 
1839     private static final int StateActive = 0;
1840     private static final int StateDestroyInProgress = 1;
1841     private static final int StateDestroyed = 2;
1842     private int _state;
1843 
1844     private final Ice.InitializationData _initData; // Immutable, not reset by destroy().
1845     private final TraceLevels _traceLevels; // Immutable, not reset by destroy().
1846     private final DefaultsAndOverrides _defaultsAndOverrides; // Immutable, not reset by destroy().
1847     private final int _messageSizeMax; // Immutable, not reset by destroy().
1848     private final int _batchAutoFlushSize; // Immutable, not reset by destroy().
1849     private final Ice.ToStringMode _toStringMode; // Immutable, not reset by destroy().
1850     private final int _cacheMessageBuffers; // Immutable, not reset by destroy().
1851     private final ACMConfig _clientACM; // Immutable, not reset by destroy().
1852     private final ACMConfig _serverACM; // Immutable, not reset by destroy().
1853     private final Ice.ImplicitContextI _implicitContext;
1854     private RouterManager _routerManager;
1855     private LocatorManager _locatorManager;
1856     private ReferenceFactory _referenceFactory;
1857     private RequestHandlerFactory _requestHandlerFactory;
1858     private ProxyFactory _proxyFactory;
1859     private OutgoingConnectionFactory _outgoingConnectionFactory;
1860     private ObjectAdapterFactory _objectAdapterFactory;
1861     private int _protocolSupport;
1862     private boolean _preferIPv6;
1863     private NetworkProxy _networkProxy;
1864     private ThreadPool _clientThreadPool;
1865     private ThreadPool _serverThreadPool;
1866     private EndpointHostResolver _endpointHostResolver;
1867     private RetryQueue _retryQueue;
1868     private Timer _timer;
1869     private EndpointFactoryManager _endpointFactoryManager;
1870     private Ice.PluginManager _pluginManager;
1871 
1872     private boolean _adminEnabled = false;
1873     private Ice.ObjectAdapter _adminAdapter;
1874     private java.util.Map<String, Ice.Object> _adminFacets = new java.util.HashMap<String, Ice.Object>();
1875     private java.util.Set<String> _adminFacetFilter = new java.util.HashSet<String>();
1876     private Ice.Identity _adminIdentity;
1877     private java.util.Map<Short, BufSizeWarnInfo> _setBufSizeWarn = new java.util.HashMap<Short, BufSizeWarnInfo>();
1878 
1879     private java.util.Map<String, String> _typeToClassMap = new java.util.HashMap<String, String>();
1880     final private String[] _packages;
1881     final private boolean _useApplicationClassLoader;
1882 
1883     private static boolean _oneOffDone = false;
1884     private QueueExecutorService _queueExecutorService;
1885     private QueueExecutor _queueExecutor;
1886 
1887     @SuppressWarnings("deprecation")
1888     private java.util.HashMap<String, Ice.ObjectFactory> _objectFactoryMap =
1889         new java.util.HashMap<String, Ice.ObjectFactory>();
1890 }
1891