Пример #1
0
 public RemoteObjectAdapterI(Ice.ObjectAdapter adapter)
 {
     _adapter = adapter;
     _testIntf = TestIntfPrxHelper.uncheckedCast(_adapter.add(new TestI(),
                                                 Ice.Util.stringToIdentity("test")));
     _adapter.activate();
 }
Пример #2
0
 static minie_backend_client()
 {
     string[] parray = new string[] {"--Ice.Plugin.IceSSL=IceSSL.dll:IceSSL.PluginFactory",
         "--IceSSL.DefaultDir=.",
         "--IceSSL.CAs=root.pem",
         "--IceSSL.CertFile=client.p12",
         "--IceSSL.VerifyPeer=2",
         "--Ice.ThreadPool.Server.SizeMax=8",
         "--Ice.ThreadPool.Client.SizeMax=16",
         "--Ice.MessageSizeMax=10485760",
         "--Ice.Override.ConnectTimeout=5000",
         "--Ice.Override.Timeout=5000"};
     //Ice.InitializationData inid = new Ice.InitializationData();
     //inid.properties = Ice.Util.createProperties();
     //inid.properties.setProperty("Ice.Plugin.IceSSL", "IceSSL.dll:IceSSL.PluginFactory");
     //inid.properties.setProperty("IceSSL.DefaultDir", ".");
     //inid.properties.setProperty("IceSSL.CAs", "root.pem");
     //inid.properties.setProperty("IceSSL.CertFile", "client.p12");
     //inid.properties.setProperty("IceSSL.VerifyPeer", "2");
     //inid.properties.setProperty("Ice.ThreadPool.Server.SizeMax", "8");
     //inid.properties.setProperty("Ice.ThreadPool.Client.SizeMax", "16");
     //inid.properties.setProperty("Ice.MessageSizeMax", "10485760");
     //inid.properties.setProperty("Ice.Override.ConnectTimeout", "5000");
     //inid.properties.setProperty("Ice.Override.Timeout", "5000");
     s_ic = Ice.Util.initialize(ref parray);
     s_adapter = s_ic.createObjectAdapter("");
     s_adapter.activate();
 }
Пример #3
0
    internal TestI(Ice.ObjectAdapter adapter1, Ice.ObjectAdapter adapter2, ServerLocatorRegistry registry)
    {
        _adapter1 = adapter1;
        _adapter2 = adapter2;
        _registry = registry;

        _registry.addObject(_adapter1.add(new HelloI(), adapter1.getCommunicator().stringToIdentity("hello")));
    }
Пример #4
0
    public void start(string name, Ice.Communicator communicator, string[] args)
    {
        _adapter = communicator.createObjectAdapter("Hello-" + name);

        string helloIdentity = communicator.getProperties().getProperty("Hello.Identity");
        _adapter.add(new HelloI(name), Ice.Util.stringToIdentity(helloIdentity));
        _adapter.activate();
    }
Пример #5
0
        public static Ice.ObjectAdapter createAdapter(
        Ice.Communicator ic, string adapterName, uint port)
        {
            instance = ic.createObjectAdapterWithEndpoints(
            adapterName, "default -p " + port);
            instance.activate();

            return instance;
        }
Пример #6
0
    public InitialI(Ice.ObjectAdapter adapter)
    {
        _adapter = adapter;
        _b1 = new BI();
        _b2 = new BI();
        _c = new CI();
        _d = new DI();
        _e = new EI();
        _f = new FI(_e);

        _b1.theA = _b2; // Cyclic reference to another B
        _b1.theB = _b1; // Self reference.
        _b1.theC = null; // Null reference.

        _b2.theA = _b2; // Self reference, using base.
        _b2.theB = _b1; // Cyclic reference to another B
        _b2.theC = _c; // Cyclic reference to a C.

        _c.theB = _b2; // Cyclic reference to a B.

        _d.theA = _b1; // Reference to a B.
        _d.theB = _b2; // Reference to a B.
        _d.theC = null; // Reference to a C.
    }
Пример #7
0
        private bool doMain(string[] args, Ice.InitializationData initData, out int status)
        {
            //
            // Reset internal state variables from Ice.Application. The
            // remainder are reset at the end of this method.
            //
            callbackInProgress__ = false;
            destroyed__ = false;
            interrupted__ = false;

            bool restart = false;
            status = 0;

            try
            {
            communicator__ = Ice.Util.initialize(ref args, initData);

            _router = Glacier2.RouterPrxHelper.uncheckedCast(communicator().getDefaultRouter());
            if(_router == null)
            {
                Ice.Util.getProcessLogger().error(appName__ + ": no Glacier2 router configured");
                status = 1;
            }
            else
            {
                //
                // The default is to destroy when a signal is received.
                //
                if(signalPolicy__ == Ice.SignalPolicy.HandleSignals)
                {
                    destroyOnInterrupt();
                }

                //
                // If createSession throws, we're done.
                //
                try
                {
                    _session = createSession();
                    _createdSession = true;
                }
                catch(Ice.LocalException ex)
                {
                    Ice.Util.getProcessLogger().error(ex.ToString());
                    status = 1;
                }

                if(_createdSession)
                {
                    int acmTimeout = 0;
                    try
                    {
                        acmTimeout = _router.getACMTimeout();
                    }
                    catch(Ice.OperationNotExistException)
                    {
                    }
                    if(acmTimeout <= 0)
                    {
                        acmTimeout = (int)_router.getSessionTimeout();
                    }
                    if(acmTimeout > 0)
                    {
                        Ice.Connection connection = _router.ice_getCachedConnection();
                        Debug.Assert(connection != null);
                        connection.setACM((int)acmTimeout, Ice.Util.None, Ice.ACMHeartbeat.HeartbeatAlways);
                        connection.setCloseCallback(_ => sessionDestroyed());
                    }
                    _category = _router.getCategoryForClient();
                    status = runWithSession(args);
                }
            }
            }
            //
            // We want to restart on those exceptions that indicate a
            // break down in communications, but not those exceptions that
            // indicate a programming logic error (i.e., marshal, protocol
            // failure, etc).
            //
            catch(RestartSessionException)
            {
            restart = true;
            }
            catch(Ice.ConnectionRefusedException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
            }
            catch(Ice.ConnectionLostException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
            }
            catch(Ice.UnknownLocalException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
            }
            catch(Ice.RequestFailedException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
            }
            catch(Ice.TimeoutException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
            }
            catch(Ice.LocalException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            status = 1;
            }
            catch(System.Exception ex)
            {
            Ice.Util.getProcessLogger().error("unknown exception:\n" + ex.ToString());
            status = 1;
            }

            //
            // Don't want any new interrupt. And at this point
            // (post-run), it would not make sense to release a held
            // signal to run shutdown or destroy.
            //
            if(signalPolicy__ == Ice.SignalPolicy.HandleSignals)
            {
            ignoreInterrupt();
            }

            lock(mutex__)
            {
            while(callbackInProgress__)
            {
                System.Threading.Monitor.Wait(mutex__);
            }

            if(destroyed__)
            {
                communicator__ = null;
            }
            else
            {
                destroyed__ = true;
                //
                // And communicator__ != null, meaning will be
                // destroyed next, destroyed__ = true also ensures that
                // any remaining callback won't do anything
                //
            }
            }

            if(_createdSession && _router != null)
            {
            try
            {
                _router.destroySession();
            }
            catch(Ice.ConnectionLostException)
            {
                //
                // Expected if another thread invoked on an object from the session concurrently.
                //
            }
            catch(Glacier2.SessionNotExistException)
            {
                //
                // This can also occur.
                //
            }
            catch(System.Exception ex)
            {
                //
                // Not expected.
                //
                Ice.Util.getProcessLogger().error("unexpected exception when destroying the session:\n" +
                                                  ex.ToString());
            }
            _router = null;
            }

            if(communicator__ != null)
            {
            try
            {
                communicator__.destroy();
            }
            catch(Ice.LocalException ex)
            {
                Ice.Util.getProcessLogger().error(ex.ToString());
                status = 1;
            }
            catch(System.Exception ex)
            {
                Ice.Util.getProcessLogger().error("unknown exception:\n" + ex.ToString());
                status = 1;
            }
            communicator__ = null;
            }

            //
            // Reset internal state. We cannot reset the Application state
            // here, since destroyed__ must remain true until we re-run
            // this method.
            //
            _adapter = null;
            _router = null;
            _session = null;
            _createdSession = false;
            _category = null;

            return restart;
        }
Пример #8
0
        public Ice.ObjectPrx getAdmin()
        {
            Ice.ObjectAdapter adapter = null;
            string serverId = null;
            Ice.LocatorPrx defaultLocator = null;

            lock(this)
            {
                if(_state == StateDestroyed)
                {
                    throw new Ice.CommunicatorDestroyedException();
                }

                string adminOA = "Ice.Admin";

                if(_adminAdapter != null)
                {
                    return _adminAdapter.createProxy(_adminIdentity);
                }
                else if(_initData.properties.getProperty(adminOA + ".Endpoints").Length == 0)
                {
                    return null;
                }
                else
                {
                    serverId = _initData.properties.getProperty("Ice.Admin.ServerId");
                    string instanceName = _initData.properties.getProperty("Ice.Admin.InstanceName");

                    defaultLocator = _referenceFactory.getDefaultLocator();

                    if((defaultLocator != null && serverId.Length > 0) || instanceName.Length > 0)
                    {
                        if(_adminIdentity == null)
                        {
                            if(instanceName.Length == 0)
                            {
                                instanceName = System.Guid.NewGuid().ToString();
                            }
                            _adminIdentity = new Ice.Identity("admin", instanceName);
                            //
                            // Afterwards, _adminIdentity is read-only
                            //
                        }

                        //
                        // Create OA
                        //
                        _adminAdapter = _objectAdapterFactory.createObjectAdapter(adminOA, null);

                        //
                        // Add all facets to OA
                        //
                        Dictionary<string, Ice.Object> filteredFacets = new Dictionary<string, Ice.Object>();

                        foreach(KeyValuePair<string, Ice.Object> entry in _adminFacets)
                        {
                            if(_adminFacetFilter.Count == 0 || _adminFacetFilter.Contains(entry.Key))
                            {
                                _adminAdapter.addFacet(entry.Value, _adminIdentity, entry.Key);
                            }
                            else
                            {
                                filteredFacets.Add(entry.Key, entry.Value);
                            }
                        }
                        _adminFacets = filteredFacets;

                        adapter = _adminAdapter;
                    }
                }
            }

            if(adapter == null)
            {
                return null;
            }
            else
            {
                try
                {
                    adapter.activate();
                }
                catch(Ice.LocalException)
                {
                    //
                    // We cleanup _adminAdapter, however this error is not recoverable
                    // (can't call again getAdmin() after fixing the problem)
                    // since all the facets (servants) in the adapter are lost
                    //
                    adapter.destroy();
                    lock(this)
                    {
                        _adminAdapter = null;
                    }
                    throw;
                }

                Ice.ObjectPrx admin = adapter.createProxy(_adminIdentity);
                if(defaultLocator != null && serverId.Length > 0)
                {
                    Ice.ProcessPrx process = Ice.ProcessPrxHelper.uncheckedCast(admin.ice_facet("Process"));
                    try
                    {
                        //
                        // Note that as soon as the process proxy is registered, the communicator might be
                        // shutdown by a remote client and admin facets might start receiving calls.
                        //
                        defaultLocator.getRegistry().setServerProcessProxy(serverId, process);
                    }
                    catch(Ice.ServerNotFoundException)
                    {
                        if(_traceLevels.location >= 1)
                        {
                            System.Text.StringBuilder s = new System.Text.StringBuilder();
                            s.Append("couldn't register server `" + serverId + "' with the locator registry:\n");
                            s.Append("the server is not known to the locator registry");
                            _initData.logger.trace(_traceLevels.locationCat, s.ToString());
                        }

                        throw new Ice.InitializationException("Locator knows nothing about server '" + serverId +
                                                              "'");
                    }
                    catch(Ice.LocalException ex)
                    {
                        if(_traceLevels.location >= 1)
                        {
                            System.Text.StringBuilder s = new System.Text.StringBuilder();
                            s.Append("couldn't register server `" + serverId + "' with the locator registry:\n" + ex);
                            _initData.logger.trace(_traceLevels.locationCat, s.ToString());
                        }
                        throw; // TODO: Shall we raise a special exception instead of a non obvious local exception?
                    }

                    if(_traceLevels.location >= 1)
                    {
                        System.Text.StringBuilder s = new System.Text.StringBuilder();
                        s.Append("registered server `" + serverId + "' with the locator registry");
                        _initData.logger.trace(_traceLevels.locationCat, s.ToString());
                    }
                }
                return admin;
            }
        }
Пример #9
0
 public void destroy()
 {
     lock(this)
     {
         _clientEndpoints = new EndpointI[0];
         _serverEndpoints = new EndpointI[0];
         _adapter = null;
         _identities.Clear();
     }
 }
Пример #10
0
 public HoldI(Timer timer, Ice.ObjectAdapter adapter)
 {
     _timer   = timer;
     _adapter = adapter;
 }
Пример #11
0
        //
        // Only for use by Ice.CommunicatorI
        //
        public void destroy()
        {
            lock(this)
            {
                //
                // If destroy is in progress, wait for it to be done. This
                // is necessary in case destroy() is called concurrently
                // by multiple threads.
                //
                while(_state == StateDestroyInProgress)
                {
                    Monitor.Wait(this);
                }

                if(_state == StateDestroyed)
                {
                    return;
                }
                _state = StateDestroyInProgress;
            }

            //
            // Shutdown and destroy all the incoming and outgoing Ice
            // connections and wait for the connections to be finished.
            //
            if(_objectAdapterFactory != null)
            {
                _objectAdapterFactory.shutdown();
            }

            if(_outgoingConnectionFactory != null)
            {
                _outgoingConnectionFactory.destroy();
            }

            if(_objectAdapterFactory != null)
            {
                _objectAdapterFactory.destroy();
            }

            if(_outgoingConnectionFactory != null)
            {
                _outgoingConnectionFactory.waitUntilFinished();
            }

            if(_retryQueue != null)
            {
                _retryQueue.destroy(); // Must be called before destroying thread pools.
            }

            if(_initData.observer != null)
            {
                _initData.observer.setObserverUpdater(null);
            }

            LoggerAdminLogger logger = _initData.logger as LoggerAdminLogger;
            if(logger != null)
            {
                logger.destroy();
            }

            //
            // Now, destroy the thread pools. This must be done *only* after
            // all the connections are finished (the connections destruction
            // can require invoking callbacks with the thread pools).
            //
            if(_serverThreadPool != null)
            {
                _serverThreadPool.destroy();
            }
            if(_clientThreadPool != null)
            {
                _clientThreadPool.destroy();
            }
            if(_asyncIOThread != null)
            {
                _asyncIOThread.destroy();
            }
            if(_endpointHostResolver != null)
            {
                _endpointHostResolver.destroy();
            }

            //
            // Wait for all the threads to be finished.
            //
            if(_timer != null)
            {
                _timer.destroy();
            }
            if(_clientThreadPool != null)
            {
                _clientThreadPool.joinWithAllThreads();
            }
            if(_serverThreadPool != null)
            {
                _serverThreadPool.joinWithAllThreads();
            }
            if(_asyncIOThread != null)
            {
                _asyncIOThread.joinWithThread();
            }
            if(_endpointHostResolver != null)
            {
                _endpointHostResolver.joinWithThread();
            }

            foreach(Ice.ObjectFactory factory in _objectFactoryMap.Values)
            {
            // Disable Obsolete warning/error
            #pragma warning disable 612, 618
                factory.destroy();
            #pragma warning restore 612, 618
            }
            _objectFactoryMap.Clear();

            if(_routerManager != null)
            {
                _routerManager.destroy();
            }

            if(_locatorManager != null)
            {
                _locatorManager.destroy();
            }

            if(_endpointFactoryManager != null)
            {
                _endpointFactoryManager.destroy();
            }

            if(_initData.properties.getPropertyAsInt("Ice.Warn.UnusedProperties") > 0)
            {
                List<string> unusedProperties = ((Ice.PropertiesI)_initData.properties).getUnusedProperties();
                if (unusedProperties.Count != 0)
                {
                    StringBuilder message = new StringBuilder("The following properties were set but never read:");
                    foreach (string s in unusedProperties)
                    {
                        message.Append("\n    ");
                        message.Append(s);
                    }
                    _initData.logger.warning(message.ToString());
                }
            }

            //
            // Destroy last so that a Logger plugin can receive all log/traces before its destruction.
            //
            if(_pluginManager != null)
            {
                _pluginManager.destroy();
            }

            lock(this)
            {
                _objectAdapterFactory = null;
                _outgoingConnectionFactory = null;
                _retryQueue = null;

                _serverThreadPool = null;
                _clientThreadPool = null;
                _asyncIOThread = null;
                _endpointHostResolver = null;
                _timer = null;

                _referenceFactory = null;
                _requestHandlerFactory = null;
                _proxyFactory = null;
                _routerManager = null;
                _locatorManager = null;
                _endpointFactoryManager = null;
                _pluginManager = null;

                _adminAdapter = null;
                _adminFacets.Clear();

                _state = StateDestroyed;
                Monitor.PulseAll(this);
            }
        }
Пример #12
0
            public static void allTests(global::Test.TestHelper helper)
            {
                Ice.Communicator communicator = helper.communicator();
                communicator.getProperties().setProperty("ReplyAdapter.Endpoints", "udp");
                Ice.ObjectAdapter adapter = communicator.createObjectAdapter("ReplyAdapter");
                PingReplyI        replyI  = new PingReplyI();

                Test.PingReplyPrx reply =
                    (Test.PingReplyPrx)Test.PingReplyPrxHelper.uncheckedCast(adapter.addWithUUID(replyI)).ice_datagram();
                adapter.activate();

                Console.Out.Write("testing udp... ");
                Console.Out.Flush();
                Ice.ObjectPrx    @base = communicator.stringToProxy("test:" + helper.getTestEndpoint(0, "udp")).ice_datagram();
                Test.TestIntfPrx obj   = Test.TestIntfPrxHelper.uncheckedCast(@base);

                int  nRetry = 5;
                bool ret    = false;

                while (nRetry-- > 0)
                {
                    replyI.reset();
                    obj.ping(reply);
                    obj.ping(reply);
                    obj.ping(reply);
                    ret = replyI.waitReply(3, 2000);
                    if (ret)
                    {
                        break; // Success
                    }

                    // If the 3 datagrams were not received within the 2 seconds, we try again to
                    // receive 3 new datagrams using a new object. We give up after 5 retries.
                    replyI = new PingReplyI();
                    reply  = (Test.PingReplyPrx)Test.PingReplyPrxHelper.uncheckedCast(adapter.addWithUUID(replyI)).ice_datagram();
                }
                test(ret == true);

                if (communicator.getProperties().getPropertyAsInt("Ice.Override.Compress") == 0)
                {
                    //
                    // Only run this test if compression is disabled, the test expect fixed message size
                    // to be sent over the wire.
                    //
                    byte[] seq = null;
                    try
                    {
                        seq = new byte[1024];
                        while (true)
                        {
                            seq = new byte[seq.Length * 2 + 10];
                            replyI.reset();
                            obj.sendByteSeq(seq, reply);
                            replyI.waitReply(1, 10000);
                        }
                    }
                    catch (Ice.DatagramLimitException)
                    {
                        //
                        // The server's Ice.UDP.RcvSize property is set to 16384, which means that DatagramLimitException
                        // will be throw when try to send a packet bigger than that.
                        //
                        test(seq.Length > 16384);
                    }
                    obj.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                    communicator.getProperties().setProperty("Ice.UDP.SndSize", "64000");
                    seq = new byte[50000];
                    try
                    {
                        replyI.reset();
                        obj.sendByteSeq(seq, reply);

                        bool b = replyI.waitReply(1, 500);
                        //
                        // The server's Ice.UDP.RcvSize property is set to 16384, which means this packet
                        // should not be delivered.
                        //
                        test(!b);
                    }
                    catch (Ice.DatagramLimitException)
                    {
                    }
                    catch (Ice.LocalException ex)
                    {
                        Console.Out.WriteLine(ex);
                        test(false);
                    }
                }

                Console.Out.WriteLine("ok");

                Console.Out.Write("testing udp multicast... ");
                Console.Out.Flush();
                StringBuilder endpoint = new StringBuilder();

                //
                // Use loopback to prevent other machines to answer.
                //
                if (communicator.getProperties().getProperty("Ice.IPv6").Equals("1"))
                {
                    endpoint.Append("udp -h \"ff15::1:1\"");
                    if (IceInternal.AssemblyUtil.isWindows || IceInternal.AssemblyUtil.isMacOS)
                    {
                        endpoint.Append(" --interface \"::1\"");
                    }
                }
                else
                {
                    endpoint.Append("udp -h 239.255.1.1");
                    if (IceInternal.AssemblyUtil.isWindows || IceInternal.AssemblyUtil.isMacOS)
                    {
                        endpoint.Append(" --interface 127.0.0.1");
                    }
                }
                endpoint.Append(" -p ");
                endpoint.Append(helper.getTestPort(10));
                @base = communicator.stringToProxy("test -d:" + endpoint.ToString());
                var objMcast = Test.TestIntfPrxHelper.uncheckedCast(@base);

                nRetry = 5;
                while (nRetry-- > 0)
                {
                    replyI.reset();
                    objMcast.ping(reply);
                    ret = replyI.waitReply(5, 5000);
                    if (ret)
                    {
                        break;
                    }
                    replyI = new PingReplyI();
                    reply  = (Test.PingReplyPrx)Test.PingReplyPrxHelper.uncheckedCast(adapter.addWithUUID(replyI)).ice_datagram();
                }
                if (!ret)
                {
                    Console.Out.WriteLine("failed(is a firewall enabled?)");
                }
                else
                {
                    Console.Out.WriteLine("ok");
                }

                Console.Out.Write("testing udp bi-dir connection... ");
                Console.Out.Flush();
                obj.ice_getConnection().setAdapter(adapter);
                objMcast.ice_getConnection().setAdapter(adapter);
                nRetry = 5;
                while (nRetry-- > 0)
                {
                    replyI.reset();
                    obj.pingBiDir(reply.ice_getIdentity());
                    obj.pingBiDir(reply.ice_getIdentity());
                    obj.pingBiDir(reply.ice_getIdentity());
                    ret = replyI.waitReply(3, 2000);
                    if (ret)
                    {
                        break; // Success
                    }
                    replyI = new PingReplyI();
                    reply  = (Test.PingReplyPrx)Test.PingReplyPrxHelper.uncheckedCast(adapter.addWithUUID(replyI)).ice_datagram();
                }
                test(ret);
                Console.Out.WriteLine("ok");

                //
                // Sending the replies back on the multicast UDP connection doesn't work for most
                // platform(it works for macOS Leopard but not Snow Leopard, doesn't work on SLES,
                // Windows...). For Windows, see UdpTransceiver constructor for the details. So
                // we don't run this test.
                //
                //         Console.Out.Write("testing udp bi-dir connection... ");
                //         nRetry = 5;
                //         while(nRetry-- > 0)
                //         {
                //             replyI.reset();
                //             objMcast.pingBiDir(reply.ice_getIdentity());
                //             ret = replyI.waitReply(5, 2000);
                //             if(ret)
                //             {
                //                 break; // Success
                //             }
                //             replyI = new PingReplyI();
                //             reply =(PingReplyPrx)PingReplyPrxHelper.uncheckedCast(adapter.addWithUUID(replyI)).ice_datagram();
                //         }

                //         if(!ret)
                //         {
                //             Console.Out.WriteLine("failed(is a firewall enabled?)");
                //         }
                //         else
                //         {
                //             Console.Out.WriteLine("ok");
                //         }
            }
Пример #13
0
    // Add servant to ASM and parent's _contents map.

    public void activate(Ice.ObjectAdapter a)
    {
        var thisNode = NodePrxHelper.uncheckedCast(a.add(this, _id));

        _parent.addChild(thisNode);
    }
Пример #14
0
    public static void allTests(Ice.Communicator communicator)
#endif
    {
        Write("testing communicator operations... ");
        Flush();
        {
            //
            // Test: Exercise addAdminFacet, findAdminFacet, removeAdminFacet with a typical configuration.
            //
            Ice.InitializationData init = new Ice.InitializationData();
            init.properties = Ice.Util.createProperties();
            init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            init.properties.setProperty("Ice.Admin.InstanceName", "Test");
            Ice.Communicator com = Ice.Util.initialize(init);
            testFacets(com, true);
            com.destroy();
        }
        {
            //
            // Test: Verify that the operations work correctly in the presence of facet filters.
            //
            Ice.InitializationData init = new Ice.InitializationData();
            init.properties = Ice.Util.createProperties();
            init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            init.properties.setProperty("Ice.Admin.InstanceName", "Test");
            init.properties.setProperty("Ice.Admin.Facets", "Properties");
            Ice.Communicator com = Ice.Util.initialize(init);
            testFacets(com, false);
            com.destroy();
        }
        {
            //
            // Test: Verify that the operations work correctly with the Admin object disabled.
            //
            Ice.Communicator com = Ice.Util.initialize();
            testFacets(com, false);
            com.destroy();
        }
        {
            //
            // Test: Verify that the operations work correctly with Ice.Admin.Enabled=1
            //
            Ice.InitializationData init = new Ice.InitializationData();
            init.properties = Ice.Util.createProperties();
            init.properties.setProperty("Ice.Admin.Enabled", "1");
            Ice.Communicator com = Ice.Util.initialize(init);
            test(com.getAdmin() == null);
            Ice.Identity id = com.stringToIdentity("test-admin");
            try
            {
                com.createAdmin(null, id);
                test(false);
            }
            catch (Ice.InitializationException)
            {
            }

            Ice.ObjectAdapter adapter = com.createObjectAdapter("");
            test(com.createAdmin(adapter, id) != null);
            test(com.getAdmin() != null);

            testFacets(com, true);
            com.destroy();
        }
        {
            //
            // Test: Verify that the operations work correctly when creation of the Admin object is delayed.
            //
            Ice.InitializationData init = new Ice.InitializationData();
            init.properties = Ice.Util.createProperties();
            init.properties.setProperty("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            init.properties.setProperty("Ice.Admin.InstanceName", "Test");
            init.properties.setProperty("Ice.Admin.DelayCreation", "1");
            Ice.Communicator com = Ice.Util.initialize(init);
            testFacets(com, true);
            com.getAdmin();
            testFacets(com, true);
            com.destroy();
        }
        WriteLine("ok");

        string @ref = "factory:default -p 12010 -t 10000";
        RemoteCommunicatorFactoryPrx factory =
            RemoteCommunicatorFactoryPrxHelper.uncheckedCast(communicator.stringToProxy(@ref));

        Write("testing process facet... ");
        Flush();
        {
            //
            // Test: Verify that Process::shutdown() operation shuts down the communicator.
            //
            Dictionary <string, string> props = new Dictionary <string, string>();
            props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            props.Add("Ice.Admin.InstanceName", "Test");
            RemoteCommunicatorPrx com  = factory.createCommunicator(props);
            Ice.ObjectPrx         obj  = com.getAdmin();
            Ice.ProcessPrx        proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process");
            proc.shutdown();
            com.waitForShutdown();
            com.destroy();
        }
        WriteLine("ok");

        Write("testing properties facet... ");
        Flush();
        {
            Dictionary <string, string> props = new Dictionary <string, string>();
            props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            props.Add("Ice.Admin.InstanceName", "Test");
            props.Add("Prop1", "1");
            props.Add("Prop2", "2");
            props.Add("Prop3", "3");
            RemoteCommunicatorPrx  com = factory.createCommunicator(props);
            Ice.ObjectPrx          obj = com.getAdmin();
            Ice.PropertiesAdminPrx pa  = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties");

            //
            // Test: PropertiesAdmin::getProperty()
            //
            test(pa.getProperty("Prop2").Equals("2"));
            test(pa.getProperty("Bogus").Equals(""));

            //
            // Test: PropertiesAdmin::getProperties()
            //
            Dictionary <string, string> pd = pa.getPropertiesForPrefix("");
            test(pd.Count == 5);
            test(pd["Ice.Admin.Endpoints"].Equals("tcp -h 127.0.0.1"));
            test(pd["Ice.Admin.InstanceName"].Equals("Test"));
            test(pd["Prop1"].Equals("1"));
            test(pd["Prop2"].Equals("2"));
            test(pd["Prop3"].Equals("3"));

            Dictionary <string, string> changes;

            //
            // Test: PropertiesAdmin::setProperties()
            //
            Dictionary <string, string> setProps = new Dictionary <string, string>();
            setProps.Add("Prop1", "10"); // Changed
            setProps.Add("Prop2", "20"); // Changed
            setProps.Add("Prop3", "");   // Removed
            setProps.Add("Prop4", "4");  // Added
            setProps.Add("Prop5", "5");  // Added
            pa.setProperties(setProps);
            test(pa.getProperty("Prop1").Equals("10"));
            test(pa.getProperty("Prop2").Equals("20"));
            test(pa.getProperty("Prop3").Equals(""));
            test(pa.getProperty("Prop4").Equals("4"));
            test(pa.getProperty("Prop5").Equals("5"));
            changes = com.getChanges();
            test(changes.Count == 5);
            test(changes["Prop1"].Equals("10"));
            test(changes["Prop2"].Equals("20"));
            test(changes["Prop3"].Equals(""));
            test(changes["Prop4"].Equals("4"));
            test(changes["Prop5"].Equals("5"));
            pa.setProperties(setProps);
            changes = com.getChanges();
            test(changes.Count == 0);

            com.destroy();
        }
        WriteLine("ok");

        Write("testing logger facet... ");
        Flush();
        {
            Dictionary <String, String> props = new Dictionary <String, String>();
            props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            props.Add("Ice.Admin.InstanceName", "Test");
            props.Add("NullLogger", "1");
            RemoteCommunicatorPrx com = factory.createCommunicator(props);

            com.trace("testCat", "trace");
            com.warning("warning");
            com.error("error");
            com.print("print");

            Ice.ObjectPrx      obj    = com.getAdmin();
            Ice.LoggerAdminPrx logger = Ice.LoggerAdminPrxHelper.checkedCast(obj, "Logger");
            test(logger != null);

            string prefix = null;

            //
            // Get all
            //
            Ice.LogMessage[] logMessages = logger.getLog(null, null, -1, out prefix);

            test(logMessages.Length == 4);
            test(prefix.Equals("NullLogger"));
            test(logMessages[0].traceCategory.Equals("testCat") && logMessages[0].message.Equals("trace"));
            test(logMessages[1].message.Equals("warning"));
            test(logMessages[2].message.Equals("error"));
            test(logMessages[3].message.Equals("print"));

            //
            // Get only errors and warnings
            //
            com.error("error2");
            com.print("print2");
            com.trace("testCat", "trace2");
            com.warning("warning2");

            Ice.LogMessageType[] messageTypes = { Ice.LogMessageType.ErrorMessage, Ice.LogMessageType.WarningMessage };

            logMessages = logger.getLog(messageTypes, null, -1, out prefix);

            test(logMessages.Length == 4);
            test(prefix.Equals("NullLogger"));

            foreach (var msg in logMessages)
            {
                test(msg.type == Ice.LogMessageType.ErrorMessage || msg.type == Ice.LogMessageType.WarningMessage);
            }

            //
            // Get only errors and traces with Cat = "testCat"
            //
            com.trace("testCat2", "A");
            com.trace("testCat", "trace3");
            com.trace("testCat2", "B");

            messageTypes = new Ice.LogMessageType[] { Ice.LogMessageType.ErrorMessage, Ice.LogMessageType.TraceMessage };
            string[] categories = { "testCat" };
            logMessages = logger.getLog(messageTypes, categories, -1, out prefix);
            test(logMessages.Length == 5);
            test(prefix.Equals("NullLogger"));

            foreach (var msg in logMessages)
            {
                test(msg.type == Ice.LogMessageType.ErrorMessage ||
                     (msg.type == Ice.LogMessageType.TraceMessage && msg.traceCategory.Equals("testCat")));
            }

            //
            // Same, but limited to last 2 messages (trace3 + error3)
            //
            com.error("error3");

            logMessages = logger.getLog(messageTypes, categories, 2, out prefix);
            test(logMessages.Length == 2);
            test(prefix.Equals("NullLogger"));

            test(logMessages[0].message.Equals("trace3"));
            test(logMessages[1].message.Equals("error3"));

            //
            // Now, test RemoteLogger
            //
            Ice.ObjectAdapter adapter =
                communicator.createObjectAdapterWithEndpoints("RemoteLoggerAdapter", "tcp -h localhost");

            RemoteLoggerI remoteLogger = new RemoteLoggerI();

            Ice.RemoteLoggerPrx myProxy = Ice.RemoteLoggerPrxHelper.uncheckedCast(adapter.addWithUUID(remoteLogger));

            adapter.activate();

            //
            // No filtering
            //
            logMessages = logger.getLog(null, null, -1, out prefix);
            remoteLogger.checkNextInit(prefix, logMessages);

            logger.attachRemoteLogger(myProxy, null, null, -1);
            remoteLogger.wait(1);

            remoteLogger.checkNextLog(Ice.LogMessageType.TraceMessage, "rtrace", "testCat");
            remoteLogger.checkNextLog(Ice.LogMessageType.WarningMessage, "rwarning", "");
            remoteLogger.checkNextLog(Ice.LogMessageType.ErrorMessage, "rerror", "");
            remoteLogger.checkNextLog(Ice.LogMessageType.PrintMessage, "rprint", "");

            com.trace("testCat", "rtrace");
            com.warning("rwarning");
            com.error("rerror");
            com.print("rprint");

            remoteLogger.wait(4);

            test(logger.detachRemoteLogger(myProxy));
            test(!logger.detachRemoteLogger(myProxy));

            //
            // Use Error + Trace with "traceCat" filter with 4 limit
            //
            logMessages = logger.getLog(messageTypes, categories, 4, out prefix);
            test(logMessages.Length == 4);
            remoteLogger.checkNextInit(prefix, logMessages);

            logger.attachRemoteLogger(myProxy, messageTypes, categories, 4);
            remoteLogger.wait(1);

            remoteLogger.checkNextLog(Ice.LogMessageType.TraceMessage, "rtrace2", "testCat");
            remoteLogger.checkNextLog(Ice.LogMessageType.ErrorMessage, "rerror2", "");

            com.warning("rwarning2");
            com.trace("testCat", "rtrace2");
            com.warning("rwarning3");
            com.error("rerror2");
            com.print("rprint2");

            remoteLogger.wait(2);

            //
            // Attempt reconnection with slightly different proxy
            //
            try
            {
                logger.attachRemoteLogger(Ice.RemoteLoggerPrxHelper.uncheckedCast(myProxy.ice_oneway()),
                                          messageTypes, categories, 4);
                test(false);
            }
            catch (Ice.RemoteLoggerAlreadyAttachedException)
            {
                // expected
            }

            com.destroy();
        }
        WriteLine("ok");


        Write("testing custom facet... ");
        Flush();
        {
            //
            // Test: Verify that the custom facet is present.
            //
            Dictionary <string, string> props = new Dictionary <string, string>();
            props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            props.Add("Ice.Admin.InstanceName", "Test");
            RemoteCommunicatorPrx com = factory.createCommunicator(props);
            Ice.ObjectPrx         obj = com.getAdmin();
            TestFacetPrx          tf  = TestFacetPrxHelper.checkedCast(obj, "TestFacet");
            tf.op();
            com.destroy();
        }
        WriteLine("ok");

        Write("testing facet filtering... ");
        Flush();
        {
            //
            // Test: Set Ice.Admin.Facets to expose only the Properties facet,
            // meaning no other facet is available.
            //
            Dictionary <string, string> props = new Dictionary <string, string>();
            props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            props.Add("Ice.Admin.InstanceName", "Test");
            props.Add("Ice.Admin.Facets", "Properties");
            RemoteCommunicatorPrx com  = factory.createCommunicator(props);
            Ice.ObjectPrx         obj  = com.getAdmin();
            Ice.ProcessPrx        proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process");
            test(proc == null);
            TestFacetPrx tf = TestFacetPrxHelper.checkedCast(obj, "TestFacet");
            test(tf == null);
            com.destroy();
        }
        {
            //
            // Test: Set Ice.Admin.Facets to expose only the Process facet,
            // meaning no other facet is available.
            //
            Dictionary <string, string> props = new Dictionary <string, string>();
            props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            props.Add("Ice.Admin.InstanceName", "Test");
            props.Add("Ice.Admin.Facets", "Process");
            RemoteCommunicatorPrx  com = factory.createCommunicator(props);
            Ice.ObjectPrx          obj = com.getAdmin();
            Ice.PropertiesAdminPrx pa  = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties");
            test(pa == null);
            TestFacetPrx tf = TestFacetPrxHelper.checkedCast(obj, "TestFacet");
            test(tf == null);
            com.destroy();
        }
        {
            //
            // Test: Set Ice.Admin.Facets to expose only the TestFacet facet,
            // meaning no other facet is available.
            //
            Dictionary <string, string> props = new Dictionary <string, string>();
            props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            props.Add("Ice.Admin.InstanceName", "Test");
            props.Add("Ice.Admin.Facets", "TestFacet");
            RemoteCommunicatorPrx  com = factory.createCommunicator(props);
            Ice.ObjectPrx          obj = com.getAdmin();
            Ice.PropertiesAdminPrx pa  = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties");
            test(pa == null);
            Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process");
            test(proc == null);
            com.destroy();
        }
        {
            //
            // Test: Set Ice.Admin.Facets to expose two facets. Use whitespace to separate the
            // facet names.
            //
            Dictionary <string, string> props = new Dictionary <string, string>();
            props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            props.Add("Ice.Admin.InstanceName", "Test");
            props.Add("Ice.Admin.Facets", "Properties TestFacet");
            RemoteCommunicatorPrx  com = factory.createCommunicator(props);
            Ice.ObjectPrx          obj = com.getAdmin();
            Ice.PropertiesAdminPrx pa  = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties");
            test(pa.getProperty("Ice.Admin.InstanceName").Equals("Test"));
            TestFacetPrx tf = TestFacetPrxHelper.checkedCast(obj, "TestFacet");
            tf.op();
            Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process");
            test(proc == null);
            com.destroy();
        }
        {
            //
            // Test: Set Ice.Admin.Facets to expose two facets. Use a comma to separate the
            // facet names.
            //
            Dictionary <string, string> props = new Dictionary <string, string>();
            props.Add("Ice.Admin.Endpoints", "tcp -h 127.0.0.1");
            props.Add("Ice.Admin.InstanceName", "Test");
            props.Add("Ice.Admin.Facets", "TestFacet, Process");
            RemoteCommunicatorPrx  com = factory.createCommunicator(props);
            Ice.ObjectPrx          obj = com.getAdmin();
            Ice.PropertiesAdminPrx pa  = Ice.PropertiesAdminPrxHelper.checkedCast(obj, "Properties");
            test(pa == null);
            TestFacetPrx tf = TestFacetPrxHelper.checkedCast(obj, "TestFacet");
            tf.op();
            Ice.ProcessPrx proc = Ice.ProcessPrxHelper.checkedCast(obj, "Process");
            proc.shutdown();
            com.waitForShutdown();
            com.destroy();
        }
        WriteLine("ok");

        factory.shutdown();
    }
Пример #15
0
    public static ThrowerPrx allTests(TestCommon.Application app)
    {
        Ice.Communicator communicator = app.communicator();
        {
            Write("testing object adapter registration exceptions... ");
            Ice.ObjectAdapter first;
            try
            {
                first = communicator.createObjectAdapter("TestAdapter0");
            }
            catch (Ice.InitializationException)
            {
                // Expected
            }

            communicator.getProperties().setProperty("TestAdapter0.Endpoints", "tcp -h *");
            first = communicator.createObjectAdapter("TestAdapter0");
            try
            {
                communicator.createObjectAdapter("TestAdapter0");
                test(false);
            }
            catch (Ice.AlreadyRegisteredException)
            {
                // Expected.
            }

            try
            {
                Ice.ObjectAdapter second =
                    communicator.createObjectAdapterWithEndpoints("TestAdapter0", "ssl -h foo -p 12011");
                test(false);

                //
                // Quell mono error that variable second isn't used.
                //
                second.deactivate();
            }
            catch (Ice.AlreadyRegisteredException)
            {
                // Expected
            }
            first.deactivate();
            WriteLine("ok");
        }

        {
            Write("testing servant registration exceptions... ");
            communicator.getProperties().setProperty("TestAdapter1.Endpoints", "tcp -h *");
            Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TestAdapter1");
            Ice.Object        obj     = new EmptyI();
            adapter.add(obj, Ice.Util.stringToIdentity("x"));
            try
            {
                adapter.add(obj, Ice.Util.stringToIdentity("x"));
                test(false);
            }
            catch (Ice.AlreadyRegisteredException)
            {
            }

            try
            {
                adapter.add(obj, Ice.Util.stringToIdentity(""));
                test(false);
            }
            catch (Ice.IllegalIdentityException e)
            {
                test(e.id.name.Equals(""));
            }

            try
            {
                adapter.add(null, Ice.Util.stringToIdentity("x"));
                test(false);
            }
            catch (Ice.IllegalServantException)
            {
            }

            adapter.remove(Ice.Util.stringToIdentity("x"));
            try
            {
                adapter.remove(Ice.Util.stringToIdentity("x"));
                test(false);
            }
            catch (Ice.NotRegisteredException)
            {
            }
            adapter.deactivate();
            WriteLine("ok");
        }

        {
            Write("testing servant locator registration exceptions... ");
            communicator.getProperties().setProperty("TestAdapter2.Endpoints", "tcp -h *");
            Ice.ObjectAdapter  adapter = communicator.createObjectAdapter("TestAdapter2");
            Ice.ServantLocator loc     = new ServantLocatorI();
            adapter.addServantLocator(loc, "x");
            try
            {
                adapter.addServantLocator(loc, "x");
                test(false);
            }
            catch (Ice.AlreadyRegisteredException)
            {
            }

            adapter.deactivate();
            WriteLine("ok");
        }

        {
            Write("testing object factory registration exception... ");
            communicator.getValueFactoryManager().add(_ => { return(null); }, "::x");
            try
            {
                communicator.getValueFactoryManager().add(_ => { return(null); }, "::x");
                test(false);
            }
            catch (Ice.AlreadyRegisteredException)
            {
            }
            WriteLine("ok");
        }

        Write("testing stringToProxy... ");
        Flush();
        String @ref = "thrower:" + app.getTestEndpoint(0);

        Ice.ObjectPrx @base = communicator.stringToProxy(@ref);
        test(@base != null);
        WriteLine("ok");

        Write("testing checked cast... ");
        Flush();
        ThrowerPrx thrower = ThrowerPrxHelper.checkedCast(@base);

        test(thrower != null);
        test(thrower.Equals(@base));
        WriteLine("ok");

        Write("catching exact types... ");
        Flush();

        try
        {
            thrower.throwAasA(1);
            test(false);
        }
        catch (A ex)
        {
            test(ex.aMem == 1);
        }
        catch (Exception ex)
        {
            System.Console.WriteLine(ex);
            test(false);
        }

        try
        {
            thrower.throwAorDasAorD(1);
            test(false);
        }
        catch (A ex)
        {
            test(ex.aMem == 1);
        }
        catch (Exception)
        {
            test(false);
        }

        try
        {
            thrower.throwAorDasAorD(-1);
            test(false);
        }
        catch (D ex)
        {
            test(ex.dMem == -1);
        }
        catch (Exception)
        {
            test(false);
        }

        try
        {
            thrower.throwBasB(1, 2);
            test(false);
        }
        catch (B ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
        }
        catch (Exception)
        {
            test(false);
        }

        try
        {
            thrower.throwCasC(1, 2, 3);
            test(false);
        }
        catch (C ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
            test(ex.cMem == 3);
        }
        catch (Exception)
        {
            test(false);
        }

        WriteLine("ok");

        Write("catching base types... ");
        Flush();

        try
        {
            thrower.throwBasB(1, 2);
            test(false);
        }
        catch (A ex)
        {
            test(ex.aMem == 1);
        }
        catch (Exception)
        {
            test(false);
        }

        try
        {
            thrower.throwCasC(1, 2, 3);
            test(false);
        }
        catch (B ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
        }
        catch (Exception)
        {
            test(false);
        }

        WriteLine("ok");

        Write("catching derived types... ");
        Flush();

        try
        {
            thrower.throwBasA(1, 2);
            test(false);
        }
        catch (B ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
        }
        catch (Exception)
        {
            test(false);
        }

        try
        {
            thrower.throwCasA(1, 2, 3);
            test(false);
        }
        catch (C ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
            test(ex.cMem == 3);
        }
        catch (Exception)
        {
            test(false);
        }

        try
        {
            thrower.throwCasB(1, 2, 3);
            test(false);
        }
        catch (C ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
            test(ex.cMem == 3);
        }
        catch (Exception)
        {
            test(false);
        }

        WriteLine("ok");

        if (thrower.supportsUndeclaredExceptions())
        {
            Write("catching unknown user exception... ");
            Flush();

            try
            {
                thrower.throwUndeclaredA(1);
                test(false);
            }
            catch (Ice.UnknownUserException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            try
            {
                thrower.throwUndeclaredB(1, 2);
                test(false);
            }
            catch (Ice.UnknownUserException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            try
            {
                thrower.throwUndeclaredC(1, 2, 3);
                test(false);
            }
            catch (Ice.UnknownUserException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            WriteLine("ok");
        }

        if (thrower.ice_getConnection() != null)
        {
            Write("testing memory limit marshal exception...");
            Flush();
            try
            {
                thrower.throwMemoryLimitException(null);
                test(false);
            }
            catch (Ice.MemoryLimitException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            try
            {
                thrower.throwMemoryLimitException(new byte[20 * 1024]); // 20KB
                test(false);
            }
            catch (Ice.ConnectionLostException)
            {
            }
            catch (Ice.UnknownLocalException)
            {
                // Expected with JS bidir server
            }
            catch (Exception)
            {
                test(false);
            }

            try
            {
                ThrowerPrx thrower2 = ThrowerPrxHelper.uncheckedCast(
                    communicator.stringToProxy("thrower:" + app.getTestEndpoint(1)));
                try
                {
                    thrower2.throwMemoryLimitException(new byte[2 * 1024 * 1024]); // 2MB (no limits)
                }
                catch (Ice.MemoryLimitException)
                {
                }
                ThrowerPrx thrower3 = ThrowerPrxHelper.uncheckedCast(
                    communicator.stringToProxy("thrower:" + app.getTestEndpoint(2)));
                try
                {
                    thrower3.throwMemoryLimitException(new byte[1024]); // 1KB limit
                    test(false);
                }
                catch (Ice.ConnectionLostException)
                {
                }
            }
            catch (Ice.ConnectionRefusedException)
            {
                // Expected with JS bidir server
            }

            WriteLine("ok");
        }

        Write("catching object not exist exception... ");
        Flush();

        {
            Ice.Identity id = Ice.Util.stringToIdentity("does not exist");
            try
            {
                ThrowerPrx thrower2 = ThrowerPrxHelper.uncheckedCast(thrower.ice_identity(id));
                thrower2.ice_ping();
                test(false);
            }
            catch (Ice.ObjectNotExistException ex)
            {
                test(ex.id.Equals(id));
            }
            catch (Exception)
            {
                test(false);
            }
        }

        WriteLine("ok");

        Write("catching facet not exist exception... ");
        Flush();

        try
        {
            ThrowerPrx thrower2 = ThrowerPrxHelper.uncheckedCast(thrower, "no such facet");
            try
            {
                thrower2.ice_ping();
                test(false);
            }
            catch (Ice.FacetNotExistException ex)
            {
                test(ex.facet.Equals("no such facet"));
            }
        }
        catch (Exception)
        {
            test(false);
        }

        WriteLine("ok");

        Write("catching operation not exist exception... ");
        Flush();

        try
        {
            WrongOperationPrx thrower2 = WrongOperationPrxHelper.uncheckedCast(thrower);
            thrower2.noSuchOperation();
            test(false);
        }
        catch (Ice.OperationNotExistException ex)
        {
            test(ex.operation.Equals("noSuchOperation"));
        }
        catch (Exception)
        {
            test(false);
        }

        WriteLine("ok");

        Write("catching unknown local exception... ");
        Flush();

        try
        {
            thrower.throwLocalException();
            test(false);
        }
        catch (Ice.UnknownLocalException)
        {
        }
        catch (Exception)
        {
            test(false);
        }
        try
        {
            thrower.throwLocalExceptionIdempotent();
            test(false);
        }
        catch (Ice.UnknownLocalException)
        {
        }
        catch (Ice.OperationNotExistException)
        {
        }
        catch (Exception)
        {
            test(false);
        }

        WriteLine("ok");

        Write("catching unknown non-Ice exception... ");
        Flush();

        try
        {
            thrower.throwNonIceException();
            test(false);
        }
        catch (Ice.UnknownException)
        {
        }
        catch (System.Exception)
        {
            test(false);
        }

        WriteLine("ok");

        Write("testing asynchronous exceptions... ");
        Flush();

        try
        {
            thrower.throwAfterResponse();
        }
        catch (Exception)
        {
            test(false);
        }

        try
        {
            thrower.throwAfterException();
            test(false);
        }
        catch (A)
        {
        }
        catch (Exception)
        {
            test(false);
        }

        WriteLine("ok");

        Write("catching exact types with AMI mapping... ");
        Flush();

        {
            Callback cb = new Callback();
            thrower.begin_throwAasA(1).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                test(exc is A);
                A ex = exc as A;
                test(ex.aMem == 1);
                cb.called();
            });
            cb.check();
        }

        {
            Callback cb = new Callback();
            thrower.begin_throwAorDasAorD(1).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (A ex)
                {
                    test(ex.aMem == 1);
                }
                catch (D ex)
                {
                    test(ex.dMem == -1);
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        {
            Callback cb = new Callback();
            thrower.begin_throwAorDasAorD(-1).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (A ex)
                {
                    test(ex.aMem == 1);
                }
                catch (D ex)
                {
                    test(ex.dMem == -1);
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        {
            Callback cb = new Callback();
            thrower.begin_throwBasB(1, 2).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (B ex)
                {
                    test(ex.aMem == 1);
                    test(ex.bMem == 2);
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        {
            Callback cb = new Callback();
            thrower.begin_throwCasC(1, 2, 3).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (C ex)
                {
                    test(ex.aMem == 1);
                    test(ex.bMem == 2);
                    test(ex.cMem == 3);
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");

        Write("catching derived types with new AMI mapping... ");
        Flush();

        {
            Callback cb = new Callback();
            thrower.begin_throwBasA(1, 2).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (B ex)
                {
                    test(ex.aMem == 1);
                    test(ex.bMem == 2);
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        {
            Callback cb = new Callback();
            thrower.begin_throwCasA(1, 2, 3).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (C ex)
                {
                    test(ex.aMem == 1);
                    test(ex.bMem == 2);
                    test(ex.cMem == 3);
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        {
            Callback cb = new Callback();
            thrower.begin_throwCasB(1, 2, 3).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (C ex)
                {
                    test(ex.aMem == 1);
                    test(ex.bMem == 2);
                    test(ex.cMem == 3);
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");

        if (thrower.supportsUndeclaredExceptions())
        {
            Write("catching unknown user exception with new AMI mapping... ");
            Flush();

            {
                Callback cb = new Callback();
                thrower.begin_throwUndeclaredA(1).whenCompleted(
                    () =>
                {
                    test(false);
                },
                    (Ice.Exception exc) =>
                {
                    try
                    {
                        throw exc;
                    }
                    catch (Ice.UnknownUserException)
                    {
                    }
                    catch (Exception)
                    {
                        test(false);
                    }
                    cb.called();
                });
                cb.check();
            }

            {
                Callback cb = new Callback();
                thrower.begin_throwUndeclaredB(1, 2).whenCompleted(
                    () =>
                {
                    test(false);
                },
                    (Ice.Exception exc) =>
                {
                    try
                    {
                        throw exc;
                    }
                    catch (Ice.UnknownUserException)
                    {
                    }
                    catch (Exception)
                    {
                        test(false);
                    }
                    cb.called();
                });
                cb.check();
            }

            {
                Callback cb = new Callback();
                thrower.begin_throwUndeclaredC(1, 2, 3).whenCompleted(
                    () =>
                {
                    test(false);
                },
                    (Ice.Exception exc) =>
                {
                    try
                    {
                        throw exc;
                    }
                    catch (Ice.UnknownUserException)
                    {
                    }
                    catch (Exception)
                    {
                        test(false);
                    }
                    cb.called();
                });
                cb.check();
            }

            WriteLine("ok");
        }

        Write("catching object not exist exception with new AMI mapping... ");
        Flush();

        {
            Ice.Identity id       = Ice.Util.stringToIdentity("does not exist");
            ThrowerPrx   thrower2 = ThrowerPrxHelper.uncheckedCast(thrower.ice_identity(id));
            Callback     cb       = new Callback();
            thrower2.begin_throwAasA(1).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.ObjectNotExistException ex)
                {
                    test(ex.id.Equals(id));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");

        Write("catching facet not exist exception with new AMI mapping... ");
        Flush();

        {
            ThrowerPrx thrower2 = ThrowerPrxHelper.uncheckedCast(thrower, "no such facet");
            Callback   cb       = new Callback();
            thrower2.begin_throwAasA(1).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.FacetNotExistException ex)
                {
                    test(ex.facet.Equals("no such facet"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");

        Write("catching operation not exist exception with new AMI mapping... ");
        Flush();

        {
            Callback          cb       = new Callback();
            WrongOperationPrx thrower4 = WrongOperationPrxHelper.uncheckedCast(thrower);
            thrower4.begin_noSuchOperation().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.OperationNotExistException ex)
                {
                    test(ex.operation.Equals("noSuchOperation"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");

        Write("catching unknown local exception with new AMI mapping... ");
        Flush();

        {
            Callback cb = new Callback();
            thrower.begin_throwLocalException().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.UnknownLocalException)
                {
                }
                catch (Ice.OperationNotExistException)
                {
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        {
            Callback cb = new Callback();
            thrower.begin_throwLocalExceptionIdempotent().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.UnknownLocalException)
                {
                }
                catch (Ice.OperationNotExistException)
                {
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");

        Write("catching unknown non-Ice exception with new AMI mapping... ");
        Flush();

        {
            Callback cb = new Callback();
            thrower.begin_throwNonIceException().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.UnknownException)
                {
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");

        if (thrower.supportsUndeclaredExceptions())
        {
            Write("catching unknown user exception with new AMI mapping... ");
            Flush();

            {
                Callback cb = new Callback();
                thrower.begin_throwUndeclaredA(1).whenCompleted(
                    () =>
                {
                    test(false);
                },
                    (Ice.Exception exc) =>
                {
                    try
                    {
                        throw exc;
                    }
                    catch (Ice.UnknownUserException)
                    {
                    }
                    catch (Exception)
                    {
                        test(false);
                    }
                    cb.called();
                });
                cb.check();
            }

            {
                Callback cb = new Callback();
                thrower.begin_throwUndeclaredB(1, 2).whenCompleted(
                    () =>
                {
                    test(false);
                },
                    (Ice.Exception exc) =>
                {
                    try
                    {
                        throw exc;
                    }
                    catch (Ice.UnknownUserException)
                    {
                    }
                    catch (Exception)
                    {
                        test(false);
                    }
                    cb.called();
                });
                cb.check();
            }

            {
                Callback cb = new Callback();
                thrower.begin_throwUndeclaredC(1, 2, 3).whenCompleted(
                    () =>
                {
                    test(false);
                },
                    (Ice.Exception exc) =>
                {
                    try
                    {
                        throw exc;
                    }
                    catch (Ice.UnknownUserException)
                    {
                    }
                    catch (Exception)
                    {
                        test(false);
                    }
                    cb.called();
                });
                cb.check();
            }

            WriteLine("ok");
        }

        Write("catching object not exist exception with new AMI mapping... ");
        Flush();

        {
            Ice.Identity id       = Ice.Util.stringToIdentity("does not exist");
            ThrowerPrx   thrower2 = ThrowerPrxHelper.uncheckedCast(thrower.ice_identity(id));
            Callback     cb       = new Callback();
            thrower2.begin_throwAasA(1).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.ObjectNotExistException ex)
                {
                    test(ex.id.Equals(id));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");

        Write("catching facet not exist exception with new AMI mapping... ");
        Flush();

        {
            ThrowerPrx thrower2 = ThrowerPrxHelper.uncheckedCast(thrower, "no such facet");
            Callback   cb       = new Callback();
            thrower2.begin_throwAasA(1).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.FacetNotExistException ex)
                {
                    test(ex.facet.Equals("no such facet"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");

        Write("catching operation not exist exception with new AMI mapping... ");
        Flush();

        {
            Callback          cb       = new Callback();
            WrongOperationPrx thrower4 = WrongOperationPrxHelper.uncheckedCast(thrower);
            thrower4.begin_noSuchOperation().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.OperationNotExistException ex)
                {
                    test(ex.operation.Equals("noSuchOperation"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");

        Write("catching unknown local exception with new AMI mapping... ");
        Flush();

        {
            Callback cb = new Callback();
            thrower.begin_throwLocalException().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.UnknownLocalException)
                {
                }
                catch (Ice.OperationNotExistException)
                {
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        {
            Callback cb = new Callback();
            thrower.begin_throwLocalExceptionIdempotent().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.UnknownLocalException)
                {
                }
                catch (Ice.OperationNotExistException)
                {
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");

        Write("catching unknown non-Ice exception with new AMI mapping... ");
        Flush();

        {
            Callback cb = new Callback();
            thrower.begin_throwNonIceException().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception exc) =>
            {
                try
                {
                    throw exc;
                }
                catch (Ice.UnknownException)
                {
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }

        WriteLine("ok");
        return(thrower);
    }
Пример #16
0
    public static TestIntfPrx allTests(Test.TestHelper helper, bool collocated)
    {
        Ice.Communicator communicator = helper.communicator();
        var output = helper.getWriter();

        output.Write("testing stringToProxy... ");
        output.Flush();
        String @ref = "Test:" + helper.getTestEndpoint(0) + " -t 2000";

        Ice.ObjectPrx @base = communicator.stringToProxy(@ref);
        test(@base != null);
        output.WriteLine("ok");

        output.Write("testing checked cast... ");
        output.Flush();
        TestIntfPrx testPrx = TestIntfPrxHelper.checkedCast(@base);

        test(testPrx != null);
        test(testPrx.Equals(@base));
        output.WriteLine("ok");

        output.Write("base... ");
        output.Flush();
        {
            try
            {
                testPrx.baseAsBase();
                test(false);
            }
            catch (Base b)
            {
                test(b.b.Equals("Base.b"));
                test(b.GetType().FullName.Equals("Test.Base"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("base (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.baseAsBaseAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (Base b)
                {
                    test(b.b.Equals("Base.b"));
                    test(b.GetType().Name.Equals("Base"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of unknown derived... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownDerivedAsBase();
                test(false);
            }
            catch (Base b)
            {
                test(b.b.Equals("UnknownDerived.b"));
                test(b.GetType().FullName.Equals("Test.Base"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of unknown derived (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownDerivedAsBaseAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (Base b)
                {
                    test(b.b.Equals("UnknownDerived.b"));
                    test(b.GetType().Name.Equals("Base"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("non-slicing of known derived as base... ");
        output.Flush();
        {
            try
            {
                testPrx.knownDerivedAsBase();
                test(false);
            }
            catch (KnownDerived k)
            {
                test(k.b.Equals("KnownDerived.b"));
                test(k.kd.Equals("KnownDerived.kd"));
                test(k.GetType().FullName.Equals("Test.KnownDerived"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("non-slicing of known derived as base (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.knownDerivedAsBaseAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (KnownDerived k)
                {
                    test(k.b.Equals("KnownDerived.b"));
                    test(k.kd.Equals("KnownDerived.kd"));
                    test(k.GetType().Name.Equals("KnownDerived"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("non-slicing of known derived as derived... ");
        output.Flush();
        {
            try
            {
                testPrx.knownDerivedAsKnownDerived();
                test(false);
            }
            catch (KnownDerived k)
            {
                test(k.b.Equals("KnownDerived.b"));
                test(k.kd.Equals("KnownDerived.kd"));
                test(k.GetType().FullName.Equals("Test.KnownDerived"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("non-slicing of known derived as derived (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.knownDerivedAsKnownDerivedAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (KnownDerived k)
                {
                    test(k.b.Equals("KnownDerived.b"));
                    test(k.kd.Equals("KnownDerived.kd"));
                    test(k.GetType().Name.Equals("KnownDerived"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of unknown intermediate as base... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownIntermediateAsBase();
                test(false);
            }
            catch (Base b)
            {
                test(b.b.Equals("UnknownIntermediate.b"));
                test(b.GetType().FullName.Equals("Test.Base"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of unknown intermediate as base (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownIntermediateAsBaseAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (Base b)
                {
                    test(b.b.Equals("UnknownIntermediate.b"));
                    test(b.GetType().Name.Equals("Base"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of known intermediate as base... ");
        output.Flush();
        {
            try
            {
                testPrx.knownIntermediateAsBase();
                test(false);
            }
            catch (KnownIntermediate ki)
            {
                test(ki.b.Equals("KnownIntermediate.b"));
                test(ki.ki.Equals("KnownIntermediate.ki"));
                test(ki.GetType().FullName.Equals("Test.KnownIntermediate"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of known intermediate as base (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.knownIntermediateAsBaseAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (KnownIntermediate ki)
                {
                    test(ki.b.Equals("KnownIntermediate.b"));
                    test(ki.ki.Equals("KnownIntermediate.ki"));
                    test(ki.GetType().Name.Equals("KnownIntermediate"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of known most derived as base... ");
        output.Flush();
        {
            try
            {
                testPrx.knownMostDerivedAsBase();
                test(false);
            }
            catch (KnownMostDerived kmd)
            {
                test(kmd.b.Equals("KnownMostDerived.b"));
                test(kmd.ki.Equals("KnownMostDerived.ki"));
                test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                test(kmd.GetType().FullName.Equals("Test.KnownMostDerived"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of known most derived as base (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.knownMostDerivedAsBaseAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (KnownMostDerived kmd)
                {
                    test(kmd.b.Equals("KnownMostDerived.b"));
                    test(kmd.ki.Equals("KnownMostDerived.ki"));
                    test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                    test(kmd.GetType().Name.Equals("KnownMostDerived"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("non-slicing of known intermediate as intermediate... ");
        output.Flush();
        {
            try
            {
                testPrx.knownIntermediateAsKnownIntermediate();
                test(false);
            }
            catch (KnownIntermediate ki)
            {
                test(ki.b.Equals("KnownIntermediate.b"));
                test(ki.ki.Equals("KnownIntermediate.ki"));
                test(ki.GetType().FullName.Equals("Test.KnownIntermediate"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("non-slicing of known intermediate as intermediate (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.knownIntermediateAsKnownIntermediateAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (KnownIntermediate ki)
                {
                    test(ki.b.Equals("KnownIntermediate.b"));
                    test(ki.ki.Equals("KnownIntermediate.ki"));
                    test(ki.GetType().Name.Equals("KnownIntermediate"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("non-slicing of known most derived as intermediate... ");
        output.Flush();
        {
            try
            {
                testPrx.knownMostDerivedAsKnownIntermediate();
                test(false);
            }
            catch (KnownMostDerived kmd)
            {
                test(kmd.b.Equals("KnownMostDerived.b"));
                test(kmd.ki.Equals("KnownMostDerived.ki"));
                test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                test(kmd.GetType().FullName.Equals("Test.KnownMostDerived"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("non-slicing of known most derived as intermediate (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.knownMostDerivedAsKnownIntermediateAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (KnownMostDerived kmd)
                {
                    test(kmd.b.Equals("KnownMostDerived.b"));
                    test(kmd.ki.Equals("KnownMostDerived.ki"));
                    test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                    test(kmd.GetType().Name.Equals("KnownMostDerived"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("non-slicing of known most derived as most derived... ");
        output.Flush();
        {
            try
            {
                testPrx.knownMostDerivedAsKnownMostDerived();
                test(false);
            }
            catch (KnownMostDerived kmd)
            {
                test(kmd.b.Equals("KnownMostDerived.b"));
                test(kmd.ki.Equals("KnownMostDerived.ki"));
                test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                test(kmd.GetType().FullName.Equals("Test.KnownMostDerived"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("non-slicing of known most derived as most derived (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.knownMostDerivedAsKnownMostDerivedAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (KnownMostDerived kmd)
                {
                    test(kmd.b.Equals("KnownMostDerived.b"));
                    test(kmd.ki.Equals("KnownMostDerived.ki"));
                    test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                    test(kmd.GetType().Name.Equals("KnownMostDerived"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of unknown most derived, known intermediate as base... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownMostDerived1AsBase();
                test(false);
            }
            catch (KnownIntermediate ki)
            {
                test(ki.b.Equals("UnknownMostDerived1.b"));
                test(ki.ki.Equals("UnknownMostDerived1.ki"));
                test(ki.GetType().FullName.Equals("Test.KnownIntermediate"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of unknown most derived, known intermediate as base (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownMostDerived1AsBaseAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (KnownIntermediate ki)
                {
                    test(ki.b.Equals("UnknownMostDerived1.b"));
                    test(ki.ki.Equals("UnknownMostDerived1.ki"));
                    test(ki.GetType().Name.Equals("KnownIntermediate"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of unknown most derived, known intermediate as intermediate... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownMostDerived1AsKnownIntermediate();
                test(false);
            }
            catch (KnownIntermediate ki)
            {
                test(ki.b.Equals("UnknownMostDerived1.b"));
                test(ki.ki.Equals("UnknownMostDerived1.ki"));
                test(ki.GetType().FullName.Equals("Test.KnownIntermediate"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of unknown most derived, known intermediate as intermediate (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownMostDerived1AsKnownIntermediateAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (KnownIntermediate ki)
                {
                    test(ki.b.Equals("UnknownMostDerived1.b"));
                    test(ki.ki.Equals("UnknownMostDerived1.ki"));
                    test(ki.GetType().Name.Equals("KnownIntermediate"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of unknown most derived, unknown intermediate thrown as base... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownMostDerived2AsBase();
                test(false);
            }
            catch (Base b)
            {
                test(b.b.Equals("UnknownMostDerived2.b"));
                test(b.GetType().FullName.Equals("Test.Base"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("slicing of unknown most derived, unknown intermediate thrown as base (AMI)... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownMostDerived2AsBaseAsync().Wait();
                test(false);
            }
            catch (AggregateException ae)
            {
                try
                {
                    throw ae.InnerException;
                }
                catch (Base b)
                {
                    test(b.b.Equals("UnknownMostDerived2.b"));
                    test(b.GetType().Name.Equals("Base"));
                }
                catch (Exception)
                {
                    test(false);
                }
            }
        }
        output.WriteLine("ok");

        output.Write("unknown most derived in compact format... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownMostDerived2AsBaseCompact();
                test(false);
            }
            catch (Base)
            {
                //
                // For the 1.0 encoding, the unknown exception is sliced to Base.
                //
                test(testPrx.ice_getEncodingVersion().Equals(Ice.Util.Encoding_1_0));
            }
            catch (Ice.UnknownUserException)
            {
                //
                // A MarshalException is raised for the compact format because the
                // most-derived type is unknown and the exception cannot be sliced.
                //
                test(!testPrx.ice_getEncodingVersion().Equals(Ice.Util.Encoding_1_0));
            }
            catch (Ice.OperationNotExistException)
            {
            }
            catch (Exception)
            {
                test(false);
            }
        }
        output.WriteLine("ok");

        output.Write("preserved exceptions... ");
        output.Flush();
        {
            try
            {
                testPrx.unknownPreservedAsBase();
                test(false);
            }
            catch (Base ex)
            {
                if (testPrx.ice_getEncodingVersion().Equals(Ice.Util.Encoding_1_0))
                {
                    test(ex.ice_getSlicedData() == null);
                }
                else
                {
                    Ice.SlicedData slicedData = ex.ice_getSlicedData();
                    test(slicedData != null);
                    test(slicedData.slices.Length == 2);
                    test(slicedData.slices[1].typeId.Equals("::Test::SPreserved1"));
                    test(slicedData.slices[0].typeId.Equals("::Test::SPreserved2"));
                }
            }

            try
            {
                testPrx.unknownPreservedAsKnownPreserved();
                test(false);
            }
            catch (KnownPreserved ex)
            {
                test(ex.kp.Equals("preserved"));
                if (testPrx.ice_getEncodingVersion().Equals(Ice.Util.Encoding_1_0))
                {
                    test(ex.ice_getSlicedData() == null);
                }
                else
                {
                    Ice.SlicedData slicedData = ex.ice_getSlicedData();
                    test(slicedData != null);
                    test(slicedData.slices.Length == 2);
                    test(slicedData.slices[1].typeId.Equals("::Test::SPreserved1"));
                    test(slicedData.slices[0].typeId.Equals("::Test::SPreserved2"));
                }
            }

            Ice.ObjectAdapter adapter = communicator.createObjectAdapter("");
            RelayPrx          relay   = RelayPrxHelper.uncheckedCast(adapter.addWithUUID(new RelayI()));
            adapter.activate();
            testPrx.ice_getConnection().setAdapter(adapter);

            try
            {
                testPrx.relayKnownPreservedAsBase(relay);
                test(false);
            }
            catch (KnownPreservedDerived ex)
            {
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
            }
            catch (Ice.OperationNotExistException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            try
            {
                testPrx.relayKnownPreservedAsKnownPreserved(relay);
                test(false);
            }
            catch (KnownPreservedDerived ex)
            {
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
            }
            catch (Ice.OperationNotExistException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            try
            {
                testPrx.relayUnknownPreservedAsBase(relay);
                test(false);
            }
            catch (Preserved2 ex)
            {
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
                test(ex.p1.ice_id().Equals(PreservedClass.ice_staticId()));
                PreservedClass pc = ex.p1 as PreservedClass;
                test(pc.bc.Equals("bc"));
                test(pc.pc.Equals("pc"));
                test(ex.p2 == ex.p1);
            }
            catch (KnownPreservedDerived ex)
            {
                //
                // For the 1.0 encoding, the unknown exception is sliced to KnownPreserved.
                //
                test(testPrx.ice_getEncodingVersion().Equals(Ice.Util.Encoding_1_0));
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
            }
            catch (Ice.OperationNotExistException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            try
            {
                testPrx.relayUnknownPreservedAsKnownPreserved(relay);
                test(false);
            }
            catch (Preserved2 ex)
            {
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
                test(ex.p1.ice_id().Equals(PreservedClass.ice_staticId()));
                PreservedClass pc = ex.p1 as PreservedClass;
                test(pc.bc.Equals("bc"));
                test(pc.pc.Equals("pc"));
                test(ex.p2 == ex.p1);
            }
            catch (KnownPreservedDerived ex)
            {
                //
                // For the 1.0 encoding, the unknown exception is sliced to KnownPreserved.
                //
                test(testPrx.ice_getEncodingVersion().Equals(Ice.Util.Encoding_1_0));
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
            }
            catch (Ice.OperationNotExistException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            adapter.destroy();
        }
        output.WriteLine("ok");

        return(testPrx);
    }
Пример #17
0
        public int run()
        {
            try
            {
                Ice.Properties properties = _communicator.Properties;

                //
                // Create an object adapter. Services probably should NOT share
                // this object adapter, as the endpoint(s) for this object adapter
                // will most likely need to be firewalled for security reasons.
                //
                Ice.ObjectAdapter adapter = null;
                if (properties.getProperty("IceBox.ServiceManager.Endpoints").Length != 0)
                {
                    adapter = _communicator.createObjectAdapter("IceBox.ServiceManager");

                    Ice.Identity identity = new Ice.Identity();
                    identity.category = properties.getPropertyWithDefault("IceBox.InstanceName", "IceBox");
                    identity.name     = "ServiceManager";
                    adapter.Add(this, identity);
                }

                //
                // Parse the property set with the prefix "IceBox.Service.". These
                // properties should have the following format:
                //
                // IceBox.Service.Foo=<assembly>:Package.Foo [args]
                //
                // We parse the service properties specified in IceBox.LoadOrder
                // first, then the ones from remaining services.
                //
                string prefix = "IceBox.Service.";
                Dictionary <string, string> services = properties.getPropertiesForPrefix(prefix);

                if (services.Count == 0)
                {
                    throw new FailureException("ServiceManager: configuration must include at least one IceBox service");
                }

                string[] loadOrder = properties.getPropertyAsList("IceBox.LoadOrder");
                List <StartServiceInfo> servicesInfo = new List <StartServiceInfo>();
                for (int i = 0; i < loadOrder.Length; ++i)
                {
                    if (loadOrder[i].Length > 0)
                    {
                        string key   = prefix + loadOrder[i];
                        string value = services[key];
                        if (value == null)
                        {
                            FailureException ex = new FailureException();
                            ex.reason = "ServiceManager: no service definition for `" + loadOrder[i] + "'";
                            throw ex;
                        }
                        servicesInfo.Add(new StartServiceInfo(loadOrder[i], value, _argv));
                        services.Remove(key);
                    }
                }
                foreach (KeyValuePair <string, string> entry in services)
                {
                    string name  = entry.Key.Substring(prefix.Length);
                    string value = entry.Value;
                    servicesInfo.Add(new StartServiceInfo(name, value, _argv));
                }

                //
                // Check if some services are using the shared communicator in which
                // case we create the shared communicator now with a property set that
                // is the union of all the service properties (from services that use
                // the shared communicator).
                //
                if (properties.getPropertiesForPrefix("IceBox.UseSharedCommunicator.").Count > 0)
                {
                    Ice.InitializationData initData = new Ice.InitializationData();
                    initData.properties = createServiceProperties("SharedCommunicator");
                    foreach (StartServiceInfo service in servicesInfo)
                    {
                        if (properties.getPropertyAsInt("IceBox.UseSharedCommunicator." + service.name) <= 0)
                        {
                            continue;
                        }

                        //
                        // Load the service properties using the shared communicator properties as
                        // the default properties.
                        //
                        Ice.Properties svcProperties = Ice.Util.createProperties(ref service.args, initData.properties);

                        //
                        // Remove properties from the shared property set that a service explicitly clears.
                        //
                        Dictionary <string, string> allProps = initData.properties.getPropertiesForPrefix("");
                        foreach (string key in allProps.Keys)
                        {
                            if (svcProperties.getProperty(key).Length == 0)
                            {
                                initData.properties.setProperty(key, "");
                            }
                        }

                        //
                        // Add the service properties to the shared communicator properties.
                        //
                        foreach (KeyValuePair <string, string> entry in svcProperties.getPropertiesForPrefix(string.Empty))
                        {
                            initData.properties.setProperty(entry.Key, entry.Value);
                        }

                        //
                        // Parse <service>.* command line options (the Ice command line options
                        // were parsed by the call to createProperties above).
                        //
                        service.args = initData.properties.parseCommandLineOptions(service.name, service.args);
                    }

                    string facetNamePrefix = "IceBox.SharedCommunicator.";
                    bool   addFacets       = configureAdmin(initData.properties, facetNamePrefix);

                    _sharedCommunicator = Ice.Util.initialize(initData);

                    if (addFacets)
                    {
                        // Add all facets created on shared communicator to the IceBox communicator
                        // but renamed <prefix>.<facet-name>, except for the Process facet which is
                        // never added.
                        foreach (var p in _sharedCommunicator.FindAllAdminFacets())
                        {
                            if (!p.Key.Equals("Process"))
                            {
                                _communicator.AddAdminFacet(p.Value.servant, p.Value.disp, facetNamePrefix + p.Key);
                            }
                        }
                    }
                }

                foreach (StartServiceInfo s in servicesInfo)
                {
                    startService(s.name, s.entryPoint, s.args);
                }

                //
                // Start Admin (if enabled) and/or deprecated IceBox.ServiceManager OA
                //
                _communicator.AddAdminFacet <ServiceManager, ServiceManagerTraits>(this, "IceBox.ServiceManager");
                _communicator.getAdmin();
                if (adapter != null)
                {
                    adapter.Activate();
                }

                //
                // We may want to notify external scripts that the services
                // have started and that IceBox is "ready".
                // This is done by defining the property IceBox.PrintServicesReady=bundleName
                //
                // bundleName is whatever you choose to call this set of
                // services. It will be echoed back as "bundleName ready".
                //
                // This must be done after start() has been invoked on the
                // services.
                //
                string bundleName = properties.getProperty("IceBox.PrintServicesReady");
                if (bundleName.Length > 0)
                {
                    Console.Out.WriteLine(bundleName + " ready");
                }

                _communicator.waitForShutdown();
            }
            catch (FailureException ex)
            {
                _logger.error(ex.ToString());
                return(1);
            }
            catch (Ice.CommunicatorDestroyedException)
            {
                // Expected if the communicator is shutdown
            }
            catch (Ice.ObjectAdapterDeactivatedException)
            {
                // Expected if the mmunicator is shutdown
            }
            catch (Exception ex)
            {
                _logger.error("ServiceManager: caught exception:\n" + ex.ToString());
                return(1);
            }
            finally
            {
                //
                // Invoke stop() on the services.
                //
                stopAll();
            }

            return(0);
        }
Пример #18
0
 public HoldI(Timer timer, Ice.ObjectAdapter adapter)
 {
     _timer = timer;
     _adapter = adapter;
 }
Пример #19
0
            public static void allTests(global::Test.TestHelper helper)
            {
                Ice.Communicator communicator = helper.communicator();
                var manager = Test.ServerManagerPrxHelper.checkedCast(
                    communicator.stringToProxy("ServerManager :" + helper.getTestEndpoint(0)));

                test(manager != null);
                var locator = Test.TestLocatorPrxHelper.uncheckedCast(communicator.getDefaultLocator());

                test(locator != null);
                var registry = Test.TestLocatorRegistryPrxHelper.checkedCast(locator.getRegistry());

                test(registry != null);

                var output = helper.getWriter();

                output.Write("testing stringToProxy... ");
                output.Flush();
                Ice.ObjectPrx @base = communicator.stringToProxy("test @ TestAdapter");
                Ice.ObjectPrx base2 = communicator.stringToProxy("test @ TestAdapter");
                Ice.ObjectPrx base3 = communicator.stringToProxy("test");
                Ice.ObjectPrx base4 = communicator.stringToProxy("ServerManager");
                Ice.ObjectPrx base5 = communicator.stringToProxy("test2");
                Ice.ObjectPrx base6 = communicator.stringToProxy("test @ ReplicatedAdapter");
                output.WriteLine("ok");

                output.Write("testing ice_locator and ice_getLocator... ");
                test(Ice.Util.proxyIdentityCompare(@base.ice_getLocator(), communicator.getDefaultLocator()) == 0);
                Ice.LocatorPrx anotherLocator =
                    Ice.LocatorPrxHelper.uncheckedCast(communicator.stringToProxy("anotherLocator"));
                @base = @base.ice_locator(anotherLocator);
                test(Ice.Util.proxyIdentityCompare(@base.ice_getLocator(), anotherLocator) == 0);
                communicator.setDefaultLocator(null);
                @base = communicator.stringToProxy("test @ TestAdapter");
                test(@base.ice_getLocator() == null);
                @base = @base.ice_locator(anotherLocator);
                test(Ice.Util.proxyIdentityCompare(@base.ice_getLocator(), anotherLocator) == 0);
                communicator.setDefaultLocator(locator);
                @base = communicator.stringToProxy("test @ TestAdapter");
                test(Ice.Util.proxyIdentityCompare(@base.ice_getLocator(), communicator.getDefaultLocator()) == 0);

                //
                // We also test ice_router/ice_getRouter(perhaps we should add a
                // test/Ice/router test?)
                //
                test(@base.ice_getRouter() == null);
                Ice.RouterPrx anotherRouter =
                    Ice.RouterPrxHelper.uncheckedCast(communicator.stringToProxy("anotherRouter"));
                @base = @base.ice_router(anotherRouter);
                test(Ice.Util.proxyIdentityCompare(@base.ice_getRouter(), anotherRouter) == 0);
                Ice.RouterPrx router = Ice.RouterPrxHelper.uncheckedCast(communicator.stringToProxy("dummyrouter"));
                communicator.setDefaultRouter(router);
                @base = communicator.stringToProxy("test @ TestAdapter");
                test(Ice.Util.proxyIdentityCompare(@base.ice_getRouter(), communicator.getDefaultRouter()) == 0);
                communicator.setDefaultRouter(null);
                @base = communicator.stringToProxy("test @ TestAdapter");
                test(@base.ice_getRouter() == null);
                output.WriteLine("ok");

                output.Write("starting server... ");
                output.Flush();
                manager.startServer();
                output.WriteLine("ok");

                output.Write("testing checked cast... ");
                output.Flush();
                var obj = Test.TestIntfPrxHelper.checkedCast(@base);

                test(obj != null);
                var obj2 = Test.TestIntfPrxHelper.checkedCast(base2);

                test(obj2 != null);
                var obj3 = Test.TestIntfPrxHelper.checkedCast(base3);

                test(obj3 != null);
                var obj4 = Test.ServerManagerPrxHelper.checkedCast(base4);

                test(obj4 != null);
                var obj5 = Test.TestIntfPrxHelper.checkedCast(base5);

                test(obj5 != null);
                var obj6 = Test.TestIntfPrxHelper.checkedCast(base6);

                test(obj6 != null);
                output.WriteLine("ok");

                output.Write("testing id@AdapterId indirect proxy... ");
                output.Flush();
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj2.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                output.WriteLine("ok");

                output.Write("testing id@ReplicaGroupId indirect proxy... ");
                output.Flush();
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj6.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                output.WriteLine("ok");

                output.Write("testing identity indirect proxy... ");
                output.Flush();
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj3.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                try
                {
                    obj2.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj2.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                try
                {
                    obj3.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj2.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj3.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                obj.shutdown();
                manager.startServer();
                try
                {
                    obj5 = Test.TestIntfPrxHelper.checkedCast(base5);
                    obj5.ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                output.WriteLine("ok");

                output.Write("testing proxy with unknown identity... ");
                output.Flush();
                try
                {
                    @base = communicator.stringToProxy("unknown/unknown");
                    @base.ice_ping();
                    test(false);
                }
                catch (Ice.NotRegisteredException ex)
                {
                    test(ex.kindOfObject.Equals("object"));
                    test(ex.id.Equals("unknown/unknown"));
                }
                output.WriteLine("ok");

                output.Write("testing proxy with unknown adapter... ");
                output.Flush();
                try
                {
                    @base = communicator.stringToProxy("test @ TestAdapterUnknown");
                    @base.ice_ping();
                    test(false);
                }
                catch (Ice.NotRegisteredException ex)
                {
                    test(ex.kindOfObject.Equals("object adapter"));
                    test(ex.id.Equals("TestAdapterUnknown"));
                }
                output.WriteLine("ok");

                output.Write("testing locator cache timeout... ");
                output.Flush();

                Ice.ObjectPrx basencc = communicator.stringToProxy("test@TestAdapter").ice_connectionCached(false);
                int           count   = locator.getRequestCount();

                basencc.ice_locatorCacheTimeout(0).ice_ping(); // No locator cache.
                test(++count == locator.getRequestCount());
                basencc.ice_locatorCacheTimeout(0).ice_ping(); // No locator cache.
                test(++count == locator.getRequestCount());
                basencc.ice_locatorCacheTimeout(2).ice_ping(); // 2s timeout.
                test(count == locator.getRequestCount());
                System.Threading.Thread.Sleep(1300);           // 1300ms
                basencc.ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout.
                test(++count == locator.getRequestCount());

                communicator.stringToProxy("test").ice_locatorCacheTimeout(0).ice_ping(); // No locator cache.
                count += 2;
                test(count == locator.getRequestCount());
                communicator.stringToProxy("test").ice_locatorCacheTimeout(2).ice_ping(); // 2s timeout
                test(count == locator.getRequestCount());
                System.Threading.Thread.Sleep(1300);                                      // 1300ms
                communicator.stringToProxy("test").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout
                count += 2;
                test(count == locator.getRequestCount());

                communicator.stringToProxy("test@TestAdapter").ice_locatorCacheTimeout(-1).ice_ping();
                test(count == locator.getRequestCount());
                communicator.stringToProxy("test").ice_locatorCacheTimeout(-1).ice_ping();
                test(count == locator.getRequestCount());
                communicator.stringToProxy("test@TestAdapter").ice_ping();
                test(count == locator.getRequestCount());
                communicator.stringToProxy("test").ice_ping();
                test(count == locator.getRequestCount());

                test(communicator.stringToProxy("test").ice_locatorCacheTimeout(99).ice_getLocatorCacheTimeout() == 99);

                output.WriteLine("ok");

                output.Write("testing proxy from server... ");
                output.Flush();
                obj = Test.TestIntfPrxHelper.checkedCast(communicator.stringToProxy("test@TestAdapter"));
                var hello = obj.getHello();

                test(hello.ice_getAdapterId().Equals("TestAdapter"));
                hello.sayHello();
                hello = obj.getReplicatedHello();
                test(hello.ice_getAdapterId().Equals("ReplicatedAdapter"));
                hello.sayHello();
                output.WriteLine("ok");

                output.Write("testing locator request queuing... ");
                output.Flush();
                hello = (Test.HelloPrx)obj.getReplicatedHello().ice_locatorCacheTimeout(0).ice_connectionCached(false);
                count = locator.getRequestCount();
                hello.ice_ping();
                test(++count == locator.getRequestCount());
                List <Ice.AsyncResult <Test.Callback_Hello_sayHello> > results =
                    new List <Ice.AsyncResult <Test.Callback_Hello_sayHello> >();

                for (int i = 0; i < 1000; i++)
                {
                    Ice.AsyncResult <Test.Callback_Hello_sayHello> result = hello.begin_sayHello().
                                                                            whenCompleted(
                        () =>
                    {
                    },
                        (Ice.Exception ex) =>
                    {
                        test(false);
                    });
                    results.Add(result);
                }
                foreach (Ice.AsyncResult <Test.Callback_Hello_sayHello> result in results)
                {
                    result.waitForCompleted();
                }
                results.Clear();
                test(locator.getRequestCount() > count && locator.getRequestCount() < count + 999);
                if (locator.getRequestCount() > count + 800)
                {
                    output.Write("queuing = " + (locator.getRequestCount() - count));
                }
                count = locator.getRequestCount();
                hello = (Test.HelloPrx)hello.ice_adapterId("unknown");
                for (int i = 0; i < 1000; i++)
                {
                    Ice.AsyncResult <Test.Callback_Hello_sayHello> result = hello.begin_sayHello().
                                                                            whenCompleted(
                        () =>
                    {
                        test(false);
                    },
                        (Ice.Exception ex) =>
                    {
                        test(ex is Ice.NotRegisteredException);
                    });
                    results.Add(result);
                }
                foreach (Ice.AsyncResult <Test.Callback_Hello_sayHello> result in results)
                {
                    result.waitForCompleted();
                }
                results.Clear();
                // XXX:
                // Take into account the retries.
                test(locator.getRequestCount() > count && locator.getRequestCount() < count + 1999);
                if (locator.getRequestCount() > count + 800)
                {
                    output.Write("queuing = " + (locator.getRequestCount() - count));
                }
                output.WriteLine("ok");

                output.Write("testing adapter locator cache... ");
                output.Flush();
                try
                {
                    communicator.stringToProxy("test@TestAdapter3").ice_ping();
                    test(false);
                }
                catch (Ice.NotRegisteredException ex)
                {
                    test(ex.kindOfObject == "object adapter");
                    test(ex.id.Equals("TestAdapter3"));
                }
                registry.setAdapterDirectProxy("TestAdapter3", locator.findAdapterById("TestAdapter"));
                try
                {
                    communicator.stringToProxy("test@TestAdapter3").ice_ping();
                    registry.setAdapterDirectProxy("TestAdapter3",
                                                   communicator.stringToProxy("dummy:" + helper.getTestEndpoint(99)));
                    communicator.stringToProxy("test@TestAdapter3").ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }

                try
                {
                    communicator.stringToProxy("test@TestAdapter3").ice_locatorCacheTimeout(0).ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                try
                {
                    communicator.stringToProxy("test@TestAdapter3").ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                registry.setAdapterDirectProxy("TestAdapter3", locator.findAdapterById("TestAdapter"));
                try
                {
                    communicator.stringToProxy("test@TestAdapter3").ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }
                output.WriteLine("ok");

                output.Write("testing well-known object locator cache... ");
                output.Flush();
                registry.addObject(communicator.stringToProxy("test3@TestUnknown"));
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                    test(false);
                }
                catch (Ice.NotRegisteredException ex)
                {
                    test(ex.kindOfObject == "object adapter");
                    test(ex.id.Equals("TestUnknown"));
                }
                registry.addObject(communicator.stringToProxy("test3@TestAdapter4")); // Update
                registry.setAdapterDirectProxy("TestAdapter4",
                                               communicator.stringToProxy("dummy:" + helper.getTestEndpoint(99)));
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                registry.setAdapterDirectProxy("TestAdapter4", locator.findAdapterById("TestAdapter"));
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }

                registry.setAdapterDirectProxy("TestAdapter4",
                                               communicator.stringToProxy("dummy:" + helper.getTestEndpoint(99)));
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }

                try
                {
                    communicator.stringToProxy("test@TestAdapter4").ice_locatorCacheTimeout(0).ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                try
                {
                    communicator.stringToProxy("test@TestAdapter4").ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                registry.addObject(communicator.stringToProxy("test3@TestAdapter"));
                try
                {
                    communicator.stringToProxy("test3").ice_ping();
                }
                catch (Ice.LocalException)
                {
                    test(false);
                }

                registry.addObject(communicator.stringToProxy("test4"));
                try
                {
                    communicator.stringToProxy("test4").ice_ping();
                    test(false);
                }
                catch (Ice.NoEndpointException)
                {
                }
                output.WriteLine("ok");

                output.Write("testing locator cache background updates... ");
                output.Flush();
                {
                    Ice.InitializationData initData = new Ice.InitializationData();
                    initData.properties = communicator.getProperties().ice_clone_();
                    initData.properties.setProperty("Ice.BackgroundLocatorCacheUpdates", "1");
                    Ice.Communicator ic = helper.initialize(initData);

                    registry.setAdapterDirectProxy("TestAdapter5", locator.findAdapterById("TestAdapter"));
                    registry.addObject(communicator.stringToProxy("test3@TestAdapter"));

                    count = locator.getRequestCount();
                    ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(0).ice_ping(); // No locator cache.
                    ic.stringToProxy("test3").ice_locatorCacheTimeout(0).ice_ping();             // No locator cache.
                    count += 3;
                    test(count == locator.getRequestCount());
                    registry.setAdapterDirectProxy("TestAdapter5", null);
                    registry.addObject(communicator.stringToProxy("test3:" + helper.getTestEndpoint(99)));
                    ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(10).ice_ping(); // 10s timeout.
                    ic.stringToProxy("test3").ice_locatorCacheTimeout(10).ice_ping();             // 10s timeout.
                    test(count == locator.getRequestCount());
                    System.Threading.Thread.Sleep(1200);

                    // The following request should trigger the background
                    // updates but still use the cached endpoints and
                    // therefore succeed.
                    ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout.
                    ic.stringToProxy("test3").ice_locatorCacheTimeout(1).ice_ping();             // 1s timeout.

                    try
                    {
                        while (true)
                        {
                            ic.stringToProxy("test@TestAdapter5").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout.
                            System.Threading.Thread.Sleep(10);
                        }
                    }
                    catch (Ice.LocalException)
                    {
                        // Expected to fail once they endpoints have been updated in the background.
                    }
                    try
                    {
                        while (true)
                        {
                            ic.stringToProxy("test3").ice_locatorCacheTimeout(1).ice_ping(); // 1s timeout.
                            System.Threading.Thread.Sleep(10);
                        }
                    }
                    catch (Ice.LocalException)
                    {
                        // Expected to fail once they endpoints have been updated in the background.
                    }
                    ic.destroy();
                }
                output.WriteLine("ok");

                output.Write("testing proxy from server after shutdown... ");
                output.Flush();
                hello = obj.getReplicatedHello();
                obj.shutdown();
                manager.startServer();
                hello.sayHello();
                output.WriteLine("ok");

                output.Write("testing object migration... ");
                output.Flush();
                hello = Test.HelloPrxHelper.checkedCast(communicator.stringToProxy("hello"));
                obj.migrateHello();
                hello.ice_getConnection().close(Ice.ConnectionClose.GracefullyWithWait);
                hello.sayHello();
                obj.migrateHello();
                hello.sayHello();
                obj.migrateHello();
                hello.sayHello();
                output.WriteLine("ok");

                output.Write("testing locator encoding resolution... ");
                output.Flush();
                hello = Test.HelloPrxHelper.checkedCast(communicator.stringToProxy("hello"));
                count = locator.getRequestCount();
                communicator.stringToProxy("test@TestAdapter").ice_encodingVersion(Ice.Util.Encoding_1_1).ice_ping();
                test(count == locator.getRequestCount());
                communicator.stringToProxy("test@TestAdapter10").ice_encodingVersion(Ice.Util.Encoding_1_0).ice_ping();
                test(++count == locator.getRequestCount());
                communicator.stringToProxy("test -e 1.0@TestAdapter10-2").ice_ping();
                test(++count == locator.getRequestCount());
                output.WriteLine("ok");

                output.Write("shutdown server... ");
                output.Flush();
                obj.shutdown();
                output.WriteLine("ok");

                output.Write("testing whether server is gone... ");
                output.Flush();
                try
                {
                    obj2.ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                try
                {
                    obj3.ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                try
                {
                    obj5.ice_ping();
                    test(false);
                }
                catch (Ice.LocalException)
                {
                }
                output.WriteLine("ok");

                output.Write("testing indirect proxies to collocated objects... ");
                output.Flush();

                communicator.getProperties().setProperty("Hello.AdapterId", Guid.NewGuid().ToString());
                Ice.ObjectAdapter adapter = communicator.createObjectAdapterWithEndpoints("Hello", "default");

                Ice.Identity id = new Ice.Identity();
                id.name = Guid.NewGuid().ToString();
                adapter.add(new HelloI(), id);
                adapter.activate();

                // Ensure that calls on the well-known proxy is collocated.
                var helloPrx = Test.HelloPrxHelper.checkedCast(
                    communicator.stringToProxy("\"" + communicator.identityToString(id) + "\""));

                test(helloPrx.ice_getConnection() == null);

                // Ensure that calls on the indirect proxy (with adapter ID) is collocated
                helloPrx = Test.HelloPrxHelper.checkedCast(adapter.createIndirectProxy(id));
                test(helloPrx.ice_getConnection() == null);

                // Ensure that calls on the direct proxy is collocated
                helloPrx = Test.HelloPrxHelper.checkedCast(adapter.createDirectProxy(id));
                test(helloPrx.ice_getConnection() == null);

                output.WriteLine("ok");

                output.Write("shutdown server manager... ");
                output.Flush();
                manager.shutdown();
                output.WriteLine("ok");
            }
Пример #20
0
        public void initialize()
        {
            Ice.Properties properties = _communicator.getProperties();

            bool ipv4 = properties.getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0;
            bool preferIPv6 = properties.getPropertyAsInt("Ice.PreferIPv6Address") > 0;
            string address;
            if(ipv4 && !preferIPv6)
            {
                address = properties.getPropertyWithDefault("IceDiscovery.Address", "239.255.0.1");
            }
            else
            {
                address = properties.getPropertyWithDefault("IceDiscovery.Address", "ff15::1");
            }
            int port = properties.getPropertyAsIntWithDefault("IceDiscovery.Port", 4061);
            string intf = properties.getProperty("IceDiscovery.Interface");

            if(properties.getProperty("IceDiscovery.Multicast.Endpoints").Length == 0)
            {
                StringBuilder s = new StringBuilder();
                s.Append("udp -h \"").Append(address).Append("\" -p ").Append(port);
                if(intf.Length != 0)
                {
                    s.Append(" --interface \"").Append(intf).Append("\"");
                }
                properties.setProperty("IceDiscovery.Multicast.Endpoints", s.ToString());
            }
            if(properties.getProperty("IceDiscovery.Reply.Endpoints").Length == 0)
            {
                StringBuilder s = new StringBuilder();
                s.Append("udp");
                if(intf.Length != 0)
                {
                    s.Append(" -h \"").Append(intf).Append("\"");
                }
                properties.setProperty("IceDiscovery.Reply.Endpoints", s.ToString());
            }
            if(properties.getProperty("IceDiscovery.Locator.Endpoints").Length == 0)
            {
                properties.setProperty("IceDiscovery.Locator.AdapterId", Guid.NewGuid().ToString());
            }

            _multicastAdapter = _communicator.createObjectAdapter("IceDiscovery.Multicast");
            _replyAdapter = _communicator.createObjectAdapter("IceDiscovery.Reply");
            _locatorAdapter = _communicator.createObjectAdapter("IceDiscovery.Locator");

            //
            // Setup locatory registry.
            //
            LocatorRegistryI locatorRegistry = new LocatorRegistryI(_communicator);
            Ice.LocatorRegistryPrx locatorRegistryPrx = Ice.LocatorRegistryPrxHelper.uncheckedCast(
                _locatorAdapter.addWithUUID(locatorRegistry));

            string lookupEndpoints = properties.getProperty("IceDiscovery.Lookup");
            if(lookupEndpoints.Length == 0)
            {
                lookupEndpoints = "udp -h \"" + address + "\" -p " + port;
                if(intf.Length > 0)
                {
                    lookupEndpoints += " --interface \"" + intf + "\"";
                }
            }

            Ice.ObjectPrx lookupPrx = _communicator.stringToProxy("IceDiscovery/Lookup -d:" + lookupEndpoints);
            lookupPrx = lookupPrx.ice_collocationOptimized(false);
            try
            {
                lookupPrx.ice_getConnection();
            }
            catch(Ice.LocalException ex)
            {
                StringBuilder b = new StringBuilder();
                b.Append("IceDiscovery is unable to establish a multicast connection:\n");
                b.Append("proxy = ");
                b.Append(lookupPrx.ToString());
                b.Append('\n');
                b.Append(ex.ToString());
                throw new Ice.PluginInitializationException(b.ToString());
            }

            //
            // Add lookup and lookup reply Ice objects
            //
            LookupI lookup = new LookupI(locatorRegistry, LookupPrxHelper.uncheckedCast(lookupPrx), properties);
            _multicastAdapter.add(lookup, Ice.Util.stringToIdentity("IceDiscovery/Lookup"));

            Ice.ObjectPrx lookupReply = _replyAdapter.addWithUUID(new LookupReplyI(lookup)).ice_datagram();
            lookup.setLookupReply(LookupReplyPrxHelper.uncheckedCast(lookupReply));

            //
            // Setup locator on the communicator.
            //
            Ice.ObjectPrx loc;
            loc = _locatorAdapter.addWithUUID(
                new LocatorI(lookup, Ice.LocatorRegistryPrxHelper.uncheckedCast(locatorRegistryPrx)));
            _communicator.setDefaultLocator(Ice.LocatorPrxHelper.uncheckedCast(loc));

            _multicastAdapter.activate();
            _replyAdapter.activate();
            _locatorAdapter.activate();
        }
Пример #21
0
    public static TestIntfPrx allTests(Ice.Communicator communicator, bool collocated)
    {
        Write("testing stringToProxy... ");
        Flush();
        String @ref = "Test:default -p 12010 -t 2000";

        Ice.ObjectPrx @base = communicator.stringToProxy(@ref);
        test(@base != null);
        WriteLine("ok");

        Write("testing checked cast... ");
        Flush();
        TestIntfPrx testPrx = TestIntfPrxHelper.checkedCast(@base);

        test(testPrx != null);
        test(testPrx.Equals(@base));
        WriteLine("ok");

        Write("base... ");
        Flush();
        {
            try
            {
                testPrx.baseAsBase();
                test(false);
            }
            catch (Base b)
            {
                test(b.b.Equals("Base.b"));
                test(b.GetType().FullName.Equals("Test.Base"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("base (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_baseAsBase().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (Base b)
                {
                    test(b.b.Equals("Base.b"));
                    test(b.GetType().Name.Equals("Base"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("slicing of unknown derived... ");
        Flush();
        {
            try
            {
                testPrx.unknownDerivedAsBase();
                test(false);
            }
            catch (Base b)
            {
                test(b.b.Equals("UnknownDerived.b"));
                test(b.GetType().FullName.Equals("Test.Base"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("slicing of unknown derived (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_unknownDerivedAsBase().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (Base b)
                {
                    test(b.b.Equals("UnknownDerived.b"));
                    test(b.GetType().Name.Equals("Base"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("non-slicing of known derived as base... ");
        Flush();
        {
            try
            {
                testPrx.knownDerivedAsBase();
                test(false);
            }
            catch (KnownDerived k)
            {
                test(k.b.Equals("KnownDerived.b"));
                test(k.kd.Equals("KnownDerived.kd"));
                test(k.GetType().FullName.Equals("Test.KnownDerived"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("non-slicing of known derived as base (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_knownDerivedAsBase().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (KnownDerived k)
                {
                    test(k.b.Equals("KnownDerived.b"));
                    test(k.kd.Equals("KnownDerived.kd"));
                    test(k.GetType().Name.Equals("KnownDerived"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("non-slicing of known derived as derived... ");
        Flush();
        {
            try
            {
                testPrx.knownDerivedAsKnownDerived();
                test(false);
            }
            catch (KnownDerived k)
            {
                test(k.b.Equals("KnownDerived.b"));
                test(k.kd.Equals("KnownDerived.kd"));
                test(k.GetType().FullName.Equals("Test.KnownDerived"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("non-slicing of known derived as derived (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_knownDerivedAsKnownDerived().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (KnownDerived k)
                {
                    test(k.b.Equals("KnownDerived.b"));
                    test(k.kd.Equals("KnownDerived.kd"));
                    test(k.GetType().Name.Equals("KnownDerived"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("slicing of unknown intermediate as base... ");
        Flush();
        {
            try
            {
                testPrx.unknownIntermediateAsBase();
                test(false);
            }
            catch (Base b)
            {
                test(b.b.Equals("UnknownIntermediate.b"));
                test(b.GetType().FullName.Equals("Test.Base"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("slicing of unknown intermediate as base (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_unknownIntermediateAsBase().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (Base b)
                {
                    test(b.b.Equals("UnknownIntermediate.b"));
                    test(b.GetType().Name.Equals("Base"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("slicing of known intermediate as base... ");
        Flush();
        {
            try
            {
                testPrx.knownIntermediateAsBase();
                test(false);
            }
            catch (KnownIntermediate ki)
            {
                test(ki.b.Equals("KnownIntermediate.b"));
                test(ki.ki.Equals("KnownIntermediate.ki"));
                test(ki.GetType().FullName.Equals("Test.KnownIntermediate"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("slicing of known intermediate as base (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_knownIntermediateAsBase().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (KnownIntermediate ki)
                {
                    test(ki.b.Equals("KnownIntermediate.b"));
                    test(ki.ki.Equals("KnownIntermediate.ki"));
                    test(ki.GetType().Name.Equals("KnownIntermediate"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("slicing of known most derived as base... ");
        Flush();
        {
            try
            {
                testPrx.knownMostDerivedAsBase();
                test(false);
            }
            catch (KnownMostDerived kmd)
            {
                test(kmd.b.Equals("KnownMostDerived.b"));
                test(kmd.ki.Equals("KnownMostDerived.ki"));
                test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                test(kmd.GetType().FullName.Equals("Test.KnownMostDerived"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("slicing of known most derived as base (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_knownMostDerivedAsBase().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (KnownMostDerived kmd)
                {
                    test(kmd.b.Equals("KnownMostDerived.b"));
                    test(kmd.ki.Equals("KnownMostDerived.ki"));
                    test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                    test(kmd.GetType().Name.Equals("KnownMostDerived"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("non-slicing of known intermediate as intermediate... ");
        Flush();
        {
            try
            {
                testPrx.knownIntermediateAsKnownIntermediate();
                test(false);
            }
            catch (KnownIntermediate ki)
            {
                test(ki.b.Equals("KnownIntermediate.b"));
                test(ki.ki.Equals("KnownIntermediate.ki"));
                test(ki.GetType().FullName.Equals("Test.KnownIntermediate"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("non-slicing of known intermediate as intermediate (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_knownIntermediateAsKnownIntermediate().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (KnownIntermediate ki)
                {
                    test(ki.b.Equals("KnownIntermediate.b"));
                    test(ki.ki.Equals("KnownIntermediate.ki"));
                    test(ki.GetType().Name.Equals("KnownIntermediate"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("non-slicing of known most derived as intermediate... ");
        Flush();
        {
            try
            {
                testPrx.knownMostDerivedAsKnownIntermediate();
                test(false);
            }
            catch (KnownMostDerived kmd)
            {
                test(kmd.b.Equals("KnownMostDerived.b"));
                test(kmd.ki.Equals("KnownMostDerived.ki"));
                test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                test(kmd.GetType().FullName.Equals("Test.KnownMostDerived"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("non-slicing of known most derived as intermediate (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_knownMostDerivedAsKnownIntermediate().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (KnownMostDerived kmd)
                {
                    test(kmd.b.Equals("KnownMostDerived.b"));
                    test(kmd.ki.Equals("KnownMostDerived.ki"));
                    test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                    test(kmd.GetType().Name.Equals("KnownMostDerived"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("non-slicing of known most derived as most derived... ");
        Flush();
        {
            try
            {
                testPrx.knownMostDerivedAsKnownMostDerived();
                test(false);
            }
            catch (KnownMostDerived kmd)
            {
                test(kmd.b.Equals("KnownMostDerived.b"));
                test(kmd.ki.Equals("KnownMostDerived.ki"));
                test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                test(kmd.GetType().FullName.Equals("Test.KnownMostDerived"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("non-slicing of known most derived as most derived (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_knownMostDerivedAsKnownMostDerived().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (KnownMostDerived kmd)
                {
                    test(kmd.b.Equals("KnownMostDerived.b"));
                    test(kmd.ki.Equals("KnownMostDerived.ki"));
                    test(kmd.kmd.Equals("KnownMostDerived.kmd"));
                    test(kmd.GetType().Name.Equals("KnownMostDerived"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("slicing of unknown most derived, known intermediate as base... ");
        Flush();
        {
            try
            {
                testPrx.unknownMostDerived1AsBase();
                test(false);
            }
            catch (KnownIntermediate ki)
            {
                test(ki.b.Equals("UnknownMostDerived1.b"));
                test(ki.ki.Equals("UnknownMostDerived1.ki"));
                test(ki.GetType().FullName.Equals("Test.KnownIntermediate"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("slicing of unknown most derived, known intermediate as base (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_unknownMostDerived1AsBase().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (KnownIntermediate ki)
                {
                    test(ki.b.Equals("UnknownMostDerived1.b"));
                    test(ki.ki.Equals("UnknownMostDerived1.ki"));
                    test(ki.GetType().Name.Equals("KnownIntermediate"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("slicing of unknown most derived, known intermediate as intermediate... ");
        Flush();
        {
            try
            {
                testPrx.unknownMostDerived1AsKnownIntermediate();
                test(false);
            }
            catch (KnownIntermediate ki)
            {
                test(ki.b.Equals("UnknownMostDerived1.b"));
                test(ki.ki.Equals("UnknownMostDerived1.ki"));
                test(ki.GetType().FullName.Equals("Test.KnownIntermediate"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("slicing of unknown most derived, known intermediate as intermediate (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_unknownMostDerived1AsKnownIntermediate().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (KnownIntermediate ki)
                {
                    test(ki.b.Equals("UnknownMostDerived1.b"));
                    test(ki.ki.Equals("UnknownMostDerived1.ki"));
                    test(ki.GetType().Name.Equals("KnownIntermediate"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("slicing of unknown most derived, unknown intermediate thrown as base... ");
        Flush();
        {
            try
            {
                testPrx.unknownMostDerived2AsBase();
                test(false);
            }
            catch (Base b)
            {
                test(b.b.Equals("UnknownMostDerived2.b"));
                test(b.GetType().FullName.Equals("Test.Base"));
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("slicing of unknown most derived, unknown intermediate thrown as base (AMI)... ");
        Flush();
        {
            Callback cb = new Callback();
            testPrx.begin_unknownMostDerived2AsBase().whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                try
                {
                    throw ex;
                }
                catch (Base b)
                {
                    test(b.b.Equals("UnknownMostDerived2.b"));
                    test(b.GetType().Name.Equals("Base"));
                }
                catch (Exception)
                {
                    test(false);
                }
                cb.called();
            });
            cb.check();
        }
        WriteLine("ok");

        Write("unknown most derived in compact format... ");
        Flush();
        {
            try
            {
                testPrx.unknownMostDerived2AsBaseCompact();
                test(false);
            }
            catch (Base)
            {
                //
                // For the 1.0 encoding, the unknown exception is sliced to Base.
                //
                test(testPrx.ice_getEncodingVersion().Equals(Ice.Util.Encoding_1_0));
            }
            catch (Ice.UnknownUserException)
            {
                //
                // A MarshalException is raised for the compact format because the
                // most-derived type is unknown and the exception cannot be sliced.
                //
                test(!testPrx.ice_getEncodingVersion().Equals(Ice.Util.Encoding_1_0));
            }
            catch (Ice.OperationNotExistException)
            {
            }
            catch (Exception)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("preserved exceptions... ");
        Flush();
        {
            Ice.ObjectAdapter adapter = communicator.createObjectAdapterWithEndpoints("Relay", "default");
            RelayPrx          relay   = RelayPrxHelper.uncheckedCast(adapter.addWithUUID(new RelayI()));
            adapter.activate();

            try
            {
                testPrx.relayKnownPreservedAsBase(relay);
                test(false);
            }
            catch (KnownPreservedDerived ex)
            {
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
            }
            catch (Ice.OperationNotExistException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            try
            {
                testPrx.relayKnownPreservedAsKnownPreserved(relay);
                test(false);
            }
            catch (KnownPreservedDerived ex)
            {
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
            }

            /*
             * catch(Exception)
             * {
             *  test(false);
             * }
             */
            catch (Ice.OperationNotExistException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            try
            {
                testPrx.relayUnknownPreservedAsBase(relay);
                test(false);
            }
            catch (Preserved2 ex)
            {
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
                test(ex.p1.ice_id().Equals(PreservedClass.ice_staticId()));
                PreservedClass pc = ex.p1 as PreservedClass;
                test(pc.bc.Equals("bc"));
                test(pc.pc.Equals("pc"));
                test(ex.p2 == ex.p1);
            }
            catch (KnownPreservedDerived ex)
            {
                //
                // For the 1.0 encoding, the unknown exception is sliced to KnownPreserved.
                //
                test(testPrx.ice_getEncodingVersion().Equals(Ice.Util.Encoding_1_0));
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
            }
            catch (Ice.OperationNotExistException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            try
            {
                testPrx.relayUnknownPreservedAsKnownPreserved(relay);
                test(false);
            }
            catch (Preserved2 ex)
            {
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
                test(ex.p1.ice_id().Equals(PreservedClass.ice_staticId()));
                PreservedClass pc = ex.p1 as PreservedClass;
                test(pc.bc.Equals("bc"));
                test(pc.pc.Equals("pc"));
                test(ex.p2 == ex.p1);
            }
            catch (KnownPreservedDerived ex)
            {
                //
                // For the 1.0 encoding, the unknown exception is sliced to KnownPreserved.
                //
                test(testPrx.ice_getEncodingVersion().Equals(Ice.Util.Encoding_1_0));
                test(ex.b.Equals("base"));
                test(ex.kp.Equals("preserved"));
                test(ex.kpd.Equals("derived"));
            }
            catch (Ice.OperationNotExistException)
            {
            }
            catch (Exception)
            {
                test(false);
            }

            adapter.destroy();
        }
        WriteLine("ok");
        return(testPrx);
    }
Пример #22
0
        public void initialize()
        {
            Ice.Properties properties = _communicator.getProperties();

            bool ipv4 = properties.getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0;
            bool preferIPv6 = properties.getPropertyAsInt("Ice.PreferIPv6Address") > 0;
            string address;
            if(ipv4 && !preferIPv6)
            {
                address = properties.getPropertyWithDefault("IceLocatorDiscovery.Address", "239.255.0.1");
            }
            else
            {
                address = properties.getPropertyWithDefault("IceLocatorDiscovery.Address", "ff15::1");
            }
            int port = properties.getPropertyAsIntWithDefault("IceLocatorDiscovery.Port", 4061);
            string intf = properties.getProperty("IceLocatorDiscovery.Interface");

            if(properties.getProperty("IceLocatorDiscovery.Reply.Endpoints").Length == 0)
            {
                System.Text.StringBuilder s = new System.Text.StringBuilder();
                s.Append("udp");
                if(intf.Length > 0)
                {
                    s.Append(" -h \"");
                    s.Append(intf);
                    s.Append("\"");
                }
                properties.setProperty("IceLocatorDiscovery.Reply.Endpoints", s.ToString());
            }
            if(properties.getProperty("IceLocatorDiscovery.Locator.Endpoints").Length == 0)
            {
                properties.setProperty("IceLocatorDiscovery.Locator.AdapterId", Guid.NewGuid().ToString());
            }

            _replyAdapter = _communicator.createObjectAdapter("IceLocatorDiscovery.Reply");
            _locatorAdapter = _communicator.createObjectAdapter("IceLocatorDiscovery.Locator");

            // We don't want those adapters to be registered with the locator so clear their locator.
            _replyAdapter.setLocator(null);
            _locatorAdapter.setLocator(null);

            string lookupEndpoints = properties.getProperty("IceLocatorDiscovery.Lookup");
            if(lookupEndpoints.Length == 0)
            {
                System.Text.StringBuilder s = new System.Text.StringBuilder();
                s.Append("udp -h \"");
                s.Append(address);
                s.Append("\" -p ");
                s.Append(port);
                if(intf.Length > 0)
                {
                    s.Append(" --interface \"");
                    s.Append(intf);
                    s.Append("\"");
                }
                lookupEndpoints = s.ToString();
            }

            Ice.ObjectPrx lookupPrx = _communicator.stringToProxy("IceLocatorDiscovery/Lookup -d:" + lookupEndpoints);
            lookupPrx = lookupPrx.ice_collocationOptimized(false); // No colloc optimization for the multicast proxy!
            try
            {
                lookupPrx.ice_getConnection(); // Ensure we can establish a connection to the multicast proxy
            }
            catch (Ice.LocalException ex)
            {
                System.Text.StringBuilder s = new System.Text.StringBuilder();
                s.Append("IceLocatorDiscovery is unable to establish a multicast connection:\n");
                s.Append("proxy = ");
                s.Append(lookupPrx.ToString());
                s.Append("\n");
                s.Append(ex);
                throw new Ice.PluginInitializationException(s.ToString());
            }

            Ice.LocatorPrx voidLo = Ice.LocatorPrxHelper.uncheckedCast(_locatorAdapter.addWithUUID(new VoidLocatorI()));

            string instanceName = properties.getProperty("IceLocatorDiscovery.InstanceName");
            Ice.Identity id = new Ice.Identity();
            id.name = "Locator";
            id.category = instanceName.Length > 0 ? instanceName : Guid.NewGuid().ToString();

            LocatorI locator = new LocatorI(LookupPrxHelper.uncheckedCast(lookupPrx), properties, instanceName, voidLo);
            _communicator.setDefaultLocator(Ice.LocatorPrxHelper.uncheckedCast(_locatorAdapter.addWithUUID(locator)));

            Ice.ObjectPrx lookupReply = _replyAdapter.addWithUUID(new LookupReplyI(locator)).ice_datagram();
            locator.setLookupReply(LookupReplyPrxHelper.uncheckedCast(lookupReply));

            _replyAdapter.activate();
            _locatorAdapter.activate();
        }
Пример #23
0
            public override void startServer(Ice.Current current)
            {
                foreach (Ice.Communicator c in _communicators)
                {
                    c.waitForShutdown();
                    c.destroy();
                }
                _communicators.Clear();

                //
                // Simulate a server: create a new communicator and object
                // adapter. The object adapter is started on a system allocated
                // port. The configuration used here contains the Ice.Locator
                // configuration variable. The new object adapter will register
                // its endpoints with the locator and create references containing
                // the adapter id instead of the endpoints.
                //
                Ice.InitializationData initData = new Ice.InitializationData();
                initData.properties = _helper.communicator().getProperties().ice_clone_();
                initData.properties.setProperty("TestAdapter.AdapterId", "TestAdapter");
                initData.properties.setProperty("TestAdapter.ReplicaGroupId", "ReplicatedAdapter");
                initData.properties.setProperty("TestAdapter2.AdapterId", "TestAdapter2");

                Ice.Communicator serverCommunicator = _helper.initialize(initData);
                _communicators.Add(serverCommunicator);

                //
                // Use fixed port to ensure that OA re-activation doesn't re-use previous port from
                // another OA(e.g.: TestAdapter2 is re-activated using port of TestAdapter).
                //
                int nRetry = 10;

                while (--nRetry > 0)
                {
                    Ice.ObjectAdapter adapter  = null;
                    Ice.ObjectAdapter adapter2 = null;
                    try
                    {
                        serverCommunicator.getProperties().setProperty("TestAdapter.Endpoints",
                                                                       _helper.getTestEndpoint(_nextPort++));
                        serverCommunicator.getProperties().setProperty("TestAdapter2.Endpoints",
                                                                       _helper.getTestEndpoint(_nextPort++));

                        adapter  = serverCommunicator.createObjectAdapter("TestAdapter");
                        adapter2 = serverCommunicator.createObjectAdapter("TestAdapter2");

                        Ice.ObjectPrx locator = serverCommunicator.stringToProxy("locator:" + _helper.getTestEndpoint(0));
                        adapter.setLocator(Ice.LocatorPrxHelper.uncheckedCast(locator));
                        adapter2.setLocator(Ice.LocatorPrxHelper.uncheckedCast(locator));

                        Ice.Object @object = new TestI(adapter, adapter2, _registry);
                        _registry.addObject(adapter.add(@object, Ice.Util.stringToIdentity("test")));
                        _registry.addObject(adapter.add(@object, Ice.Util.stringToIdentity("test2")));
                        adapter.add(@object, Ice.Util.stringToIdentity("test3"));

                        adapter.activate();
                        adapter2.activate();
                        break;
                    }
                    catch (Ice.SocketException)
                    {
                        if (nRetry == 0)
                        {
                            throw;
                        }

                        // Retry, if OA creation fails with EADDRINUSE(this can occur when running with JS web
                        // browser clients if the driver uses ports in the same range as this test, ICE-8148)
                        if (adapter != null)
                        {
                            adapter.destroy();
                        }
                        if (adapter2 != null)
                        {
                            adapter2.destroy();
                        }
                    }
                }
            }
Пример #24
0
        public override int run(string[] args)
        {
            try
            {
                if (args.Length != 0)
                {
                    throw new ApplicationException("starting: too many arguments in application call.");
                }

                Log.APPNAME = Midax.Properties.Settings.Default.APP_NAME;

                Dictionary <string, string> dicSettings = new Dictionary <string, string>();
                List <string> stockList = new List <string>();
                foreach (SettingsPropertyValue prop in Midax.Properties.Settings.Default.PropertyValues)
                {
                    if (prop.Name == "STOCKS")
                    {
                        string[] stockArray = new string[100];
                        ((StringCollection)prop.PropertyValue).CopyTo(stockArray, 0);
                        foreach (string stock in stockArray)
                        {
                            if (stock != null && stock != "")
                            {
                                stockList.Add(stock);
                            }
                        }
                    }
                    else
                    {
                        dicSettings.Add(prop.Name, (string)prop.PropertyValue);
                    }
                }
                Config.Settings = dicSettings;

                Ice.ObjectAdapter adapter    = communicator().createObjectAdapter("MidaxIce");
                Ice.Properties    properties = communicator().getProperties();
                Ice.Identity      id         = communicator().stringToIdentity(properties.getProperty("Identity"));

                //Thread.Sleep(10000);

                /*
                 * List<string> rsiRefMappingGBP = new List<string> { dicSettings["FX_GBPEUR"], dicSettings["FX_GBPUSD"] };
                 * List<string> rsiRefMappingUSD = new List<string> { dicSettings["FX_USDJPY"], dicSettings["FX_EURUSD"] };
                 * List<decimal> volcoeffsGBP = new List<decimal> { 1m, 0.8m };
                 * List<decimal> volcoeffsUSD = new List<decimal> { 0.75m, 0.7m };*/

                var index  = IceStreamingMarketData.Instance;
                var dax    = new MarketData(dicSettings["INDEX_DAX"]);
                var dow    = new MarketData(dicSettings["INDEX_DOW"]);
                var cac    = new MarketData(dicSettings["INDEX_CAC"]);
                var ftse   = new MarketData(dicSettings["INDEX_FTSE"]);
                var icedow = new MarketData(dicSettings["INDEX_ICEDOW"]);
                var gbpusd = new MarketData(dicSettings["FX_GBPUSD"]);
                var eurusd = new MarketData(dicSettings["FX_EURUSD"]);
                var btcusd = new MarketData(dicSettings["FX_BTCUSD"]);
                var silver = new MarketData(dicSettings["COM_SILVER"]);

                /*
                 * List<MarketData> otherIndices = new List<MarketData>();
                 * otherIndices.Add(new MarketData(dicSettings["INDEX_CAC"]));
                 * otherIndices.Add(icedow);
                 * otherIndices.Add(gbpusd);
                 * otherIndices.Add(eurusd);
                 * otherIndices.Add(silver);*/
                var models = new List <Model>();
                //var macD_10_30_90_dax = new ModelMacD(dax, 10, 30, 90);
                var robinhood_eurusd = new ModelRobinHood(eurusd);
                var robinhood_gbpusd = new ModelRobinHood(gbpusd);
                //var robinhood_btcusd = new ModelRobinHood(btcusd);
                var robinhood_silver = new ModelRobinHood(silver);
                var robinhood_dax    = new ModelRobinHood(dax);
                //var robinhood_cac = new ModelRobinHood(cac);
                var robinhood_ftse = new ModelRobinHood(ftse);
                var robinhood_dow  = new ModelRobinHood(dow, 60, 48, 0, 20, 15, new IndicatorVolume(icedow, 60));
                //models.Add(macD_10_30_90_dax);
                models.Add(robinhood_eurusd);
                models.Add(robinhood_gbpusd);
                //models.Add(robinhood_btcusd);
                //models.Add(robinhood_silver);
                models.Add(robinhood_dax);
                //models.Add(robinhood_cac);
                //models.Add(robinhood_dow);
                //models.Add(robinhood_ftse);
                //models.Add(new ModelANN("WMA_5_2", macD_10_30_90_dax, null, null, otherIndices));
                _trader = new Trader(models, communicator().shutdown);
                _trader.Init(Config.GetNow);

                adapter.add(new MidaxIceI(_trader, properties.getProperty("Ice.ProgramName")), id);
                adapter.activate();
                communicator().waitForShutdown();
            }
            catch (SEHException exc)
            {
                Log.Instance.WriteEntry("Midax server interop error: " + exc.ToString() + ", Error code: " + exc.ErrorCode, EventLogEntryType.Error);
            }
            catch (Exception exc)
            {
                Log.Instance.WriteEntry("Midax server error: " + exc.ToString(), EventLogEntryType.Error);
            }

            return(0);
        }
Пример #25
0
    public static void allTests(TestCommon.Application app)
    {
        Ice.Communicator communicator = app.communicator();
        Console.Out.Write("testing stringToProxy... ");
        Console.Out.Flush();
        String rf = "test @ TestAdapter";

        Ice.ObjectPrx @base = communicator.stringToProxy(rf);
        test(@base != null);
        Console.Out.WriteLine("ok");

        Console.Out.Write("testing IceGrid.Locator is present... ");
        IceGrid.LocatorPrx locator = IceGrid.LocatorPrxHelper.uncheckedCast(@base);
        test(locator != null);
        Console.Out.WriteLine("ok");

        Console.Out.Write("testing checked cast... ");
        Console.Out.Flush();
        TestIntfPrx obj = TestIntfPrxHelper.checkedCast(@base);

        test(obj != null);
        test(obj.Equals(@base));
        Console.Out.WriteLine("ok");

        Console.Out.Write("pinging server... ");
        Console.Out.Flush();
        obj.ice_ping();
        Console.Out.WriteLine("ok");

        Console.Out.Write("testing locator finder... ");
        Ice.Identity finderId = new Ice.Identity();
        finderId.category = "Ice";
        finderId.name     = "LocatorFinder";
        Ice.LocatorFinderPrx finder = Ice.LocatorFinderPrxHelper.checkedCast(
            communicator.getDefaultLocator().ice_identity(finderId));
        test(finder.getLocator() != null);
        Console.Out.WriteLine("ok");

        Console.Out.Write("testing discovery... ");
        {
            // Add test well-known object
            IceGrid.RegistryPrx registry = IceGrid.RegistryPrxHelper.checkedCast(
                communicator.stringToProxy(communicator.getDefaultLocator().ice_getIdentity().category + "/Registry"));
            test(registry != null);

            try
            {
                IceGrid.AdminSessionPrx session = registry.createAdminSession("foo", "bar");
                session.getAdmin().addObjectWithType(@base, "::Test");
                session.destroy();
            }
            catch (Ice.UserException)
            {
                test(false);
            }

            //
            // Ensure the IceGrid discovery locator can discover the
            // registries and make sure locator requests are forwarded.
            //
            Ice.InitializationData initData = new Ice.InitializationData();
            initData.properties = communicator.getProperties().ice_clone_();
            initData.properties.setProperty("Ice.Default.Locator", "");
            initData.properties.setProperty("Ice.Plugin.IceLocatorDiscovery",
                                            "IceLocatorDiscovery:IceLocatorDiscovery.PluginFactory");
            initData.properties.setProperty("IceLocatorDiscovery.Port", app.getTestPort(99).ToString());
            initData.properties.setProperty("AdapterForDiscoveryTest.AdapterId", "discoveryAdapter");
            initData.properties.setProperty("AdapterForDiscoveryTest.Endpoints", "default");

            Ice.Communicator com = Ice.Util.initialize(initData);
            test(com.getDefaultLocator() != null);
            com.stringToProxy("test @ TestAdapter").ice_ping();
            com.stringToProxy("test").ice_ping();

            test(com.getDefaultLocator().getRegistry() != null);
            test(IceGrid.LocatorPrxHelper.uncheckedCast(com.getDefaultLocator()).getLocalRegistry() != null);
            test(IceGrid.LocatorPrxHelper.uncheckedCast(com.getDefaultLocator()).getLocalQuery() != null);

            Ice.ObjectAdapter adapter = com.createObjectAdapter("AdapterForDiscoveryTest");
            adapter.activate();
            adapter.deactivate();
            com.destroy();

            //
            // Now, ensure that the IceGrid discovery locator correctly
            // handles failure to find a locator.
            //
            initData.properties.setProperty("IceLocatorDiscovery.InstanceName", "unknown");
            initData.properties.setProperty("IceLocatorDiscovery.RetryCount", "1");
            initData.properties.setProperty("IceLocatorDiscovery.Timeout", "100");
            com = Ice.Util.initialize(initData);
            test(com.getDefaultLocator() != null);
            try
            {
                com.stringToProxy("test @ TestAdapter").ice_ping();
            }
            catch (Ice.NoEndpointException)
            {
            }
            try
            {
                com.stringToProxy("test").ice_ping();
            }
            catch (Ice.NoEndpointException)
            {
            }
            test(com.getDefaultLocator().getRegistry() == null);
            test(IceGrid.LocatorPrxHelper.checkedCast(com.getDefaultLocator()) == null);
            try
            {
                IceGrid.LocatorPrxHelper.uncheckedCast(com.getDefaultLocator()).getLocalRegistry();
            }
            catch (Ice.OperationNotExistException)
            {
            }

            adapter = com.createObjectAdapter("AdapterForDiscoveryTest");
            adapter.activate();
            adapter.deactivate();

            com.destroy();
        }
        Console.Out.WriteLine("ok");

        Console.Out.Write("shutting down server... ");
        Console.Out.Flush();
        obj.shutdown();
        Console.Out.WriteLine("ok");
    }
Пример #26
0
        //
        // Only for use by Ice.CommunicatorI
        //
        public bool destroy()
        {
            lock(this)
            {
                //
                // If the _state is not StateActive then the instance is
                // either being destroyed, or has already been destroyed.
                //
                if(_state != StateActive)
                {
                    return false;
                }

                //
                // We cannot set state to StateDestroyed otherwise instance
                // methods called during the destroy process (such as
                // outgoingConnectionFactory() from
                // ObjectAdapterI::deactivate() will cause an exception.
                //
                _state = StateDestroyInProgress;
            }

            if(_objectAdapterFactory != null)
            {
                _objectAdapterFactory.shutdown();
            }

            if(_outgoingConnectionFactory != null)
            {
                _outgoingConnectionFactory.destroy();
            }

            if(_objectAdapterFactory != null)
            {
                _objectAdapterFactory.destroy();
            }

            if(_outgoingConnectionFactory != null)
            {
                _outgoingConnectionFactory.waitUntilFinished();
            }

            if(_retryQueue != null)
            {
                _retryQueue.destroy();
            }

            ThreadPool serverThreadPool = null;
            ThreadPool clientThreadPool = null;
            AsyncIOThread asyncIOThread = null;
            EndpointHostResolver endpointHostResolver = null;

            lock(this)
            {
                _objectAdapterFactory = null;
                _outgoingConnectionFactory = null;
                _retryQueue = null;

                if(_connectionMonitor != null)
                {
                    _connectionMonitor.destroy();
                    _connectionMonitor = null;
                }

                if(_serverThreadPool != null)
                {
                    _serverThreadPool.destroy();
                    serverThreadPool = _serverThreadPool;
                    _serverThreadPool = null;
                }

                if(_clientThreadPool != null)
                {
                    _clientThreadPool.destroy();
                    clientThreadPool = _clientThreadPool;
                    _clientThreadPool = null;
                }

                if(_asyncIOThread != null)
                {
                    _asyncIOThread.destroy();
                    asyncIOThread = _asyncIOThread;
                    _asyncIOThread = null;
                }

                if(_endpointHostResolver != null)
                {
                    _endpointHostResolver.destroy();
                    endpointHostResolver = _endpointHostResolver;
                    _endpointHostResolver = null;
                }

                if(_timer != null)
                {
                    _timer.destroy();
                    _timer = null;
                }

                if(_servantFactoryManager != null)
                {
                    _servantFactoryManager.destroy();
                    _servantFactoryManager = null;
                }

                if(_referenceFactory != null)
                {
                    _referenceFactory.destroy();
                    _referenceFactory = null;
                }

                // No destroy function defined.
                // _proxyFactory.destroy();
                _proxyFactory = null;

                if(_routerManager != null)
                {
                    _routerManager.destroy();
                    _routerManager = null;
                }

                if(_locatorManager != null)
                {
                    _locatorManager.destroy();
                    _locatorManager = null;
                }

                if(_endpointFactoryManager != null)
                {
                    _endpointFactoryManager.destroy();
                    _endpointFactoryManager = null;
                }

                if(_pluginManager != null)
                {
                    _pluginManager.destroy();
                    _pluginManager = null;
                }

                _adminAdapter = null;
                _adminFacets.Clear();

                _state = StateDestroyed;
            }

            //
            // Join with threads outside the synchronization.
            //
            if(clientThreadPool != null)
            {
                clientThreadPool.joinWithAllThreads();
            }
            if(serverThreadPool != null)
            {
                serverThreadPool.joinWithAllThreads();
            }
            if(asyncIOThread != null)
            {
                asyncIOThread.joinWithThread();
            }
            if(endpointHostResolver != null)
            {
                endpointHostResolver.joinWithThread();
            }

            if(_initData.properties.getPropertyAsInt("Ice.Warn.UnusedProperties") > 0)
            {
                ArrayList unusedProperties = ((Ice.PropertiesI)_initData.properties).getUnusedProperties();
                if(unusedProperties.Count != 0)
                {
                    StringBuilder message = new StringBuilder("The following properties were set but never read:");
                    foreach(string s in unusedProperties)
                    {
                        message.Append("\n    ");
                        message.Append(s);
                    }
                    _initData.logger.warning(message.ToString());
                }
            }

            return true;
        }
Пример #27
0
 internal ActivateAdapterThread(Ice.ObjectAdapter adapter, int timeout)
 {
     _adapter = adapter;
     _timeout = timeout;
 }
Пример #28
0
        /// <summary>
        /// Returns an object adapter for callback objects, creating it if necessary.
        /// </summary>
        /// <returns>The object adapter.</returns>
        public Ice.ObjectAdapter objectAdapter()
        {
            if(_router == null)
            {
            throw new SessionNotExistException();
            }

            lock(mutex__)
            {
            if(_adapter == null)
            {
                _adapter = communicator().createObjectAdapterWithRouter("", _router);
                _adapter.activate();
            }
            }
            return _adapter;
        }
Пример #29
0
 getCollocatedObserver(Ice.ObjectAdapter adapter, int i, int j)
 {
     return(null);
 }
Пример #30
0
        public IceManager(string adapterName, string host, int port, bool catchSignals = true)
        {
            IceGridHost = host;
            IceGridPort = port;
            Name = adapterName;

            logger = log4net.LogManager.GetLogger(this.GetType().Name + "::" + Name);

            _ServantIds = new List<Ice.Identity>(); //keep track of servants for emergency cleanup
            string myIP = findLocalIPAddress();
            logger.Info("My IPAddress is: " + myIP);

            //initialize Ice
            Ice.Properties prop = Ice.Util.createProperties();
            prop.setProperty("hms.AdapterId", adapterName);
            prop.setProperty("hms.Endpoints", "tcp -h " + myIP + ":udp -h " + myIP);
            prop.setProperty("Ice.Default.Locator", "IceGrid/Locator:tcp -p " + IceGridPort + " -h " + IceGridHost);
            prop.setProperty("Ice.ThreadPool.Server.Size", "5");
            prop.setProperty("Ice.ThreadPool.Server.SizeMax", "100000");
            prop.setProperty("Ice.ThreadPool.Client.Size", "5");
            prop.setProperty("Ice.ThreadPool.Client.SizeMax", "100000");

            Ice.InitializationData iceidata = new Ice.InitializationData();
            iceidata.properties = prop;
            Communicator = Ice.Util.initialize(iceidata); // could add sys.argv
            try
            {
                _Adapter = Communicator.createObjectAdapter("hms");
                _Adapter.activate();
            }
            catch (Exception ex)
            {
                logger.Fatal("Network error, check configuration: " + ex.Message);
                logger.Fatal("Endpoint(should be local machine): " + prop.getProperty("hms.Endpoints"));
                logger.Fatal("Locator (should be IceGrid Server): " + prop.getProperty("Ice.Default.Locator"));
                throw (ex); // we are dead anyway
            }
            //Now are we ready to communicate with others
            //getting usefull proxies

            try
            {
                // proxy to icegrid to register our vc devices
                Query = IceGrid.QueryPrxHelper.checkedCast(Communicator.stringToProxy("IceGrid/Query"));
                if (Query == null)
                {
                    logger.Error("invalid ICeGrid proxy");
                }
                // proxy to icestorm to publish events
                EventMgr = IceStorm.TopicManagerPrxHelper.checkedCast(Communicator.stringToProxy("EventServer/TopicManager"));
                if (EventMgr == null)
                {
                    logger.Error("invalid IceStorm proxy");
                }
                //these 2 objects are only needed to get the IceGrid admin object in order to register
                _Registry = IceGrid.RegistryPrxHelper.uncheckedCast(Communicator.stringToProxy("IceGrid/Registry"));
                updateIceGridAdmin();

            }
            catch (Ice.NotRegisteredException e)
            {
                logger.Fatal("If we fail here it is probably because the Icebox objects are not registered: " + e.Message);
            }
            catch (Exception e)
            {
                logger.Fatal("IceGrid Server not found!!!!!: " + e.Message);
                throw (e);//without yellow page system, there is no need to start
            }
            if (catchSignals)
            {
                setupSignals();
            }
        }
Пример #31
0
    public static GPrx allTests(Ice.Communicator communicator)
#endif
    {
        Write("testing Ice.Admin.Facets property... ");
        test(communicator.getProperties().getPropertyAsList("Ice.Admin.Facets").Length == 0);
        communicator.getProperties().setProperty("Ice.Admin.Facets", "foobar");
        String[] facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
        test(facetFilter.Length == 1 && facetFilter[0].Equals("foobar"));
        communicator.getProperties().setProperty("Ice.Admin.Facets", "foo\\'bar");
        facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
        test(facetFilter.Length == 1 && facetFilter[0].Equals("foo'bar"));
        communicator.getProperties().setProperty("Ice.Admin.Facets", "'foo bar' toto 'titi'");
        facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
        test(facetFilter.Length == 3 && facetFilter[0].Equals("foo bar") && facetFilter[1].Equals("toto") &&
             facetFilter[2].Equals("titi"));
        communicator.getProperties().setProperty("Ice.Admin.Facets", "'foo bar\\' toto' 'titi'");
        facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
        test(facetFilter.Length == 2 && facetFilter[0].Equals("foo bar' toto") && facetFilter[1].Equals("titi"));
        //  communicator.getProperties().setProperty("Ice.Admin.Facets", "'foo bar' 'toto titi");
        // facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
        // test(facetFilter.Length == 0);
        communicator.getProperties().setProperty("Ice.Admin.Facets", "");
        WriteLine("ok");

#if !SILVERLIGHT
        Write("testing facet registration exceptions... ");
        communicator.getProperties().setProperty("FacetExceptionTestAdapter.Endpoints", "default");
        Ice.ObjectAdapter adapter = communicator.createObjectAdapter("FacetExceptionTestAdapter");
        Ice.Object        obj     = new EmptyI();
        adapter.add(obj, communicator.stringToIdentity("d"));
        adapter.addFacet(obj, communicator.stringToIdentity("d"), "facetABCD");
        try
        {
            adapter.addFacet(obj, communicator.stringToIdentity("d"), "facetABCD");
            test(false);
        }
        catch (Ice.AlreadyRegisteredException)
        {
        }
        adapter.removeFacet(communicator.stringToIdentity("d"), "facetABCD");
        try
        {
            adapter.removeFacet(communicator.stringToIdentity("d"), "facetABCD");
            test(false);
        }
        catch (Ice.NotRegisteredException)
        {
        }
        WriteLine("ok");

        Write("testing removeAllFacets... ");
        Ice.Object obj1 = new EmptyI();
        Ice.Object obj2 = new EmptyI();
        adapter.addFacet(obj1, communicator.stringToIdentity("id1"), "f1");
        adapter.addFacet(obj2, communicator.stringToIdentity("id1"), "f2");
        Ice.Object obj3 = new EmptyI();
        adapter.addFacet(obj1, communicator.stringToIdentity("id2"), "f1");
        adapter.addFacet(obj2, communicator.stringToIdentity("id2"), "f2");
        adapter.addFacet(obj3, communicator.stringToIdentity("id2"), "");
        Dictionary <string, Ice.Object> fm
            = adapter.removeAllFacets(communicator.stringToIdentity("id1"));
        test(fm.Count == 2);
        test(fm["f1"] == obj1);
        test(fm["f2"] == obj2);
        try
        {
            adapter.removeAllFacets(communicator.stringToIdentity("id1"));
            test(false);
        }
        catch (Ice.NotRegisteredException)
        {
        }
        fm = adapter.removeAllFacets(communicator.stringToIdentity("id2"));
        test(fm.Count == 3);
        test(fm["f1"] == obj1);
        test(fm["f2"] == obj2);
        test(fm[""] == obj3);
        WriteLine("ok");

        adapter.deactivate();
#endif
        Write("testing stringToProxy... ");
        Flush();
        string        @ref = "d:default -p 12010";
        Ice.ObjectPrx db   = communicator.stringToProxy(@ref);
        test(db != null);
        WriteLine("ok");

        Write("testing unchecked cast... ");
        Flush();
        Ice.ObjectPrx prx = Ice.ObjectPrxHelper.uncheckedCast(db);
        test(prx.ice_getFacet().Length == 0);
        prx = Ice.ObjectPrxHelper.uncheckedCast(db, "facetABCD");
        test(prx.ice_getFacet() == "facetABCD");
        Ice.ObjectPrx prx2 = Ice.ObjectPrxHelper.uncheckedCast(prx);
        test(prx2.ice_getFacet() == "facetABCD");
        Ice.ObjectPrx prx3 = Ice.ObjectPrxHelper.uncheckedCast(prx, "");
        test(prx3.ice_getFacet().Length == 0);
        DPrx d = Test.DPrxHelper.uncheckedCast(db);
        test(d.ice_getFacet().Length == 0);
        DPrx df = Test.DPrxHelper.uncheckedCast(db, "facetABCD");
        test(df.ice_getFacet() == "facetABCD");
        DPrx df2 = Test.DPrxHelper.uncheckedCast(df);
        test(df2.ice_getFacet() == "facetABCD");
        DPrx df3 = Test.DPrxHelper.uncheckedCast(df, "");
        test(df3.ice_getFacet().Length == 0);
        WriteLine("ok");

        Write("testing checked cast... ");
        Flush();
        prx = Ice.ObjectPrxHelper.checkedCast(db);
        test(prx.ice_getFacet().Length == 0);
        prx = Ice.ObjectPrxHelper.checkedCast(db, "facetABCD");
        test(prx.ice_getFacet() == "facetABCD");
        prx2 = Ice.ObjectPrxHelper.checkedCast(prx);
        test(prx2.ice_getFacet() == "facetABCD");
        prx3 = Ice.ObjectPrxHelper.checkedCast(prx, "");
        test(prx3.ice_getFacet().Length == 0);
        d = Test.DPrxHelper.checkedCast(db);
        test(d.ice_getFacet().Length == 0);
        df = Test.DPrxHelper.checkedCast(db, "facetABCD");
        test(df.ice_getFacet() == "facetABCD");
        df2 = Test.DPrxHelper.checkedCast(df);
        test(df2.ice_getFacet() == "facetABCD");
        df3 = Test.DPrxHelper.checkedCast(df, "");
        test(df3.ice_getFacet().Length == 0);
        WriteLine("ok");

        Write("testing non-facets A, B, C, and D... ");
        Flush();
        d = DPrxHelper.checkedCast(db);
        test(d != null);
        test(d.Equals(db));
        test(d.callA().Equals("A"));
        test(d.callB().Equals("B"));
        test(d.callC().Equals("C"));
        test(d.callD().Equals("D"));
        WriteLine("ok");

        Write("testing facets A, B, C, and D... ");
        Flush();
        df = DPrxHelper.checkedCast(d, "facetABCD");
        test(df != null);
        test(df.callA().Equals("A"));
        test(df.callB().Equals("B"));
        test(df.callC().Equals("C"));
        test(df.callD().Equals("D"));
        WriteLine("ok");

        Write("testing facets E and F... ");
        Flush();
        FPrx ff = FPrxHelper.checkedCast(d, "facetEF");
        test(ff != null);
        test(ff.callE().Equals("E"));
        test(ff.callF().Equals("F"));
        WriteLine("ok");

        Write("testing facet G... ");
        Flush();
        GPrx gf = GPrxHelper.checkedCast(ff, "facetGH");
        test(gf != null);
        test(gf.callG().Equals("G"));
        WriteLine("ok");

        Write("testing whether casting preserves the facet... ");
        Flush();
        HPrx hf = HPrxHelper.checkedCast(gf);
        test(hf != null);
        test(hf.callG().Equals("G"));
        test(hf.callH().Equals("H"));
        WriteLine("ok");

#if SILVERLIGHT
        gf.shutdown();
#else
        return(gf);
#endif
    }
        /// <summary>
        /// Initializes a new instance of the 
        /// <see cref="T:Ferda.Modules.BoxModuleI"/> class.
        /// </summary>
        /// <param name="boxInfo">The box info.</param>
        /// <param name="myIdentity">My identity.</param>
        /// <param name="myFactoryProxy">My factory proxy.</param>
        /// <param name="manager">The manager.</param>
        /// <param name="adapter">The adapter.</param>
        /// <param name="localePrefs">The localization preferences.</param>
        public BoxModuleI(IBoxInfo boxInfo,
            Ice.Identity myIdentity,
            BoxModuleFactoryPrx myFactoryProxy,
            Ferda.ModulesManager.ManagersEnginePrx manager,
            Ice.ObjectAdapter adapter,
            string[] localePrefs)
        {
            System.Diagnostics.Debug.WriteLine("BoxModuleI Constructor (entering): " + boxInfo.Identifier);

            // initializes inner fields by specified parameters
            this.boxInfo = boxInfo;
            this.iceIdentity = myIdentity;
            this.stringIceIdentity = Ice.Util.identityToString(IceIdentity);
            this.myFactoryProxy = myFactoryProxy;
            this.manager = manager;
            this.adapter = adapter;
            this.localePrefs = localePrefs;

            // add the new box module to the specified adapter
            adapter.add(this, this.iceIdentity);
            // get my proxy
            this.myProxy = BoxModulePrxHelper.uncheckedCast(adapter.createProxy(myIdentity));

            // initializes box module`s functions object
            this.boxInfo.CreateFunctions(this, out this.functionsIceObj, out this.functionsIObj);
            this.functionsIObj.setBoxModuleInfo(this, this.boxInfo);
            this.functionsObjPrx = Ice.ObjectPrxHelper.uncheckedCast(adapter.addWithUUID(this.functionsIceObj));

            // initializes properties
            this.properties = new Dictionary<string, PropertyValue>();
            foreach (string propertyName in boxInfo.GetPropertiesNames())
            {
                if (!boxInfo.IsPropertyReadOnly(propertyName))
                {
                    this.setProperty(propertyName, boxInfo.GetPropertyDefaultValue(propertyName));
                }
            }

            // initializes sockets (connections and functions)
            this.connections = new Dictionary<string, Dictionary<string, BoxModulePrx>>();
            foreach (string socketName in boxInfo.GetSocketNames())
            {
                connections[socketName] = new Dictionary<string, BoxModulePrx>();
            }

            System.Diagnostics.Debug.WriteLine("BoxModuleI Constructor (leaving): " + this.boxInfo.Identifier);
        }
Пример #33
0
        public Ice.ObjectAdapter createObjectAdapter(string name, Ice.IRouterPrx?router)
        {
            lock (this)
            {
                if (_communicator == null)
                {
                    throw new Ice.CommunicatorDestroyedException();
                }

                if (name.Length > 0)
                {
                    if (_adapterNamesInUse.Contains(name))
                    {
                        throw new System.ArgumentException($"An object adapter with name `{name}' is already registered",
                                                           nameof(name));
                    }
                    _adapterNamesInUse.Add(name);
                }
            }

            //
            // Must be called outside the synchronization since initialize can make client invocations
            // on the router if it's set.
            //
            Ice.ObjectAdapter?adapter = null;
            try
            {
                if (name.Length == 0)
                {
                    string uuid = System.Guid.NewGuid().ToString();
                    adapter = new Ice.ObjectAdapter(_communicator, this, uuid, null, true);
                }
                else
                {
                    adapter = new Ice.ObjectAdapter(_communicator, this, name, router, false);
                }

                lock (this)
                {
                    if (_communicator == null)
                    {
                        throw new Ice.CommunicatorDestroyedException();
                    }
                    _adapters.Add(adapter);
                }
            }
            catch (Ice.CommunicatorDestroyedException)
            {
                if (adapter != null)
                {
                    adapter.Destroy();
                }
                throw;
            }
            catch (System.Exception)
            {
                if (name.Length > 0)
                {
                    lock (this)
                    {
                        _adapterNamesInUse.Remove(name);
                    }
                }
                throw;
            }

            return(adapter);
        }
Пример #34
0
 public TestControllerI(Ice.ObjectAdapter adapter)
 {
     _adapter = adapter;
 }
Пример #35
0
 TestControllerI(Ice.ObjectAdapter adapter)
 {
     _adapter = adapter;
 }
Пример #36
0
        public Ice.ObjectPrx createAdmin(Ice.ObjectAdapter adminAdapter, Ice.Identity adminIdentity)
        {
            bool createAdapter = (adminAdapter == null);

            lock(this)
            {
                if(_state == StateDestroyed)
                {
                    throw new Ice.CommunicatorDestroyedException();
                }

                if(adminIdentity == null || string.IsNullOrEmpty(adminIdentity.name))
                {
                    throw new Ice.IllegalIdentityException(adminIdentity);
                }

                if(_adminAdapter != null)
                {
                    throw new Ice.InitializationException("Admin already created");
                }

                if(!_adminEnabled)
                {
                    throw new Ice.InitializationException("Admin is disabled");
                }

                if(createAdapter)
                {
                    if(_initData.properties.getProperty("Ice.Admin.Endpoints").Length > 0)
                    {
                        adminAdapter = _objectAdapterFactory.createObjectAdapter("Ice.Admin", null);
                    }
                    else
                    {
                        throw new Ice.InitializationException("Ice.Admin.Endpoints is not set");
                    }
                }

                _adminIdentity = adminIdentity;
                _adminAdapter = adminAdapter;
                addAllAdminFacets();
            }

            if(createAdapter)
            {
                try
                {
                    adminAdapter.activate();
                }
                catch(Ice.LocalException)
                {
                    //
                    // We cleanup _adminAdapter, however this error is not recoverable
                    // (can't call again getAdmin() after fixing the problem)
                    // since all the facets (servants) in the adapter are lost
                    //
                    adminAdapter.destroy();
                    lock(this)
                    {
                        _adminAdapter = null;
                    }
                    throw;
                }
            }
            setServerProcessProxy(adminAdapter, adminIdentity);
            return adminAdapter.createProxy(adminIdentity);
        }
Пример #37
0
            public static Test.GPrx allTests(global::Test.TestHelper helper)
            {
                Ice.Communicator communicator = helper.communicator();
                var output = helper.getWriter();

                output.Write("testing Ice.Admin.Facets property... ");
                test(communicator.getProperties().getPropertyAsList("Ice.Admin.Facets").Length == 0);
                communicator.getProperties().setProperty("Ice.Admin.Facets", "foobar");
                String[] facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
                test(facetFilter.Length == 1 && facetFilter[0].Equals("foobar"));
                communicator.getProperties().setProperty("Ice.Admin.Facets", "foo\\'bar");
                facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
                test(facetFilter.Length == 1 && facetFilter[0].Equals("foo'bar"));
                communicator.getProperties().setProperty("Ice.Admin.Facets", "'foo bar' toto 'titi'");
                facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
                test(facetFilter.Length == 3 && facetFilter[0].Equals("foo bar") && facetFilter[1].Equals("toto") &&
                     facetFilter[2].Equals("titi"));
                communicator.getProperties().setProperty("Ice.Admin.Facets", "'foo bar\\' toto' 'titi'");
                facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
                test(facetFilter.Length == 2 && facetFilter[0].Equals("foo bar' toto") && facetFilter[1].Equals("titi"));
                // communicator.getProperties().setProperty("Ice.Admin.Facets", "'foo bar' 'toto titi");
                // facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
                // test(facetFilter.Length == 0);
                communicator.getProperties().setProperty("Ice.Admin.Facets", "");
                output.WriteLine("ok");

                output.Write("testing facet registration exceptions... ");
                communicator.getProperties().setProperty("FacetExceptionTestAdapter.Endpoints", "tcp -h *");
                Ice.ObjectAdapter adapter = communicator.createObjectAdapter("FacetExceptionTestAdapter");
                Ice.Object        obj     = new EmptyI();
                adapter.add(obj, Ice.Util.stringToIdentity("d"));
                adapter.addFacet(obj, Ice.Util.stringToIdentity("d"), "facetABCD");
                try
                {
                    adapter.addFacet(obj, Ice.Util.stringToIdentity("d"), "facetABCD");
                    test(false);
                }
                catch (Ice.AlreadyRegisteredException)
                {
                }
                adapter.removeFacet(Ice.Util.stringToIdentity("d"), "facetABCD");
                try
                {
                    adapter.removeFacet(Ice.Util.stringToIdentity("d"), "facetABCD");
                    test(false);
                }
                catch (Ice.NotRegisteredException)
                {
                }
                output.WriteLine("ok");

                output.Write("testing removeAllFacets... ");
                Ice.Object obj1 = new EmptyI();
                Ice.Object obj2 = new EmptyI();
                adapter.addFacet(obj1, Ice.Util.stringToIdentity("id1"), "f1");
                adapter.addFacet(obj2, Ice.Util.stringToIdentity("id1"), "f2");
                Ice.Object obj3 = new EmptyI();
                adapter.addFacet(obj1, Ice.Util.stringToIdentity("id2"), "f1");
                adapter.addFacet(obj2, Ice.Util.stringToIdentity("id2"), "f2");
                adapter.addFacet(obj3, Ice.Util.stringToIdentity("id2"), "");
                Dictionary <string, Ice.Object> fm
                    = adapter.removeAllFacets(Ice.Util.stringToIdentity("id1"));

                test(fm.Count == 2);
                test(fm["f1"] == obj1);
                test(fm["f2"] == obj2);
                try
                {
                    adapter.removeAllFacets(Ice.Util.stringToIdentity("id1"));
                    test(false);
                }
                catch (Ice.NotRegisteredException)
                {
                }
                fm = adapter.removeAllFacets(Ice.Util.stringToIdentity("id2"));
                test(fm.Count == 3);
                test(fm["f1"] == obj1);
                test(fm["f2"] == obj2);
                test(fm[""] == obj3);
                output.WriteLine("ok");

                adapter.deactivate();

                output.Write("testing stringToProxy... ");
                output.Flush();
                string @ref = "d:" + helper.getTestEndpoint(0);

                Ice.ObjectPrx db = communicator.stringToProxy(@ref);
                test(db != null);
                output.WriteLine("ok");

                output.Write("testing unchecked cast... ");
                output.Flush();
                Ice.ObjectPrx prx = Ice.ObjectPrxHelper.uncheckedCast(db);
                test(prx.ice_getFacet().Length == 0);
                prx = Ice.ObjectPrxHelper.uncheckedCast(db, "facetABCD");
                test(prx.ice_getFacet() == "facetABCD");
                Ice.ObjectPrx prx2 = Ice.ObjectPrxHelper.uncheckedCast(prx);
                test(prx2.ice_getFacet() == "facetABCD");
                Ice.ObjectPrx prx3 = Ice.ObjectPrxHelper.uncheckedCast(prx, "");
                test(prx3.ice_getFacet().Length == 0);
                var d = Test.DPrxHelper.uncheckedCast(db);

                test(d.ice_getFacet().Length == 0);
                var df = Test.DPrxHelper.uncheckedCast(db, "facetABCD");

                test(df.ice_getFacet() == "facetABCD");
                var df2 = Test.DPrxHelper.uncheckedCast(df);

                test(df2.ice_getFacet() == "facetABCD");
                var df3 = Test.DPrxHelper.uncheckedCast(df, "");

                test(df3.ice_getFacet().Length == 0);
                output.WriteLine("ok");

                output.Write("testing checked cast... ");
                output.Flush();
                prx = Ice.ObjectPrxHelper.checkedCast(db);
                test(prx.ice_getFacet().Length == 0);
                prx = Ice.ObjectPrxHelper.checkedCast(db, "facetABCD");
                test(prx.ice_getFacet() == "facetABCD");
                prx2 = Ice.ObjectPrxHelper.checkedCast(prx);
                test(prx2.ice_getFacet() == "facetABCD");
                prx3 = Ice.ObjectPrxHelper.checkedCast(prx, "");
                test(prx3.ice_getFacet().Length == 0);
                d = Test.DPrxHelper.checkedCast(db);
                test(d.ice_getFacet().Length == 0);
                df = Test.DPrxHelper.checkedCast(db, "facetABCD");
                test(df.ice_getFacet() == "facetABCD");
                df2 = Test.DPrxHelper.checkedCast(df);
                test(df2.ice_getFacet() == "facetABCD");
                df3 = Test.DPrxHelper.checkedCast(df, "");
                test(df3.ice_getFacet().Length == 0);
                output.WriteLine("ok");

                output.Write("testing non-facets A, B, C, and D... ");
                output.Flush();
                d = Test.DPrxHelper.checkedCast(db);
                test(d != null);
                test(d.Equals(db));
                test(d.callA().Equals("A"));
                test(d.callB().Equals("B"));
                test(d.callC().Equals("C"));
                test(d.callD().Equals("D"));
                output.WriteLine("ok");

                output.Write("testing facets A, B, C, and D... ");
                output.Flush();
                df = Test.DPrxHelper.checkedCast(d, "facetABCD");
                test(df != null);
                test(df.callA().Equals("A"));
                test(df.callB().Equals("B"));
                test(df.callC().Equals("C"));
                test(df.callD().Equals("D"));
                output.WriteLine("ok");

                output.Write("testing facets E and F... ");
                output.Flush();
                var ff = Test.FPrxHelper.checkedCast(d, "facetEF");

                test(ff != null);
                test(ff.callE().Equals("E"));
                test(ff.callF().Equals("F"));
                output.WriteLine("ok");

                output.Write("testing facet G... ");
                output.Flush();
                var gf = Test.GPrxHelper.checkedCast(ff, "facetGH");

                test(gf != null);
                test(gf.callG().Equals("G"));
                output.WriteLine("ok");

                output.Write("testing whether casting preserves the facet... ");
                output.Flush();
                var hf = Test.HPrxHelper.checkedCast(gf);

                test(hf != null);
                test(hf.callG().Equals("G"));
                test(hf.callH().Equals("H"));
                output.WriteLine("ok");
                return(gf);
            }
Пример #38
0
        public Ice.ObjectPrx getAdmin()
        {
            Ice.ObjectAdapter adminAdapter;
            Ice.Identity adminIdentity;

            lock(this)
            {
                if(_state == StateDestroyed)
                {
                    throw new Ice.CommunicatorDestroyedException();
                }

                if(_adminAdapter != null)
                {
                    return _adminAdapter.createProxy(_adminIdentity);
                }
                else if(_adminEnabled)
                {
                    if(_initData.properties.getProperty("Ice.Admin.Endpoints").Length > 0)
                    {
                        adminAdapter = _objectAdapterFactory.createObjectAdapter("Ice.Admin", null);
                    }
                    else
                    {
                        return null;
                    }
                    adminIdentity = new Ice.Identity("admin", _initData.properties.getProperty("Ice.Admin.InstanceName"));
                    if(adminIdentity.category.Length == 0)
                    {
                        adminIdentity.category = System.Guid.NewGuid().ToString();
                    }

                    _adminIdentity = adminIdentity;
                    _adminAdapter = adminAdapter;
                    addAllAdminFacets();
                    // continue below outside synchronization
                }
                else
                {
                    return null;
                }
            }

            try
            {
                adminAdapter.activate();
            }
            catch(Ice.LocalException)
            {
                //
                // We cleanup _adminAdapter, however this error is not recoverable
                // (can't call again getAdmin() after fixing the problem)
                // since all the facets (servants) in the adapter are lost
                //
                adminAdapter.destroy();
                lock(this)
                {
                    _adminAdapter = null;
                }
                throw;
            }

            setServerProcessProxy(adminAdapter, adminIdentity);
            return adminAdapter.createProxy(adminIdentity);
        }
        /// <summary>
        /// Service execution method
        /// </summary>
        /// <param name="name">Name of service</param>
        /// <param name="communicator">Ice communicator</param>
        /// <param name="args">Arguments from command line</param>
        public void start(string name, Ice.Communicator communicator, string[] args)
        {
            Debug.Listeners.Clear();
            Debug.Listeners.Add(new TextWriterTraceListener(name + ".log"));
            Debug.AutoFlush = true;
            Debug.WriteLine("Starting service...");
            _adapter = communicator.createObjectAdapter(name);
            ObjectFactoryForPropertyTypes factory =
                new ObjectFactoryForPropertyTypes();
            ObjectFactoryForPropertyTypes.addFactoryToCommunicator(
                communicator, factory);
            Debug.WriteLine("Activating adapter...");
            _adapter.activate();

            reaper = new ReapThread();
            reaperThread = new Thread(new ThreadStart(reaper.Run));
            reaperThread.Start();

            Debug.WriteLine("Registering boxes...");
            registerBoxes();

            if (havePropertyBoxes)
            {
                propertyReaper = new PropertyReapThread();
                propertyReaperThread = new Thread(new ThreadStart(propertyReaper.Run));
                propertyReaperThread.Start();

                Debug.WriteLine("Registering property boxes...");
                registerPropertyBoxes();
            }
        }
Пример #40
0
            public static Test.TestIntfPrx allTests(global::Test.TestHelper helper)
            {
                Ice.Communicator communicator = helper.communicator();
                var output = helper.getWriter();

                output.Write("testing stringToProxy... ");
                output.Flush();
                string @ref = "test:" + helper.getTestEndpoint(0);

                Ice.ObjectPrx @base = communicator.stringToProxy(@ref);
                test(@base != null);
                output.WriteLine("ok");

                output.Write("testing checked cast... ");
                output.Flush();
                var obj = Test.TestIntfPrxHelper.checkedCast(@base);

                test(obj != null);
                test(obj.Equals(@base));
                output.WriteLine("ok");

                {
                    output.Write("creating/destroying/recreating object adapter... ");
                    output.Flush();
                    Ice.ObjectAdapter adapter =
                        communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
                    try
                    {
                        communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
                        test(false);
                    }
                    catch (Ice.AlreadyRegisteredException)
                    {
                    }
                    adapter.destroy();

                    //
                    // Use a different port than the first adapter to avoid an "address already in use" error.
                    //
                    adapter = communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
                    adapter.destroy();
                    output.WriteLine("ok");
                }

                output.Write("creating/activating/deactivating object adapter in one operation... ");
                output.Flush();
                obj.transient();
                obj.end_transient(obj.begin_transient());
                output.WriteLine("ok");

                {
                    output.Write("testing connection closure... ");
                    output.Flush();
                    for (int i = 0; i < 10; ++i)
                    {
                        Ice.InitializationData initData = new Ice.InitializationData();
                        initData.properties = communicator.getProperties().ice_clone_();
                        Ice.Communicator comm = Ice.Util.initialize(initData);
                        comm.stringToProxy("test:" + helper.getTestEndpoint(0)).begin_ice_ping();
                        comm.destroy();
                    }
                    output.WriteLine("ok");
                }

                output.Write("testing object adapter published endpoints... ");
                output.Flush();
                {
                    communicator.getProperties().setProperty("PAdapter.PublishedEndpoints", "tcp -h localhost -p 12345 -t 30000");
                    Ice.ObjectAdapter adapter = communicator.createObjectAdapter("PAdapter");
                    test(adapter.getPublishedEndpoints().Length == 1);
                    Ice.Endpoint endpt = adapter.getPublishedEndpoints()[0];
                    test(endpt.ToString().Equals("tcp -h localhost -p 12345 -t 30000"));
                    Ice.ObjectPrx prx =
                        communicator.stringToProxy("dummy:tcp -h localhost -p 12346 -t 20000:tcp -h localhost -p 12347 -t 10000");
                    adapter.setPublishedEndpoints(prx.ice_getEndpoints());
                    test(adapter.getPublishedEndpoints().Length == 2);
                    Ice.Identity id = new Ice.Identity();
                    id.name = "dummy";
                    test(IceUtilInternal.Arrays.Equals(adapter.createProxy(id).ice_getEndpoints(), prx.ice_getEndpoints()));
                    test(IceUtilInternal.Arrays.Equals(adapter.getPublishedEndpoints(), prx.ice_getEndpoints()));
                    adapter.refreshPublishedEndpoints();
                    test(adapter.getPublishedEndpoints().Length == 1);
                    test(adapter.getPublishedEndpoints()[0].Equals(endpt));
                    communicator.getProperties().setProperty("PAdapter.PublishedEndpoints", "tcp -h localhost -p 12345 -t 20000");
                    adapter.refreshPublishedEndpoints();
                    test(adapter.getPublishedEndpoints().Length == 1);
                    test(adapter.getPublishedEndpoints()[0].ToString().Equals("tcp -h localhost -p 12345 -t 20000"));
                    adapter.destroy();
                    test(adapter.getPublishedEndpoints().Length == 0);
                }
                output.WriteLine("ok");

                if (obj.ice_getConnection() != null)
                {
                    output.Write("testing object adapter with bi-dir connection... ");
                    output.Flush();
                    Ice.ObjectAdapter adapter = communicator.createObjectAdapter("");
                    obj.ice_getConnection().setAdapter(adapter);
                    obj.ice_getConnection().setAdapter(null);
                    adapter.deactivate();
                    try
                    {
                        obj.ice_getConnection().setAdapter(adapter);
                        test(false);
                    }
                    catch (Ice.ObjectAdapterDeactivatedException)
                    {
                    }
                    output.WriteLine("ok");
                }

                output.Write("testing object adapter with router... ");
                output.Flush();
                {
                    Ice.Identity routerId = new Ice.Identity();
                    routerId.name = "router";
                    Ice.RouterPrx router =
                        Ice.RouterPrxHelper.uncheckedCast(@base.ice_identity(routerId).ice_connectionId("rc"));
                    Ice.ObjectAdapter adapter = communicator.createObjectAdapterWithRouter("", router);
                    test(adapter.getPublishedEndpoints().Length == 1);
                    test(adapter.getPublishedEndpoints()[0].ToString().Equals("tcp -h localhost -p 23456 -t 30000"));
                    adapter.refreshPublishedEndpoints();
                    test(adapter.getPublishedEndpoints().Length == 1);
                    test(adapter.getPublishedEndpoints()[0].ToString().Equals("tcp -h localhost -p 23457 -t 30000"));
                    try
                    {
                        adapter.setPublishedEndpoints(router.ice_getEndpoints());
                        test(false);
                    }
                    catch (ArgumentException)
                    {
                        // Expected.
                    }
                    adapter.destroy();

                    try
                    {
                        routerId.name = "test";
                        router        = Ice.RouterPrxHelper.uncheckedCast(@base.ice_identity(routerId));
                        communicator.createObjectAdapterWithRouter("", router);
                        test(false);
                    }
                    catch (Ice.OperationNotExistException)
                    {
                        // Expected: the "test" object doesn't implement Ice::Router!
                    }

                    try
                    {
                        router = Ice.RouterPrxHelper.uncheckedCast(communicator.stringToProxy("test:" +
                                                                                              helper.getTestEndpoint(1)));
                        communicator.createObjectAdapterWithRouter("", router);
                        test(false);
                    }
                    catch (Ice.ConnectFailedException)
                    {
                    }
                }
                output.WriteLine("ok");

                output.Write("testing object adapter creation with port in use... ");
                output.Flush();
                {
                    var adapter1 = communicator.createObjectAdapterWithEndpoints("Adpt1", helper.getTestEndpoint(10));
                    try
                    {
                        communicator.createObjectAdapterWithEndpoints("Adpt2", helper.getTestEndpoint(10));
                        test(false);
                    }
                    catch (Ice.LocalException)
                    {
                        // Expected can't re-use the same endpoint.
                    }
                    adapter1.destroy();
                }
                output.WriteLine("ok");

                output.Write("deactivating object adapter in the server... ");
                output.Flush();
                obj.deactivate();
                output.WriteLine("ok");

                output.Write("testing whether server is gone... ");
                output.Flush();
                try
                {
                    obj.ice_timeout(100).ice_ping(); // Use timeout to speed up testing on Windows
                    test(false);
                }
                catch (Ice.LocalException)
                {
                    output.WriteLine("ok");
                }

                return(obj);
            }
Пример #41
0
    private static int run(Ice.Communicator communicator, string[] args)
    {
        args = communicator.getProperties().parseCommandLineOptions("Clock", args);

        string topicName  = "time";
        string option     = "None";
        bool   batch      = false;
        string id         = null;
        string retryCount = null;
        int    i;

        for (i = 0; i < args.Length; ++i)
        {
            String oldoption = option;
            if (args[i].Equals("--datagram"))
            {
                option = "Datagram";
            }
            else if (args[i].Equals("--twoway"))
            {
                option = "Twoway";
            }
            else if (args[i].Equals("--ordered"))
            {
                option = "Ordered";
            }
            else if (args[i].Equals("--oneway"))
            {
                option = "Oneway";
            }
            else if (args[i].Equals("--batch"))
            {
                batch = true;
            }
            else if (args[i].Equals("--id"))
            {
                ++i;
                if (i >= args.Length)
                {
                    usage();
                    return(1);
                }
                id = args[i];
            }
            else if (args[i].Equals("--retryCount"))
            {
                ++i;
                if (i >= args.Length)
                {
                    usage();
                    return(1);
                }
                retryCount = args[i];
            }
            else if (args[i].StartsWith("--"))
            {
                usage();
                return(1);
            }
            else
            {
                topicName = args[i++];
                break;
            }

            if (!oldoption.Equals(option) && !oldoption.Equals("None"))
            {
                usage();
                return(1);
            }
        }

        if (i != args.Length)
        {
            usage();
            return(1);
        }

        if (retryCount != null)
        {
            if (option.Equals("None"))
            {
                option = "Twoway";
            }
            else if (!option.Equals("Twoway") && !option.Equals("Ordered"))
            {
                usage();
                return(1);
            }
        }

        if (batch && (option.Equals("Twoway") || option.Equals("Ordered")))
        {
            Console.WriteLine("batch can only be set with oneway or datagram");
            return(1);
        }

        IceStorm.TopicManagerPrx manager = IceStorm.TopicManagerPrxHelper.checkedCast(
            communicator.propertyToProxy("TopicManager.Proxy"));
        if (manager == null)
        {
            Console.WriteLine("invalid proxy");
            return(1);
        }

        //
        // Retrieve the topic.
        //
        IceStorm.TopicPrx topic;
        try
        {
            topic = manager.retrieve(topicName);
        }
        catch (IceStorm.NoSuchTopic)
        {
            try
            {
                topic = manager.create(topicName);
            }
            catch (IceStorm.TopicExists)
            {
                Console.WriteLine("temporary error. try again.");
                return(1);
            }
        }

        Ice.ObjectAdapter adapter = communicator.createObjectAdapter("Clock.Subscriber");
        //
        // Add a servant for the Ice object. If --id is used the
        // identity comes from the command line, otherwise a UUID is
        // used.
        //
        // id is not directly altered since it is used below to
        // detect whether subscribeAndGetPublisher can raise
        // AlreadySubscribed.
        //
        Ice.Identity subId = new Ice.Identity(id, "");
        if (subId.name == null)
        {
            subId.name = Guid.NewGuid().ToString();
        }
        Ice.ObjectPrx subscriber = adapter.add(new ClockI(), subId);

        //
        // Activate the object adapter before subscribing.
        //
        adapter.activate();

        Dictionary <string, string> qos = new Dictionary <string, string>();

        if (retryCount != null)
        {
            qos["retryCount"] = retryCount;
        }
        //
        // Set up the proxy.
        //
        if (option.Equals("Datagram"))
        {
            if (batch)
            {
                subscriber = subscriber.ice_batchDatagram();
            }
            else
            {
                subscriber = subscriber.ice_datagram();
            }
        }
        else if (option.Equals("Twoway"))
        {
            // Do nothing to the subscriber proxy. Its already twoway.
        }
        else if (option.Equals("Ordered"))
        {
            // Do nothing to the subscriber proxy. Its already twoway.
            qos["reliability"] = "ordered";
        }
        else if (option.Equals("Oneway") || option.Equals("None"))
        {
            if (batch)
            {
                subscriber = subscriber.ice_batchOneway();
            }
            else
            {
                subscriber = subscriber.ice_oneway();
            }
        }

        try
        {
            topic.subscribeAndGetPublisher(qos, subscriber);
        }
        catch (IceStorm.AlreadySubscribed)
        {
            // If we're manually setting the subscriber id ignore.
            if (id == null)
            {
                throw;
            }
            System.Console.Out.WriteLine("reactivating persistent subscriber");
        }

        communicator.waitForShutdown();
        topic.unsubscribe(subscriber);

        return(0);
    }
Пример #42
0
 internal BackgroundControllerI(Ice.ObjectAdapter adapter)
 {
     _adapter       = adapter;
     _configuration = Configuration.getInstance();
 }
        public void Initialize(IScene scene)
        {
            try
            {
                if (!m_enabled)
                    return;

                IMurmurService service = scene.RequestModuleInterface<IMurmurService>();
                if (service == null)
                    return;

                MurmurConfig config = service.GetConfiguration(scene.RegionInfo.RegionName);
                if (config == null)
                    return;

                bool justStarted = false;
                if (!m_started)
                {
                    justStarted = true;
                    m_started = true;

                    // retrieve configuration variables
                    m_murmurd_host = config.MurmurHost;
                    m_server_version = config.ServerVersion;
                    //Fix the callback URL, its our IP, so we deal with it
                    IConfig m_config = m_source.Configs["MurmurService"];
                    if (m_config != null)
                        config.IceCB = m_config.GetString("murmur_ice_cb", "tcp -h 127.0.0.1");

                    // Admin interface required values
                    if (String.IsNullOrEmpty(m_murmurd_host))
                    {
                        m_log.Error("[MurmurVoice] plugin disabled: incomplete configuration");
                        return;
                    }

                    Ice.Communicator comm = Ice.Util.initialize();

                    if (config.GlacierEnabled)
                    {
                        router = RouterPrxHelper.uncheckedCast(comm.stringToProxy(config.GlacierIce));
                        comm.setDefaultRouter(router);
                        router.createSession(config.GlacierUser, config.GlacierPass);
                    }

                    MetaPrx meta = MetaPrxHelper.checkedCast(comm.stringToProxy(config.MetaIce));

                    // Create the adapter
                    comm.getProperties().setProperty("Ice.PrintAdapterReady", "0");
                    if (config.GlacierEnabled)
                        adapter = comm.createObjectAdapterWithRouter("Callback.Client", comm.getDefaultRouter());
                    else
                        adapter = comm.createObjectAdapterWithEndpoints("Callback.Client", config.IceCB);
                    adapter.activate();

                    // Create identity and callback for Metaserver
                    Ice.Identity metaCallbackIdent = new Ice.Identity();
                    metaCallbackIdent.name = "metaCallback";
                    if (router != null)
                        metaCallbackIdent.category = router.getCategoryForClient();
                    MetaCallbackPrx meta_callback = MetaCallbackPrxHelper.checkedCast(adapter.add(new MetaCallbackImpl(), metaCallbackIdent));
                    meta.addCallback(meta_callback);

                    m_log.InfoFormat("[MurmurVoice] using murmur server ice '{0}'", config.MetaIce);

                    // create a server and figure out the port name
                    Dictionary<string, string> defaults = meta.getDefaultConf();
                    m_server = ServerPrxHelper.checkedCast(meta.getServer(config.ServerID));

                    // start thread to ping glacier2 router and/or determine if con$
                    m_keepalive = new KeepAlive(m_server);
                    ThreadStart ka_d = new ThreadStart(m_keepalive.StartPinging);
                    m_keepalive_t = new Thread(ka_d);
                    m_keepalive_t.Start();

                    // first check the conf for a port, if not then use server id and default port to find the right one.
                    string conf_port = m_server.getConf("port");
                    if (!String.IsNullOrEmpty(conf_port))
                        m_murmurd_port = Convert.ToInt32(conf_port);
                    else
                        m_murmurd_port = Convert.ToInt32(defaults["port"]) + config.ServerID - 1;

                    try
                    {
                        m_server.start();
                    }
                    catch
                    {
                    }
                }

                // starts the server and gets a callback
                ServerManager manager = new ServerManager(m_server, config.ChannelName);

                // Create identity and callback for this current server
                AddServerCallback(scene, new ServerCallbackImpl(manager));
                AddServerManager(scene, manager);

                if (justStarted)
                {
                    Ice.Identity serverCallbackIdent = new Ice.Identity();
                    serverCallbackIdent.name = "serverCallback";
                    if (router != null)
                        serverCallbackIdent.category = router.getCategoryForClient();

                    m_server.addCallback(ServerCallbackPrxHelper.checkedCast(adapter.add(GetServerCallback(scene), serverCallbackIdent)));
                }

                // Show information on console for debugging purposes
                m_log.InfoFormat("[MurmurVoice] using murmur server '{0}:{1}', sid '{2}'", m_murmurd_host, m_murmurd_port, config.ServerID);
                m_log.Info("[MurmurVoice] plugin enabled");
                m_enabled = true;
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[MurmurVoice] plugin initialization failed: {0}", e.ToString());
                return;
            }
        }
Пример #44
0
 internal ActivateAdapterThread(Ice.ObjectAdapter adapter, int timeout)
 {
     _adapter = adapter;
     _timeout = timeout;
 }
Пример #45
0
        public void Initialize(Scene scene)
        {
            try
            {
                if (!m_enabled) return;

                if (!m_started)
                {
                    m_started = true;

                    scene.AddCommand(this, "mumble report", "mumble report",
                        "Returns mumble report", MumbleReport);

                    scene.AddCommand(this, "mumble unregister", "mumble unregister <userid>",
                        "Unregister User by userid", UnregisterUser);

                    scene.AddCommand(this, "mumble remove", "mumble remove <UUID>",
                        "Remove Agent by UUID", RemoveAgent);

                    Ice.Communicator comm = Ice.Util.initialize();

                    /*
                    if (m_glacier_enabled)
                    {
                        m_router = RouterPrxHelper.uncheckedCast(comm.stringToProxy(m_glacier_ice));
                        comm.setDefaultRouter(m_router);
                        m_router.createSession(m_glacier_user, m_glacier_pass);
                    }
                    */

                    MetaPrx meta = MetaPrxHelper.checkedCast(comm.stringToProxy(m_murmurd_ice));

                    // Create the adapter
                    comm.getProperties().setProperty("Ice.PrintAdapterReady", "0");
                    if (m_glacier_enabled)
                        m_adapter = comm.createObjectAdapterWithRouter("Callback.Client", comm.getDefaultRouter() );
                    else
                        m_adapter = comm.createObjectAdapterWithEndpoints("Callback.Client", m_murmur_ice_cb);
                    m_adapter.activate();

                    // Create identity and callback for Metaserver
                    Ice.Identity metaCallbackIdent = new Ice.Identity();
                    metaCallbackIdent.name = "metaCallback";
                    //if (m_router != null)
                    //    metaCallbackIdent.category = m_router.getCategoryForClient();
                    MetaCallbackPrx meta_callback = MetaCallbackPrxHelper.checkedCast(m_adapter.add(new MetaCallbackImpl(), metaCallbackIdent));
                    meta.addCallback(meta_callback);

                    m_log.InfoFormat("[MurmurVoice] using murmur server ice '{0}'", m_murmurd_ice);

                    // create a server and figure out the port name
                    Dictionary<string,string> defaults = meta.getDefaultConf();
                    m_server = ServerPrxHelper.checkedCast(meta.getServer(m_server_id));

                    // start thread to ping glacier2 router and/or determine if con$
                    m_keepalive = new KeepAlive(m_server);
                    ThreadStart ka_d = new ThreadStart(m_keepalive.StartPinging);
                    m_keepalive_t = new Thread(ka_d);
                    m_keepalive_t.Start();

                    // first check the conf for a port, if not then use server id and default port to find the right one.
                    string conf_port = m_server.getConf("port");
                    if(!String.IsNullOrEmpty(conf_port))
                        m_murmurd_port = Convert.ToInt32(conf_port);
                    else
                        m_murmurd_port = Convert.ToInt32(defaults["port"])+m_server_id-1;

                    try
                    {
                        m_server.start();
                    }
                    catch
                    {
                    }

                    m_log.Info("[MurmurVoice] started");
                }

                // starts the server and gets a callback
                ServerManager manager = new ServerManager(m_server, m_channel_name);

                // Create identity and callback for this current server
                AddServerCallback(scene, new ServerCallbackImpl(manager));
                AddServerManager(scene, manager);

                Ice.Identity serverCallbackIdent = new Ice.Identity();
                serverCallbackIdent.name = "serverCallback_" + scene.RegionInfo.RegionName.Replace(" ","_");
                //if (m_router != null)
                //    serverCallbackIdent.category = m_router.getCategoryForClient();

                m_server.addCallback(ServerCallbackPrxHelper.checkedCast(m_adapter.add(GetServerCallback(scene), serverCallbackIdent)));

                // Show information on console for debugging purposes
                m_log.InfoFormat("[MurmurVoice] using murmur server '{0}:{1}', sid '{2}'", m_murmurd_host, m_murmurd_port, m_server_id);
                m_log.Info("[MurmurVoice] plugin enabled");
                m_enabled = true;
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[MurmurVoice] plugin initialization failed: {0}", e.ToString());
                return;
            }
        }
Пример #46
0
 public void start(string name, Ice.Communicator communicator, string[] args)
 {
     _adapter = communicator.createObjectAdapter(name);
     _adapter.add(new HelloI(), Ice.Util.stringToIdentity("hello"));
     _adapter.activate();
 }
Пример #47
0
 internal BackgroundControllerI(Ice.ObjectAdapter adapter)
 {
     _adapter = adapter;
     _configuration = Configuration.getInstance();
 }
Пример #48
0
 public void setAdapter(Ice.ObjectAdapter adapter)
 {
     lock(this)
     {
         _adapter = adapter;
     }
 }
Пример #49
0
    public static void allTests(TestCommon.Application app)
    {
        Ice.Communicator communicator = app.communicator();
        string           sref         = "timeout:" + app.getTestEndpoint(0);

        Ice.ObjectPrx obj = communicator.stringToProxy(sref);
        test(obj != null);

        Test.TimeoutPrx timeout = Test.TimeoutPrxHelper.checkedCast(obj);
        test(timeout != null);

        Test.ControllerPrx controller = Test.ControllerPrxHelper.checkedCast(
            communicator.stringToProxy("controller:" + app.getTestEndpoint(1)));
        test(controller != null);

        Write("testing connect timeout... ");
        Flush();
        {
            //
            // Expect ConnectTimeoutException.
            //
            Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(100));
            controller.holdAdapter(-1);
            try
            {
                to.op();
                test(false);
            }
            catch (Ice.ConnectTimeoutException)
            {
                // Expected.
            }
            controller.resumeAdapter();
            timeout.op(); // Ensure adapter is active.
        }
        {
            //
            // Expect success.
            //
            Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(2000));
            controller.holdAdapter(100);
            try
            {
                to.op();
            }
            catch (Ice.ConnectTimeoutException)
            {
                test(false);
            }
        }
        WriteLine("ok");

        // The sequence needs to be large enough to fill the write/recv buffers
        byte[] seq = new byte[2000000];

        Write("testing connection timeout... ");
        Flush();
        {
            //
            // Expect TimeoutException.
            //
            Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(250));
            connect(to);
            controller.holdAdapter(-1);
            try
            {
                to.sendData(seq);
                test(false);
            }
            catch (Ice.TimeoutException)
            {
                // Expected.
            }
            controller.resumeAdapter();
            timeout.op(); // Ensure adapter is active.
        }
        {
            //
            // Expect success.
            //
            Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(2000));
            controller.holdAdapter(100);
            try
            {
                to.sendData(new byte[1000000]);
            }
            catch (Ice.TimeoutException)
            {
                test(false);
            }
        }
        WriteLine("ok");

        Write("testing invocation timeout... ");
        Flush();
        {
            Ice.Connection  connection = obj.ice_getConnection();
            Test.TimeoutPrx to         = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(100));
            test(connection == to.ice_getConnection());
            try
            {
                to.sleep(500);
                test(false);
            }
            catch (Ice.InvocationTimeoutException)
            {
            }
            obj.ice_ping();
            to = Test.TimeoutPrxHelper.checkedCast(obj.ice_invocationTimeout(1000));
            test(connection == to.ice_getConnection());
            try
            {
                to.sleep(100);
            }
            catch (Ice.InvocationTimeoutException)
            {
                test(false);
            }
            test(connection == to.ice_getConnection());
        }
        {
            //
            // Expect InvocationTimeoutException.
            //
            Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(100));
            Callback        cb = new Callback();
            to.begin_sleep(500).whenCompleted(
                () =>
            {
                test(false);
            },
                (Ice.Exception ex) =>
            {
                test(ex is Ice.InvocationTimeoutException);
                cb.called();
            });
            cb.check();
            obj.ice_ping();
        }
        {
            //
            // Expect success.
            //
            Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(1000));
            Callback        cb = new Callback();
            to.begin_sleep(100).whenCompleted(
                () =>
            {
                cb.called();
            },
                (Ice.Exception ex) =>
            {
                test(false);
            });
            cb.check();
        }
        {
            //
            // Backward compatible connection timeouts
            //
            Test.TimeoutPrx to  = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_invocationTimeout(-2).ice_timeout(250));
            Ice.Connection  con = connect(to);
            try
            {
                to.sleep(750);
                test(false);
            }
            catch (Ice.TimeoutException)
            {
                try
                {
                    con.getInfo();
                    test(false);
                }
                catch (Ice.TimeoutException)
                {
                    // Connection got closed as well.
                }
            }
            obj.ice_ping();

            try
            {
                con = connect(to);
                to.end_sleep(to.begin_sleep(750));
                test(false);
            }
            catch (Ice.TimeoutException)
            {
                try
                {
                    con.getInfo();
                    test(false);
                }
                catch (Ice.TimeoutException)
                {
                    // Connection got closed as well.
                }
            }
            obj.ice_ping();
        }
        WriteLine("ok");

        Write("testing close timeout... ");
        Flush();
        {
            Test.TimeoutPrx to         = Test.TimeoutPrxHelper.uncheckedCast(obj.ice_timeout(250));
            Ice.Connection  connection = connect(to);
            controller.holdAdapter(-1);
            connection.close(Ice.ConnectionClose.GracefullyWithWait);
            try
            {
                connection.getInfo(); // getInfo() doesn't throw in the closing state.
            }
            catch (Ice.LocalException)
            {
                test(false);
            }
            while (true)
            {
                try
                {
                    connection.getInfo();
                    Thread.Sleep(10);
                }
                catch (Ice.ConnectionManuallyClosedException ex)
                {
                    // Expected.
                    test(ex.graceful);
                    break;
                }
            }
            controller.resumeAdapter();
            timeout.op(); // Ensure adapter is active.
        }
        WriteLine("ok");

        Write("testing timeout overrides... ");
        Flush();
        {
            //
            // Test Ice.Override.Timeout. This property overrides all
            // endpoint timeouts.
            //
            string[] args = new string[0];
            Ice.InitializationData initData = new Ice.InitializationData();
            initData.properties = communicator.getProperties().ice_clone_();
            initData.properties.setProperty("Ice.Override.ConnectTimeout", "250");
            initData.properties.setProperty("Ice.Override.Timeout", "100");
            Ice.Communicator comm = Ice.Util.initialize(ref args, initData);
            Test.TimeoutPrx  to   = Test.TimeoutPrxHelper.uncheckedCast(comm.stringToProxy(sref));
            connect(to);
            controller.holdAdapter(-1);
            try
            {
                to.sendData(seq);
                test(false);
            }
            catch (Ice.TimeoutException)
            {
                // Expected.
            }
            controller.resumeAdapter();
            timeout.op(); // Ensure adapter is active.

            //
            // Calling ice_timeout() should have no effect.
            //
            to = Test.TimeoutPrxHelper.uncheckedCast(to.ice_timeout(1000));
            connect(to);
            controller.holdAdapter(-1);
            try
            {
                to.sendData(seq);
                test(false);
            }
            catch (Ice.TimeoutException)
            {
                // Expected.
            }
            controller.resumeAdapter();
            timeout.op(); // Ensure adapter is active.
            comm.destroy();
        }
        {
            //
            // Test Ice.Override.ConnectTimeout.
            //
            string[] args = new string[0];
            Ice.InitializationData initData = new Ice.InitializationData();
            initData.properties = communicator.getProperties().ice_clone_();
            initData.properties.setProperty("Ice.Override.ConnectTimeout", "250");
            Ice.Communicator comm = Ice.Util.initialize(ref args, initData);
            controller.holdAdapter(-1);
            Test.TimeoutPrx to = Test.TimeoutPrxHelper.uncheckedCast(comm.stringToProxy(sref));
            try
            {
                to.op();
                test(false);
            }
            catch (Ice.ConnectTimeoutException)
            {
                // Expected.
            }
            controller.resumeAdapter();
            timeout.op(); // Ensure adapter is active.

            //
            // Calling ice_timeout() should have no effect on the connect timeout.
            //
            controller.holdAdapter(-1);
            to = Test.TimeoutPrxHelper.uncheckedCast(to.ice_timeout(1000));
            try
            {
                to.op();
                test(false);
            }
            catch (Ice.ConnectTimeoutException)
            {
                // Expected.
            }
            controller.resumeAdapter();
            timeout.op(); // Ensure adapter is active.

            //
            // Verify that timeout set via ice_timeout() is still used for requests.
            //
            to = Test.TimeoutPrxHelper.uncheckedCast(to.ice_timeout(250));
            connect(to);
            controller.holdAdapter(-1);
            try
            {
                to.sendData(seq);
                test(false);
            }
            catch (Ice.TimeoutException)
            {
                // Expected.
            }
            controller.resumeAdapter();
            timeout.op(); // Ensure adapter is active.
            comm.destroy();
        }
        {
            //
            // Test Ice.Override.CloseTimeout.
            //
            Ice.InitializationData initData = new Ice.InitializationData();
            initData.properties = communicator.getProperties().ice_clone_();
            initData.properties.setProperty("Ice.Override.CloseTimeout", "100");
            Ice.Communicator comm = Ice.Util.initialize(initData);
            comm.stringToProxy(sref).ice_getConnection();
            controller.holdAdapter(-1);
            long begin = System.DateTime.Now.Ticks;
            comm.destroy();
            test(((long)new System.TimeSpan(System.DateTime.Now.Ticks - begin).TotalMilliseconds - begin) < 700);
            controller.resumeAdapter();
        }
        WriteLine("ok");

        Write("testing invocation timeouts with collocated calls... ");
        Flush();
        {
            communicator.getProperties().setProperty("TimeoutCollocated.AdapterId", "timeoutAdapter");

            Ice.ObjectAdapter adapter = communicator.createObjectAdapter("TimeoutCollocated");
            adapter.activate();

            Test.TimeoutPrx proxy = Test.TimeoutPrxHelper.uncheckedCast(adapter.addWithUUID(new TimeoutI()));
            proxy = (Test.TimeoutPrx)proxy.ice_invocationTimeout(100);
            try
            {
                proxy.sleep(500);
                test(false);
            }
            catch (Ice.InvocationTimeoutException)
            {
            }

            try
            {
                proxy.end_sleep(proxy.begin_sleep(500));
                test(false);
            }
            catch (Ice.InvocationTimeoutException)
            {
            }

            try
            {
                ((Test.TimeoutPrx)proxy.ice_invocationTimeout(-2)).ice_ping();
                ((Test.TimeoutPrx)proxy.ice_invocationTimeout(-2)).begin_ice_ping().waitForCompleted();
            }
            catch (Ice.Exception)
            {
                test(false);
            }

            Test.TimeoutPrx batchTimeout = (Test.TimeoutPrx)proxy.ice_batchOneway();
            batchTimeout.ice_ping();
            batchTimeout.ice_ping();
            batchTimeout.ice_ping();

            ((Test.TimeoutPrx)proxy.ice_invocationTimeout(-1)).begin_sleep(300); // Keep the server thread pool busy.
            try
            {
                batchTimeout.ice_flushBatchRequests();
                test(false);
            }
            catch (Ice.InvocationTimeoutException)
            {
            }

            batchTimeout.ice_ping();
            batchTimeout.ice_ping();
            batchTimeout.ice_ping();

            ((Test.TimeoutPrx)proxy.ice_invocationTimeout(-1)).begin_sleep(300); // Keep the server thread pool busy.
            try
            {
                batchTimeout.end_ice_flushBatchRequests(batchTimeout.begin_ice_flushBatchRequests());
                test(false);
            }
            catch (Ice.InvocationTimeoutException)
            {
            }

            adapter.destroy();
        }
        WriteLine("ok");

        controller.shutdown();
    }