void
Client::run(int argc, char** argv)
{
    Ice::CommunicatorHolder communicator = initialize(argc, argv);
    instance = this;
    string protocol = getTestProtocol();
    string host = getTestHost();
    _initData.properties = Ice::createProperties(argc, argv, communicator->getProperties());
    _initData.properties->setProperty("Ice.Default.Router", "Glacier2/router:" + getTestEndpoint(50));

    DispatcherPtr dispatcher = new Dispatcher();
    dispatcher->start();
#ifdef ICE_CPP11_MAPPING
    _initData.dispatcher = [dispatcher](std::function<void()> call, const std::shared_ptr<Ice::Connection>& conn)
        {
            dispatcher->dispatch(call, conn);
        };
#else
    _initData.dispatcher = dispatcher;
#endif
    _factory = ICE_MAKE_SHARED(Glacier2::SessionFactoryHelper, _initData, ICE_MAKE_SHARED(FailSessionCallback));

    //
    // Test to create a session with wrong userid/password
    //

    {
        IceUtil::Monitor<IceUtil::Mutex>::Lock lock(_monitor);

        cout << "testing SessionHelper connect with wrong userid/password... " << flush;

        _session = _factory->connect("userid", "xxx");
        //
        // Wait for connectFailed callback
        //
        _monitor.timedWait(IceUtil::Time::seconds(30));

        test(!_session->isConnected());
    }
    _factory->destroy();

    //
    // Test to interrupt connection establishment
    //

    _initData.properties->setProperty("Ice.Default.Router", "");
    _factory = ICE_MAKE_SHARED(Glacier2::SessionFactoryHelper, _initData, ICE_MAKE_SHARED(InterruptConnectCallback));

    {
        IceUtil::Monitor<IceUtil::Mutex>::Lock lock(_monitor);
        cout << "testing SessionHelper connect interrupt... " << flush;
        _factory->setRouterHost(host);
        _factory->setPort(getTestPort(_initData.properties, 1));
        _factory->setProtocol(protocol);
        _session = _factory->connect("userid", "abc123");

        IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100));
        _session->destroy();

        //
        // Wait for connectFailed callback
        //
        _monitor.timedWait(IceUtil::Time::seconds(30));
        test(!_session->isConnected());
    }
    _factory->destroy();

    _factory = ICE_MAKE_SHARED(Glacier2::SessionFactoryHelper, _initData, ICE_MAKE_SHARED(SuccessSessionCallback));

    {
        IceUtil::Monitor<IceUtil::Mutex>::Lock lock(_monitor);
        cout << "testing SessionHelper connect... " << flush;
        _factory->setRouterHost(host);
        _factory->setPort(getTestPort(_initData.properties, 50));
        _factory->setProtocol(protocol);
        _session = _factory->connect("userid", "abc123");

        //
        // Wait for connect callback
        //
        _monitor.timedWait(IceUtil::Time::seconds(30));

        cout << "testing SessionHelper isConnected after connect... " << flush;
        test(_session->isConnected());
        cout << "ok" << endl;

        cout << "testing SessionHelper categoryForClient after connect... " << flush;
        try
        {
            test(!_session->categoryForClient().empty());
        }
        catch(const Glacier2::SessionNotExistException&)
        {
            test(false);
        }
        cout << "ok" << endl;

        test(!_session->session());

        cout << "testing stringToProxy for server object... " << flush;
        Ice::ObjectPrxPtr base =
            _session->communicator()->stringToProxy("callback:" + getTestEndpoint(_session->communicator()->getProperties()));
        cout << "ok" << endl;

        cout << "pinging server after session creation... " << flush;
        base->ice_ping();
        cout << "ok" << endl;

        cout << "testing checked cast for server object... " << flush;
        CallbackPrxPtr twoway = ICE_CHECKED_CAST(CallbackPrx, base);
        test(twoway);
        cout << "ok" << endl;

        cout << "testing server shutdown... " << flush;
        twoway->shutdown();
        cout << "ok" << endl;

        test(_session->communicator());
        cout << "testing SessionHelper destroy... " << flush;
        _session->destroy();

        //
        // Wait for disconnected callback
        //
        _monitor.wait();

        cout << "testing SessionHelper isConnected after destroy... " << flush;
        test(_session->isConnected() == false);
        cout << "ok" << endl;

        cout << "testing SessionHelper categoryForClient after destroy... " << flush;
        try
        {
            test(!_session->categoryForClient().empty());
            test(false);
        }
        catch(const Glacier2::SessionNotExistException&)
        {
        }
        cout << "ok" << endl;

        cout << "testing SessionHelper session after destroy... " << flush;
        test(_session->session() == ICE_NULLPTR);
        cout << "ok" << endl;

        cout << "testing SessionHelper communicator after destroy... " << flush;
        try
        {
            test(_session->communicator());
            _session->communicator()->stringToProxy("dummy");
            test(false);
        }
        catch(const Ice::CommunicatorDestroyedException&)
        {
        }
        cout << "ok" << endl;

        cout << "uninstalling router with communicator... " << flush;
        communicator->setDefaultRouter(0);
        cout << "ok" << endl;

        Ice::ObjectPrxPtr processBase;
        {
            cout << "testing stringToProxy for process object... " << flush;
            processBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51));
            cout << "ok" << endl;
        }

        Ice::ProcessPrxPtr process;
        {
            cout << "testing checked cast for admin object... " << flush;
            process = ICE_CHECKED_CAST(Ice::ProcessPrx, processBase);
            test(process != 0);
            cout << "ok" << endl;
        }

        cout << "testing Glacier2 shutdown... " << flush;
        process->shutdown();
        try
        {
            process->ice_ping();
            test(false);
        }
        catch(const Ice::LocalException&)
        {
            cout << "ok" << endl;
        }
    }

    _factory->destroy();

    _factory = ICE_MAKE_SHARED(Glacier2::SessionFactoryHelper, _initData, ICE_MAKE_SHARED(AfterShutdownSessionCallback));

    //
    // Wait a bit to ensure glaci2router has been shutdown.
    //
    IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100));

    {
        IceUtil::Monitor<IceUtil::Mutex>::Lock lock(_monitor);
        cout << "testing SessionHelper connect after router shutdown... " << flush;
        _factory->setRouterHost(host);
        _factory->setPort(getTestPort(_initData.properties, 50));
        _factory->setProtocol(protocol);
        _session = _factory->connect("userid", "abc123");

        //
        // Wait for connectFailed callback
        //
        _monitor.wait();

        cout << "testing SessionHelper isConnect after connect failure... " << flush;
        test(_session->isConnected() == false);
        cout << "ok" << endl;

        cout << "testing SessionHelper communicator after connect failure... " << flush;
        try
        {
            test(_session->communicator());
            _session->communicator()->stringToProxy("dummy");
            test(false);
        }
        catch(const Ice::CommunicatorDestroyedException&)
        {
        }
        cout << "ok" << endl;

        cout << "testing SessionHelper destroy after connect failure... " << flush;
        _session->destroy();
        cout << "ok" << endl;
    }

    _factory->destroy();

    if(dispatcher)
    {
        dispatcher->destroy();
        dispatcher->getThreadControl().join();
    }
}
Example #2
0
vector<EndpointIPtr>
IceInternal::RouterInfo::setClientEndpoints(const Ice::ObjectPrxPtr& proxy)
{
    IceUtil::Mutex::Lock sync(*this);
    if(_clientEndpoints.empty())
    {
        if(!proxy)
        {
            //
            // If getClientProxy() return nil, use router endpoints.
            //
            _clientEndpoints = _router->__reference()->getEndpoints();
        }
        else
        {
            Ice::ObjectPrxPtr clientProxy = proxy->ice_router(0); // The client proxy cannot be routed.

            //
            // In order to avoid creating a new connection to the router,
            // we must use the same timeout as the already existing
            // connection.
            //
            if(_router->ice_getConnection())
            {
                clientProxy = clientProxy->ice_timeout(_router->ice_getConnection()->timeout());
            }

            _clientEndpoints = clientProxy->__reference()->getEndpoints();
        }
    }
    return _clientEndpoints;
}
Example #3
0
ProxyFlushBatch::ProxyFlushBatch(const Ice::ObjectPrxPtr& proxy, const string& operation) :
    ProxyOutgoingBase(proxy, ICE_ENUM(OperationMode, Normal))
{
    checkSupportedProtocol(getCompatibleProtocol(proxy->__reference()->getProtocol()));
    _observer.attach(proxy, operation, ::Ice::noExplicitContext);

    _batchRequestNum = proxy->__getBatchRequestQueue()->swap(&_os);
}
Example #4
0
void
BatchRequestQueue::finishBatchRequest(OutputStream* os, const Ice::ObjectPrxPtr& proxy, const std::string& operation)
{
    //
    // No need for synchronization, no other threads are supposed
    // to modify the queue since we set _batchStreamInUse to true.
    //
    assert(_batchStreamInUse);
    _batchStream.swap(*os);

    try
    {
        _batchStreamCanFlush = true; // Allow flush to proceed even if the stream is marked in use.

        if(_maxSize > 0 && _batchStream.b.size() >= _maxSize)
        {
#ifdef ICE_CPP11_MAPPING
            proxy->ice_flushBatchRequests_async();
#else
            proxy->begin_ice_flushBatchRequests();
#endif
        }

        assert(_batchMarker < _batchStream.b.size());
        if(_interceptor)
        {
            BatchRequestI request(*this, proxy, operation, static_cast<int>(_batchStream.b.size() - _batchMarker));
#ifdef ICE_CPP11_MAPPING
            _interceptor(request, _batchRequestNum, static_cast<int>(_batchMarker));
#else
            _interceptor->enqueue(request, _batchRequestNum, static_cast<int>(_batchMarker));
#endif
        }
        else
        {
            _batchMarker = _batchStream.b.size();
            ++_batchRequestNum;
        }

        Lock sync(*this);
        _batchStream.resize(_batchMarker);
        _batchStreamInUse = false;
        _batchStreamCanFlush = false;
        notifyAll();
    }
    catch(const std::exception&)
    {
        Lock sync(*this);
        _batchStream.resize(_batchMarker);
        _batchStreamInUse = false;
        _batchStreamCanFlush = false;
        notifyAll();
        throw;
    }
}
Example #5
0
Ice::ObjectPrxPtr
LocatorRegistryI::findObject(const Ice::Identity& id) const
{
    Lock sync(*this);
    if(id.name.empty())
    {
        return 0;
    }

    Ice::ObjectPrxPtr prx = _wellKnownProxy->ice_identity(id);

    vector<string> adapterIds;
    for(map<string, set<string> >::const_iterator p = _replicaGroups.begin(); p != _replicaGroups.end(); ++p)
    {
        try
        {
            prx->ice_adapterId(p->first)->ice_ping();
            adapterIds.push_back(p->first);
        }
        catch(const Ice::Exception&)
        {
            // Ignore
        }
    }

    if(adapterIds.empty())
    {
        for(map<string, Ice::ObjectPrxPtr>::const_iterator p = _adapters.begin(); p != _adapters.end(); ++p)
        {
            try
            {
                prx->ice_adapterId(p->first)->ice_ping();
                adapterIds.push_back(p->first);
            }
            catch(const Ice::Exception&)
            {
                // Ignore
            }
        }
    }

    if(adapterIds.empty())
    {
        return 0;
    }

    random_shuffle(adapterIds.begin(), adapterIds.end());
    return prx->ice_adapterId(adapterIds[0]);
}
Example #6
0
int
run(int, char**, const Ice::CommunicatorPtr& communicator)
{
    communicator->getProperties()->setProperty("TestAdapter.Endpoints", getTestEndpoint(communicator, 0));
    communicator->getProperties()->setProperty("TestAdapter.AdapterId", "test");
    Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TestAdapter");
    Ice::ObjectPrxPtr prx = adapter->add(ICE_MAKE_SHARED(MyDerivedClassI), Ice::stringToIdentity("test"));
    //adapter->activate(); // Don't activate OA to ensure collocation is used.

    test(!prx->ice_getConnection());

    Test::MyClassPrxPtr allTests(const Ice::CommunicatorPtr&);
    allTests(communicator);

    return EXIT_SUCCESS;
}
Example #7
0
IceInternal::InvocationObserver::InvocationObserver(const Ice::ObjectPrxPtr& proxy, const string& op, const Context& ctx)
{
    const CommunicatorObserverPtr& obsv = proxy->__reference()->getInstance()->initializationData().observer;
    if(!obsv)
    {
        return;
    }
    attach(obsv->getInvocationObserver(proxy, op, ctx));
}
Example #8
0
Ice::ObjectPrxPtr
LocatorRegistryI::findAdapter(const string& adapterId, bool& isReplicaGroup) const
{
    Lock sync(*this);

    map<string, Ice::ObjectPrxPtr>::const_iterator p = _adapters.find(adapterId);
    if(p != _adapters.end())
    {
        isReplicaGroup = false;
        return p->second;
    }

    map<string, set<string> >::const_iterator q = _replicaGroups.find(adapterId);
    if(q != _replicaGroups.end())
    {
        Ice::EndpointSeq endpoints;
        Ice::ObjectPrxPtr prx;
        for(set<string>::const_iterator r = q->second.begin(); r != q->second.end(); ++r)
        {
            map<string, Ice::ObjectPrxPtr>::const_iterator s = _adapters.find(*r);
            if(s == _adapters.end())
            {
                continue; // TODO: Inconsistency
            }

            if(!prx)
            {
                prx = s->second;
            }

            Ice::EndpointSeq endpts = s->second->ice_getEndpoints();
            copy(endpts.begin(), endpts.end(), back_inserter(endpoints));
        }

        if(prx)
        {
            isReplicaGroup = true;
            return prx->ice_endpoints(endpoints);
        }
    }

    isReplicaGroup = false;
    return 0;
}
ICE_DECLSPEC_EXPORT void
consume(const Ice::ObjectPtr& o, const Ice::ObjectPrxPtr& p)
{
    cout << "testing dynamic cast across libraries... " << flush;

    //
    // Make sure dynamic cast works as expected
    // and exception raised by a shared library can be caught by another
    // shared library
    //

    Test::MyInterfacePtr servant = ICE_DYNAMIC_CAST(Test::MyInterface, o);
    test(servant);

#ifdef ICE_CPP11_MAPPING
    auto proxy = dynamic_pointer_cast<Test::MyInterfacePrx>(p);
#else
    Test::MyInterfacePrx proxy = dynamic_cast<IceProxy::Test::MyInterface*>(p.get());
#endif
    test(proxy);

    proxy->op(false);
    servant->op(false, Ice::emptyCurrent);

    cout << "ok" << endl;

    cout << "testing exceptions thrown across libraries... " << flush;

    try
    {
        proxy->op(true);
    }
    catch(const Test::UserError&)
    {
        // expected
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        servant->op(true, Ice::emptyCurrent);
    }
    catch(const Test::UserError&)
    {
        // expected
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;
}
Example #10
0
ProxyOutgoingBase::ProxyOutgoingBase(const Ice::ObjectPrxPtr& proxy, OperationMode mode) :
    OutgoingBase(proxy->__reference()->getInstance().get()),
    _proxy(proxy),
    _mode(mode),
    _state(StateUnsent)
{
    int invocationTimeout = _proxy->__reference()->getInvocationTimeout();
    if(invocationTimeout > 0)
    {
        _invocationTimeoutDeadline = Time::now(Time::Monotonic) + Time::milliSeconds(invocationTimeout);
    }
}
Example #11
0
void
IceInternal::RouterInfo::addAndEvictProxies(const Ice::ObjectPrxPtr& proxy, const Ice::ObjectProxySeq& evictedProxies)
{
    IceUtil::Mutex::Lock sync(*this);

    //
    // Check if the proxy hasn't already been evicted by a concurrent addProxies call.
    // If it's the case, don't add it to our local map.
    //
    multiset<Identity>::iterator p = _evictedIdentities.find(proxy->ice_getIdentity());
    if(p != _evictedIdentities.end())
    {
        _evictedIdentities.erase(p);
    }
    else
    {
        //
        // If we successfully added the proxy to the router,
        // we add it to our local map.
        //
        _identities.insert(proxy->ice_getIdentity());
    }

    //
    // We also must remove whatever proxies the router evicted.
    //
    for(Ice::ObjectProxySeq::const_iterator q = evictedProxies.begin(); q != evictedProxies.end(); ++q)
    {
        if(_identities.erase((*q)->ice_getIdentity()) == 0)
        {
            //
            // It's possible for the proxy to not have been
            // added yet in the local map if two threads
            // concurrently call addProxies.
            //
            _evictedIdentities.insert((*q)->ice_getIdentity());
        }
    }
}
Example #12
0
bool
IceInternal::RouterInfo::addProxy(const Ice::ObjectPrxPtr& proxy, const AddProxyCallbackPtr& callback)
{
    assert(proxy);
    {
        IceUtil::Mutex::Lock sync(*this);
        if(_identities.find(proxy->ice_getIdentity()) != _identities.end())
        {
            //
            // Only add the proxy to the router if it's not already in our local map.
            //
            return true;
        }
    }


    Ice::ObjectProxySeq proxies;
    proxies.push_back(proxy);
    AddProxyCookiePtr cookie = new AddProxyCookie(callback, proxy);

#ifdef ICE_CPP11_MAPPING
    RouterInfoPtr self = this;
    _router->addProxies_async(proxies,
        [self, cookie](const Ice::ObjectProxySeq& proxies)
        {
            self->addProxyResponse(proxies, cookie);
        },
        [self, cookie](exception_ptr e)
        {
            try
            {
                rethrow_exception(e);
            }
            catch(const Ice::Exception& ex)
            {
                self->addProxyException(ex, cookie);
            }
        });
#else
    _router->begin_addProxies(proxies,
                              newCallback_Router_addProxies(this,
                                                            &RouterInfo::addProxyResponse,
                                                            &RouterInfo::addProxyException),
                              cookie);
#endif
    return false;
}
void
allTests(Test::TestHelper* helper)
{
    Ice::CommunicatorPtr communicator = helper->communicator();
    cout << "testing proxy endpoint information... " << flush;
    {
        Ice::ObjectPrxPtr p1 =
            communicator->stringToProxy("test -t:default -h tcphost -p 10000 -t 1200 -z --sourceAddress 10.10.10.10:"
                                        "udp -h udphost -p 10001 --interface eth0 --ttl 5 --sourceAddress 10.10.10.10:"
                                        "opaque -e 1.8 -t 100 -v ABCD");

        Ice::EndpointSeq endps = p1->ice_getEndpoints();

        Ice::EndpointInfoPtr info = endps[0]->getInfo();
        Ice::TCPEndpointInfoPtr ipEndpoint = getTCPEndpointInfo(info);
        test(ipEndpoint);
        test(ipEndpoint->host == "tcphost");
        test(ipEndpoint->port == 10000);
        test(ipEndpoint->timeout == 1200);
#if !defined(ICE_OS_UWP)
        test(ipEndpoint->sourceAddress == "10.10.10.10");
#endif
        test(ipEndpoint->compress);
        test(!ipEndpoint->datagram());
        test((ipEndpoint->type() == Ice::TCPEndpointType && !ipEndpoint->secure()) ||
             (ipEndpoint->type() == Ice::SSLEndpointType && ipEndpoint->secure()) ||
             (ipEndpoint->type() == Ice::WSEndpointType && !ipEndpoint->secure()) ||
             (ipEndpoint->type() == Ice::WSSEndpointType && ipEndpoint->secure()));

        test((ipEndpoint->type() == Ice::TCPEndpointType && ICE_DYNAMIC_CAST(Ice::TCPEndpointInfo, info)) ||
             (ipEndpoint->type() == Ice::SSLEndpointType && ICE_DYNAMIC_CAST(IceSSL::EndpointInfo, info)) ||
             (ipEndpoint->type() == Ice::WSEndpointType && ICE_DYNAMIC_CAST(Ice::WSEndpointInfo, info)) ||
             (ipEndpoint->type() == Ice::WSSEndpointType && ICE_DYNAMIC_CAST(Ice::WSEndpointInfo, info)));

        Ice::UDPEndpointInfoPtr udpEndpoint = ICE_DYNAMIC_CAST(Ice::UDPEndpointInfo, endps[1]->getInfo());
        test(udpEndpoint);
        test(udpEndpoint->host == "udphost");
        test(udpEndpoint->port == 10001);
#if !defined(ICE_OS_UWP)
        test(udpEndpoint->sourceAddress == "10.10.10.10");
#endif
        test(udpEndpoint->mcastInterface == "eth0");
        test(udpEndpoint->mcastTtl == 5);
        test(udpEndpoint->timeout == -1);
        test(!udpEndpoint->compress);
        test(!udpEndpoint->secure());
        test(udpEndpoint->datagram());
        test(udpEndpoint->type() == Ice::UDPEndpointType);

        Ice::OpaqueEndpointInfoPtr opaqueEndpoint = ICE_DYNAMIC_CAST(Ice::OpaqueEndpointInfo, endps[2]->getInfo());
        test(opaqueEndpoint);
        Ice::EncodingVersion rev;
        rev.major = 1;
        rev.minor = 8;
        test(opaqueEndpoint->rawEncoding == rev);
    }
    cout << "ok" << endl;

    string defaultHost = communicator->getProperties()->getProperty("Ice.Default.Host");
#ifdef ICE_OS_UWP
    bool uwp = true;
#else
    bool uwp = false;
#endif
    if(!uwp || (communicator->getProperties()->getProperty("Ice.Default.Protocol") != "ssl" &&
                  communicator->getProperties()->getProperty("Ice.Default.Protocol") != "wss"))
    {
        cout << "test object adapter endpoint information... " << flush;
        {
            communicator->getProperties()->setProperty("TestAdapter.Endpoints",
                                                       "default -h 127.0.0.1 -t 15000:udp -h 127.0.0.1");
            Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TestAdapter");

            Ice::EndpointSeq endpoints = adapter->getEndpoints();
            test(endpoints.size() == 2);
            Ice::EndpointSeq publishedEndpoints = adapter->getPublishedEndpoints();
            test(endpoints == publishedEndpoints);

            Ice::TCPEndpointInfoPtr ipEndpoint = getTCPEndpointInfo(endpoints[0]->getInfo());
            test(ipEndpoint);
            test(ipEndpoint->type() == Ice::TCPEndpointType || ipEndpoint->type() == Ice::SSLEndpointType ||
                ipEndpoint->type() == Ice::WSEndpointType || ipEndpoint->type() == Ice::WSSEndpointType);
            test(ipEndpoint->host == "127.0.0.1");
            test(ipEndpoint->port > 0);
            test(ipEndpoint->timeout == 15000);

            Ice::UDPEndpointInfoPtr udpEndpoint = ICE_DYNAMIC_CAST(Ice::UDPEndpointInfo, endpoints[1]->getInfo());
            test(udpEndpoint);
            test(udpEndpoint->host == "127.0.0.1");
            test(udpEndpoint->datagram());
            test(udpEndpoint->port > 0);

            endpoints.pop_back();
            test(endpoints.size() == 1);
            adapter->setPublishedEndpoints(endpoints);
            publishedEndpoints = adapter->getPublishedEndpoints();
            test(endpoints == publishedEndpoints);

            adapter->destroy();

            int port = helper->getTestPort(1);
            ostringstream portStr;
            portStr << port;
            communicator->getProperties()->setProperty("TestAdapter.Endpoints", "default -h * -p " + portStr.str());
            communicator->getProperties()->setProperty("TestAdapter.PublishedEndpoints", helper->getTestEndpoint(1));
            adapter = communicator->createObjectAdapter("TestAdapter");

            endpoints = adapter->getEndpoints();
            test(endpoints.size() >= 1);
            publishedEndpoints = adapter->getPublishedEndpoints();
            test(publishedEndpoints.size() == 1);

            for(Ice::EndpointSeq::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p)
            {
                ipEndpoint = getTCPEndpointInfo((*p)->getInfo());
                test(ipEndpoint->port == port);
            }

            ipEndpoint = getTCPEndpointInfo(publishedEndpoints[0]->getInfo());
            test(ipEndpoint->host == helper->getTestHost());
            test(ipEndpoint->port == port);

            adapter->destroy();
        }
        cout << "ok" << endl;
    }

    string endpoints = helper->getTestEndpoint() + ":" + helper->getTestEndpoint("udp") + " -c";
    int port = helper->getTestPort();
    Ice::ObjectPrxPtr base = communicator->stringToProxy("test:" + endpoints);
    TestIntfPrxPtr testIntf = ICE_CHECKED_CAST(TestIntfPrx, base);

    cout << "test connection endpoint information... " << flush;
    {
        Ice::EndpointInfoPtr info = base->ice_getConnection()->getEndpoint()->getInfo();
        Ice::TCPEndpointInfoPtr tcpinfo = getTCPEndpointInfo(info);
        test(tcpinfo->port == port);
        test(!tcpinfo->compress);
        test(tcpinfo->host == defaultHost);

        ostringstream os;

        Ice::Context ctx = testIntf->getEndpointInfoAsContext();
        test(ctx["host"] == tcpinfo->host);
        test(ctx["compress"] == "false");
        istringstream is(ctx["port"]);
        int portCtx;
        is >> portCtx;
        test(portCtx > 0);

        info = base->ice_datagram()->ice_getConnection()->getEndpoint()->getInfo();
        Ice::UDPEndpointInfoPtr udp = ICE_DYNAMIC_CAST(Ice::UDPEndpointInfo, info);
        test(udp);
        test(udp->port == portCtx);
        test(udp->host == defaultHost);
    }
    cout << "ok" << endl;

    cout << "testing connection information... " << flush;
    {
        Ice::ConnectionPtr connection = base->ice_getConnection();
        connection->setBufferSize(1024, 2048);

        Ice::TCPConnectionInfoPtr info = getTCPConnectionInfo(connection->getInfo());
        test(info);
        test(!info->incoming);
        test(info->adapterName.empty());
        test(info->localPort > 0);
        test(info->remotePort == port);
        if(defaultHost == "127.0.0.1")
        {
            test(info->remoteAddress == defaultHost);
            test(info->localAddress == defaultHost);
        }
#if !defined(ICE_OS_UWP)
        test(info->rcvSize >= 1024);
        test(info->sndSize >= 2048);
#endif

        ostringstream os;

        Ice::Context ctx = testIntf->getConnectionInfoAsContext();
        test(ctx["incoming"] == "true");
        test(ctx["adapterName"] == "TestAdapter");
        test(ctx["remoteAddress"] == info->localAddress);
        test(ctx["localAddress"] == info->remoteAddress);
        os.str("");
        os << info->localPort;
        test(ctx["remotePort"] == os.str());
        os.str("");
        os << info->remotePort;
        test(ctx["localPort"] == os.str());

        if(base->ice_getConnection()->type() == "ws" || base->ice_getConnection()->type() == "wss")
        {
            Ice::HeaderDict headers;

            Ice::WSConnectionInfoPtr wsinfo = ICE_DYNAMIC_CAST(Ice::WSConnectionInfo, connection->getInfo());
            test(wsinfo);
            headers = wsinfo->headers;

            if(base->ice_getConnection()->type() == "wss")
            {
                IceSSL::ConnectionInfoPtr wssinfo = ICE_DYNAMIC_CAST(IceSSL::ConnectionInfo, wsinfo->underlying);
                test(wssinfo->verified);
#if !defined(ICE_OS_UWP) && TARGET_OS_IPHONE==0
                test(!wssinfo->certs.empty());
#endif
            }

            test(headers["Upgrade"] == "websocket");
            test(headers["Connection"] == "Upgrade");
            test(headers["Sec-WebSocket-Protocol"] == "ice.zeroc.com");
            test(headers.find("Sec-WebSocket-Accept") != headers.end());

            test(ctx["ws.Upgrade"] == "websocket");
            test(ctx["ws.Connection"] == "Upgrade");
            test(ctx["ws.Sec-WebSocket-Protocol"] == "ice.zeroc.com");
            test(ctx["ws.Sec-WebSocket-Version"] == "13");
            test(ctx.find("ws.Sec-WebSocket-Key") != ctx.end());
        }

        connection = base->ice_datagram()->ice_getConnection();
        connection->setBufferSize(2048, 1024);

        Ice::UDPConnectionInfoPtr udpinfo = ICE_DYNAMIC_CAST(Ice::UDPConnectionInfo, connection->getInfo());
        test(!udpinfo->incoming);
        test(udpinfo->adapterName.empty());
        test(udpinfo->localPort > 0);
        test(udpinfo->remotePort == port);
        if(defaultHost == "127.0.0.1")
        {
            test(udpinfo->remoteAddress == defaultHost);
            test(udpinfo->localAddress == defaultHost);
        }

#if !defined(ICE_OS_UWP)
        test(udpinfo->rcvSize >= 2048);
        test(udpinfo->sndSize >= 1024);
#endif
    }
    cout << "ok" << endl;

    testIntf->shutdown();

    communicator->shutdown();
    communicator->waitForShutdown();
}
Example #14
0
TimeoutPrxPtr
allTests(const Ice::CommunicatorPtr& communicator)
{
    string sref = "timeout:" + getTestEndpoint(communicator, 0);
    Ice::ObjectPrxPtr obj = communicator->stringToProxy(sref);
    test(obj);

    TimeoutPrxPtr timeout = ICE_CHECKED_CAST(TimeoutPrx, obj);
    test(timeout);

    cout << "testing connect timeout... " << flush;
    {
        //
        // Expect ConnectTimeoutException.
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_timeout(100));
        timeout->holdAdapter(500);
        try
        {
            to->op();
            test(false);
        }
        catch(const Ice::ConnectTimeoutException&)
        {
            // Expected.
        }
    }
    {
        //
        // Expect success.
        //
        timeout->op(); // Ensure adapter is active.
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_timeout(1000));
        timeout->holdAdapter(500);
        try
        {
            to->op();
        }
        catch(const Ice::ConnectTimeoutException&)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    // The sequence needs to be large enough to fill the write/recv buffers
    ByteSeq seq(2000000);

    cout << "testing connection timeout... " << flush;
    {
        //
        // Expect TimeoutException.
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_timeout(100));
        timeout->holdAdapter(500);
        try
        {
            to->sendData(seq);
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            // Expected.
        }
    }
    {
        //
        // Expect success.
        //
        timeout->op(); // Ensure adapter is active.
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_timeout(1000));
        timeout->holdAdapter(500);
        try
        {
            ByteSeq seq(1000000);
            to->sendData(seq);
        }
        catch(const Ice::TimeoutException&)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "testing invocation timeout... " << flush;
    {
        Ice::ConnectionPtr connection = obj->ice_getConnection();
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_invocationTimeout(100));
        test(connection == to->ice_getConnection());
        try
        {
            to->sleep(750);
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }
        obj->ice_ping();
        to = ICE_CHECKED_CAST(TimeoutPrx, obj->ice_invocationTimeout(500));
        test(connection == to->ice_getConnection());
        try
        {
            to->sleep(250);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
            test(false);
        }
        test(connection == to->ice_getConnection());
    }
    {
        //
        // Expect InvocationTimeoutException.
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_invocationTimeout(100));
        
#ifdef ICE_CPP11_MAPPING
        auto f = to->sleep_async(750);
        try
        {
            f.get();
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback();
        to->begin_sleep(750, newCallback_Timeout_sleep(cb, &Callback::responseEx, &Callback::exceptionEx));
        cb->check();
#endif
        obj->ice_ping();
    }
    {
        //
        // Expect success.
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_invocationTimeout(500));
#ifdef ICE_CPP11_MAPPING
        auto f = to->sleep_async(250);
        try
        {
            f.get();
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback();
        to->begin_sleep(250, newCallback_Timeout_sleep(cb, &Callback::response, &Callback::exception));
        cb->check();
#endif
    }
    {
        //
        // Backward compatible connection timeouts
        //
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, obj->ice_invocationTimeout(-2)->ice_timeout(250));
        Ice::ConnectionPtr con;
        try
        {
            con = to->ice_getConnection();
            to->sleep(750);
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            try
            {
                con->getInfo();
                test(false);
            }
            catch(const Ice::TimeoutException&)
            {
                // Connection got closed as well.
            }
        }
        obj->ice_ping();
        try
        {
            con = to->ice_getConnection();
#ifdef ICE_CPP11_MAPPING
            to->sleep_async(750).get();
#else
            to->end_sleep(to->begin_sleep(750));
#endif
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            try
            {
                con->getInfo();
                test(false);
            }
            catch(const Ice::TimeoutException&)
            {
                // Connection got closed as well.
            }
        }
        obj->ice_ping();
    }
    cout << "ok" << endl;

    cout << "testing close timeout... " << flush;
    {
        TimeoutPrxPtr to = ICE_CHECKED_CAST(TimeoutPrx, obj->ice_timeout(250));
        Ice::ConnectionPtr connection = to->ice_getConnection();
        timeout->holdAdapter(600);
        connection->close(false);
        try
        {
            connection->getInfo(); // getInfo() doesn't throw in the closing state.
        }
        catch(const Ice::LocalException&)
        {
            test(false);
        }
        IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(650));
        try
        {
            connection->getInfo();
            test(false);
        }
        catch(const Ice::CloseConnectionException&)
        {
            // Expected.
        }
        timeout->op(); // Ensure adapter is active.
    }
    cout << "ok" << endl;

    cout << "testing timeout overrides... " << flush;
    {
        //
        // Test Ice.Override.Timeout. This property overrides all
        // endpoint timeouts.
        //
        Ice::InitializationData initData;
        initData.properties = communicator->getProperties()->clone();
        initData.properties->setProperty("Ice.Override.Timeout", "250");
        Ice::CommunicatorPtr comm = Ice::initialize(initData);
        TimeoutPrxPtr to = ICE_CHECKED_CAST(TimeoutPrx, comm->stringToProxy(sref));
        timeout->holdAdapter(700);
        try
        {
            to->sendData(seq);
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            // Expected.
        }

        //
        // Calling ice_timeout() should have no effect.
        //
        timeout->op(); // Ensure adapter is active.
        to = ICE_CHECKED_CAST(TimeoutPrx, to->ice_timeout(1000));
        timeout->holdAdapter(500);
        try
        {
            to->sendData(seq);
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            // Expected.
        }
        comm->destroy();
    }
    {
        //
        // Test Ice.Override.ConnectTimeout.
        //
        Ice::InitializationData initData;
        initData.properties = communicator->getProperties()->clone();
        initData.properties->setProperty("Ice.Override.ConnectTimeout", "250");
        Ice::CommunicatorPtr comm = Ice::initialize(initData);
        timeout->holdAdapter(750);
        TimeoutPrxPtr to = ICE_UNCHECKED_CAST(TimeoutPrx, comm->stringToProxy(sref));
        try
        {
            to->op();
            test(false);
        }
        catch(const Ice::ConnectTimeoutException&)
        {
            // Expected.
        }
        //
        // Calling ice_timeout() should have no effect on the connect timeout.
        //
        timeout->op(); // Ensure adapter is active.
        timeout->holdAdapter(750);
        to = ICE_UNCHECKED_CAST(TimeoutPrx, to->ice_timeout(1000));
        try
        {
            to->op();
            test(false);
        }
        catch(const Ice::ConnectTimeoutException&)
        {
            // Expected.
        }
        //
        // Verify that timeout set via ice_timeout() is still used for requests.
        //
        timeout->op(); // Ensure adapter is active.
        to = ICE_UNCHECKED_CAST(TimeoutPrx, to->ice_timeout(250));
        to->ice_getConnection(); // Establish connection
        timeout->holdAdapter(750);
        try
        {
            to->sendData(seq);
            test(false);
        }
        catch(const Ice::TimeoutException&)
        {
            // Expected.
        }
        comm->destroy();
    }
    {
        //
        // Test Ice.Override.CloseTimeout.
        //
        Ice::InitializationData initData;
        initData.properties = communicator->getProperties()->clone();
        initData.properties->setProperty("Ice.Override.CloseTimeout", "250");
        Ice::CommunicatorPtr comm = Ice::initialize(initData);
        Ice::ConnectionPtr connection = comm->stringToProxy(sref)->ice_getConnection();
        timeout->holdAdapter(500);
        IceUtil::Time now = IceUtil::Time::now();
        comm->destroy();
        test(IceUtil::Time::now() - now < IceUtil::Time::milliSeconds(400));
    }
    cout << "ok" << endl;

    cout << "testing invocation timeouts with collocated calls... " << flush;
    {
        communicator->getProperties()->setProperty("TimeoutCollocated.AdapterId", "timeoutAdapter");

        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TimeoutCollocated");
        adapter->activate();

        TimeoutPrxPtr timeout = ICE_UNCHECKED_CAST(TimeoutPrx, adapter->addWithUUID(ICE_MAKE_SHARED(TimeoutI)));
        timeout = timeout->ice_invocationTimeout(100);
        try
        {
            timeout->sleep(300);
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }

        try
        {
#ifdef ICE_CPP11_MAPPING
            timeout->sleep_async(300).get();
#else
            timeout->end_sleep(timeout->begin_sleep(300));
#endif
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }

        TimeoutPrxPtr batchTimeout = timeout->ice_batchOneway();
        batchTimeout->ice_ping();
        batchTimeout->ice_ping();
        batchTimeout->ice_ping();

        // Keep the server thread pool busy.
#ifdef ICE_CPP11_MAPPING
        timeout->ice_invocationTimeout(-1)->sleep_async(300); 
#else
        timeout->ice_invocationTimeout(-1)->begin_sleep(300);
#endif
        try
        {
            batchTimeout->ice_flushBatchRequests();
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }

        batchTimeout->ice_ping();
        batchTimeout->ice_ping();
        batchTimeout->ice_ping();

        // Keep the server thread pool busy.
#ifdef ICE_CPP11_MAPPING
        timeout->ice_invocationTimeout(-1)->sleep_async(300); 
#else
        timeout->ice_invocationTimeout(-1)->begin_sleep(300);
#endif
        try
        {
#ifdef ICE_CPP11_MAPPING
            batchTimeout->ice_flushBatchRequests_async().get();
#else
            batchTimeout->end_ice_flushBatchRequests(batchTimeout->begin_ice_flushBatchRequests());
#endif
            test(false);
        }
        catch(const Ice::InvocationTimeoutException&)
        {
        }

        adapter->destroy();
    }
    cout << "ok" << endl;

    return timeout;
}
Example #15
0
void
batchOneways(const Test::MyClassPrxPtr& p)
{
    const Test::ByteS bs1(10  * 1024);

    Test::MyClassPrxPtr batch = ICE_UNCHECKED_CAST(Test::MyClassPrx, p->ice_batchOneway());

    batch->ice_flushBatchRequests(); // Empty flush
    if(batch->ice_getConnection())
    {
        batch->ice_getConnection()->flushBatchRequests(Ice::ICE_SCOPED_ENUM(CompressBatch, BasedOnProxy));
    }
    batch->ice_getCommunicator()->flushBatchRequests(Ice::ICE_SCOPED_ENUM(CompressBatch, BasedOnProxy));

    int i;
    p->opByteSOnewayCallCount(); // Reset the call count
    for(i = 0 ; i < 30 ; ++i)
    {
        try
        {
            batch->opByteSOneway(bs1);
        }
        catch(const Ice::LocalException& ex)
        {
            cerr << ex << endl;
            test(false);
        }
    }

    int count = 0;
    while(count < 27) // 3 * 9 requests auto-flushed.
    {
        count += p->opByteSOnewayCallCount();
        IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(10));
    }

    if(batch->ice_getConnection() &&
       p->ice_getCommunicator()->getProperties()->getProperty("Ice.Default.Protocol") != "bt")
    {
        Test::MyClassPrxPtr batch1 = ICE_UNCHECKED_CAST(Test::MyClassPrx, p->ice_batchOneway());
        Test::MyClassPrxPtr batch2 = ICE_UNCHECKED_CAST(Test::MyClassPrx, p->ice_batchOneway());

        batch1->ice_ping();
        batch2->ice_ping();
        batch1->ice_flushBatchRequests();
        batch1->ice_getConnection()->close(Ice::ICE_SCOPED_ENUM(ConnectionClose, GracefullyWithWait));
        batch1->ice_ping();
        batch2->ice_ping();

        batch1->ice_getConnection();
        batch2->ice_getConnection();

        batch1->ice_ping();
        batch1->ice_getConnection()->close(Ice::ICE_SCOPED_ENUM(ConnectionClose, GracefullyWithWait));
        batch1->ice_ping();
        batch2->ice_ping();
    }

    Ice::Identity identity;
    identity.name = "invalid";
    Ice::ObjectPrxPtr batch3 = batch->ice_identity(identity);
    batch3->ice_ping();
    batch3->ice_flushBatchRequests();

    // Make sure that a bogus batch request doesn't cause troubles to other ones.
    batch3->ice_ping();
    batch->ice_ping();
    batch->ice_flushBatchRequests();
    batch->ice_ping();

    if(batch->ice_getConnection() &&
       p->ice_getCommunicator()->getProperties()->getProperty("Ice.Default.Protocol") != "bt")
    {
        Ice::InitializationData initData;
        initData.properties = p->ice_getCommunicator()->getProperties()->clone();
        BatchRequestInterceptorIPtr interceptor = ICE_MAKE_SHARED(BatchRequestInterceptorI);

#if defined(ICE_CPP11_MAPPING)
        initData.batchRequestInterceptor = [=](const Ice::BatchRequest& request, int count, int size)
        {
            interceptor->enqueue(request, count, size);
        };
#else
        initData.batchRequestInterceptor = interceptor;
#endif
        Ice::CommunicatorPtr ic = Ice::initialize(initData);

        Test::MyClassPrxPtr batch =
            ICE_UNCHECKED_CAST(Test::MyClassPrx, ic->stringToProxy(p->ice_toString()))->ice_batchOneway();

        test(interceptor->count() == 0);
        batch->ice_ping();
        batch->ice_ping();
        batch->ice_ping();
        test(interceptor->count() == 0);

        interceptor->enqueue(true);
        batch->ice_ping();
        batch->ice_ping();
        batch->ice_ping();
        test(interceptor->count() == 3);

        batch->ice_flushBatchRequests();
        batch->ice_ping();
        test(interceptor->count() == 1);

        batch->opByteSOneway(bs1);
        test(interceptor->count() == 2);
        batch->opByteSOneway(bs1);
        test(interceptor->count() == 3);

        batch->opByteSOneway(bs1); // This should trigger the flush
        batch->ice_ping();
        test(interceptor->count() == 2);

        ic->destroy();
    }

    bool supportsCompress = true;
    try
    {
        supportsCompress = p->supportsCompress();
    }
    catch(const Ice::OperationNotExistException&)
    {
    }

    if(supportsCompress && batch->ice_getConnection() &&
       p->ice_getCommunicator()->getProperties()->getProperty("Ice.Override.Compress") == "")
    {
        Ice::ObjectPrxPtr prx = batch->ice_getConnection()->createProxy(batch->ice_getIdentity())->ice_batchOneway();

        Test::MyClassPrxPtr batch1 = ICE_UNCHECKED_CAST(Test::MyClassPrx, prx->ice_compress(false));
        Test::MyClassPrxPtr batch2 = ICE_UNCHECKED_CAST(Test::MyClassPrx, prx->ice_compress(true));
        Test::MyClassPrxPtr batch3 = ICE_UNCHECKED_CAST(Test::MyClassPrx, prx->ice_identity(identity));

        batch1->opByteSOneway(bs1);
        batch1->opByteSOneway(bs1);
        batch1->opByteSOneway(bs1);
        batch1->ice_getConnection()->flushBatchRequests(Ice::ICE_SCOPED_ENUM(CompressBatch, Yes));

        batch2->opByteSOneway(bs1);
        batch2->opByteSOneway(bs1);
        batch2->opByteSOneway(bs1);
        batch1->ice_getConnection()->flushBatchRequests(Ice::ICE_SCOPED_ENUM(CompressBatch, No));

        batch1->opByteSOneway(bs1);
        batch1->opByteSOneway(bs1);
        batch1->opByteSOneway(bs1);
        batch1->ice_getConnection()->flushBatchRequests(Ice::ICE_SCOPED_ENUM(CompressBatch, BasedOnProxy));

        batch1->opByteSOneway(bs1);
        batch2->opByteSOneway(bs1);
        batch1->opByteSOneway(bs1);
        batch1->ice_getConnection()->flushBatchRequests(Ice::ICE_SCOPED_ENUM(CompressBatch, BasedOnProxy));

        batch1->opByteSOneway(bs1);
        batch3->opByteSOneway(bs1);
        batch1->opByteSOneway(bs1);
        batch1->ice_getConnection()->flushBatchRequests(Ice::ICE_SCOPED_ENUM(CompressBatch, BasedOnProxy));
    }
}
Example #16
0
void
ObjectAdapterI::updateLocatorRegistry(const IceInternal::LocatorInfoPtr& locatorInfo, const Ice::ObjectPrxPtr& proxy)
{
    if(_id.empty() || !locatorInfo)
    {
        return; // Nothing to update.
    }

    LocatorRegistryPrxPtr locatorRegistry = locatorInfo->getLocatorRegistry();
    if(!locatorRegistry)
    {
        return;
    }

    try
    {
        if(_replicaGroupId.empty())
        {
            locatorRegistry->setAdapterDirectProxy(_id, proxy);
        }
        else
        {
            locatorRegistry->setReplicatedAdapterDirectProxy(_id, _replicaGroupId, proxy);
        }
    }
    catch(const AdapterNotFoundException&)
    {
        if(_instance->traceLevels()->location >= 1)
        {
            Trace out(_instance->initializationData().logger, _instance->traceLevels()->locationCat);
            out << "couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n";
            out << "the object adapter is not known to the locator registry";
        }

        throw NotRegisteredException(__FILE__, __LINE__, "object adapter", _id);
    }
    catch(const InvalidReplicaGroupIdException&)
    {
        if(_instance->traceLevels()->location >= 1)
        {
            Trace out(_instance->initializationData().logger, _instance->traceLevels()->locationCat);
            out << "couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n";
            out << "the replica group `" << _replicaGroupId << "' is not known to the locator registry";
        }

        throw NotRegisteredException(__FILE__, __LINE__, "replica group", _replicaGroupId);
    }
    catch(const AdapterAlreadyActiveException&)
    {
        if(_instance->traceLevels()->location >= 1)
        {
            Trace out(_instance->initializationData().logger, _instance->traceLevels()->locationCat);
            out << "couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n";
            out << "the object adapter endpoints are already set";
        }

        throw ObjectAdapterIdInUseException(__FILE__, __LINE__, _id);
    }
    catch(const ObjectAdapterDeactivatedException&)
    {
        // Expected if collocated call and OA is deactivated, ignore.
    }
    catch(const CommunicatorDestroyedException&)
    {
        // Ignore.
    }
    catch(const LocalException& ex)
    {
        if(_instance->traceLevels()->location >= 1)
        {
            Trace out(_instance->initializationData().logger, _instance->traceLevels()->locationCat);
            out << "couldn't update object adapter `" + _id + "' endpoints with the locator registry:\n" << ex;
        }
        throw; // TODO: Shall we raise a special exception instead of a non obvious local exception?
    }

    if(_instance->traceLevels()->location >= 1)
    {
        Trace out(_instance->initializationData().logger, _instance->traceLevels()->locationCat);
        out << "updated object adapter `" + _id + "' endpoints with the locator registry\n";
        out << "endpoints = ";
        if(proxy)
        {
            EndpointSeq endpts = proxy ? proxy->ice_getEndpoints() : EndpointSeq();
            ostringstream o;
            transform(endpts.begin(), endpts.end(), ostream_iterator<string>(o, endpts.size() > 1 ? ":" : ""),
                      Ice::constMemFun(&Endpoint::toString));
            out << o.str();
        }
    }
}
Example #17
0
Outgoing::Outgoing(const Ice::ObjectPrxPtr& proxy, const string& operation, OperationMode mode, const Context& context) :
    ProxyOutgoingBase(proxy, mode),
    _encoding(getCompatibleEncoding(proxy->__reference()->getEncoding())),
    _is(proxy->__reference()->getInstance().get(), Ice::currentProtocolEncoding),
    _operation(operation)
{
    checkSupportedProtocol(getCompatibleProtocol(proxy->__reference()->getProtocol()));
    _observer.attach(proxy, operation, context);
    switch(_proxy->__reference()->getMode())
    {
        case Reference::ModeTwoway:
        case Reference::ModeOneway:
        case Reference::ModeDatagram:
        {
            _os.writeBlob(requestHdr, sizeof(requestHdr));
            break;
        }

        case Reference::ModeBatchOneway:
        case Reference::ModeBatchDatagram:
        {
            _proxy->__getBatchRequestQueue()->prepareBatchRequest(&_os);
            break;
        }
    }

    try
    {
        _os.write(_proxy->__reference()->getIdentity());

        //
        // For compatibility with the old FacetPath.
        //
        if(_proxy->__reference()->getFacet().empty())
        {
            _os.write(static_cast<string*>(0), static_cast<string*>(0));
        }
        else
        {
            string facet = _proxy->__reference()->getFacet();
            _os.write(&facet, &facet + 1);
        }

        _os.write(operation, false);

        _os.write(static_cast<Ice::Byte>(mode));

        if(&context != &Ice::noExplicitContext)
        {
            //
            // Explicit context
            //
            _os.write(context);
        }
        else
        {
            //
            // Implicit context
            //
            const ImplicitContextIPtr& implicitContext = _proxy->__reference()->getInstance()->getImplicitContext();
            const Context& prxContext = _proxy->__reference()->getContext()->getValue();
            if(implicitContext == 0)
            {
                _os.write(prxContext);
            }
            else
            {
                implicitContext->write(prxContext, &_os);
            }
        }
    }
    catch(const LocalException& ex)
    {
        abort(ex);
    }
}
Example #18
0
void
allTests(const Ice::CommunicatorPtr& communicator, const string& ref)
{
    ServerManagerPrxPtr manager = ICE_CHECKED_CAST(ServerManagerPrx, communicator->stringToProxy(ref));
    TestLocatorPrxPtr locator = ICE_UNCHECKED_CAST(TestLocatorPrx, communicator->getDefaultLocator());
    test(manager);

    TestLocatorRegistryPrxPtr registry = ICE_CHECKED_CAST(TestLocatorRegistryPrx, locator->getRegistry());
    test(registry);

    cout << "testing stringToProxy... " << flush;
    Ice::ObjectPrxPtr base = communicator->stringToProxy("test @ TestAdapter");
    Ice::ObjectPrxPtr base2 = communicator->stringToProxy("test @ TestAdapter");
    Ice::ObjectPrxPtr base3 = communicator->stringToProxy("test");
    Ice::ObjectPrxPtr base4 = communicator->stringToProxy("ServerManager"); 
    Ice::ObjectPrxPtr base5 = communicator->stringToProxy("test2");
    Ice::ObjectPrxPtr base6 = communicator->stringToProxy("test @ ReplicatedAdapter");
    cout << "ok" << endl;

    cout << "testing ice_locator and ice_getLocator... " << flush;
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), communicator->getDefaultLocator()));
    Ice::LocatorPrxPtr anotherLocator = ICE_UNCHECKED_CAST(Ice::LocatorPrx, communicator->stringToProxy("anotherLocator"));
    base = base->ice_locator(anotherLocator);
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), anotherLocator));
    communicator->setDefaultLocator(ICE_NULLPTR);
    base = communicator->stringToProxy("test @ TestAdapter");
    test(!base->ice_getLocator());
    base = base->ice_locator(anotherLocator);
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), anotherLocator));
    communicator->setDefaultLocator(locator);
    base = communicator->stringToProxy("test @ TestAdapter");
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), communicator->getDefaultLocator())); 
    
    //
    // We also test ice_router/ice_getRouter (perhaps we should add a
    // test/Ice/router test?)
    //
    test(!base->ice_getRouter());
    Ice::RouterPrxPtr anotherRouter = ICE_UNCHECKED_CAST(Ice::RouterPrx, communicator->stringToProxy("anotherRouter"));
    base = base->ice_router(anotherRouter);
    test(Ice::proxyIdentityEqual(base->ice_getRouter(), anotherRouter));
    Ice::RouterPrxPtr router = ICE_UNCHECKED_CAST(Ice::RouterPrx, communicator->stringToProxy("dummyrouter"));
    communicator->setDefaultRouter(router);
    base = communicator->stringToProxy("test @ TestAdapter");
    test(Ice::proxyIdentityEqual(base->ice_getRouter(), communicator->getDefaultRouter()));
    communicator->setDefaultRouter(0);
    base = communicator->stringToProxy("test @ TestAdapter");
    test(!base->ice_getRouter());
    cout << "ok" << endl;

    cout << "starting server... " << flush;
    manager->startServer();
    cout << "ok" << endl;

    cout << "testing checked cast... " << flush;
    TestIntfPrxPtr obj = ICE_CHECKED_CAST(TestIntfPrx, base);
    test(obj);
    TestIntfPrxPtr obj2 = ICE_CHECKED_CAST(TestIntfPrx, base2);
    test(obj2);
    TestIntfPrxPtr obj3 = ICE_CHECKED_CAST(TestIntfPrx, base3);
    test(obj3);
    ServerManagerPrxPtr obj4 = ICE_CHECKED_CAST(ServerManagerPrx, base4);
    test(obj4);
    TestIntfPrxPtr obj5 = ICE_CHECKED_CAST(TestIntfPrx, base5);
    test(obj5);
    TestIntfPrxPtr obj6 = ICE_CHECKED_CAST(TestIntfPrx, base6);
    test(obj6);
    cout << "ok" << endl;
 
    cout << "testing id@AdapterId indirect proxy... " << flush;
    obj->shutdown();
    manager->startServer();
    try
    {
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    cout << "ok" << endl;    
    
    cout << "testing id@ReplicaGroupId indirect proxy... " << flush;
    obj->shutdown();
    manager->startServer();
    try
    {
        obj6->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    cout << "ok" << endl;    

    cout << "testing identity indirect proxy... " << flush;
    obj->shutdown();
    manager->startServer();
    try
    {
        obj3->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    try
    {
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();
    try
    {
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    try
    {
        obj3->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();

    try
    {
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();
    try
    {
        obj3->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();
    try
    {
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();

    try
    {
        obj5->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    cout << "ok" << endl;

    cout << "testing proxy with unknown identity... " << flush;
    try
    {
        base = communicator->stringToProxy("unknown/unknown");
        base->ice_ping();
        test(false);
    }
    catch (const Ice::NotRegisteredException& ex)
    {
        test(ex.kindOfObject == "object");
        test(ex.id == "unknown/unknown");
    }
    cout << "ok" << endl;

    cout << "testing proxy with unknown adapter... " << flush;
    try
    {
        base = communicator->stringToProxy("test @ TestAdapterUnknown");
        base->ice_ping();
        test(false);
    }
    catch (const Ice::NotRegisteredException& ex)
    {
        test(ex.kindOfObject == "object adapter");
        test(ex.id == "TestAdapterUnknown");
    }
    cout << "ok" << endl;

    cout << "testing locator cache timeout... " << flush;

    int count = locator->getRequestCount();
    communicator->stringToProxy("test@TestAdapter")->ice_locatorCacheTimeout(0)->ice_ping(); // No locator cache.
    test(++count == locator->getRequestCount());
    communicator->stringToProxy("test@TestAdapter")->ice_locatorCacheTimeout(0)->ice_ping(); // No locator cache.
    test(++count == locator->getRequestCount());
    communicator->stringToProxy("test@TestAdapter")->ice_locatorCacheTimeout(1)->ice_ping(); // 1s timeout.
    test(count == locator->getRequestCount());
    IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(1300));
    communicator->stringToProxy("test@TestAdapter")->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(1)->ice_ping(); // 1s timeout
    test(count == locator->getRequestCount());
    IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(1300));
    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);

    cout << "ok" << endl;

    cout << "testing proxy from server... " << flush;
    obj = ICE_CHECKED_CAST(TestIntfPrx, communicator->stringToProxy("test@TestAdapter"));
    HelloPrxPtr hello = obj->getHello();
    test(hello->ice_getAdapterId() == "TestAdapter");
    hello->sayHello();
    hello = obj->getReplicatedHello();
    test(hello->ice_getAdapterId() == "ReplicatedAdapter");
    hello->sayHello();
    cout << "ok" << endl;

    cout << "testing locator request queuing... " << flush;
    hello = obj->getReplicatedHello()->ice_locatorCacheTimeout(0)->ice_connectionCached(false);
    count = locator->getRequestCount();
    hello->ice_ping();
    test(++count == locator->getRequestCount());
    int i;

#ifdef ICE_CPP11_MAPPING
    list<future<void>>  results;
    for(i = 0; i < 1000; i++)
    {
        auto result = make_shared<promise<void>>();
        hello->sayHello_async(
            [result]()
            {
                result->set_value();
            },
            [result](exception_ptr)
            {
                test(false);
            });
        results.push_back(result->get_future());
    }
    for(auto& result : results)
    {
        result.get();
    }
    results.clear();
    test(locator->getRequestCount() > count && locator->getRequestCount() < count + 999);
    if(locator->getRequestCount() > count + 800)
    {
        cout << "queuing = " << locator->getRequestCount() - count;
    }
    count = locator->getRequestCount();
    hello = hello->ice_adapterId("unknown");
    for(i = 0; i < 1000; i++)
    {
        auto result = make_shared<promise<void>>();
        hello->sayHello_async(
            [result]()
            {
                test(false);
            },
            [result](exception_ptr ex)
            {
                try
                {
                    rethrow_exception(ex);
                }
                catch(const Ice::NotRegisteredException&)
                {
                    result->set_value();
                }
                catch(...)
                {
                    test(false);
                }
            });
        results.push_back(result->get_future());
    }
    for(auto& result : results)
    {
        result.get();
    }
    results.clear();
    // Take into account the retries.
    test(locator->getRequestCount() > count && locator->getRequestCount() < count + 1999);
    if(locator->getRequestCount() > count + 800)
    {
        cout << "queuing = " << locator->getRequestCount() - count;
    }
#else
    list<Ice::AsyncResultPtr>  results;
    AMICallbackPtr cb = new AMICallback;
    for(i = 0; i < 1000; i++)
    {
        Ice::AsyncResultPtr result = hello->begin_sayHello(
            newCallback_Hello_sayHello(cb, &AMICallback::response1, &AMICallback::exception1));
        results.push_back(result);
    }
    while(!results.empty())
    {
        Ice::AsyncResultPtr result = results.front();
        results.pop_front();
        result->waitForCompleted();
    }

    test(locator->getRequestCount() > count && locator->getRequestCount() < count + 999);
    if(locator->getRequestCount() > count + 800)
    {
        cout << "queuing = " << locator->getRequestCount() - count;
    }
    count = locator->getRequestCount();
    hello = hello->ice_adapterId("unknown");
    for(i = 0; i < 1000; i++)
    {
        Ice::AsyncResultPtr result = hello->begin_sayHello(
            newCallback_Hello_sayHello(cb, &AMICallback::response2, &AMICallback::exception2));
        results.push_back(result);
    }
    while(!results.empty())
    {
        Ice::AsyncResultPtr result = results.front();
        results.pop_front();
        result->waitForCompleted();
    }
    // Take into account the retries.
    test(locator->getRequestCount() > count && locator->getRequestCount() < count + 1999);
    if(locator->getRequestCount() > count + 800)
    {
        cout << "queuing = " << locator->getRequestCount() - count;
    }
#endif
    cout << "ok" << endl;

    cout << "testing adapter locator cache... " << flush;
    try
    {
        communicator->stringToProxy("test@TestAdapter3")->ice_ping();
        test(false);
    }
    catch(const Ice::NotRegisteredException& ex)
    {
        test(ex.kindOfObject == "object adapter");
        test(ex.id == "TestAdapter3");
    }
    registry->setAdapterDirectProxy("TestAdapter3", locator->findAdapterById("TestAdapter"));
    try
    {
        communicator->stringToProxy("test@TestAdapter3")->ice_ping();
        registry->setAdapterDirectProxy("TestAdapter3", communicator->stringToProxy("dummy:tcp"));
        communicator->stringToProxy("test@TestAdapter3")->ice_ping();
    }
    catch(const Ice::LocalException&)
    {
        test(false);
    }
    
    try
    {
        communicator->stringToProxy("test@TestAdapter3")->ice_locatorCacheTimeout(0)->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    try
    {
        communicator->stringToProxy("test@TestAdapter3")->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {   
    }
    registry->setAdapterDirectProxy("TestAdapter3", locator->findAdapterById("TestAdapter"));
    try
    {
        communicator->stringToProxy("test@TestAdapter3")->ice_ping();
    }
    catch(const Ice::LocalException&)
    {
        test(false);
    }
    cout << "ok" <<endl;

    cout << "testing well-known object locator cache... " << flush;

    registry->addObject(communicator->stringToProxy("test3@TestUnknown"));
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
        test(false);
    }
    catch(const Ice::NotRegisteredException& ex)
    {
        test(ex.kindOfObject == "object adapter");
        test(ex.id == "TestUnknown");
    }
    registry->addObject(communicator->stringToProxy("test3@TestAdapter4")); // Update
    registry->setAdapterDirectProxy("TestAdapter4", communicator->stringToProxy("dummy:tcp"));
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    registry->setAdapterDirectProxy("TestAdapter4", locator->findAdapterById("TestAdapter"));
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
    }
    catch(const Ice::LocalException&)
    {
        test(false);
    }

    registry->setAdapterDirectProxy("TestAdapter4", communicator->stringToProxy("dummy:tcp"));
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
    }
    catch(const Ice::LocalException&)
    {
        test(false);
    }

    try
    {
        communicator->stringToProxy("test@TestAdapter4")->ice_locatorCacheTimeout(0)->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    try
    {
        communicator->stringToProxy("test@TestAdapter4")->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {   
    }
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    registry->addObject(communicator->stringToProxy("test3@TestAdapter"));
    try
    {
        communicator->stringToProxy("test3")->ice_ping();
    }
    catch(const Ice::LocalException&)
    {
        test(false);
    }
    
    registry->addObject(communicator->stringToProxy("test4"));
    try
    {
        communicator->stringToProxy("test4")->ice_ping();
        test(false);
    }
    catch(const Ice::NoEndpointException&)
    {
    }
    cout << "ok" << endl;

    cout << "testing locator cache background updates... " << flush;
    {
        Ice::InitializationData initData;
        initData.properties = communicator->getProperties()->clone();
        initData.properties->setProperty("Ice.BackgroundLocatorCacheUpdates", "1");
        Ice::CommunicatorPtr ic = Ice::initialize(initData);

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

        int 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", 0);
        registry->addObject(communicator->stringToProxy("test3:tcp"));
        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());
        IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(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.
                IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(10));
            }
        }
        catch(const 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.
                IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(10));
            }
        }
        catch(const Ice::LocalException&)
        {
            // Expected to fail once they endpoints have been updated in the background.
        }
        ic->destroy();
    }
    cout << "ok" << endl;

    cout << "testing proxy from server after shutdown... " << flush;
    hello = obj->getReplicatedHello();
    obj->shutdown();
    manager->startServer();
    hello->sayHello();
    cout << "ok" << endl;

    cout << "testing object migration... " << flush;
    hello = ICE_CHECKED_CAST(HelloPrx, communicator->stringToProxy("hello"));
    obj->migrateHello();
    hello->ice_getConnection()->close(false);
    hello->sayHello();
    obj->migrateHello();
    hello->sayHello();
    obj->migrateHello();
    hello->sayHello();
    cout << "ok" << endl;

    cout << "testing locator encoding resolution... " << flush;

    hello = ICE_CHECKED_CAST(HelloPrx, communicator->stringToProxy("hello"));
    count = locator->getRequestCount();
    communicator->stringToProxy("test@TestAdapter")->ice_encodingVersion(Ice::Encoding_1_1)->ice_ping();
    test(count == locator->getRequestCount());
    communicator->stringToProxy("test@TestAdapter10")->ice_encodingVersion(Ice::Encoding_1_0)->ice_ping();
    test(++count == locator->getRequestCount());
    communicator->stringToProxy("test -e 1.0@TestAdapter10-2")->ice_ping();
    test(++count == locator->getRequestCount());

    cout << "ok" << endl;

    cout << "shutdown server... " << flush;
    obj->shutdown();
    cout << "ok" << endl;

    cout << "testing whether server is gone... " << flush;
    try
    {
        obj2->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    try
    {
        obj3->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    try
    {
        obj5->ice_ping();
        test(false);
    }
    catch(const Ice::LocalException&)
    {
    }
    cout << "ok" << endl;

    string host = communicator->getProperties()->getPropertyAsIntWithDefault("Ice.IPv6", 0) == 0 ? 
            "127.0.0.1" : "\"0:0:0:0:0:0:0:1\"";
    if(communicator->getProperties()->getProperty("Ice.Default.Host") == host)
    {
        cout << "testing indirect proxies to collocated objects... " << flush;
        //
        // Set up test for calling a collocated object through an indirect, adapterless reference.
        //
        Ice::PropertiesPtr properties = communicator->getProperties();
        properties->setProperty("Ice.PrintAdapterReady", "0");
        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("Hello", "default");
        adapter->setLocator(locator);

        Ice::Identity id;
        id.name = IceUtil::generateUUID();
        registry->addObject(adapter->add(ICE_MAKE_SHARED(HelloI), id));
        adapter->activate();
        
        HelloPrxPtr helloPrx = ICE_CHECKED_CAST(HelloPrx, communicator->stringToProxy(communicator->identityToString(id)));
        test(!helloPrx->ice_getConnection());

        adapter->deactivate();
        cout << "ok" << endl;
    }
    cout << "shutdown server manager... " << flush;
    manager->shutdown();
    cout << "ok" << endl;
}
Example #19
0
void
allTests(const Ice::CommunicatorPtr& communicator)
{
    string ref = "communicator:" + getTestEndpoint(communicator, 0);
    RemoteCommunicatorPrxPtr com = ICE_UNCHECKED_CAST(RemoteCommunicatorPrx, communicator->stringToProxy(ref));

    RandomNumberGenerator rng;

    cout << "testing binding with single endpoint... " << flush;
    {
        RemoteObjectAdapterPrxPtr adapter = com->createObjectAdapter("Adapter", "default");

        TestIntfPrxPtr test1 = adapter->getTestIntf();
        TestIntfPrxPtr test2 = adapter->getTestIntf();
        test(test1->ice_getConnection() == test2->ice_getConnection());

        test1->ice_ping();
        test2->ice_ping();

        com->deactivateObjectAdapter(adapter);

        TestIntfPrxPtr test3 = ICE_UNCHECKED_CAST(TestIntfPrx, test1);
        test(test3->ice_getConnection() == test1->ice_getConnection());
        test(test3->ice_getConnection() == test2->ice_getConnection());

        try
        {
            test3->ice_ping();
            test(false);
        }
        catch(const Ice::ConnectFailedException&)
        {
        }
    }
    cout << "ok" << endl;

    cout << "testing binding with multiple endpoints... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter11", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter12", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter13", "default"));

        //
        // Ensure that when a connection is opened it's reused for new
        // proxies and that all endpoints are eventually tried.
        //
        set<string> names;
        names.insert("Adapter11");
        names.insert("Adapter12");
        names.insert("Adapter13");
        while(!names.empty())
        {
            vector<RemoteObjectAdapterPrxPtr> adpts = adapters;

            TestIntfPrxPtr test1 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test2 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test3 = createTestIntfPrx(adpts);

            test(test1->ice_getConnection() == test2->ice_getConnection());
            test(test2->ice_getConnection() == test3->ice_getConnection());

            names.erase(test1->getAdapterName());
            test1->ice_getConnection()->close(false);
        }

        //
        // Ensure that the proxy correctly caches the connection (we
        // always send the request over the same connection.)
        //
        {
            for(vector<RemoteObjectAdapterPrxPtr>::const_iterator p = adapters.begin(); p != adapters.end(); ++p)
            {
                (*p)->getTestIntf()->ice_ping();
            }

            TestIntfPrxPtr test = createTestIntfPrx(adapters);
            string name = test->getAdapterName();
            const int nRetry = 10;
            int i;
            for(i = 0; i < nRetry &&  test->getAdapterName() == name; i++);
            test(i == nRetry);

            for(vector<RemoteObjectAdapterPrxPtr>::const_iterator q = adapters.begin(); q != adapters.end(); ++q)
            {
                (*q)->getTestIntf()->ice_getConnection()->close(false);
            }
        }

        //
        // Deactivate an adapter and ensure that we can still
        // establish the connection to the remaining adapters.
        //
        com->deactivateObjectAdapter(adapters[0]);
        names.insert("Adapter12");
        names.insert("Adapter13");
        while(!names.empty())
        {
            vector<RemoteObjectAdapterPrxPtr> adpts = adapters;

            TestIntfPrxPtr test1 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test2 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test3 = createTestIntfPrx(adpts);

            test(test1->ice_getConnection() == test2->ice_getConnection());
            test(test2->ice_getConnection() == test3->ice_getConnection());

            names.erase(test1->getAdapterName());
            test1->ice_getConnection()->close(false);
        }

        //
        // Deactivate an adapter and ensure that we can still
        // establish the connection to the remaining adapter.
        //
        com->deactivateObjectAdapter(adapters[2]);
        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test(test->getAdapterName() == "Adapter12");

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing binding with multiple random endpoints... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("AdapterRandom11", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterRandom12", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterRandom13", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterRandom14", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterRandom15", "default"));

#ifdef _WIN32
        int count = 60;
#else
        int count = 20;
#endif
        int adapterCount = static_cast<int>(adapters.size());
        while(--count > 0)
        {
#ifdef _WIN32
            if(count == 10)
            {
                com->deactivateObjectAdapter(adapters[4]);
                --adapterCount;
            }
            vector<TestIntfPrxPtr> proxies;
            proxies.resize(10);
#else
            if(count < 60 && count % 10 == 0)
            {
                com->deactivateObjectAdapter(adapters[count / 10 - 1]);
                --adapterCount;
            }
            vector<TestIntfPrxPtr> proxies;
            proxies.resize(40);
#endif
            unsigned int i;
            for(i = 0; i < proxies.size(); ++i)
            {
                vector<RemoteObjectAdapterPrxPtr> adpts;
                adpts.resize(IceUtilInternal::random(static_cast<int>(adapters.size())));
                if(adpts.empty())
                {
                    adpts.resize(1);
                }
                for(vector<RemoteObjectAdapterPrxPtr>::iterator p = adpts.begin(); p != adpts.end(); ++p)
                {
                    *p = adapters[IceUtilInternal::random(static_cast<int>(adapters.size()))];
                }
                proxies[i] = createTestIntfPrx(adpts);
            }

            for(i = 0; i < proxies.size(); i++)
            {
#ifdef ICE_CPP11_MAPPING
                proxies[i]->getAdapterName_async();
#else
                proxies[i]->begin_getAdapterName();
#endif
            }
            for(i = 0; i < proxies.size(); i++)
            {
                try
                {
                    proxies[i]->ice_ping();
                }
                catch(const Ice::LocalException&)
                {
                }
            }
            set<Ice::ConnectionPtr> connections;
            for(i = 0; i < proxies.size(); i++)
            {
                if(proxies[i]->ice_getCachedConnection())
                {
                    connections.insert(proxies[i]->ice_getCachedConnection());
                }
            }
            test(static_cast<int>(connections.size()) <= adapterCount);

            for(vector<RemoteObjectAdapterPrxPtr>::const_iterator q = adapters.begin(); q != adapters.end(); ++q)
            {
                try
                {
                    (*q)->getTestIntf()->ice_getConnection()->close(false);
                }
                catch(const Ice::LocalException&)
                {
                    // Expected if adapter is down.
                }
            }
        }
    }
    cout << "ok" << endl;

    cout << "testing binding with multiple endpoints and AMI... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("AdapterAMI11", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI12", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI13", "default"));

        //
        // Ensure that when a connection is opened it's reused for new
        // proxies and that all endpoints are eventually tried.
        //
        set<string> names;
        names.insert("AdapterAMI11");
        names.insert("AdapterAMI12");
        names.insert("AdapterAMI13");
        while(!names.empty())
        {
            vector<RemoteObjectAdapterPrxPtr> adpts = adapters;

            TestIntfPrxPtr test1 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test2 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test3 = createTestIntfPrx(adpts);

            test(test1->ice_getConnection() == test2->ice_getConnection());
            test(test2->ice_getConnection() == test3->ice_getConnection());

            names.erase(getAdapterNameWithAMI(test1));
            test1->ice_getConnection()->close(false);
        }

        //
        // Ensure that the proxy correctly caches the connection (we
        // always send the request over the same connection.)
        //
        {
            for(vector<RemoteObjectAdapterPrxPtr>::const_iterator p = adapters.begin(); p != adapters.end(); ++p)
            {
                (*p)->getTestIntf()->ice_ping();
            }

            TestIntfPrxPtr test = createTestIntfPrx(adapters);
            string name = getAdapterNameWithAMI(test);
            const int nRetry = 10;
            int i;
            for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == name; i++);
            test(i == nRetry);

            for(vector<RemoteObjectAdapterPrxPtr>::const_iterator q = adapters.begin(); q != adapters.end(); ++q)
            {
                (*q)->getTestIntf()->ice_getConnection()->close(false);
            }
        }

        //
        // Deactivate an adapter and ensure that we can still
        // establish the connection to the remaining adapters.
        //
        com->deactivateObjectAdapter(adapters[0]);
        names.insert("AdapterAMI12");
        names.insert("AdapterAMI13");
        while(!names.empty())
        {
            vector<RemoteObjectAdapterPrxPtr> adpts = adapters;

            TestIntfPrxPtr test1 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test2 = createTestIntfPrx(adpts);
            random_shuffle(adpts.begin(), adpts.end(), rng);
            TestIntfPrxPtr test3 = createTestIntfPrx(adpts);

            test(test1->ice_getConnection() == test2->ice_getConnection());
            test(test2->ice_getConnection() == test3->ice_getConnection());

            names.erase(test1->getAdapterName());
            test1->ice_getConnection()->close(false);
        }

        //
        // Deactivate an adapter and ensure that we can still
        // establish the connection to the remaining adapter.
        //
        com->deactivateObjectAdapter(adapters[2]);
        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test(test->getAdapterName() == "AdapterAMI12");

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing random endpoint selection... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter21", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter22", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter23", "default"));

        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test(test->ice_getEndpointSelection() == Ice::Random);

        set<string> names;
        names.insert("Adapter21");
        names.insert("Adapter22");
        names.insert("Adapter23");
        while(!names.empty())
        {
            names.erase(test->getAdapterName());
            test->ice_getConnection()->close(false);
        }

        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_endpointSelection(Ice::Random));
        test(test->ice_getEndpointSelection() == Ice::Random);

        names.insert("Adapter21");
        names.insert("Adapter22");
        names.insert("Adapter23");
        while(!names.empty())
        {
            names.erase(test->getAdapterName());
            test->ice_getConnection()->close(false);
        }

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing ordered endpoint selection... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter31", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter32", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter33", "default"));

        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_endpointSelection(Ice::Ordered));
        test(test->ice_getEndpointSelection() == Ice::Ordered);
        const int nRetry = 5;
        int i;

        //
        // Ensure that endpoints are tried in order by deactiving the adapters
        // one after the other.
        //
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter31"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter31"; i++);
        }
#endif
        test(i == nRetry);
        com->deactivateObjectAdapter(adapters[0]);
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter32"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter32"; i++);
        }
#endif
        test(i == nRetry);
        com->deactivateObjectAdapter(adapters[1]);
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter33"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter33"; i++);
        }
#endif
        test(i == nRetry);
        com->deactivateObjectAdapter(adapters[2]);

        try
        {
            test->getAdapterName();
        }
        catch(const Ice::ConnectFailedException&)
        {
        }

        Ice::EndpointSeq endpoints = test->ice_getEndpoints();

        adapters.clear();

        //
        // Now, re-activate the adapters with the same endpoints in the opposite
        // order.
        //
        adapters.push_back(com->createObjectAdapter("Adapter36", endpoints[2]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter36"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter36"; i++);
        }
#endif
        test(i == nRetry);
        test->ice_getConnection()->close(false);
        adapters.push_back(com->createObjectAdapter("Adapter35", endpoints[1]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter35"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter35"; i++);
        }
#endif
        test(i == nRetry);
        test->ice_getConnection()->close(false);
        adapters.push_back(com->createObjectAdapter("Adapter34", endpoints[0]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter34"; i++);
#if TARGET_OS_IPHONE > 0
        if(i != nRetry)
        {
            test->ice_getConnection()->close(false);
            for(i = 0; i < nRetry && test->getAdapterName() == "Adapter34"; i++);
        }
#endif
        test(i == nRetry);

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing per request binding with single endpoint... " << flush;
    {
        RemoteObjectAdapterPrxPtr adapter = com->createObjectAdapter("Adapter41", "default");

        TestIntfPrxPtr test1 = ICE_UNCHECKED_CAST(TestIntfPrx, adapter->getTestIntf()->ice_connectionCached(false));
        TestIntfPrxPtr test2 = ICE_UNCHECKED_CAST(TestIntfPrx, adapter->getTestIntf()->ice_connectionCached(false));
        test(!test1->ice_isConnectionCached());
        test(!test2->ice_isConnectionCached());
        test(test1->ice_getConnection() == test2->ice_getConnection());

        test1->ice_ping();

        com->deactivateObjectAdapter(adapter);

        TestIntfPrxPtr test3 = ICE_UNCHECKED_CAST(TestIntfPrx, test1);
        try
        {
            test(test3->ice_getConnection() == test1->ice_getConnection());
            test(false);
        }
        catch(const Ice::ConnectFailedException&)
        {
        }
    }
    cout << "ok" << endl;

    cout << "testing per request binding with multiple endpoints... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter51", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter52", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter53", "default"));

        TestIntfPrxPtr test = ICE_UNCHECKED_CAST(TestIntfPrx, createTestIntfPrx(adapters)->ice_connectionCached(false));
        test(!test->ice_isConnectionCached());

        set<string> names;
        names.insert("Adapter51");
        names.insert("Adapter52");
        names.insert("Adapter53");
        while(!names.empty())
        {
            names.erase(test->getAdapterName());
        }

        com->deactivateObjectAdapter(adapters[0]);

        names.insert("Adapter52");
        names.insert("Adapter53");
        while(!names.empty())
        {
            names.erase(test->getAdapterName());
        }

        com->deactivateObjectAdapter(adapters[2]);

        test(test->getAdapterName() == "Adapter52");

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing per request binding with multiple endpoints and AMI... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("AdapterAMI51", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI52", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI53", "default"));

        TestIntfPrxPtr test = ICE_UNCHECKED_CAST(TestIntfPrx, createTestIntfPrx(adapters)->ice_connectionCached(false));
        test(!test->ice_isConnectionCached());

        set<string> names;
        names.insert("AdapterAMI51");
        names.insert("AdapterAMI52");
        names.insert("AdapterAMI53");
        while(!names.empty())
        {
            names.erase(getAdapterNameWithAMI(test));
        }

        com->deactivateObjectAdapter(adapters[0]);

        names.insert("AdapterAMI52");
        names.insert("AdapterAMI53");
        while(!names.empty())
        {
            names.erase(getAdapterNameWithAMI(test));
        }

        com->deactivateObjectAdapter(adapters[2]);

        test(test->getAdapterName() == "AdapterAMI52");

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing per request binding and ordered endpoint selection... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter61", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter62", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter63", "default"));

        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_endpointSelection(Ice::Ordered));
        test(test->ice_getEndpointSelection() == Ice::Ordered);
        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_connectionCached(false));
        test(!test->ice_isConnectionCached());
        const int nRetry = 5;
        int i;

        //
        // Ensure that endpoints are tried in order by deactiving the adapters
        // one after the other.
        //
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter61"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[0]);
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter62"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[1]);
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter63"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[2]);

        try
        {
            test->getAdapterName();
        }
        catch(const Ice::ConnectFailedException&)
        {
        }

        Ice::EndpointSeq endpoints = test->ice_getEndpoints();

        adapters.clear();

        //
        // Now, re-activate the adapters with the same endpoints in the opposite
        // order.
        //
        adapters.push_back(com->createObjectAdapter("Adapter66", endpoints[2]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter66"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        adapters.push_back(com->createObjectAdapter("Adapter65", endpoints[1]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter65"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        adapters.push_back(com->createObjectAdapter("Adapter64", endpoints[0]->toString()));
        for(i = 0; i < nRetry && test->getAdapterName() == "Adapter64"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing per request binding and ordered endpoint selection and AMI... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("AdapterAMI61", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI62", "default"));
        adapters.push_back(com->createObjectAdapter("AdapterAMI63", "default"));

        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_endpointSelection(Ice::Ordered));
        test(test->ice_getEndpointSelection() == Ice::Ordered);
        test = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_connectionCached(false));
        test(!test->ice_isConnectionCached());
        const int nRetry = 5;
        int i;

        //
        // Ensure that endpoints are tried in order by deactiving the adapters
        // one after the other.
        //
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI61"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[0]);
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI62"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[1]);
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI63"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        com->deactivateObjectAdapter(adapters[2]);

        try
        {
            test->getAdapterName();
        }
        catch(const Ice::ConnectFailedException&)
        {
        }

        Ice::EndpointSeq endpoints = test->ice_getEndpoints();

        adapters.clear();

        //
        // Now, re-activate the adapters with the same endpoints in the opposite
        // order.
        //
        adapters.push_back(com->createObjectAdapter("AdapterAMI66", endpoints[2]->toString()));
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI66"; i++);
#if TARGET_OS_IPHONE > 0
        test(i >= nRetry - 1); // WORKAROUND: for connection establishment hang.
#else
        test(i == nRetry);
#endif
        adapters.push_back(com->createObjectAdapter("AdapterAMI65", endpoints[1]->toString()));
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI65"; i++);
        test(i == nRetry);
        adapters.push_back(com->createObjectAdapter("AdapterAMI64", endpoints[0]->toString()));
        for(i = 0; i < nRetry && getAdapterNameWithAMI(test) == "AdapterAMI64"; i++);
        test(i == nRetry);

        deactivate(com, adapters);
    }
    cout << "ok" << endl;

    cout << "testing endpoint mode filtering... " << flush;
    {
        vector<RemoteObjectAdapterPrxPtr> adapters;
        adapters.push_back(com->createObjectAdapter("Adapter71", "default"));
        adapters.push_back(com->createObjectAdapter("Adapter72", "udp"));

        TestIntfPrxPtr test = createTestIntfPrx(adapters);
        test(test->getAdapterName() == "Adapter71");

        TestIntfPrxPtr testUDP = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_datagram());
        test(test->ice_getConnection() != testUDP->ice_getConnection());
        try
        {
            testUDP->getAdapterName();
        }
        catch(const Ice::TwowayOnlyException&)
        {
        }
        catch(const IceUtil::IllegalArgumentException&)
        {
        }
    }
    cout << "ok" << endl;

    if(!communicator->getProperties()->getProperty("Ice.Plugin.IceSSL").empty() &&
            communicator->getProperties()->getProperty("Ice.Default.Protocol") == "ssl")
    {
        cout << "testing unsecure vs. secure endpoints... " << flush;
        {
            vector<RemoteObjectAdapterPrxPtr> adapters;
            adapters.push_back(com->createObjectAdapter("Adapter81", "ssl"));
            adapters.push_back(com->createObjectAdapter("Adapter82", "tcp"));

            TestIntfPrxPtr test = createTestIntfPrx(adapters);
            int i;
            for(i = 0; i < 5; i++)
            {
                test(test->getAdapterName() == "Adapter82");
                test->ice_getConnection()->close(false);
            }

            TestIntfPrxPtr testSecure = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_secure(true));
            test(testSecure->ice_isSecure());
            testSecure = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_secure(false));
            test(!testSecure->ice_isSecure());
            testSecure = ICE_UNCHECKED_CAST(TestIntfPrx, test->ice_secure(true));
            test(testSecure->ice_isSecure());
            test(test->ice_getConnection() != testSecure->ice_getConnection());

            com->deactivateObjectAdapter(adapters[1]);

            for(i = 0; i < 5; i++)
            {
                test(test->getAdapterName() == "Adapter81");
                test->ice_getConnection()->close(false);
            }

            com->createObjectAdapter("Adapter83", (test->ice_getEndpoints()[1])->toString()); // Reactive tcp OA.

            for(i = 0; i < 5; i++)
            {
                test(test->getAdapterName() == "Adapter83");
                test->ice_getConnection()->close(false);
            }

            com->deactivateObjectAdapter(adapters[0]);
            try
            {
                testSecure->ice_ping();
                test(false);
            }
            catch(const Ice::ConnectFailedException&)
            {
            }

            deactivate(com, adapters);
        }
        cout << "ok" << endl;
    }

    {
        cout << "testing ipv4 & ipv6 connections... " << flush;

        Ice::PropertiesPtr ipv4 = Ice::createProperties();
        ipv4->setProperty("Ice.IPv4", "1");
        ipv4->setProperty("Ice.IPv6", "0");
        ipv4->setProperty("Adapter.Endpoints", "tcp -h localhost");

        Ice::PropertiesPtr ipv6 = Ice::createProperties();
        ipv6->setProperty("Ice.IPv4", "0");
        ipv6->setProperty("Ice.IPv6", "1");
        ipv6->setProperty("Adapter.Endpoints", "tcp -h localhost");

        Ice::PropertiesPtr bothPreferIPv4 = Ice::createProperties();
        bothPreferIPv4->setProperty("Ice.IPv4", "1");
        bothPreferIPv4->setProperty("Ice.IPv6", "1");
        bothPreferIPv4->setProperty("Ice.PreferIPv6Address", "0");
        bothPreferIPv4->setProperty("Adapter.Endpoints", "tcp -h localhost");

        Ice::PropertiesPtr bothPreferIPv6 = Ice::createProperties();
        bothPreferIPv6->setProperty("Ice.IPv4", "1");
        bothPreferIPv6->setProperty("Ice.IPv6", "1");
        bothPreferIPv6->setProperty("Ice.PreferIPv6Address", "1");
        bothPreferIPv6->setProperty("Adapter.Endpoints", "tcp -h localhost");

        vector<Ice::PropertiesPtr> clientProps;
        clientProps.push_back(ipv4);
        clientProps.push_back(ipv6);
        clientProps.push_back(bothPreferIPv4);
        clientProps.push_back(bothPreferIPv6);

        Ice::PropertiesPtr anyipv4 = ipv4->clone();
        anyipv4->setProperty("Adapter.Endpoints", "tcp -p 12012");
        anyipv4->setProperty("Adapter.PublishedEndpoints", "tcp -h 127.0.0.1 -p 12012");

        Ice::PropertiesPtr anyipv6 = ipv6->clone();
        anyipv6->setProperty("Adapter.Endpoints", "tcp -p 12012");
        anyipv6->setProperty("Adapter.PublishedEndpoints", "tcp -h \"::1\" -p 12012");

        Ice::PropertiesPtr anyboth = Ice::createProperties();
        anyboth->setProperty("Ice.IPv4", "1");
        anyboth->setProperty("Ice.IPv6", "1");
        anyboth->setProperty("Adapter.Endpoints", "tcp -p 12012");
        anyboth->setProperty("Adapter.PublishedEndpoints", "tcp -h \"::1\" -p 12012:tcp -h 127.0.0.1 -p 12012");

        Ice::PropertiesPtr localipv4 = ipv4->clone();
        localipv4->setProperty("Adapter.Endpoints", "tcp -h 127.0.0.1");

        Ice::PropertiesPtr localipv6 = ipv6->clone();
        localipv6->setProperty("Adapter.Endpoints", "tcp -h \"::1\"");

        vector<Ice::PropertiesPtr> serverProps = clientProps;
        serverProps.push_back(anyipv4);
        serverProps.push_back(anyipv6);
        serverProps.push_back(anyboth);
        serverProps.push_back(localipv4);
        serverProps.push_back(localipv6);

#if defined(_WIN32) && !defined(ICE_OS_WINRT)
        OSVERSIONINFO ver;
        ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
#  if defined(_MSC_VER) && _MSC_VER >= 1800
#    pragma warning (disable : 4996)
#  endif
        GetVersionEx(&ver);
#  if defined(_MSC_VER) && _MSC_VER >= 1800
#    pragma warning (default : 4996)
#  endif
        const bool dualStack = ver.dwMajorVersion >= 6; // Windows XP IPv6 doesn't support dual-stack
#else
        const bool dualStack = true;
#endif

        bool ipv6NotSupported = false;
        for(vector<Ice::PropertiesPtr>::const_iterator p = serverProps.begin(); p != serverProps.end(); ++p)
        {
            Ice::InitializationData serverInitData;
            serverInitData.properties = *p;
            Ice::CommunicatorPtr serverCommunicator = Ice::initialize(serverInitData);
            Ice::ObjectAdapterPtr oa;
            try
            {
                oa = serverCommunicator->createObjectAdapter("Adapter");
                oa->activate();
            }
            catch(const Ice::DNSException&)
            {
                serverCommunicator->destroy();
                continue; // IP version not supported.
            }
            catch(const Ice::SocketException&)
            {
                if(*p == ipv6)
                {
                    ipv6NotSupported = true;
                }
                serverCommunicator->destroy();
                continue; // IP version not supported.
            }

            // Ensure the published endpoints are actually valid. On
            // Fedora, binding to "localhost" with IPv6 only works but
            // resolving localhost don't return the IPv6 adress.
            Ice::ObjectPrxPtr prx = oa->createProxy(serverCommunicator->stringToIdentity("dummy"));
            try
            {
                prx->ice_collocationOptimized(false)->ice_ping();
            }
            catch(const Ice::LocalException&)
            {
                serverCommunicator->destroy();
                continue; // IP version not supported.
            }

            string strPrx = prx->ice_toString();
            for(vector<Ice::PropertiesPtr>::const_iterator q = clientProps.begin(); q != clientProps.end(); ++q)
            {
                Ice::InitializationData clientInitData;
                clientInitData.properties = *q;
                Ice::CommunicatorHolder clientCommunicator = Ice::initialize(clientInitData);
                Ice::ObjectPrxPtr prx = clientCommunicator->stringToProxy(strPrx);
                try
                {
                    prx->ice_ping();
                    test(false);
                }
                catch(const Ice::ObjectNotExistException&)
                {
                    // Expected, no object registered.
                }
                catch(const Ice::DNSException&)
                {
                    // Expected if no IPv4 or IPv6 address is
                    // associated to localhost or if trying to connect
                    // to an any endpoint with the wrong IP version,
                    // e.g.: resolving an IPv4 address when only IPv6
                    // is enabled fails with a DNS exception.
                }
                catch(const Ice::SocketException&)
                {
                    test((*p == ipv4 && *q == ipv6) || (*p == ipv6 && *q == ipv4) ||
                         (*p == bothPreferIPv4 && *q == ipv6) || (*p == bothPreferIPv6 && *q == ipv4) ||
                         (*p == bothPreferIPv6 && *q == ipv6 && ipv6NotSupported) ||
                         (*p == anyipv4 && *q == ipv6) || (*p == anyipv6 && *q == ipv4) ||
                         (*p == anyboth && *q == ipv4 && !dualStack) ||
                         (*p == localipv4 && *q == ipv6) || (*p == localipv6 && *q == ipv4) ||
                         (*p == ipv6 && *q == bothPreferIPv4) || (*p == ipv6 && *q == bothPreferIPv6) ||
                         (*p == bothPreferIPv6 && *q == ipv6));
                }
            }
            serverCommunicator->destroy();
        }

        cout << "ok" << endl;
    }

    com->shutdown();
}
Example #20
0
GPrxPtr
allTests(const Ice::CommunicatorPtr& communicator)
{
#ifdef ICE_OS_UWP
    bool uwp = true;
#else
    bool uwp = false;
#endif

    cout << "testing Ice.Admin.Facets property... " << flush;
    test(communicator->getProperties()->getPropertyAsList("Ice.Admin.Facets").empty());
    communicator->getProperties()->setProperty("Ice.Admin.Facets", "foobar");
    Ice::StringSeq facetFilter = communicator->getProperties()->getPropertyAsList("Ice.Admin.Facets");
    test(facetFilter.size() == 1 && facetFilter[0] == "foobar");
    communicator->getProperties()->setProperty("Ice.Admin.Facets", "foo\\'bar");
    facetFilter = communicator->getProperties()->getPropertyAsList("Ice.Admin.Facets");
    test(facetFilter.size() == 1 && facetFilter[0] == "foo'bar");
    communicator->getProperties()->setProperty("Ice.Admin.Facets", "'foo bar' toto 'titi'");
    facetFilter = communicator->getProperties()->getPropertyAsList("Ice.Admin.Facets");
    test(facetFilter.size() == 3 && facetFilter[0] == "foo bar" && facetFilter[1] == "toto" &&
         facetFilter[2] == "titi");
    communicator->getProperties()->setProperty("Ice.Admin.Facets", "'foo bar\\' toto' 'titi'");
    facetFilter = communicator->getProperties()->getPropertyAsList("Ice.Admin.Facets");
    test(facetFilter.size() == 2 && facetFilter[0] == "foo bar' toto" && facetFilter[1] == "titi");
    // communicator->getProperties()->setProperty("Ice.Admin.Facets", "'foo bar' 'toto titi");
    // facetFilter = communicator->getProperties()->getPropertyAsList("Ice.Admin.Facets");
    // test(facetFilter.size() == 0);
    communicator->getProperties()->setProperty("Ice.Admin.Facets", "");
    cout << "ok" << endl;

    cout << "testing facet registration exceptions... " << flush;
    string localOAEndpoint;
    {
        ostringstream ostr;
        if(communicator->getProperties()->getProperty("Ice.Default.Protocol") == "bt")
        {
            ostr << "default -a *";
        }
        else
        {
            ostr << "default -h *";
        }
        localOAEndpoint = ostr.str();
    }
    communicator->getProperties()->setProperty("FacetExceptionTestAdapter.Endpoints", localOAEndpoint);
    if(uwp || (communicator->getProperties()->getProperty("Ice.Default.Protocol") != "ssl" &&
                 communicator->getProperties()->getProperty("Ice.Default.Protocol") != "wss"))
    {
        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("FacetExceptionTestAdapter");
        Ice::ObjectPtr obj = ICE_MAKE_SHARED(EmptyI);
        adapter->add(obj, Ice::stringToIdentity("d"));
        adapter->addFacet(obj, Ice::stringToIdentity("d"), "facetABCD");
        try
        {
            adapter->addFacet(obj, Ice::stringToIdentity("d"), "facetABCD");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException&)
        {
        }
        adapter->removeFacet(Ice::stringToIdentity("d"), "facetABCD");
        try
        {
            adapter->removeFacet(Ice::stringToIdentity("d"), "facetABCD");
            test(false);
        }
        catch(const Ice::NotRegisteredException&)
        {
        }
        cout << "ok" << endl;

        cout << "testing removeAllFacets... " << flush;
        Ice::ObjectPtr obj1 = ICE_MAKE_SHARED(EmptyI);
        Ice::ObjectPtr obj2 = ICE_MAKE_SHARED(EmptyI);
        adapter->addFacet(obj1, Ice::stringToIdentity("id1"), "f1");
        adapter->addFacet(obj2, Ice::stringToIdentity("id1"), "f2");
        Ice::ObjectPtr obj3 = ICE_MAKE_SHARED(EmptyI);
        adapter->addFacet(obj1, Ice::stringToIdentity("id2"), "f1");
        adapter->addFacet(obj2, Ice::stringToIdentity("id2"), "f2");
        adapter->addFacet(obj3, Ice::stringToIdentity("id2"), "");
        Ice::FacetMap fm = adapter->removeAllFacets(Ice::stringToIdentity("id1"));
        test(fm.size() == 2);
        test(fm["f1"] == obj1);
        test(fm["f2"] == obj2);
        try
        {
            adapter->removeAllFacets(Ice::stringToIdentity("id1"));
            test(false);
        }
        catch(const Ice::NotRegisteredException&)
        {
        }
        fm = adapter->removeAllFacets(Ice::stringToIdentity("id2"));
        test(fm.size() == 3);
        test(fm["f1"] == obj1);
        test(fm["f2"] == obj2);
        test(fm[""] == obj3);
        cout << "ok" << endl;

        adapter->deactivate();
    }

    cout << "testing stringToProxy... " << flush;
    string ref = "d:" + getTestEndpoint(communicator, 0);
    Ice::ObjectPrxPtr db = communicator->stringToProxy(ref);
    test(db);
    cout << "ok" << endl;

    cout << "testing unchecked cast... " << flush;
    Ice::ObjectPrxPtr prx = ICE_UNCHECKED_CAST(Ice::ObjectPrx, db);
    test(prx->ice_getFacet().empty());
#ifdef ICE_CPP11_MAPPING
    prx = Ice::uncheckedCast<Ice::ObjectPrx>(db, "facetABCD");
#else
    prx = Ice::ObjectPrx::uncheckedCast(db, "facetABCD");
#endif
    test(prx->ice_getFacet() == "facetABCD");
    Ice::ObjectPrxPtr prx2 = ICE_UNCHECKED_CAST(Ice::ObjectPrx, prx);
    test(prx2->ice_getFacet() == "facetABCD");

#ifdef ICE_CPP11_MAPPING
    shared_ptr<Ice::ObjectPrx> prx3 = Ice::uncheckedCast<Ice::ObjectPrx>(prx, "");
#else
    Ice::ObjectPrx prx3 = Ice::ObjectPrx::uncheckedCast(prx, "");
#endif
    test(prx3->ice_getFacet().empty());
    DPrxPtr d = ICE_UNCHECKED_CAST(Test::DPrx, db);
    test(d->ice_getFacet().empty());
#ifdef ICE_CPP11_MAPPING
    shared_ptr<DPrx> df = Ice::uncheckedCast<Test::DPrx>(db, "facetABCD");
#else
    DPrx df = Test::DPrx::uncheckedCast(db, "facetABCD");
#endif
    test(df->ice_getFacet() == "facetABCD");
    DPrxPtr df2 = ICE_UNCHECKED_CAST(Test::DPrx, df);
    test(df2->ice_getFacet() == "facetABCD");
#ifdef ICE_CPP11_MAPPING
    shared_ptr<DPrx> df3 = Ice::uncheckedCast<Test::DPrx>(df, "");
#else
    DPrx df3 = Test::DPrx::uncheckedCast(df, "");
#endif
    test(df3->ice_getFacet().empty());
    cout << "ok" << endl;

    cout << "testing checked cast... " << flush;
    prx = ICE_CHECKED_CAST(Ice::ObjectPrx, db);
    test(prx->ice_getFacet().empty());
#ifdef ICE_CPP11_MAPPING
    prx = Ice::checkedCast<Ice::ObjectPrx>(db, "facetABCD");
#else
    prx = Ice::ObjectPrx::checkedCast(db, "facetABCD");
#endif
    test(prx->ice_getFacet() == "facetABCD");
    prx2 = ICE_CHECKED_CAST(Ice::ObjectPrx, prx);
    test(prx2->ice_getFacet() == "facetABCD");
#ifdef ICE_CPP11_MAPPING
    prx3 = Ice::checkedCast<Ice::ObjectPrx>(prx, "");
#else
    prx3 = Ice::ObjectPrx::checkedCast(prx, "");
#endif
    test(prx3->ice_getFacet().empty());
    d = ICE_CHECKED_CAST(Test::DPrx, db);
    test(d->ice_getFacet().empty());
#ifdef ICE_CPP11_MAPPING
    df = Ice::checkedCast<Test::DPrx>(db, "facetABCD");
#else
    df = Test::DPrx::checkedCast(db, "facetABCD");
#endif
    test(df->ice_getFacet() == "facetABCD");
    df2 = ICE_CHECKED_CAST(Test::DPrx, df);
    test(df2->ice_getFacet() == "facetABCD");
#ifdef ICE_CPP11_MAPPING
    df3 = Ice::checkedCast<Test::DPrx>(df, "");
#else
    df3 = Test::DPrx::checkedCast(df, "");
#endif
    test(df3->ice_getFacet().empty());
    cout << "ok" << endl;

    cout << "testing non-facets A, B, C, and D... " << flush;
    d = ICE_CHECKED_CAST(DPrx, db);
    test(d);
#ifdef ICE_CPP11_MAPPING
    test(Ice::targetEqualTo(d, db));
#else
    test(d == db);
#endif
    test(d->callA() == "A");
    test(d->callB() == "B");
    test(d->callC() == "C");
    test(d->callD() == "D");
    cout << "ok" << endl;

    cout << "testing facets A, B, C, and D... " << flush;
#ifdef ICE_CPP11_MAPPING
    df = Ice::checkedCast<DPrx>(d, "facetABCD");
#else
    df = DPrx::checkedCast(d, "facetABCD");
#endif
    test(df);
    test(df->callA() == "A");
    test(df->callB() == "B");
    test(df->callC() == "C");
    test(df->callD() == "D");
    cout << "ok" << endl;

    cout << "testing facets E and F... " << flush;
#ifdef ICE_CPP11_MAPPING
    auto ff = Ice::checkedCast<FPrx>(d, "facetEF");
#else
    FPrx ff = FPrx::checkedCast(d, "facetEF");
#endif
    test(ff);
    test(ff->callE() == "E");
    test(ff->callF() == "F");
    cout << "ok" << endl;

    cout << "testing facet G... " << flush;
#ifdef ICE_CPP11_MAPPING
    auto gf = Ice::checkedCast<GPrx>(ff, "facetGH");
#else
    GPrx gf = GPrx::checkedCast(ff, "facetGH");
#endif
    test(gf);
    test(gf->callG() == "G");
    cout << "ok" << endl;

    cout << "testing whether casting preserves the facet... " << flush;
    HPrxPtr hf = ICE_CHECKED_CAST(HPrx, gf);
    test(hf);
    test(hf->callG() == "G");
    test(hf->callH() == "H");
    cout << "ok" << endl;

    return gf;
}
Example #21
0
void
ServerLocatorRegistry::addObject(const Ice::ObjectPrxPtr& object)
{
    _objects[object->ice_getIdentity()] = object;
}