Ejemplo n.º 1
0
RemoteObjectAdapterPrx
RemoteCommunicatorI::createObjectAdapter(int timeout, int close, int heartbeat, const Current& current)
{
    Ice::CommunicatorPtr com = current.adapter->getCommunicator();
    Ice::PropertiesPtr properties = com->getProperties();
    string protocol = properties->getPropertyWithDefault("Ice.Default.Protocol", "tcp");
    string host = properties->getPropertyWithDefault("Ice.Default.Host", "127.0.0.1");

    string name = IceUtil::generateUUID();
    if(timeout >= 0)
    {
        properties->setProperty(name + ".ACM.Timeout", toString(timeout));
    }
    if(close >= 0)
    {
        properties->setProperty(name + ".ACM.Close", toString(close));
    }
    if(heartbeat >= 0)
    {
        properties->setProperty(name + ".ACM.Heartbeat", toString(heartbeat));
    }
    properties->setProperty(name + ".ThreadPool.Size", "2");
    ObjectAdapterPtr adapter = com->createObjectAdapterWithEndpoints(name, protocol + " -h \"" + host + "\"");
    return RemoteObjectAdapterPrx::uncheckedCast(current.adapter->addWithUUID(new RemoteObjectAdapterI(adapter)));
}
Ejemplo n.º 2
0
int main(int argc, char* argv[])
{
    int status = 0;
    Ice::CommunicatorPtr ic;
    try {
        ic = Ice::initialize(argc, argv);
        Ice::ObjectAdapterPtr adapter
		= ic->createObjectAdapterWithEndpoints("lcdshow", "default -p 10000");
	ram::tortuga::SensorBoardI* board = new ram::tortuga::SensorBoardI();

	// Check if the board initialized correctly
	if (board->isInitialized()) {
	    Ice::ObjectPtr object = board;
	    adapter->add(object, ic->stringToIdentity("SensorBoard"));
	    adapter->activate();
	    ic->waitForShutdown();
	}
	delete board;
    } catch (const Ice::Exception& e) {
	std::cerr << e << std::endl;
        status = 1;
    } catch (const char* msg) {
	std::cerr << msg << std::endl;
        status = 1;
    }
    if (ic) {
        try {
            ic->destroy();
        } catch (const Ice::Exception& e) {
	    std::cerr << e << std::endl;
            status = 1;
        }
    }
    return status;
}
Ejemplo n.º 3
0
void ConnectionPoolManager::initialize() {
	IceUtil::RWRecMutex::WLock lock(_mutex);
	if (_observer || _descriptor) {
		return;
	}
	
  Ice::CommunicatorPtr ic = xiaonei_grid();
	ostringstream adapterEndpoints;
  adapterEndpoints << "tcp -h " << ::base::Network::local_ip();
	_adapter = ic->createObjectAdapterWithEndpoints("DbCxxPool",
			adapterEndpoints.str());
	_adapter->activate();
	Ice::PropertiesPtr props = ic->getProperties();

	string identity = props->getPropertyWithDefault(
			"Service.DbDescriptor.Identity", "DCS@DbDescriptor");

	if (identity != "") {
		_descriptor = DbDescriptorPrx::uncheckedCast(
				ic->stringToProxy(identity));
		LOG(INFO) << "ConnectionPoolManager::DbDescriptor.Proxy -> "
				<< _descriptor;
	}
	_observer = DbObserverPrx::uncheckedCast(_adapter->addWithUUID(this));
	LOG(INFO) << "ConnectionPoolManager::DbObserver.Proxy -> " << _observer;

	// MyUtil::TaskManager::instance().schedule(new VerifyTimerTask(10 * 60 ));
  ::base::Post(boost::bind(&ConnectionPoolManager::verify, this), 10 * 60 * 1000, 0);
}
Ejemplo n.º 4
0
RemoteObjectAdapterPrx
RemoteCommunicatorI::createObjectAdapter(const string& name, const string& endpts, const Current& current)
#endif
{
    Ice::CommunicatorPtr com = current.adapter->getCommunicator();
    const string defaultProtocol = com->getProperties()->getProperty("Ice.Default.Protocol");

    string endpoints = endpts;
    if(defaultProtocol != "bt")
    {
        if(endpoints.find("-p") == string::npos)
        {
            // Use a fixed port if none is specified (bug 2896)
            ostringstream os;
            os << endpoints << " -h \""
               << (com->getProperties()->getPropertyWithDefault("Ice.Default.Host", "127.0.0.1"))
               << "\" -p " << _nextPort++;
            endpoints = os.str();
        }
    }
    
    com->getProperties()->setProperty(name + ".ThreadPool.Size", "1");
    ObjectAdapterPtr adapter = com->createObjectAdapterWithEndpoints(name, endpoints);
    return ICE_UNCHECKED_CAST(RemoteObjectAdapterPrx, current.adapter->addWithUUID(ICE_MAKE_SHARED(RemoteObjectAdapterI, adapter)));
}
Ejemplo n.º 5
0
int main(int argc, char* argv[])
{
    int status = 0;
    Ice::CommunicatorPtr ic;
    try
    {
        ic = Ice::initialize(argc, argv);
        Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints(
                "SimplePrinterAdapter", "default -p 10000");
        Ice::ObjectPtr object = new PrinterI;
        adapter->add(object, ic->stringToIdentity("SimplePrinter"));
        adapter->activate();
        ic->waitForShutdown();
    }
    catch (const Ice::Exception& e)
    {
        std::cerr << e << std::endl;
        status = 1;
    }
    if (ic)
    {
        try
        {
            ic->destroy();
        }
        catch (const Ice::Exception& e)
        {
            std::cerr << e << std::endl;
            status = 1;
        }
    }
    return status;
}
Ejemplo n.º 6
0
int
main(int argc, char* argv[])
{
int status = 0;
Ice::InitializationData id;
id.properties = Ice::createProperties(argc, argv);
id.properties->setProperty("Ice.ThreadPool.Server.Size", "50");
id.properties->setProperty("Ice.ThreadPool.Server.SizeMax", "5000");
//    _communicator = Ice::initialize(id);
Ice::CommunicatorPtr ic;
try {
ic = Ice::initialize(id);
Ice::ObjectAdapterPtr adapter
= ic->createObjectAdapterWithEndpoints(
"SimplePrinterAdapter", "default -p 10000");  //默认建立的是tcp 连接
Ice::ObjectPtr object = new PrinterI;
PrinterPrx spPrx = PrinterPrx::uncheckedCast(adapter->add(object, ic->stringToIdentity("SimplePrinter")));
cout << "PrinterPrx:" <<spPrx <<endl;
adapter->activate();
ic->waitForShutdown();
} catch (const Ice::Exception & e) {
cerr << e << endl;
status = 1;
} catch (const char * msg) {
cerr << msg << endl;
status = 1;
}
if (ic)
ic->destroy();
return status;
}
Ejemplo n.º 7
0
Archivo: TestI.cpp Proyecto: zmyer/ice
RemoteObjectAdapterPrx
RemoteCommunicatorI::createObjectAdapter(const string& name, const string& endpts, const Current& current)
#endif
{
    Ice::CommunicatorPtr com = current.adapter->getCommunicator();
    const string defaultProtocol = com->getProperties()->getProperty("Ice.Default.Protocol");
    int retry = 5;
    while(true)
    {
        try
        {
            string endpoints = endpts;
            if(defaultProtocol != "bt")
            {
                if(endpoints.find("-p") == string::npos)
                {
                    endpoints = getTestEndpoint(com, _nextPort++, endpoints);
                }
            }
            com->getProperties()->setProperty(name + ".ThreadPool.Size", "1");
            ObjectAdapterPtr adapter = com->createObjectAdapterWithEndpoints(name, endpoints);
            return ICE_UNCHECKED_CAST(RemoteObjectAdapterPrx,
                                      current.adapter->addWithUUID(ICE_MAKE_SHARED(RemoteObjectAdapterI, adapter)));
        }
        catch(const Ice::SocketException&)
        {
            if(--retry == 0)
            {
                throw;
            }
        }
    }
}
Ejemplo n.º 8
0
int main(int argc, char* argv[])
{
  int status = 0;
  Ice::CommunicatorPtr ic;
  try {
    ic = Ice::initialize(argc, argv);

    if (argc != 4) {
      cerr << "Usage: " << argv[0] << " servername NameService-host local-port\n";
      goto clean_up;
    }

    // Look up the name service.
    ostringstream ns_formatter;
    ns_formatter << "NameService:tcp -h " << argv[2] << " -p 9010";
    Ice::ObjectPrx base =
      ic->stringToProxy(ns_formatter.str().c_str());
    NameServicePrx ns = NameServicePrx::checkedCast(base);
    if (!ns)
      throw "Invalid NameService";

    // Create local chat display object and support infrastructure.
    ostringstream server_formatter;
    server_formatter << "tcp -p " << argv[3];
    Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints(
      "ChatterAdapter", server_formatter.str().c_str());
    Ice::ObjectPtr object = new RoomManager_impl(adapter);
    Ice::ObjectPrx server =
      adapter->add(object, ic->stringToIdentity("RoomManager"));
    adapter->activate();

    // Register object.
    // ns->registerName(argv[1], server);

    ic->waitForShutdown();
  }
  catch (const Ice::Exception& e) {
    cerr << e << endl;
    status = 1;
  }
  catch (const char* msg) {
    cerr << msg << endl;
    status = 1;
  }

 clean_up:
  // We must call ic->destroy() even if an exception is throw above.
  if (ic) {
    try {
      ic->destroy();
    }
    catch (const Ice::Exception& e) {
      cerr << e << endl;
      status = 1;
    }
  }
  return status;
}
Ejemplo n.º 9
0
int main(int argc, char** argv){


	killed=false;
	struct sigaction sigIntHandler;

   sigIntHandler.sa_handler = exitApplication;
   sigemptyset(&sigIntHandler.sa_mask);
   sigIntHandler.sa_flags = 0;

   sigaction(SIGINT, &sigIntHandler, NULL);

	Ice::PropertiesPtr prop;
	std::string componentPrefix("myComponent");

	
	

	try{
			ic = Ice::initialize(argc,argv);
			prop = ic->getProperties();
	}
	catch (const Ice::Exception& ex) {
			std::cerr << ex << std::endl;
			return 1;
	}
	catch (const char* msg) {
			std::cerr <<"Error :" << msg << std::endl;
			return 1;
	}

	std::string Endpoints = prop->getProperty(componentPrefix + ".Endpoints");
	Ice::ObjectAdapterPtr adapter =ic->createObjectAdapterWithEndpoints(componentPrefix, Endpoints);

	// for each interface:

	std::string objPrefix="myInterface";
	std::string Name = "pointcloud1";
	std::cout << "Creating pointcloud1 " << Name << std::endl;
	interface1 = new myClassI();
	adapter->add(interface1, ic->stringToIdentity(Name));

	//starting the adapter
	adapter->activate();
	ic->waitForShutdown();

	if (!killed)
		exitApplication(1);
   
   return 0;

}
Ejemplo n.º 10
0
int main(int argc, char **argv)
{
	Ice::CommunicatorPtr ic;
	int status = 0;
	std::string port("20000");

	if (argc > 1) {
		try {
			std::stoul(argv[1]);
		}
		catch (const std::exception& e) {
			std::cerr << "Invalid port number: " << argv[1] << '\n';
			return 1;
		}

		port = argv[1];
	}

	try {
		ic = Ice::initialize(argc, argv);
		Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("PocketSphinxServerAdapter", "default -p " + port);
		PocketSphinxServer* srv = new PocketSphinxServer;
		std::cout << "init done\n";
		Ice::ObjectPtr object = srv;
		adapter->add(object, ic->stringToIdentity("PocketSphinxServer"));
		adapter->activate();
		ic->waitForShutdown();
	}
	catch (const Ice::Exception& e) {
		std::cerr << e << std::endl;
		status = 1;
	}
	catch (const std::exception& e) {
		std::cerr << e.what() << std::endl;
		status = 1;
	}
	catch (...) {
		status = 1;
	}

	if (ic) {
		try {
			ic->destroy();
		}
		catch (const Ice::Exception& e) {
			std::cerr << e << std::endl;
			status = 1;
		}
	}

	return status;
}
Ejemplo n.º 11
0
int main(int argc, char** argv)
{
    Ice::ObjectPtr viewerPtr;
    //signal(SIGINT,signalHandler);
    Ice::CommunicatorPtr ic;
    try{
        ic = EasyIce::initialize(argc, argv);

        Ice::PropertiesPtr prop = ic->getProperties();
        std::string Endpoints = prop->getProperty("Visualization.Endpoints");

        // Naming Service
        int nsActive = prop->getPropertyAsIntWithDefault("NamingService.Enabled", 0);

        if (nsActive)
        {
            std::string ns_proxy = prop->getProperty("NamingService.Proxy");
            try
            {
                namingService = new jderobot::ns(ic, ns_proxy);
            }
            catch (Ice::ConnectionRefusedException& ex)
            {
                jderobot::Logger::getInstance()->error("Impossible to connect with NameService!");
                exit(-1);
            }
        }

        Ice::ObjectAdapterPtr adapter =ic->createObjectAdapterWithEndpoints("Visualization", Endpoints);
        std::string objPrefix("Visualization.");
        std::string viewerName = prop->getProperty(objPrefix + "Name");
        Ice::ObjectPtr object = new visualization::VisualizationI(objPrefix, ic);

        adapter->add(object, ic->stringToIdentity(viewerName));

        if (namingService)
            namingService->bind(viewerName, Endpoints, object->ice_staticId());


        adapter->activate();
        ic->waitForShutdown();

    }catch (const Ice::Exception& ex) {
        std::cerr << ex<<" 1 " << std::endl;
        exit(-1);
    } catch (const char* msg) {
        std::cerr << msg<< " 2 " << std::endl;
        exit(-1);
    }

}
Ejemplo n.º 12
0
int main(int argc, char* argv[]) {
    int status = 0;
    Ice::CommunicatorPtr ic;
    try {
        ic = Ice::initialize(argc, argv);
        if (argc < 5 || 5 < argc)
            throw "Incorrect arguments\n"
            "Take a look at docs/html/index.html for more info.\n\n";
        int model = atoi(argv[1]);
        int server_id = atoi(argv[2]);
        int num_clients = atoi(argv[3]);
        string host_port(argv[4]);
        cerr << "Attaching DM_Server_Adapter to endpoint "
                << LDAUtil::DM_Server_Names::get_server_endpoint(host_port)
                << endl;
        Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints(
                "DM_Server_Adapter",
                LDAUtil::DM_Server_Names::get_server_endpoint(host_port));

        Server_Helper* helper = NULL;
        if (model == Model::UNIGRAM)
            helper = new Unigram_Model_Server_Helper;
        Ice::ObjectPtr object = new DM_Server(num_clients, *helper);
        cerr << "Adding servant with name "
                << LDAUtil::DM_Server_Names::get_servant_name(server_id)
                << endl;
        adapter->add(object, ic->stringToIdentity(
                LDAUtil::DM_Server_Names::get_servant_name(server_id)));
        adapter->activate();
        ic->waitForShutdown();
        delete helper;
    } catch (const Ice::Exception& e) {
        cerr << e << endl;
        status = 1;
    } catch (const char* msg) {
        cerr << msg << endl;
        status = 1;
    }
    if (ic) {
        try {
            ic->destroy();
        } catch (const Ice::Exception& e) {
            cerr << e << endl;
            status = 1;
        }
    }
    return status;
}
Ejemplo n.º 13
0
RemoteObjectAdapterPrx
RemoteCommunicatorI::createObjectAdapter(const string& name, const string& endpts, const Current& current)
{
    string endpoints = endpts;
    if(endpoints.find("-p") == string::npos)
    {
        // Use a fixed port if none is specified (bug 2896)
        ostringstream os;
        os << endpoints << " -h 127.0.0.1 -p " << _nextPort++;
    }

    Ice::CommunicatorPtr com = current.adapter->getCommunicator();
    com->getProperties()->setProperty(name + ".ThreadPool.Size", "1");
    ObjectAdapterPtr adapter = com->createObjectAdapterWithEndpoints(name, endpoints);
    return RemoteObjectAdapterPrx::uncheckedCast(current.adapter->addWithUUID(new RemoteObjectAdapterI(adapter)));
}
Ejemplo n.º 14
0
int main(int argc, char** argv){
  int status;
  Ice::CommunicatorPtr ic;

  try{
    ic = Ice::initialize(argc,argv);
    std::string topicName = ic->getProperties()->getProperty("Cameraview_icestorm.Camera.TopicName");

	std::cout << "Trying to conect to: " << topicName << std::endl;

    Ice::ObjectPrx obj=ic->propertyToProxy("Cameraview_icestorm.Camera.TopicManager");
    IceStorm::TopicManagerPrx topicManager=IceStorm::TopicManagerPrx::checkedCast(obj);

    std::string objAdapterEndpoint = ic->getProperties()->getProperty("Cameraview_icestorm.Camera.ObjectAdapter");
    Ice::ObjectAdapterPtr adapter=ic->createObjectAdapterWithEndpoints("CameraAdapter",objAdapterEndpoint);

    ImageConsumerI* imageConsumer = new ImageConsumerI;
    Ice::ObjectPrx proxy = adapter->addWithUUID(imageConsumer)->ice_oneway();

    IceStorm::TopicPrx topic;
    try {
        topic = topicManager->retrieve(topicName);
        IceStorm::QoS qos;
        topic->subscribeAndGetPublisher(qos, proxy);
    }
    catch (const IceStorm::NoSuchTopic& ex) {
        std::cerr << ex << std::endl;
    }

    adapter->activate();
    ic->waitForShutdown();

    topic->unsubscribe(proxy);

    if (ic)
    	ic->destroy();
    return status;

  }catch (const Ice::Exception& ex) {
    std::cerr << ex << std::endl;
    status = 1;
  } catch (const char* msg) {
    std::cerr << msg << std::endl;
    status = 1;
  }
}
Ejemplo n.º 15
0
int main(int argc, char* argv[])
{
	int status = 0;
	Ice::CommunicatorPtr ic;
	//status变量含有程序的退出状态,而类型为 Ice::Communicator 的 ic 变量含有 Ice run time 的主句柄.

	try {
		ic = Ice::initialize(argc, argv);
	//initialize 调用返回的是一个智能指针,指向一个 Ice::Communicator 对象,这个指针是 Ice run time 的主句柄

		Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("SimplePrinterAdapter", "default -p 10000");
//创建对象适配器.传入参数"SimplePrinterAdapter"(适配器名字)和"default -p 10000",适配器用缺省协议(TCP/IP)在端口 10000 处侦听到来的请求

		Ice::ObjectPtr object = new PrinterI;
	//服务器端 run time 已经初始化,我们实例化一个 PrinterI 对象,为 Printer 接口创建一个 servant

		adapter->add(object,ic->stringToIdentity("SimplePrinter"));
//调用适配器的add,告诉它有了一个新的servant;传给 add 的参数是我们刚才实例化的 servant,再加上一个标识符.
//"SimplePrinter"串是servant的名字

		adapter->activate();
	//调用适配器的 activate 方法激活适配器.一旦适配器被激活,服务器就会开始处理来自客户的请求
/*
适配器开始是在扣留(holding)状态创建的;这种做法在下面这样的情况下很有用:我们有多个 servant,它们共享同一个适配器,
而在所有 servant实例化之前我们不想处理请求
*/
		ic->waitForShutdown();
// waitForShutdown方法挂起发出调用的线程,直到服务器实现终止为止:或者是通过发出一个调用关闭 run time,或者是对某个信号作出响应


	//第一个处理器捕捉 Ice run time 可能抛出的所有异常
	} catch (const Ice::Exception & e) {
		cerr << e << endl;
		status = 1;
	//第二个处理器捕捉串常量
	} catch (const char * msg) {
		cerr << msg << endl;
		status = 1;
	}

	if (ic)//清理代码调用通信器的 destroy 方法,(前提是通信器进行过初始化)
		ic->destroy();
	//清理调用之所以在 try 块的外部,原因是:不管代码是正常终止,还是由于异常而终止,我们都必须确保 Ice run time 得以执行结束工作 

	return status;
}
Ejemplo n.º 16
0
	int serve_daemon( int argc, char** argv)
	{
		
		Ice::CommunicatorPtr ic;
		
		ic = Ice::initialize(argc,argv);
		Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("Anspypher","default -p 5000");
		Ice::ObjectPtr object = new TransporterI;
		adapter->add(object,ic->stringToIdentity("Anspypherd"));
		adapter->activate();
		ic->waitForShutdown();
		
		if (ic) {
			try {
				ic->destroy();
			}
			catch (const Ice::Exception& e) {
				cerr << e << endl;
			}
		}
		return 0;
	}
Ejemplo n.º 17
0
bool serverI::initStreaming(){

	try {
		cout<<"OK"<<endl;
		string options = "default -p " + port;
		Ice::ObjectAdapterPtr adapter =ic->createObjectAdapterWithEndpoints("serverAdapter",options);
		adapter->add(this, ic->stringToIdentity("server"));
		adapter->activate();
		ic->waitForShutdown();
	} catch (const Ice::Exception& e) {
		cerr << e << endl;
	} catch (const char* msg) {
		cerr << msg << endl;
	}
	if (1) {
	
		try {ic->destroy();} catch (const Ice::Exception& e) {
			cerr << e << endl;
		}
	}

}
Ejemplo n.º 18
0
int main(int argc, char *argv[])
{
    Ice::CommunicatorPtr ic;
    try {
     //-----------------ICE----------------//
        ic = Ice::initialize(argc, argv);

		Ice::PropertiesPtr prop = ic->getProperties();

        std::string Endpoints = prop->getProperty("Laser.Endpoints");
        std::string laserControl_string = "Laser";

		Ice::ObjectAdapterPtr adapter =
            ic->createObjectAdapterWithEndpoints(laserControl_string, Endpoints);
        Ice::ObjectPtr object = new laser::LaserI(prop);
        adapter->add(object, ic->stringToIdentity(laserControl_string));
        adapter->activate();
		std::cout << "laser_server start on " <<Endpoints<<std::endl;
        ic->waitForShutdown();
    } catch (const Ice::Exception& ex) {
        std::cerr << ex << std::endl;
        exit(-1);
    } catch (const char* msg) {
        std::cerr << msg << std::endl;
        exit(-1);
    }

	if (ic) {
        try {
            ic->destroy();
        } catch (const Ice::Exception& e) {
            std::cerr << e << std::endl;
        }
    }


    exit(0);
}
Ejemplo n.º 19
0
void
allTests(const Ice::CommunicatorPtr& communicator, const string& ref)
{
    ServerManagerPrx manager = ServerManagerPrx::checkedCast(communicator->stringToProxy(ref));
    TestLocatorPrx locator = TestLocatorPrx::uncheckedCast(communicator->getDefaultLocator());
    test(manager);

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

    cout << "testing ice_locator and ice_getLocator... " << flush;
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), communicator->getDefaultLocator()));
    Ice::LocatorPrx anotherLocator = Ice::LocatorPrx::uncheckedCast(communicator->stringToProxy("anotherLocator"));
    base = base->ice_locator(anotherLocator);
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), anotherLocator));
    communicator->setDefaultLocator(0);
    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::RouterPrx anotherRouter = Ice::RouterPrx::uncheckedCast(communicator->stringToProxy("anotherRouter"));
    base = base->ice_router(anotherRouter);
    test(Ice::proxyIdentityEqual(base->ice_getRouter(), anotherRouter));
    Ice::RouterPrx router = Ice::RouterPrx::uncheckedCast(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;
    TestIntfPrx obj = TestIntfPrx::checkedCast(base);
    obj = TestIntfPrx::checkedCast(communicator->stringToProxy("test@TestAdapter"));
    obj = TestIntfPrx::checkedCast(communicator->stringToProxy("test   @TestAdapter"));
    obj = TestIntfPrx::checkedCast(communicator->stringToProxy("test@   TestAdapter"));
    test(obj);
    TestIntfPrx obj2 = TestIntfPrx::checkedCast(base2);
    test(obj2);
    TestIntfPrx obj3 = TestIntfPrx::checkedCast(base3);
    test(obj3);
    ServerManagerPrx obj4 = ServerManagerPrx::checkedCast(base4);
    test(obj4);
    TestIntfPrx obj5 = TestIntfPrx::checkedCast(base5);
    test(obj5);
    TestIntfPrx obj6 = TestIntfPrx::checkedCast(base6);
    test(obj6);
    cout << "ok" << endl;

    cout << "testing id@AdapterId indirect proxy... " << flush;
    obj->shutdown();
    manager->startServer();
    try
    {
        obj2 = TestIntfPrx::checkedCast(base2);
        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 = TestIntfPrx::checkedCast(base6);
        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 = TestIntfPrx::checkedCast(base3);
        obj3->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    try
    {
        obj2 = TestIntfPrx::checkedCast(base2);
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();
    try
    {
        obj2 = TestIntfPrx::checkedCast(base2);
        obj2->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    try
    {
        obj3 = TestIntfPrx::checkedCast(base3);
        obj3->ice_ping();
    }
    catch(const Ice::LocalException& ex)
    {
        cerr << ex << endl;
        test(false);
    }
    obj->shutdown();
    manager->startServer();

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

    try
    {
        obj5 = TestIntfPrx::checkedCast(base5);
        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(1200));
    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(1200));
    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;
    HelloPrx 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 proxy from server after shutdown... " << flush;
    obj->shutdown();
    manager->startServer();
    hello->sayHello();
    cout << "ok" << endl;

    cout << "testing object migration... " << flush;
    hello = HelloPrx::checkedCast(communicator->stringToProxy("hello"));
    obj->migrateHello();
    hello->sayHello();
    obj->migrateHello();
    hello->sayHello();
    obj->migrateHello();
    hello->sayHello();
    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;

    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);

    TestLocatorRegistryPrx registry = TestLocatorRegistryPrx::checkedCast(locator->getRegistry());
    test(registry);

    Ice::Identity id;
    id.name = IceUtil::generateUUID();
    registry->addObject(adapter->add(new HelloI, id));
    adapter->activate();

    try
    {
        HelloPrx helloPrx = HelloPrx::checkedCast(communicator->stringToProxy(communicator->identityToString(id)));
        Ice::ConnectionPtr connection = helloPrx->ice_getConnection();
        test(false);
    }
    catch(const Ice::CollocationOptimizationException&)
    {
    }
    adapter->deactivate();
    cout << "ok" << endl;

    cout << "shutdown server manager... " << flush;
    manager->shutdown();
    cout << "ok" << endl;
}
Ejemplo n.º 20
0
ThrowerPrx
allTests(const Ice::CommunicatorPtr& communicator)
{
    cout << "testing ice_print()/what()... " << flush;
    {
        A a;
        string aMsg = "Test::A";

        Ice::UnknownLocalException ule("thisFile", 99);
        string uleMsg = "thisFile:99: Ice::UnknownLocalException:\nunknown local exception";

        //
        // Test ice_print().
        //
        {
            stringstream str;
            a.ice_print(str);
            test(str.str() == aMsg);
        }
        {
            stringstream str;
            ule.ice_print(str);
            test(str.str() == uleMsg);
        }

        //
        // Test operator<<().
        //
        {
            stringstream str;
            str << a;
            test(str.str() == aMsg);
        }
        {
            stringstream str;
            str << ule;
            test(str.str() == uleMsg);
        }

        //
        // Test what(). (Called twice because of lazy initialization in what().)
        //
        test(aMsg == a.what());
        test(aMsg == a.what());

        test(uleMsg == ule.what());
        test(uleMsg == ule.what());

        {
            E ex("E");
            ostringstream os;
            ex.ice_print(os);
            test(os.str() == "Test::E");
            test(ex.data == "E");
        }
    
        //
        // Test custom ice_print
        // 
        {
            F ex("F");
            ostringstream os;
            ex.ice_print(os);
            test(os.str() == "Test::F data:'F'");
            test(ex.data == "F");
        }

        {
            G ex(__FILE__, __LINE__, "G");
            ostringstream os;
            ex.ice_print(os);
            test(endsWith(os.str(), "Test::G"));
            test(ex.data == "G");
        }

        {
            H ex(__FILE__, __LINE__, "H");
            ostringstream os;
            ex.ice_print(os);
            test(endsWith(os.str(), "Test::H data:'H'"));
            test(ex.data == "H");
        }

    }
    cout << "ok" << endl;

    cout << "testing object adapter registration exceptions... " << flush;
    {
        Ice::ObjectAdapterPtr first;
        try
        {
            first = communicator->createObjectAdapter("TestAdapter0");
            test(false);
        }
        catch(const Ice::InitializationException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
            // Expected
        }

        string host = communicator->getProperties()->getPropertyAsIntWithDefault("Ice.IPv6", 0) == 0 ? 
            "127.0.0.1" : "\"0:0:0:0:0:0:0:1\"";
        communicator->getProperties()->setProperty("TestAdapter0.Endpoints", "default -h " + host);
        first = communicator->createObjectAdapter("TestAdapter0");
        try
        {
            Ice::ObjectAdapterPtr second = communicator->createObjectAdapter("TestAdapter0");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }

            // Expected
        }

        try
        {
            Ice::ObjectAdapterPtr second =
                communicator->createObjectAdapterWithEndpoints("TestAdapter0", "ssl -h foo -p 12011");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }

            // Expected.
        }
        first->deactivate();
    }
    cout << "ok" << endl;

    cout << "testing servant registration exceptions... " << flush;
    {
        string host = communicator->getProperties()->getPropertyAsIntWithDefault("Ice.IPv6", 0) == 0 ? 
            "127.0.0.1" : "\"0:0:0:0:0:0:0:1\"";
        communicator->getProperties()->setProperty("TestAdapter1.Endpoints", "default -h " + host);
        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TestAdapter1");
        Ice::ObjectPtr obj = new EmptyI;
        adapter->add(obj, communicator->stringToIdentity("x"));
        try
        {
            adapter->add(obj, communicator->stringToIdentity("x"));
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }

        try
        {
            adapter->add(obj, communicator->stringToIdentity(""));
        }
        catch(const Ice::IllegalIdentityException& ex)
        {
            test(ex.id.name == "");
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }
        
        try
        {
            adapter->add(0, communicator->stringToIdentity("x"));
        }
        catch(const Ice::IllegalServantException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }


        adapter->remove(communicator->stringToIdentity("x"));
        try
        {
            adapter->remove(communicator->stringToIdentity("x"));
            test(false);
        }
        catch(const Ice::NotRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }

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

    cout << "testing servant locator registrations exceptions... " << flush;
    {
        string host = communicator->getProperties()->getPropertyAsIntWithDefault("Ice.IPv6", 0) == 0 ? 
            "127.0.0.1" : "\"0:0:0:0:0:0:0:1\"";
        communicator->getProperties()->setProperty("TestAdapter2.Endpoints", "default -h " + host);
        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TestAdapter2");
        Ice::ServantLocatorPtr loc = new ServantLocatorI;
        adapter->addServantLocator(loc, "x");
        try
        {
            adapter->addServantLocator(loc, "x");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException&)
        {
        }

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

    cout << "testing object factory registration exception... " << flush;
    {
        Ice::ObjectFactoryPtr of = new ObjectFactoryI;
        communicator->addObjectFactory(of, "x");
        try
        {
            communicator->addObjectFactory(of, "x");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException&)
        {
        }
    }
    cout << "ok" << endl;

    cout << "testing stringToProxy... " << flush;
    string ref = "thrower:default -p 12010";
    Ice::ObjectPrx base = communicator->stringToProxy(ref);
    test(base);
    cout << "ok" << endl;

    cout << "testing checked cast... " << flush;
    ThrowerPrx thrower = ThrowerPrx::checkedCast(base);
    test(thrower);
    test(thrower == base);
    cout << "ok" << endl;

    cout << "catching exact types... " << flush;

    try
    {
        thrower->throwAasA(1);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(const Ice::Exception& ex)
    {
        cout << ex << endl;
        test(false);
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwAorDasAorD(1);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(...)
    {
        test(false);
    }

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

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

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

    try
    {
        thrower->throwModA(1, 2);
        test(false);
    }
    catch(const Mod::A& ex)
    {
        test(ex.aMem == 1);
        test(ex.a2Mem == 2);
    }
    catch(const Ice::OperationNotExistException&)
    {
        //
        // This operation is not supported in Java.
        //
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching base types... " << flush;

    try
    {
        thrower->throwBasB(1, 2);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(...)
    {
        test(false);
    }

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

    try
    {
        thrower->throwModA(1, 2);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(const Ice::OperationNotExistException&)
    {
        //
        // This operation is not supported in Java.
        //
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching derived types... " << flush;

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

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

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

    cout << "ok" << endl;

    if(thrower->supportsUndeclaredExceptions())
    {
        cout << "catching unknown user exception... " << flush;

        try
        {
            thrower->throwUndeclaredA(1);
            test(false);
        }
        catch(const Ice::UnknownUserException&)
        {
        }
        catch(const Ice::Exception& ex)
        {
            cout << ex << endl;
            cout << ex.ice_stackTrace() << endl;
            test(false);
        }
        catch(...)
        {
            test(false);
        }

        try
        {
            thrower->throwUndeclaredB(1, 2);
            test(false);
        }
        catch(const Ice::UnknownUserException&)
        {
        }
        catch(...)
        {
            test(false);
        }

        try
        {
            thrower->throwUndeclaredC(1, 2, 3);
            test(false);
        }
        catch(const Ice::UnknownUserException&)
        {
        }
        catch(...)
        {
            test(false);
        }

        cout << "ok" << endl;
    }

    if(thrower->ice_getConnection())
    {
        cout << "testing memory limit marshal exception..." << flush;
        try
        {
            thrower->throwMemoryLimitException(Ice::ByteSeq());
            test(false);
        }
        catch(const Ice::MemoryLimitException&)
        {
        }
        catch(...)
        {
            test(false);
        }

        try
        {
            thrower->throwMemoryLimitException(Ice::ByteSeq(20 * 1024)); // 20KB
            test(false);
        }
        catch(const Ice::ConnectionLostException&)
        {
        }
        catch(const Ice::LocalException& ex)
        {
            cerr << ex << endl;
            test(false);
        }
        
        ThrowerPrx thrower2 = ThrowerPrx::uncheckedCast(communicator->stringToProxy("thrower:default -p 12011"));
        try
        {
            thrower2->throwMemoryLimitException(Ice::ByteSeq(2 * 1024 * 1024)); // 2MB (no limits)
        }
        catch(const Ice::MemoryLimitException&)
        {
        }
        ThrowerPrx thrower3 = ThrowerPrx::uncheckedCast(communicator->stringToProxy("thrower:default -p 12012"));
        try
        {
            thrower3->throwMemoryLimitException(Ice::ByteSeq(1024)); // 1KB limit
            test(false);
        }
        catch(const Ice::ConnectionLostException&)
        {
        }

        cout << "ok" << endl;
    }

    cout << "catching object not exist exception... " << flush;

    Ice::Identity id = communicator->stringToIdentity("does not exist");
    try
    {
        ThrowerPrx thrower2 = ThrowerPrx::uncheckedCast(thrower->ice_identity(id));
        thrower2->throwAasA(1);
//      thrower2->ice_ping();
        test(false);
    }
    catch(const Ice::ObjectNotExistException& ex)
    {
        test(ex.id == id);
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching facet not exist exception... " << flush;

    try
    {
        ThrowerPrx thrower2 = ThrowerPrx::uncheckedCast(thrower, "no such facet");
        try
        {
            thrower2->ice_ping();
            test(false);
        }
        catch(const Ice::FacetNotExistException& ex)
        {
            test(ex.facet == "no such facet");
        }
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching operation not exist exception... " << flush;

    try
    {
        WrongOperationPrx thrower2 = WrongOperationPrx::uncheckedCast(thrower);
        thrower2->noSuchOperation();
        test(false);
    }
    catch(const Ice::OperationNotExistException& ex)
    {
        test(ex.operation == "noSuchOperation");
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching unknown local exception... " << flush;

    try
    {
        thrower->throwLocalException();
        test(false);
    }
    catch(const Ice::UnknownLocalException&)
    {
    }
    catch(...)
    {
        test(false);
    }
    try
    {
        thrower->throwLocalExceptionIdempotent();
        test(false);
    }
    catch(const Ice::UnknownLocalException&)
    {
    }
    catch(const Ice::OperationNotExistException&)
    {
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching unknown non-Ice exception... " << flush;

    try
    {
        thrower->throwNonIceException();
        test(false);
    }
    catch(const Ice::UnknownException&)
    {
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "testing asynchronous exceptions... " << flush;

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

    try
    {
        thrower->throwAfterException();
    }
    catch(const A&)
    {
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching exact types with new AMI mapping... " << flush;

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAasAPtr callback = 
            newCallback_Thrower_throwAasA(cb, &Callback::response, &Callback::exception_AasA);
        thrower->begin_throwAasA(1, callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAorDasAorDPtr callback = 
            newCallback_Thrower_throwAorDasAorD(cb, &Callback::response, &Callback::exception_AorDasAorD);
        thrower->begin_throwAorDasAorD(1, callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAorDasAorDPtr callback = 
            newCallback_Thrower_throwAorDasAorD(cb, &Callback::response, &Callback::exception_AorDasAorD);
        thrower->begin_throwAorDasAorD(-1, callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwBasBPtr callback = 
            newCallback_Thrower_throwBasB(cb, &Callback::response, &Callback::exception_BasB);
        thrower->begin_throwBasB(1, 2, callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwCasCPtr callback = 
            newCallback_Thrower_throwCasC(cb, &Callback::response, &Callback::exception_CasC);
        thrower->begin_throwCasC(1, 2, 3, callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwModAPtr callback = 
            newCallback_Thrower_throwModA(cb, &Callback::response, &Callback::exception_ModA);
        thrower->begin_throwModA(1, 2, callback);
        cb->check();
    }

    cout << "ok" << endl;

    cout << "catching derived types with new AMI mapping... " << flush;

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwBasAPtr callback = 
            newCallback_Thrower_throwBasA(cb, &Callback::response, &Callback::exception_BasA);
        thrower->begin_throwBasA(1, 2, callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwCasAPtr callback = 
            newCallback_Thrower_throwCasA(cb, &Callback::response, &Callback::exception_CasA);
        thrower->begin_throwCasA(1, 2, 3, callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwCasBPtr callback = 
            newCallback_Thrower_throwCasB(cb, &Callback::response, &Callback::exception_CasB);
        thrower->begin_throwCasB(1, 2, 3, callback);
        cb->check();
    }

    cout << "ok" << endl;

    if(thrower->supportsUndeclaredExceptions())
    {
        cout << "catching unknown user exception with new AMI mapping... " << flush;

        {
            CallbackPtr cb = new Callback;
            Callback_Thrower_throwUndeclaredAPtr callback = 
                newCallback_Thrower_throwUndeclaredA(cb, &Callback::response, &Callback::exception_UndeclaredA);
            thrower->begin_throwUndeclaredA(1, callback);
            cb->check();
        }

        {
            CallbackPtr cb = new Callback;
            Callback_Thrower_throwUndeclaredBPtr callback =
                newCallback_Thrower_throwUndeclaredB(cb, &Callback::response, &Callback::exception_UndeclaredB);
            thrower->begin_throwUndeclaredB(1, 2, callback);
            cb->check();
        }

        {
            CallbackPtr cb = new Callback;
            Callback_Thrower_throwUndeclaredCPtr callback = 
                newCallback_Thrower_throwUndeclaredC(cb, &Callback::response, &Callback::exception_UndeclaredC);
            thrower->begin_throwUndeclaredC(1, 2, 3, callback);
            cb->check();
        }

        cout << "ok" << endl;
    }

    cout << "catching object not exist exception with new AMI mapping... " << flush;

    {
        id = communicator->stringToIdentity("does not exist");
        ThrowerPrx thrower2 = ThrowerPrx::uncheckedCast(thrower->ice_identity(id));
        CallbackPtr cb = new Callback(communicator);
        Callback_Thrower_throwAasAPtr callback = 
            newCallback_Thrower_throwAasA(cb, &Callback::response, &Callback::exception_AasAObjectNotExist);
        thrower2->begin_throwAasA(1, callback);
        cb->check();
    }

    cout << "ok" << endl;

    cout << "catching facet not exist exception with new AMI mapping... " << flush;

    {
        ThrowerPrx thrower2 = ThrowerPrx::uncheckedCast(thrower, "no such facet");
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAasAPtr callback = 
            newCallback_Thrower_throwAasA(cb, &Callback::response, &Callback::exception_AasAFacetNotExist);
        thrower2->begin_throwAasA(1, callback);
        cb->check();
    }

    cout << "ok" << endl;

    cout << "catching operation not exist exception with new AMI mapping... " << flush;

    {
        CallbackPtr cb = new Callback;
        Callback_WrongOperation_noSuchOperationPtr callback = 
            newCallback_WrongOperation_noSuchOperation(cb, &Callback::response, 
                                                       &Callback::exception_noSuchOperation);
        WrongOperationPrx thrower4 = WrongOperationPrx::uncheckedCast(thrower);
        thrower4->begin_noSuchOperation(callback);
        cb->check();
    }

    cout << "ok" << endl;

    cout << "catching unknown local exception with new AMI mapping... " << flush;

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwLocalExceptionPtr callback = 
            newCallback_Thrower_throwLocalException(cb, &Callback::response, &Callback::exception_LocalException);
        thrower->begin_throwLocalException(callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwLocalExceptionIdempotentPtr callback = 
            newCallback_Thrower_throwLocalExceptionIdempotent(cb, &Callback::response, 
                                                              &Callback::exception_LocalException);
        thrower->begin_throwLocalExceptionIdempotent(callback);
        cb->check();
    }

    cout << "ok" << endl;

    cout << "catching unknown non-Ice exception with new AMI mapping... " << flush;

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwNonIceExceptionPtr callback = 
            newCallback_Thrower_throwNonIceException(cb, &Callback::response, &Callback::exception_NonIceException);
        thrower->begin_throwNonIceException(callback);
        cb->check();
    }

    cout << "ok" << endl;

    return thrower;
}
Ejemplo n.º 21
0
void
allTests(const Ice::CommunicatorPtr& communicator, const string& ref)
{
    ServerManagerPrx manager = ServerManagerPrx::checkedCast(communicator->stringToProxy(ref));
    TestLocatorPrx locator = TestLocatorPrx::uncheckedCast(communicator->getDefaultLocator());
    test(manager);

    TestLocatorRegistryPrx registry = TestLocatorRegistryPrx::checkedCast(locator->getRegistry());
    test(registry);

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

    cout << "testing ice_locator and ice_getLocator... " << flush;
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), communicator->getDefaultLocator()));
    Ice::LocatorPrx anotherLocator = Ice::LocatorPrx::uncheckedCast(communicator->stringToProxy("anotherLocator"));
    base = base->ice_locator(anotherLocator);
    test(Ice::proxyIdentityEqual(base->ice_getLocator(), anotherLocator));
    communicator->setDefaultLocator(0);
    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::RouterPrx anotherRouter = Ice::RouterPrx::uncheckedCast(communicator->stringToProxy("anotherRouter"));
    base = base->ice_router(anotherRouter);
    test(Ice::proxyIdentityEqual(base->ice_getRouter(), anotherRouter));
    Ice::RouterPrx router = Ice::RouterPrx::uncheckedCast(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;
    TestIntfPrx obj = TestIntfPrx::checkedCast(base);
    test(obj);
    TestIntfPrx obj2 = TestIntfPrx::checkedCast(base2);
    test(obj2);
    TestIntfPrx obj3 = TestIntfPrx::checkedCast(base3);
    test(obj3);
    ServerManagerPrx obj4 = ServerManagerPrx::checkedCast(base4);
    test(obj4);
    TestIntfPrx obj5 = TestIntfPrx::checkedCast(base5);
    test(obj5);
    TestIntfPrx obj6 = TestIntfPrx::checkedCast(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 = TestIntfPrx::checkedCast(communicator->stringToProxy("test@TestAdapter"));
    HelloPrx 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;

    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;
    }
    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 = HelloPrx::checkedCast(communicator->stringToProxy("hello"));
    obj->migrateHello();
    // TODO: enable after fixing ICE-5489
    //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 = HelloPrx::checkedCast(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;

    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(new HelloI, id));
    adapter->activate();
    
    try
    {
        HelloPrx helloPrx = HelloPrx::checkedCast(communicator->stringToProxy(communicator->identityToString(id)));
        Ice::ConnectionPtr connection = helloPrx->ice_getConnection();
        test(false);
    }
    catch(const Ice::CollocationOptimizationException&)
    {
    }
    adapter->deactivate();
    cout << "ok" << endl;

    cout << "shutdown server manager... " << flush;
    manager->shutdown();
    cout << "ok" << endl;
}
Ejemplo n.º 22
0
int main(int argc, char** argv){

	std::string replayerFilePath("data/replayer.cfg");
	std::ofstream replayerFile;




	struct sigaction sigIntHandler;

   sigIntHandler.sa_handler = exitApplication;
   sigemptyset(&sigIntHandler.sa_mask);
   sigIntHandler.sa_flags = 0;

   sigaction(SIGINT, &sigIntHandler, NULL);

	int accion=0;
	int sentido=10;

	int status;

	struct timeval a, b, t2;
	int cycle = 100;
	long totalb,totala;
	long diff;

	// INTERFACE
	std::vector<jderobot::LaserPrx> lprx;
	std::vector<jderobot::CameraPrx> cprx;
	std::vector<jderobot::Pose3DEncodersPrx> pose3dencoders;
	std::vector<jderobot::EncodersPrx> encoders;
	std::vector <jderobot::pointCloudPrx> prx;


	//INTERFACE DATA
	jderobot::EncodersDataPtr ed;
	jderobot::LaserDataPtr ld;
	
	jderobot::ImageDataPtr imageData;

	//pools

	pthread_attr_t attr;
	//images

	int nConsumidores;
	int poolSize;
	//lasers
	std::vector<recorder::poolWriteLasers*> poolLasers;
	//pose3dencoders
	std::vector<recorder::poolWritePose3dEncoders*> poolPose3dEncoders;
	//encoders
	std::vector<recorder::poolWriteEncoders*> poolEncoders;
	//pointClouds
	std::vector<recorder::poolWritePointCloud*> poolPointClouds;

	//numero de lasers

	int Hz = 10;
	int muestrasLaser = 180;
	int pngCompressRatio;
	int jpgQuality;
	std::string imageFormat;
	std::vector<int> compression_params;

    
   
	//---------------- INPUT ARGUMENTS ---------------//

	if (argc<2){
		std::cout << std::endl << "USE: ./mycomponent --Ice.Config=mycomponent.cfg" << std::endl;
	}

	//---------------- INPUT ARGUMENTS -----------------//

	try{
		//creamos el directorio principal
		struct stat buf;
		char dire[]="./data/";
		if( stat( dire, &buf ) == -1 )
		{
			system("mkdir data");
		}
		replayerFile.open(replayerFilePath.c_str());
   
		Ice::PropertiesPtr prop;

		ic = EasyIce::initialize(argc,argv);

		prop = ic->getProperties();

		Hz = prop->getPropertyAsInt("Recorder.Hz");
		cycle = 1000.0/Hz;
      
		pthread_attr_init(&attr);
		pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
      

		nCameras = prop->getPropertyAsIntWithDefault("Recorder.nCameras",0);
		replayerFile << "Replayer.nCameras=" << nCameras << std::endl;
		if (nCameras > 0 ){
			struct stat buf;
			char dire[]="./data/images/";
			if( stat( dire, &buf ) == -1 )
			{
				system("mkdir ./data/images/");
			}
			imageFormat=prop->getProperty("Recorder.Format");
			if (imageFormat.compare(std::string("png"))==0){
				pngCompressRatio=prop->getPropertyAsIntWithDefault("Recorder.PngCompression",3);
				compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
				compression_params.push_back(pngCompressRatio);
			}
			else if (imageFormat.compare(std::string("jpg"))==0){
				jpgQuality=prop->getPropertyAsIntWithDefault("Recorder.JpgQuality",95);
				compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
				compression_params.push_back(jpgQuality);
			}
			else{
				throw "Image format is not valid";
			}
			nConsumidores=prop->getPropertyAsIntWithDefault("Recorder.nConsumers",2);
			poolSize=prop->getPropertyAsIntWithDefault("Recorder.poolSize",10);
		}


		int bufferEnabled = prop->getPropertyAsIntWithDefault("Recorder.Buffer.Enabled",0);
		int bufferSeconds = prop->getPropertyAsIntWithDefault("Recorder.Buffer.Seconds",0);
		std::string videoMode =  prop->getProperty("Recorder.Buffer.Mode");

		for (int i=0; i< nCameras; i++){
			struct stat buf;
			std::stringstream cameraPath;
			cameraPath << "./data/images/camera" << i+1;
			if( stat( cameraPath.str().c_str(), &buf ) == -1 )
			{
				std::stringstream instruction;
				instruction << "mkdir " << cameraPath.str();
				system(instruction.str().c_str());
			}


			std::stringstream sProxy;
			// Get driver camera
			sProxy << "Recorder.Camera" << i+1 << ".Proxy";


			//get the camera name
			std::string cameraName = prop->getProperty(sProxy.str());

			std::vector<std::string> splitedName = split(cameraName, ':');
			replayerFile << "Replayer.Camera." << i << ".Name=" << splitedName[0] << std::endl;
			replayerFile << "Replayer.Camera." << i << ".Dir=" << cameraPath.str() << std::endl;
			replayerFile << "Replayer.Camera." << i << ".FileFormat=" << imageFormat << std::endl;


			Ice::ObjectPrx camara = ic->propertyToProxy(sProxy.str());
			if (0==camara)
				throw "Could not create proxy to camera1 server";
			// cast to CameraPrx
			jderobot::CameraPrx cprxAux = jderobot::CameraPrx::checkedCast(camara);
			if (0== cprxAux)
				throw "Invalid proxy";
			else
				cprx.push_back(cprxAux);

			//pool
			recorder::poolWriteImages *temp = new recorder::poolWriteImages(cprxAux, Hz,poolSize,i+1,imageFormat,
					compression_params, (bufferEnabled == 0)? recorder::poolWriteImages::WRITE_FRAME : recorder::poolWriteImages::SAVE_BUFFER, bufferSeconds, videoMode);
			poolImages.push_back(temp);


			for (int j=i*nConsumidores; j< i*nConsumidores+nConsumidores; j++){
				std::cout << "Create consumer" << std::endl;
				pthread_create(&consumerThreads[j], &attr, camera_pool_consumer_thread,temp);
				totalConsumers++;
			}
			pthread_create(&producerThreads[i], &attr, camera_pool_producer_thread,temp);
			totalProducers++;
		}

		if (bufferEnabled)
		{

			// Analyze EndPoint
			std::string Endpoints = prop->getProperty("Recorder.Endpoints");
			adapter =ic->createObjectAdapterWithEndpoints("Recorder", Endpoints);
			std::string name = prop->getProperty("Recorder.Name");
			jderobot::Logger::getInstance()->info("Creating Recorder: " + name);
			RecorderI* recorder_prx = new RecorderI();
			adapter->add(recorder_prx, ic->stringToIdentity(name));

			adapter->activate();


			// Naming Service
			int nsActive = prop->getPropertyAsIntWithDefault("NamingService.Enabled", 0);

			if (nsActive) {
				std::string ns_proxy = prop->getProperty("NamingService.Proxy");
				try {
					namingService = new jderobot::ns(ic, ns_proxy);
				}
				catch (Ice::ConnectionRefusedException &ex) {
					jderobot::Logger::getInstance()->error("Impossible to connect with NameService!");
					exit(-1);
				}
				namingService->bind(name, Endpoints, recorder_prx->ice_staticId());
			}
		}



		nLasers= prop->getPropertyAsInt("Recorder.nLasers");
		if (nLasers > 0){
			struct stat buf;
			char dire[]="./data/lasers/";
			if( stat( dire, &buf ) == -1 )
			{
				system("mkdir data/lasers/");
			}
		}
		for (int i=0; i< nLasers; i++){
			struct stat buf;
			std::stringstream claserPath;
			claserPath << "./data/lasers/laser" << i+1;
			if( stat( claserPath.str().c_str(), &buf ) == -1 )
			{
				std::stringstream instruction;
				instruction << "mkdir " << claserPath.str();
				system(instruction.str().c_str());
			}

			// Contact to LASER interface
			std::stringstream sProxy;
			sProxy << "Recorder.Laser" << i+1 << ".Proxy";

			Ice::ObjectPrx baseLaser = ic->propertyToProxy(sProxy.str());
			if (0==baseLaser)
				throw "Could not create proxy with laser";

			// Cast to laser
			jderobot::LaserPrx laserPrx = jderobot::LaserPrx::checkedCast(baseLaser);
			if (0== laserPrx)
				throw "Invalid proxy Mycomponent.Laser.Proxy";
			lprx.push_back(laserPrx);
			recorder::poolWriteLasers *temp = new recorder::poolWriteLasers(laserPrx, Hz,poolSize,i+1);

			poolLasers.push_back(temp);
			pthread_create(&consumerThreads[totalConsumers], &attr, laser_pool_consumer_thread,temp);
			totalConsumers++;
			pthread_create(&producerThreads[totalProducers], &attr, laser_pool_producer_thread,temp);
			totalProducers++;
		}


		nPose3dEncoders= prop->getPropertyAsInt("Recorder.nPose3dEncoders");
		if (nPose3dEncoders > 0){
			struct stat buf;
			char dire[]="./data/pose3dencoders/";
			if( stat( dire, &buf ) == -1 )
			{
				system("mkdir data/pose3dencoders/");
			}
		}
		for (int i=0; i< nPose3dEncoders; i++){
			struct stat buf;
			std::stringstream claserPath;
			claserPath << "./data/pose3dencoders/pose3dencoder" << i+1;
			if( stat( claserPath.str().c_str(), &buf ) == -1 )
			{
				std::stringstream instruction;
				instruction << "mkdir " << claserPath.str();
				system(instruction.str().c_str());
			}

			// Contact to POSE3DENCODERS interface
			std::stringstream sProxy;
			sProxy << "Recorder.Pose3DEncoders" << i+1 << ".Proxy";

			Ice::ObjectPrx base = ic->propertyToProxy(sProxy.str());
			if (0==base)
				throw "Could not create proxy with pose3dencoders";

			// Cast to Pose3DEncodersPrx
			jderobot::Pose3DEncodersPrx prx = jderobot::Pose3DEncodersPrx::checkedCast(base);
			if (0== prx)
				throw "Invalid proxy Mycomponent.pose3dencoders.Proxy";
			pose3dencoders.push_back(prx);
			recorder::poolWritePose3dEncoders*temp = new recorder::poolWritePose3dEncoders(prx, Hz,poolSize,i+1);

			poolPose3dEncoders.push_back(temp);
			pthread_create(&consumerThreads[totalConsumers], &attr, pose3dencoders_pool_consumer_thread,temp);
			totalConsumers++;
			pthread_create(&producerThreads[totalProducers], &attr, pose3dencoders_pool_producer_thread,temp);
			totalProducers++;
		}

		nEncoders= prop->getPropertyAsInt("Recorder.nEncoders");
		if (nEncoders > 0){
			struct stat buf;
			char dire[]="./data/encoders/";
			if( stat( dire, &buf ) == -1 )
			{
				system("mkdir data/encoders/");
			}
		}
		for (int i=0; i< nEncoders; i++){
			struct stat buf;
			std::stringstream claserPath;
			claserPath << "./data/encoders/encoder" << i+1;
			if( stat( claserPath.str().c_str(), &buf ) == -1 )
			{
				std::stringstream instruction;
				instruction << "mkdir " << claserPath.str();
				system(instruction.str().c_str());
			}

			// Contact to ENCODERS interface
			std::stringstream sProxy;
			sProxy << "Recorder.Encoders" << i+1 << ".Proxy";

			Ice::ObjectPrx base = ic->propertyToProxy(sProxy.str());
			if (0==base)
				throw "Could not create proxy with encoders";

			// Cast to EncodersPrx
			jderobot::EncodersPrx prx = jderobot::EncodersPrx::checkedCast(base);
			if (0== prx)
				throw "Invalid proxy Mycomponent.encoders.Proxy";
			encoders.push_back(prx);
			recorder::poolWriteEncoders*temp = new recorder::poolWriteEncoders(prx, Hz,poolSize,i+1);

			poolEncoders.push_back(temp);
			pthread_create(&consumerThreads[totalConsumers], &attr, encoders_pool_consumer_thread,temp);
			totalConsumers++;
			pthread_create(&producerThreads[totalProducers], &attr, encoders_pool_producer_thread,temp);
			totalProducers++;
		}

		nDepthSensors = prop->getPropertyAsIntWithDefault("Recorder.nDethSensors",0);
		if (nDepthSensors){
			struct stat buf;
			char dire[]="./data/pointClouds/";
			if( stat( dire, &buf ) == -1 )
			{
				system("mkdir data/pointClouds/");
			}
		}
		for (int i=0; i< nDepthSensors; i++){
			struct stat buf;
			std::stringstream claserPath;
			claserPath << "./data/pointClouds/pointCloud" << i+1;
			if( stat( claserPath.str().c_str(), &buf ) == -1 )
			{
				std::stringstream instruction;
				instruction << "mkdir " << claserPath.str();
				system(instruction.str().c_str());
			}


			std::stringstream sProxy;
			// Get driver camera
			sProxy << "Recorder.DepthSensor" << i+1 << ".Proxy";

			Ice::ObjectPrx kinect = ic->propertyToProxy(sProxy.str());
			if (0==kinect){
				throw "Could not create proxy with Kinect1";
			}
			// Cast to KINECT
			jderobot::pointCloudPrx prxAux = jderobot::pointCloudPrx::checkedCast(kinect);
			if (0== prxAux){
				throw std::string("Invalid proxy Recorder.Kinect1.Proxy");
			}
			prx.push_back(prxAux);
			recorder::poolWritePointCloud* temp = new recorder::poolWritePointCloud(prxAux, Hz,poolSize,i+1);
			poolPointClouds.push_back(temp);
			pthread_create(&consumerThreads[totalConsumers], &attr, pointcloud_pool_consumer_thread,temp);
			totalConsumers++;
			pthread_create(&producerThreads[totalProducers], &attr, pointcloud_pool_producer_thread,temp);
			totalProducers++;
		}

		//****************************** Processing the Control ******************************///


		//---------------- ITERATIONS CONTROL -----------//
		//muestreo para el laser
		muestrasLaser = prop->getPropertyAsInt("Recorder.Laser.Samples");
		std::string robotName = prop->getPropertyWithDefault("Recorder.Hostname","localhost");
		std::string robotPort = prop->getPropertyWithDefault("Recorder.Port","9999");
      
		long timeRelative = 0;


		int guiActive=prop->getPropertyAsIntWithDefault("Recorder.GUI",0);
		recorder::recordergui *gui;

		if (guiActive){
	      gui = new recorder::recordergui();
		}
		long long int iteration=0;
		
            
		while(globalActive){
			//gui activado
			if (guiActive){
				gui->set_iteration(iteration);
				gui->update();
				globalActive=gui->get_active();
				recording=gui->get_recording();
			}
			else{
				recording=true;
			}

			if (recording){
				if (iteration==0){
					gettimeofday(&inicio,NULL);
				}
				iteration++;
				gettimeofday(&b,NULL);
				totalb=b.tv_sec*1000000+b.tv_usec;
				//calculamos la velocidad de grabación actual
				float myfps=1000000./((float)totalb-(float)totala);
				if (guiActive){
					gui->set_fps((int)myfps);
				}
				gettimeofday(&a,NULL);
				totala=a.tv_sec*1000000+a.tv_usec;

				gettimeofday(&b,NULL);
				totalb=b.tv_sec*1000000+b.tv_usec;
				if (!bufferEnabled)
					std::cout << "Recorder takes " << (totalb-totala)/1000 << " ms" << std::endl;

				diff = (totalb-totala)/1000;
				if(diff < 0 || diff > cycle)
					diff = cycle;
				else
					diff = cycle-diff;

				//Sleep Algorithm
				usleep(diff*1000);
				if(diff < 10)
					usleep(10*1000);

				// std::cout << cycle <<" ->" << diff  << " ->" << timeRelative<< std::endl;
				timeRelative+= diff + (totalb-totala)/1000;
				// std::cout << "->" << diff  << " ->" << timeRelative<< std::endl;
			}
			else{
				usleep(10*1000);
			}

		}

	//--------------ITERATIONS CONTROL-------------//
	}
	catch (const Ice::Exception& ex) {
		std::cerr << ex << std::endl;
		status = 1;
   } 
	catch (const char* msg) {
		std::cerr << msg << std::endl;
		status = 1;
	}

	if (!killed)
		exitApplication(1);
   
   return 0;
}
Ejemplo n.º 23
0
ThrowerPrxPtr
allTests(const Ice::CommunicatorPtr& communicator)
{
    cout << "testing ice_print()/what()... " << flush;
    {
        A a;
        string aMsg = "Test::A";

        Ice::UnknownLocalException ule("thisFile", 99);
        string uleMsg = "thisFile:99: Ice::UnknownLocalException:\nunknown local exception";

        //
        // Test ice_print().
        //
        {
            stringstream str;
            a.ice_print(str);
            test(str.str() == aMsg);
        }
        {
            stringstream str;
            ule.ice_print(str);
            test(str.str() == uleMsg);
        }

        //
        // Test operator<<().
        //
        {
            stringstream str;
            str << a;
            test(str.str() == aMsg);
        }
        {
            stringstream str;
            str << ule;
            test(str.str() == uleMsg);
        }

        //
        // Test what(). (Called twice because of lazy initialization in what().)
        //
        test(aMsg == a.what());
        test(aMsg == a.what());

        test(uleMsg == ule.what());
        test(uleMsg == ule.what());

        {
            E ex("E");
            ostringstream os;
            ex.ice_print(os);
            test(os.str() == "Test::E");
            test(ex.data == "E");
        }

        //
        // Test custom ice_print
        //
        {
            F ex("F");
            ostringstream os;
            ex.ice_print(os);
            test(os.str() == "Test::F data:'F'");
            test(ex.data == "F");
        }

        {
            G ex(__FILE__, __LINE__, "G");
            ostringstream os;
            ex.ice_print(os);
            test(endsWith(os.str(), "Test::G"));
            test(ex.data == "G");
        }

        {
            H ex(__FILE__, __LINE__, "H");
            ostringstream os;
            ex.ice_print(os);
            test(endsWith(os.str(), "Test::H data:'H'"));
            test(ex.data == "H");
        }

    }
    cout << "ok" << endl;

    string localOAEndpoint;
    {
        ostringstream ostr;
        if(communicator->getProperties()->getProperty("Ice.Default.Protocol") == "bt")
        {
            ostr << "default -a *";
        }
        else
        {
            ostr << "default -h *";
        }
        localOAEndpoint = ostr.str();
    }

    cout << "testing object adapter registration exceptions... " << flush;
    {
        Ice::ObjectAdapterPtr first;
        try
        {
            first = communicator->createObjectAdapter("TestAdapter0");
            test(false);
        }
        catch(const Ice::InitializationException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
            // Expected
        }

        communicator->getProperties()->setProperty("TestAdapter0.Endpoints", localOAEndpoint);
        first = communicator->createObjectAdapter("TestAdapter0");
        try
        {
            Ice::ObjectAdapterPtr second = communicator->createObjectAdapter("TestAdapter0");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }

            // Expected
        }

        try
        {
            Ice::ObjectAdapterPtr second =
                communicator->createObjectAdapterWithEndpoints("TestAdapter0", "ssl -h foo -p 12011");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }

            // Expected.
        }
        first->deactivate();
    }
    cout << "ok" << endl;

    cout << "testing servant registration exceptions... " << flush;
    {
        communicator->getProperties()->setProperty("TestAdapter1.Endpoints", localOAEndpoint);
        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TestAdapter1");
        Ice::ObjectPtr obj = ICE_MAKE_SHARED(EmptyI);
        adapter->add(obj, communicator->stringToIdentity("x"));
        try
        {
            adapter->add(obj, communicator->stringToIdentity("x"));
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }

        try
        {
            adapter->add(obj, communicator->stringToIdentity(""));
        }
        catch(const Ice::IllegalIdentityException& ex)
        {
            test(ex.id.name == "");
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }

        try
        {
            adapter->add(0, communicator->stringToIdentity("x"));
        }
        catch(const Ice::IllegalServantException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }

        adapter->remove(communicator->stringToIdentity("x"));
        try
        {
            adapter->remove(communicator->stringToIdentity("x"));
            test(false);
        }
        catch(const Ice::NotRegisteredException& ex)
        {
            if(printException)
            {
                Ice::Print printer(communicator->getLogger());
                printer << ex;
            }
        }

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

    cout << "testing servant locator registrations exceptions... " << flush;
    {
        communicator->getProperties()->setProperty("TestAdapter2.Endpoints", localOAEndpoint);
        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TestAdapter2");
        Ice::ServantLocatorPtr loc = ICE_MAKE_SHARED(ServantLocatorI);
        adapter->addServantLocator(loc, "x");
        try
        {
            adapter->addServantLocator(loc, "x");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException&)
        {
        }

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

    cout << "testing value factory registration exception... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        communicator->addValueFactory(
            [](const std::string&)
            {
                return nullptr;
            },
            "x");
        try
        {
            communicator->addValueFactory(
                [](const std::string&)
                {
                    return nullptr;
                },
                "x");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException&)
        {
        }
#else
        Ice::ValueFactoryPtr vf = new ValueFactoryI;
        communicator->addValueFactory(vf, "x");
        try
        {
            communicator->addValueFactory(vf, "x");
            test(false);
        }
        catch(const Ice::AlreadyRegisteredException&)
        {
        }
#endif
    }
    cout << "ok" << endl;

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

    cout << "testing checked cast... " << flush;
    ThrowerPrxPtr thrower = ICE_CHECKED_CAST(ThrowerPrx, base);
    test(thrower);
#ifdef ICE_CPP11_MAPPING
    test(Ice::targetEquals(thrower, base));
#else
    test(thrower == base);
#endif
    cout << "ok" << endl;

    cout << "catching exact types... " << flush;

    try
    {
        thrower->throwAasA(1);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(const Ice::Exception& ex)
    {
        cout << ex << endl;
        test(false);
    }
    catch(...)
    {
        test(false);
    }

    try
    {
        thrower->throwAorDasAorD(1);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(...)
    {
        test(false);
    }

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

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

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

    try
    {
        thrower->throwModA(1, 2);
        test(false);
    }
    catch(const Mod::A& ex)
    {
        test(ex.aMem == 1);
        test(ex.a2Mem == 2);
    }
    catch(const Ice::OperationNotExistException&)
    {
        //
        // This operation is not supported in Java.
        //
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching base types... " << flush;

    try
    {
        thrower->throwBasB(1, 2);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(...)
    {
        test(false);
    }

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

    try
    {
        thrower->throwModA(1, 2);
        test(false);
    }
    catch(const A& ex)
    {
        test(ex.aMem == 1);
    }
    catch(const Ice::OperationNotExistException&)
    {
        //
        // This operation is not supported in Java.
        //
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching derived types... " << flush;

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

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

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

    cout << "ok" << endl;

    if(thrower->supportsUndeclaredExceptions())
    {
        cout << "catching unknown user exception... " << flush;

        try
        {
            thrower->throwUndeclaredA(1);
            test(false);
        }
        catch(const Ice::UnknownUserException&)
        {
        }
        catch(const Ice::Exception& ex)
        {
            cout << ex << endl;
            cout << ex.ice_stackTrace() << endl;
            test(false);
        }
        catch(...)
        {
            test(false);
        }

        try
        {
            thrower->throwUndeclaredB(1, 2);
            test(false);
        }
        catch(const Ice::UnknownUserException&)
        {
        }
        catch(...)
        {
            test(false);
        }

        try
        {
            thrower->throwUndeclaredC(1, 2, 3);
            test(false);
        }
        catch(const Ice::UnknownUserException&)
        {
        }
        catch(...)
        {
            test(false);
        }

        cout << "ok" << endl;
    }

    if(thrower->ice_getConnection())
    {
        cout << "testing memory limit marshal exception..." << flush;
        try
        {
            thrower->throwMemoryLimitException(Ice::ByteSeq());
            test(false);
        }
        catch(const Ice::MemoryLimitException&)
        {
        }
        catch(...)
        {
            test(false);
        }

        try
        {
            thrower->throwMemoryLimitException(Ice::ByteSeq(20 * 1024)); // 20KB
            test(false);
        }
        catch(const Ice::ConnectionLostException&)
        {
        }
        catch(const Ice::LocalException& ex)
        {
            cerr << ex << endl;
            test(false);
        }

        ThrowerPrxPtr thrower2 =
            ICE_UNCHECKED_CAST(ThrowerPrx, communicator->stringToProxy("thrower:" + getTestEndpoint(communicator, 1)));
        try
        {
            thrower2->throwMemoryLimitException(Ice::ByteSeq(2 * 1024 * 1024)); // 2MB (no limits)
        }
        catch(const Ice::MemoryLimitException&)
        {
        }
        ThrowerPrxPtr thrower3 =
            ICE_UNCHECKED_CAST(ThrowerPrx, communicator->stringToProxy("thrower:" + getTestEndpoint(communicator, 2)));
        try
        {
            thrower3->throwMemoryLimitException(Ice::ByteSeq(1024)); // 1KB limit
            test(false);
        }
        catch(const Ice::ConnectionLostException&)
        {
        }

        cout << "ok" << endl;
    }

    cout << "catching object not exist exception... " << flush;

    Ice::Identity id = communicator->stringToIdentity("does not exist");
    try
    {
        ThrowerPrxPtr thrower2 = ICE_UNCHECKED_CAST(ThrowerPrx, thrower->ice_identity(id));
        thrower2->throwAasA(1);
//      thrower2->ice_ping();
        test(false);
    }
    catch(const Ice::ObjectNotExistException& ex)
    {
        test(ex.id == id);
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching facet not exist exception... " << flush;

    try
    {
#ifdef ICE_CPP11_MAPPING
        ThrowerPrxPtr thrower2 = Ice::uncheckedCast<ThrowerPrx>(thrower, "no such facet");
#else
        ThrowerPrxPtr thrower2 = ThrowerPrx::uncheckedCast(thrower, "no such facet");
#endif
        try
        {
            thrower2->ice_ping();
            test(false);
        }
        catch(const Ice::FacetNotExistException& ex)
        {
            test(ex.facet == "no such facet");
        }
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching operation not exist exception... " << flush;

    try
    {
        WrongOperationPrxPtr thrower2 = ICE_UNCHECKED_CAST(WrongOperationPrx, thrower);
        thrower2->noSuchOperation();
        test(false);
    }
    catch(const Ice::OperationNotExistException& ex)
    {
        test(ex.operation == "noSuchOperation");
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching unknown local exception... " << flush;

    try
    {
        thrower->throwLocalException();
        test(false);
    }
    catch(const Ice::UnknownLocalException&)
    {
    }
    catch(...)
    {
        test(false);
    }
    try
    {
        thrower->throwLocalExceptionIdempotent();
        test(false);
    }
    catch(const Ice::UnknownLocalException&)
    {
    }
    catch(const Ice::OperationNotExistException&)
    {
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching unknown non-Ice exception... " << flush;

    try
    {
        thrower->throwNonIceException();
        test(false);
    }
    catch(const Ice::UnknownException&)
    {
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "testing asynchronous exceptions... " << flush;

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

    try
    {
        thrower->throwAfterException();
    }
    catch(const A&)
    {
    }
    catch(...)
    {
        test(false);
    }

    cout << "ok" << endl;

    cout << "catching exact types with new AMI mapping... " << flush;
#ifdef ICE_CPP11_MAPPING
    {
        auto f = thrower->throwAasA_async(1);
        try
        {
            f.get();
            test(false);
        }
        catch(const A& ex)
        {
            test(ex.aMem == 1);
        }
        catch(const Ice::Exception&)
        {
            test(false);
        }
        catch(...)
        {
            test(false);
        }
    }
    
    {
        auto f = thrower->throwAorDasAorD_async(1);
        try
        {
            f.get();
            test(false);
        }
        catch(const A& ex)
        {
            test(ex.aMem == 1);
        }
        catch(...)
        {
            test(false);
        }
    }
    
    {
        auto f = thrower->throwAorDasAorD_async(-1);
        try
        {
            f.get();
            test(false);
        }
        catch(const D& ex)
        {
            test(ex.dMem == -1);
        }
        catch(...)
        {
            test(false);
        }
    }
    {
        auto f = thrower->throwBasB_async(1, 2);
        try
        {
            f.get();
            test(false);
        }
        catch(const B& ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
        }
        catch(...)
        {
            test(false);
        }
    }
    {
        auto f = thrower->throwCasC_async(1, 2, 3);
        try
        {
            f.get();
            test(false);
        }
        catch(const C& ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
            test(ex.cMem == 3);
        }
        catch(...)
        {
            test(false);
        }
    }
    {
        auto f = thrower->throwModA_async(1, 2);
        try
        {
            f.get();
        }
        catch(const A& ex)
        {
            test(ex.aMem == 1);
        }
        catch(const Ice::OperationNotExistException&)
        {
            //
            // This operation is not supported in Java.
            //
        }
        catch(...)
        {
            test(false);
        }
    }
    
    //
    // repeat with callback API and no exception callback
    //
    {
        promise<bool> sent;
        thrower->throwAasA_async(1,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }
    
    {
        promise<bool> sent;
        thrower->throwAorDasAorD_async(1,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }
    
    {
        promise<bool> sent;
        thrower->throwAorDasAorD_async(-1,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }

    {
        promise<bool> sent;
        thrower->throwBasB_async(1, 2,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }

    {
        promise<bool> sent;
        thrower->throwCasC_async(1, 2, 3,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }

    {
        promise<bool> sent;
        thrower->throwModA_async(1, 2,
            []()
            {
                test(false);
            },
            nullptr,
            [&](bool value)
            {
                sent.set_value(value);
            });
        sent.get_future().get(); // Wait for sent
    }
#else
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAasAPtr callback =
            newCallback_Thrower_throwAasA(cb, &Callback::response, &Callback::exception_AasA);
        thrower->begin_throwAasA(1, callback);
        cb->check();
    }
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAorDasAorDPtr callback =
            newCallback_Thrower_throwAorDasAorD(cb, &Callback::response, &Callback::exception_AorDasAorD);
        thrower->begin_throwAorDasAorD(1, callback);
        cb->check();
    }
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAorDasAorDPtr callback =
            newCallback_Thrower_throwAorDasAorD(cb, &Callback::response, &Callback::exception_AorDasAorD);
        thrower->begin_throwAorDasAorD(-1, callback);
        cb->check();
    }
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwBasBPtr callback =
            newCallback_Thrower_throwBasB(cb, &Callback::response, &Callback::exception_BasB);
        thrower->begin_throwBasB(1, 2, callback);
        cb->check();
    }
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwCasCPtr callback =
            newCallback_Thrower_throwCasC(cb, &Callback::response, &Callback::exception_CasC);
        thrower->begin_throwCasC(1, 2, 3, callback);
        cb->check();
    }
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwModAPtr callback =
            newCallback_Thrower_throwModA(cb, &Callback::response, &Callback::exception_ModA);
        thrower->begin_throwModA(1, 2, callback);
        cb->check();
    }
#endif
    cout << "ok" << endl;

    cout << "catching derived types with new AMI mapping... " << flush;
#ifdef ICE_CPP11_MAPPING
    {
        auto f = thrower->throwBasA_async(1, 2);
        try
        {
            f.get();
        }
        catch(const B& ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
        }
        catch(...)
        {
            test(false);
        }
    }

    {
        auto f = thrower->throwCasA_async(1, 2, 3);
        try
        {
            f.get();
        }
        catch(const C& ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
            test(ex.cMem == 3);
        }
        catch(...)
        {
            test(false);
        }
    }

    {
        auto f = thrower->throwCasB_async(1, 2, 3);
        try
        {
            f.get();
        }
        catch(const C& ex)
        {
            test(ex.aMem == 1);
            test(ex.bMem == 2);
            test(ex.cMem == 3);
        }
        catch(...)
        {
            test(false);
        }
    }
#else
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwBasAPtr callback =
            newCallback_Thrower_throwBasA(cb, &Callback::response, &Callback::exception_BasA);
        thrower->begin_throwBasA(1, 2, callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwCasAPtr callback =
            newCallback_Thrower_throwCasA(cb, &Callback::response, &Callback::exception_CasA);
        thrower->begin_throwCasA(1, 2, 3, callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwCasBPtr callback =
            newCallback_Thrower_throwCasB(cb, &Callback::response, &Callback::exception_CasB);
        thrower->begin_throwCasB(1, 2, 3, callback);
        cb->check();
    }
#endif
    cout << "ok" << endl;

    if(thrower->supportsUndeclaredExceptions())
    {
        cout << "catching unknown user exception with new AMI mapping... " << flush;
#ifdef ICE_CPP11_MAPPING
        {
            auto f = thrower->throwUndeclaredA_async(1);
            try
            {
                f.get();
                test(false);
            }
            catch(const Ice::UnknownUserException&)
            {
            }
            catch(const Ice::Exception& ex)
            {
                cout << ex << endl;
                cout << ex.ice_stackTrace() << endl;
                test(false);
            }
            catch(...)
            {
                test(false);
            }
        }

        {
            auto f = thrower->throwUndeclaredB_async(1, 2);
            try
            {
                f.get();
                test(false);
            }
            catch(const Ice::UnknownUserException&)
            {
            }
            catch(...)
            {
                test(false);
            }
        }

        {
            auto f = thrower->throwUndeclaredC_async(1, 2, 3);
            try
            {
                f.get();
            }
            catch(const Ice::UnknownUserException&)
            {
            }
            catch(...)
            {
                test(false);
            }
        }
#else
        {
            CallbackPtr cb = new Callback;
            Callback_Thrower_throwUndeclaredAPtr callback =
                newCallback_Thrower_throwUndeclaredA(cb, &Callback::response, &Callback::exception_UndeclaredA);
            thrower->begin_throwUndeclaredA(1, callback);
            cb->check();
        }

        {
            CallbackPtr cb = new Callback;
            Callback_Thrower_throwUndeclaredBPtr callback =
                newCallback_Thrower_throwUndeclaredB(cb, &Callback::response, &Callback::exception_UndeclaredB);
            thrower->begin_throwUndeclaredB(1, 2, callback);
            cb->check();
        }

        {
            CallbackPtr cb = new Callback;
            Callback_Thrower_throwUndeclaredCPtr callback =
                newCallback_Thrower_throwUndeclaredC(cb, &Callback::response, &Callback::exception_UndeclaredC);
            thrower->begin_throwUndeclaredC(1, 2, 3, callback);
            cb->check();
        }
#endif
        cout << "ok" << endl;
    }

    cout << "catching object not exist exception with new AMI mapping... " << flush;

    {
#ifdef ICE_CPP11_MAPPING
        id = communicator->stringToIdentity("does not exist");
        shared_ptr<ThrowerPrx> thrower2 = Ice::uncheckedCast<ThrowerPrx>(thrower->ice_identity(id));
        auto f = thrower2->throwAasA_async(1);
        try
        {
            f.get();
        }
        catch(const Ice::ObjectNotExistException& ex)
        {
            test(ex.id == id);
        }
        catch(...)
        {
            test(false);
        }
#else
        id = communicator->stringToIdentity("does not exist");
        ThrowerPrx thrower2 = ThrowerPrx::uncheckedCast(thrower->ice_identity(id));
        CallbackPtr cb = new Callback(communicator);
        Callback_Thrower_throwAasAPtr callback =
            newCallback_Thrower_throwAasA(cb, &Callback::response, &Callback::exception_AasAObjectNotExist);
        thrower2->begin_throwAasA(1, callback);
        cb->check();
#endif
    }

    cout << "ok" << endl;

    cout << "catching facet not exist exception with new AMI mapping... " << flush;

    {
#ifdef ICE_CPP11_MAPPING
        shared_ptr<ThrowerPrx> thrower2 = Ice::uncheckedCast<ThrowerPrx>(thrower, "no such facet");
        auto f = thrower2->throwAasA_async(1);
        try
        {
            f.get();
        }
        catch(const Ice::FacetNotExistException& ex)
        {
            test(ex.facet == "no such facet");
        }
#else
        ThrowerPrx thrower2 = ThrowerPrx::uncheckedCast(thrower, "no such facet");
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwAasAPtr callback =
            newCallback_Thrower_throwAasA(cb, &Callback::response, &Callback::exception_AasAFacetNotExist);
        thrower2->begin_throwAasA(1, callback);
        cb->check();
#endif
    }

    cout << "ok" << endl;

    cout << "catching operation not exist exception with new AMI mapping... " << flush;

    {
#ifdef ICE_CPP11_MAPPING
        shared_ptr<WrongOperationPrx> thrower4 = Ice::uncheckedCast<WrongOperationPrx>(thrower);
        auto f = thrower4->noSuchOperation_async();
        try
        {
            f.get();
        }
        catch(const Ice::OperationNotExistException& ex)
        {
            test(ex.operation == "noSuchOperation");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        Callback_WrongOperation_noSuchOperationPtr callback =
            newCallback_WrongOperation_noSuchOperation(cb, &Callback::response,
                                                       &Callback::exception_noSuchOperation);
        WrongOperationPrx thrower4 = WrongOperationPrx::uncheckedCast(thrower);
        thrower4->begin_noSuchOperation(callback);
        cb->check();
#endif
    }

    cout << "ok" << endl;

    cout << "catching unknown local exception with new AMI mapping... " << flush;
#ifdef ICE_CPP11_MAPPING
    {
        auto f = thrower->throwLocalException_async();
        try
        {
            f.get();
            test(false);
        }
        catch(const Ice::UnknownLocalException&)
        {
        }
        catch(...)
        {
            test(false);
        }
    }

    {
        auto f = thrower->throwLocalExceptionIdempotent_async();
        try
        {
            f.get();
            test(false);
        }
        catch(const Ice::UnknownLocalException&)
        {
        }
        catch(const Ice::OperationNotExistException&)
        {
        }
        catch(...)
        {
            test(false);
        }
    }
#else
    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwLocalExceptionPtr callback =
            newCallback_Thrower_throwLocalException(cb, &Callback::response, &Callback::exception_LocalException);
        thrower->begin_throwLocalException(callback);
        cb->check();
    }

    {
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwLocalExceptionIdempotentPtr callback =
            newCallback_Thrower_throwLocalExceptionIdempotent(cb, &Callback::response,
                                                              &Callback::exception_LocalException);
        thrower->begin_throwLocalExceptionIdempotent(callback);
        cb->check();
    }
#endif
    cout << "ok" << endl;

    cout << "catching unknown non-Ice exception with new AMI mapping... " << flush;

    {
#ifdef ICE_CPP11_MAPPING
        auto f = thrower->throwNonIceException_async();
        try
        {
            f.get();
            test(false);
        }
        catch(const Ice::UnknownException&)
        {
        }
        catch(...)
        {
            test(false);
        }

#else
        CallbackPtr cb = new Callback;
        Callback_Thrower_throwNonIceExceptionPtr callback =
            newCallback_Thrower_throwNonIceException(cb, &Callback::response, &Callback::exception_NonIceException);
        thrower->begin_throwNonIceException(callback);
        cb->check();
#endif
    }

    cout << "ok" << endl;

    return thrower;
}
Ejemplo n.º 24
0
void
allTests(const Ice::CommunicatorPtr& communicator)
{
    {
        cout << "Testing Glacier2 stub... " << flush;
        char** argv = 0;
        int argc = 0;
        SessionHelperClient client;
        client.run(argc, argv);
        cout << "ok" << endl;
    }

    {
        cout << "Testing IceStorm stub... " << flush;
        IceStorm::TopicManagerPrx manager =
                    IceStorm::TopicManagerPrx::uncheckedCast(communicator->stringToProxy("test:default -p 12010"));

        IceStorm::QoS qos;
        IceStorm::TopicPrx topic;
        string topicName = "time";

        try
        {
            topic = manager->retrieve(topicName);
            test(false);
        }
        catch(const IceStorm::NoSuchTopic&)
        {
            test(false);
        }
        catch(const Ice::LocalException&)
        {
        }

        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("subscriber" ,"tcp");
        Ice::ObjectPrx subscriber = adapter->addWithUUID(new ClockI);
        adapter->activate();
        try
        {
            topic->subscribeAndGetPublisher(qos, subscriber);
            test(false);
        }
        catch(const IceStorm::AlreadySubscribed&)
        {
            test(false);
        }
        catch(const IceUtil::NullHandleException&)
        {
        }
        cout << "ok" << endl;
    }

    {
        cout << "Testing IceGrid stub... " << flush;

        Ice::ObjectPrx base = communicator->stringToProxy("test:default -p 12010");
        IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::uncheckedCast(base);
        IceGrid::AdminSessionPrx session;
        IceGrid::AdminPrx admin;
        try
        {
            session = registry->createAdminSession("username", "password");
            test(false);
        }
        catch(const IceGrid::PermissionDeniedException&)
        {
            test(false);
        }
        catch(const Ice::LocalException&)
        {
        }

        try
        {
            admin = session->getAdmin();
            test(false);
        }
        catch(const IceUtil::NullHandleException&)
        {
        }
        cout << "ok" << endl;
    }
}
Ejemplo n.º 25
0
void main()
{
	Ice::InitializationData initData;
	initData.properties = Ice::createProperties();
	initData.properties->setProperty("Ice.MessageSizeMax", "102400" );//默认是1024,单位KB
	initData.properties->setProperty("Ice.ThreadPool.Server.Size", "1");
	initData.properties->setProperty("Ice.ThreadPool.Server.SizeMax", "1000" );
	initData.properties->setProperty("Ice.ThreadPool.Server.SizeWarn", "1024");
	Ice::CommunicatorPtr communicatorPtr = Ice::initialize(initData);

	char szStormHost[100]={0};
	char szStromPort[10]={0};

	char szDir[MAX_PATH] = {0};
	GetModuleFileName(NULL,szDir,MAX_PATH);
	string strIniFile = szDir;
	strIniFile = strIniFile.substr(0,strIniFile.length()-3) + "ini";

	GetPrivateProfileString("NewsPub","StormHost","localhost",szStormHost,100,strIniFile.c_str());
	WritePrivateProfileString("NewsPub","StormHost",szStormHost,strIniFile.c_str());

	GetPrivateProfileString("NewsPub","StromPort","10000",szStromPort,100,strIniFile.c_str());
	WritePrivateProfileString("NewsPub","StromPort",szStromPort,strIniFile.c_str());

	char szStr[1000]={0};
	sprintf_s(szStr,"StormNewsDemo/TopicManager:tcp -h %s -p %s",szStormHost,szStromPort);

	// icestorm的地址"StormNewsDemo/TopicManager:tcp -h xiangzhenwei.peraportal.com -p 10000"
	IceStorm::TopicManagerPrx manager = NULL;
	try
	{
		manager = IceStorm::TopicManagerPrx::checkedCast(communicatorPtr->stringToProxy(szStr));
	}
	catch (const Ice::Exception &e)
	{
		cerr << e.what();
		return;
	}

	if(!manager)
	{
		cerr << "NewsSub.exe" << ": invalid proxy" << endl;
		return;
	}

	IceStorm::TopicPrx topic;
	try
	{  
		topic = manager->retrieve("news");
	}
	catch(const IceStorm::NoSuchTopic&)
	{
		try
		{
			topic = manager->create("news");
		}
		catch(const IceStorm::TopicExists&)
		{
			cerr << "NewsSub.exe" << ": temporary failure. try again." << endl;
			return;
		}
	}
	// 接收端监听消息的地址"tcp -h 0.0.0.0:udp -h 0.0.0.0"
	string strEndPoint = "tcp -h 0.0.0.0:udp -h 0.0.0.0";
	Ice::ObjectAdapterPtr adapter = communicatorPtr->createObjectAdapterWithEndpoints("News.Subscriber", strEndPoint );

	//
	// Add a servant for the Ice object. If --id is used the identity
	// comes from the command line, otherwise a UUID is used.
	//
	// id is not directly altered since it is used below to detect
	// whether subscribeAndGetPublisher can raise AlreadySubscribed.
	//
	Ice::Identity subId;
	subId.name = IceUtil::generateUUID();
	Ice::ObjectPrx subscriber = adapter->add(new NewsI, subId);
	g_strClientId = subId.name;

	Ice::CommunicatorPtr communicatorPtr2 = InitCommunicator();
	char szEndPoints[1000]={0};
	sprintf_s(szEndPoints,"Pera601DemoServerService:tcp -h %s -p %s -t 5000", szStormHost, "20131");
	try
	{
		PcIdToWsServerPrx m_pPrx = PcIdToWsServerPrx::checkedCast(communicatorPtr2->stringToProxy(szEndPoints));
		m_pPrx = m_pPrx->ice_twoway()->ice_timeout(20000)->ice_secure(false);
		m_pPrx->TellClientId(subId.name);	 	
	}
	catch(const Ice::Exception& ex)
	{
		printf("远程调用服务端失败,ICE异常:%s", ex.ice_name().c_str());
		return;
	}


	//
	// Activate the object adapter before subscribing.
	//
	adapter->activate();
	subscriber = subscriber->ice_oneway();
	 IceStorm::QoS qos;
	 qos["retryCount"] = 3;

	try
	{
		topic->subscribeAndGetPublisher(qos, subscriber);
	}
	catch(const IceStorm::AlreadySubscribed&)
	{
		// If we're manually setting the subscriber id ignore.
		cout << "reactivating persistent subscriber" << endl;
	}

	communicatorPtr->waitForShutdown();
	topic->unsubscribe(subscriber);
}
Ejemplo n.º 26
0
TestIntfPrxPtr
allTests(const Ice::CommunicatorPtr& communicator)
{
    Ice::ObjectPrxPtr obj = communicator->stringToProxy("Test:" + getTestEndpoint(communicator, 0));
    TestIntfPrxPtr test = ICE_CHECKED_CAST(TestIntfPrx, obj);

    cout << "base... " << flush;
    {
        try
        {
            test->baseAsBase();
            test(false);
        }
        catch(const Base& b)
        {
            test(b.b == "Base.b");
            test(b.ice_id() == "::Test::Base");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "base (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->baseAsBase_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const Base& b)
        {
            test(b.b == "Base.b");
            test(b.ice_id() == "::Test::Base");
        }
        catch(...)
        {
            test(false);
        }
            
#else
        CallbackPtr cb = new Callback;
        test->begin_baseAsBase(
            newCallback_TestIntf_baseAsBase(cb, &Callback::response, &Callback::exception_baseAsBase));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "slicing of unknown derived... " << flush;
    {
        try
        {
            test->unknownDerivedAsBase();
            test(false);
        }
        catch(const Base& b)
        {
            test(b.b == "UnknownDerived.b");
            test(b.ice_id() == "::Test::Base");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "slicing of unknown derived (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->unknownDerivedAsBase_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const Base& b)
        {
            test(b.b == "UnknownDerived.b");
            test(b.ice_id() == "::Test::Base");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_unknownDerivedAsBase(
            newCallback_TestIntf_unknownDerivedAsBase(cb, &Callback::response,
                                                      &Callback::exception_unknownDerivedAsBase));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "non-slicing of known derived as base... " << flush;
    {
        try
        {
            test->knownDerivedAsBase();
            test(false);
        }
        catch(const KnownDerived& k)
        {
            test(k.b == "KnownDerived.b");
            test(k.kd == "KnownDerived.kd");
            test(k.ice_id() == "::Test::KnownDerived");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "non-slicing of known derived as base (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->knownDerivedAsBase_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const KnownDerived& k)
        {
            test(k.b == "KnownDerived.b");
            test(k.kd == "KnownDerived.kd");
            test(k.ice_id() == "::Test::KnownDerived");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_knownDerivedAsBase(
            newCallback_TestIntf_knownDerivedAsBase(cb, &Callback::response, &Callback::exception_knownDerivedAsBase));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "non-slicing of known derived as derived... " << flush;
    {
        try
        {
            test->knownDerivedAsKnownDerived();
            test(false);
        }
        catch(const KnownDerived& k)
        {
            test(k.b == "KnownDerived.b");
            test(k.kd == "KnownDerived.kd");
            test(k.ice_id() == "::Test::KnownDerived");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "non-slicing of known derived as derived (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->knownDerivedAsKnownDerived_async();
        try
        {
            result.get();
        }
        catch(const KnownDerived& k)
        {
            test(k.b == "KnownDerived.b");
            test(k.kd == "KnownDerived.kd");
            test(k.ice_id() == "::Test::KnownDerived");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_knownDerivedAsKnownDerived(
            newCallback_TestIntf_knownDerivedAsKnownDerived(cb, &Callback::response, 
                                                            &Callback::exception_knownDerivedAsKnownDerived));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "slicing of unknown intermediate as base... " << flush;
    {
        try
        {
            test->unknownIntermediateAsBase();
            test(false);
        }
        catch(const Base& b)
        {
            test(b.b == "UnknownIntermediate.b");
            test(b.ice_id() == "::Test::Base");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "slicing of unknown intermediate as base (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->unknownIntermediateAsBase_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const Base& b)
        {
            test(b.b == "UnknownIntermediate.b");
            test(b.ice_id() == "::Test::Base");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_unknownIntermediateAsBase(
            newCallback_TestIntf_unknownIntermediateAsBase(cb, &Callback::response, 
                                                           &Callback::exception_unknownIntermediateAsBase));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "slicing of known intermediate as base... " << flush;
    {
        try
        {
            test->knownIntermediateAsBase();
            test(false);
        }
        catch(const KnownIntermediate& ki)
        {
            test(ki.b == "KnownIntermediate.b");
            test(ki.ki == "KnownIntermediate.ki");
            test(ki.ice_id() == "::Test::KnownIntermediate");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "slicing of known intermediate as base (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->knownIntermediateAsBase_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const KnownIntermediate& ki)
        {
            test(ki.b == "KnownIntermediate.b");
            test(ki.ki == "KnownIntermediate.ki");
            test(ki.ice_id() == "::Test::KnownIntermediate");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_knownIntermediateAsBase(
            newCallback_TestIntf_knownIntermediateAsBase(cb, &Callback::response, 
                                                         &Callback::exception_knownIntermediateAsBase));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "slicing of known most derived as base... " << flush;
    {
        try
        {
            test->knownMostDerivedAsBase();
            test(false);
        }
        catch(const KnownMostDerived& kmd)
        {
            test(kmd.b == "KnownMostDerived.b");
            test(kmd.ki == "KnownMostDerived.ki");
            test(kmd.kmd == "KnownMostDerived.kmd");
            test(kmd.ice_id() == "::Test::KnownMostDerived");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "slicing of known most derived as base (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->knownMostDerivedAsBase_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const KnownMostDerived& kmd)
        {
            test(kmd.b == "KnownMostDerived.b");
            test(kmd.ki == "KnownMostDerived.ki");
            test(kmd.kmd == "KnownMostDerived.kmd");
            test(kmd.ice_id() == "::Test::KnownMostDerived");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_knownMostDerivedAsBase(
            newCallback_TestIntf_knownMostDerivedAsBase(cb, &Callback::response, 
                                                        &Callback::exception_knownMostDerivedAsBase));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "non-slicing of known intermediate as intermediate... " << flush;
    {
        try
        {
            test->knownIntermediateAsKnownIntermediate();
            test(false);
        }
        catch(const KnownIntermediate& ki)
        {
            test(ki.b == "KnownIntermediate.b");
            test(ki.ki == "KnownIntermediate.ki");
            test(ki.ice_id() == "::Test::KnownIntermediate");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "non-slicing of known intermediate as intermediate (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->knownIntermediateAsKnownIntermediate_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const KnownIntermediate& ki)
        {
            test(ki.b == "KnownIntermediate.b");
            test(ki.ki == "KnownIntermediate.ki");
            test(ki.ice_id() == "::Test::KnownIntermediate");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_knownIntermediateAsKnownIntermediate(
            newCallback_TestIntf_knownIntermediateAsKnownIntermediate(cb, &Callback::response, 
                                                        &Callback::exception_knownIntermediateAsKnownIntermediate));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "non-slicing of known most derived exception as intermediate... " << flush;
    {
        try
        {
            test->knownMostDerivedAsKnownIntermediate();
            test(false);
        }
        catch(const KnownMostDerived& kmd)
        {
            test(kmd.b == "KnownMostDerived.b");
            test(kmd.ki == "KnownMostDerived.ki");
            test(kmd.kmd == "KnownMostDerived.kmd");
            test(kmd.ice_id() == "::Test::KnownMostDerived");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "non-slicing of known most derived as intermediate (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->knownMostDerivedAsKnownIntermediate_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const KnownMostDerived& kmd)
        {
            test(kmd.b == "KnownMostDerived.b");
            test(kmd.ki == "KnownMostDerived.ki");
            test(kmd.kmd == "KnownMostDerived.kmd");
            test(kmd.ice_id() == "::Test::KnownMostDerived");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_knownMostDerivedAsKnownIntermediate(
            newCallback_TestIntf_knownMostDerivedAsKnownIntermediate(cb, &Callback::response, 
                                                        &Callback::exception_knownMostDerivedAsKnownIntermediate));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "non-slicing of known most derived as most derived... " << flush;
    {
        try
        {
            test->knownMostDerivedAsKnownMostDerived();
            test(false);
        }
        catch(const KnownMostDerived& kmd)
        {
            test(kmd.b == "KnownMostDerived.b");
            test(kmd.ki == "KnownMostDerived.ki");
            test(kmd.kmd == "KnownMostDerived.kmd");
            test(kmd.ice_id() == "::Test::KnownMostDerived");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "non-slicing of known most derived as most derived (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->knownMostDerivedAsKnownMostDerived_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const KnownMostDerived& kmd)
        {
            test(kmd.b == "KnownMostDerived.b");
            test(kmd.ki == "KnownMostDerived.ki");
            test(kmd.kmd == "KnownMostDerived.kmd");
            test(kmd.ice_id() == "::Test::KnownMostDerived");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_knownMostDerivedAsKnownMostDerived(
            newCallback_TestIntf_knownMostDerivedAsKnownMostDerived(cb, &Callback::response, 
                                                        &Callback::exception_knownMostDerivedAsKnownMostDerived));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "slicing of unknown most derived, known intermediate as base... " << flush;
    {
        try
        {
            test->unknownMostDerived1AsBase();
            test(false);
        }
        catch(const KnownIntermediate& ki)
        {
            test(ki.b == "UnknownMostDerived1.b");
            test(ki.ki == "UnknownMostDerived1.ki");
            test(ki.ice_id() == "::Test::KnownIntermediate");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "slicing of unknown most derived, known intermediate as base (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->unknownMostDerived1AsBase_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const KnownIntermediate& ki)
        {
            test(ki.b == "UnknownMostDerived1.b");
            test(ki.ki == "UnknownMostDerived1.ki");
            test(ki.ice_id() == "::Test::KnownIntermediate");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_unknownMostDerived1AsBase(
            newCallback_TestIntf_unknownMostDerived1AsBase(cb, &Callback::response, 
                                                           &Callback::exception_unknownMostDerived1AsBase));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "slicing of unknown most derived, known intermediate as intermediate... " << flush;
    {
        try
        {
            test->unknownMostDerived1AsKnownIntermediate();
            test(false);
        }
        catch(const KnownIntermediate& ki)
        {
            test(ki.b == "UnknownMostDerived1.b");
            test(ki.ki == "UnknownMostDerived1.ki");
            test(ki.ice_id() == "::Test::KnownIntermediate");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "slicing of unknown most derived, known intermediate as intermediate (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->unknownMostDerived1AsKnownIntermediate_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const KnownIntermediate& ki)
        {
            test(ki.b == "UnknownMostDerived1.b");
            test(ki.ki == "UnknownMostDerived1.ki");
            test(ki.ice_id() == "::Test::KnownIntermediate");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_unknownMostDerived1AsKnownIntermediate(
            newCallback_TestIntf_unknownMostDerived1AsKnownIntermediate(cb, &Callback::response, 
                                                         &Callback::exception_unknownMostDerived1AsKnownIntermediate));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "slicing of unknown most derived, unknown intermediate as base... " << flush;
    {
        try
        {
            test->unknownMostDerived2AsBase();
            test(false);
        }
        catch(const Base& b)
        {
            test(b.b == "UnknownMostDerived2.b");
            test(b.ice_id() == "::Test::Base");
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "slicing of unknown most derived, unknown intermediate as base (AMI)... " << flush;
    {
#ifdef ICE_CPP11_MAPPING
        auto result = test->unknownMostDerived2AsBase_async();
        try
        {
            result.get();
            test(false);
        }
        catch(const Base& b)
        {
            test(b.b == "UnknownMostDerived2.b");
            test(b.ice_id() == "::Test::Base");
        }
        catch(...)
        {
            test(false);
        }
#else
        CallbackPtr cb = new Callback;
        test->begin_unknownMostDerived2AsBase(
            newCallback_TestIntf_unknownMostDerived2AsBase(cb, &Callback::response, 
                                                         &Callback::exception_unknownMostDerived2AsBase));
        cb->check();
#endif
    }
    cout << "ok" << endl;

    cout << "unknown most derived in compact format... " << flush;
    {
        try
        {
            test->unknownMostDerived2AsBaseCompact();
            test(false);
        }
        catch(const Base&)
        {
            //
            // For the 1.0 encoding, the unknown exception is sliced to Base.
            //
            test(test->ice_getEncodingVersion() == Ice::Encoding_1_0);
        }
        catch(const Ice::UnknownUserException&)
        {
            //
            // An UnknownUserException is raised for the compact format because the
            // most-derived type is unknown and the exception cannot be sliced.
            //
            test(test->ice_getEncodingVersion() != Ice::Encoding_1_0);
        }
        catch(const Ice::OperationNotExistException&)
        {
        }
        catch(...)
        {
            test(false);
        }
    }
    cout << "ok" << endl;

    cout << "preserved exceptions... " << flush;
    string localOAEndpoint;
    {
        ostringstream ostr;
        if(communicator->getProperties()->getProperty("Ice.Default.Protocol") == "bt")
        {
            ostr << "default -a *";
        }
        else
        {
            ostr << "default -h *";
        }
        localOAEndpoint = ostr.str();
    }
    {
        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("Relay", localOAEndpoint);
        RelayPrxPtr relay = ICE_UNCHECKED_CAST(RelayPrx, adapter->addWithUUID(ICE_MAKE_SHARED(RelayI)));
        adapter->activate();

        try
        {
            test->relayKnownPreservedAsBase(relay);
            test(false);
        }
        catch(const KnownPreservedDerived& ex)
        {
            test(ex.b == "base");
            test(ex.kp == "preserved");
            test(ex.kpd == "derived");
        }
        catch(const Ice::OperationNotExistException&)
        {
        }
    catch(const Ice::LocalException& ex)
    {
        cout << endl << "** OOPS" << endl << ex << endl;
        test(false);
    }
        catch(...)
        {
            test(false);
        }

        try
        {
            test->relayKnownPreservedAsKnownPreserved(relay);
            test(false);
        }
        catch(const KnownPreservedDerived& ex)
        {
            test(ex.b == "base");
            test(ex.kp == "preserved");
            test(ex.kpd == "derived");
        }
        catch(const Ice::OperationNotExistException&)
        {
        }
        catch(...)
        {
            test(false);
        }

        try
        {
            test->relayUnknownPreservedAsBase(relay);
            test(false);
        }
        catch(const Preserved2& ex)
        {
            test(ex.b == "base");
            test(ex.kp == "preserved");
            test(ex.kpd == "derived");
            test(ex.p1->ice_id() == PreservedClass::ice_staticId());
            PreservedClassPtr pc = ICE_DYNAMIC_CAST(PreservedClass, ex.p1);
            test(pc->bc == "bc");
            test(pc->pc == "pc");
            test(ex.p2 == ex.p1);
        }
        catch(const Ice::OperationNotExistException&)
        {
        }
        catch(const KnownPreservedDerived& ex)
        {
            //
            // For the 1.0 encoding, the unknown exception is sliced to KnownPreserved.
            //
            test(test->ice_getEncodingVersion() == Ice::Encoding_1_0);
            test(ex.b == "base");
            test(ex.kp == "preserved");
            test(ex.kpd == "derived");
        }
        catch(...)
        {
            test(false);
        }

        try
        {
            test->relayUnknownPreservedAsKnownPreserved(relay);
            test(false);
        }
        catch(const Ice::OperationNotExistException&)
        {
        }
        catch(const Preserved2& ex)
        {
            test(ex.b == "base");
            test(ex.kp == "preserved");
            test(ex.kpd == "derived");
            test(ex.p1->ice_id() == PreservedClass::ice_staticId());
            PreservedClassPtr pc = ICE_DYNAMIC_CAST(PreservedClass, ex.p1);
            test(pc->bc == "bc");
            test(pc->pc == "pc");
            test(ex.p2 == ex.p1);
        }
        catch(const KnownPreservedDerived& ex)
        {
            //
            // For the 1.0 encoding, the unknown exception is sliced to KnownPreserved.
            //
            test(test->ice_getEncodingVersion() == Ice::Encoding_1_0);
            test(ex.b == "base");
            test(ex.kp == "preserved");
            test(ex.kpd == "derived");
        }
        catch(...)
        {
            test(false);
        }

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

    return test;
}
Ejemplo n.º 27
0
void
allTests(const Ice::CommunicatorPtr& communicator)
{
    {
        cout << "Testing Glacier2 stub... " << flush;
        char** argv = 0;
        int argc = 0;
        SessionHelperClient client;
        client.run(argc, argv);
        cout << "ok" << endl;
    }

    {
        cout << "Testing IceStorm stub... " << flush;
        IceStorm::TopicManagerPrxPtr manager =
                    ICE_UNCHECKED_CAST(IceStorm::TopicManagerPrx, communicator->stringToProxy("test:default -p 12010"));

        IceStorm::QoS qos;
        IceStorm::TopicPrxPtr topic;
        string topicName = "time";

        try
        {
            topic = manager->retrieve(topicName);
            test(false);
        }
        catch(const IceStorm::NoSuchTopic&)
        {
            test(false);
        }
        catch(const Ice::LocalException&)
        {
        }

        Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("subscriber" ,"tcp");
        Ice::ObjectPrxPtr subscriber = adapter->addWithUUID(ICE_MAKE_SHARED(ClockI));
        adapter->activate();
#ifdef ICE_CPP11_MAPPING
        assert(!topic);
#else
        try
        {
            topic->subscribeAndGetPublisher(qos, subscriber);
            test(false);
        }
        catch(const IceStorm::AlreadySubscribed&)
        {
            test(false);
        }
        catch(const IceUtil::NullHandleException&)
        {
        }
#endif
        cout << "ok" << endl;
    }

    {
        cout << "Testing IceGrid stub... " << flush;

        Ice::ObjectPrxPtr base = communicator->stringToProxy("test:default -p 12010");
        IceGrid::RegistryPrxPtr registry = ICE_UNCHECKED_CAST(IceGrid::RegistryPrx, base);
        IceGrid::AdminSessionPrxPtr session;
        IceGrid::AdminPrxPtr admin;
        try
        {
            session = registry->createAdminSession("username", "password");
            test(false);
        }
        catch(const IceGrid::PermissionDeniedException&)
        {
            test(false);
        }
        catch(const Ice::LocalException&)
        {
        }
#ifdef ICE_CPP11_MAPPING
        assert(!admin);
#else
        try
        {
            admin = session->getAdmin();
            test(false);
        }
        catch(const IceUtil::NullHandleException&)
        {
        }
#endif
        cout << "ok" << endl;
    }
}
Ejemplo n.º 28
0
void
allTests(const Ice::CommunicatorPtr& communicator)
{
    Ice::ObjectAdapterPtr oa = communicator->createObjectAdapterWithEndpoints("MyOA", "tcp -h localhost");
    oa->activate();

    Ice::ObjectPtr servant = ICE_MAKE_SHARED(MyObjectI);

    //
    // Register default servant with category "foo"
    //
    oa->addDefaultServant(servant, "foo");

    //
    // Start test
    //
    cout << "testing single category... " << flush;

    Ice::ObjectPtr r = oa->findDefaultServant("foo");
    test(r == servant);

    r = oa->findDefaultServant("bar");
    test(r == 0);

    Ice::Identity identity;
    identity.category = "foo";

    string names[] = { "foo", "bar", "x", "y", "abcdefg" };

    int idx;

    for(idx = 0; idx < 5; ++idx)
    {
        identity.name = names[idx];
        MyObjectPrxPtr prx = ICE_UNCHECKED_CAST(MyObjectPrx, oa->createProxy(identity));
        prx->ice_ping();
        test(prx->getName() == names[idx]);
    }

    identity.name = "ObjectNotExist";
    MyObjectPrxPtr prx = ICE_UNCHECKED_CAST(MyObjectPrx, oa->createProxy(identity));
    try
    {
        prx->ice_ping();
        test(false);
    }
    catch(const Ice::ObjectNotExistException&)
    {
        // Expected
    }

    try
    {
        prx->getName();
        test(false);
    }
    catch(const Ice::ObjectNotExistException&)
    {
        // Expected
    }

    identity.name = "FacetNotExist";
    prx = ICE_UNCHECKED_CAST(MyObjectPrx, oa->createProxy(identity));
    try
    {
        prx->ice_ping();
        test(false);
    }
    catch(const Ice::FacetNotExistException&)
    {
        // Expected
    }

    try
    {
        prx->getName();
        test(false);
    }
    catch(const Ice::FacetNotExistException&)
    {
        // Expected
    }

    identity.category = "bar";
    for(idx = 0; idx < 5; idx++)
    {
        identity.name = names[idx];
        prx = ICE_UNCHECKED_CAST(MyObjectPrx, oa->createProxy(identity));

        try
        {
            prx->ice_ping();
            test(false);
        }
        catch(const Ice::ObjectNotExistException&)
        {
            // Expected
        }

        try
        {
            prx->getName();
            test(false);
        }
        catch(const Ice::ObjectNotExistException&)
        {
            // Expected
        }
    }

    oa->removeDefaultServant("foo");
    identity.category = "foo";
    prx = ICE_UNCHECKED_CAST(MyObjectPrx, oa->createProxy(identity));
    try
    {
        prx->ice_ping();
    }
    catch(const Ice::ObjectNotExistException&)
    {
        // Expected
    }

    cout << "ok" << endl;

    cout << "testing default category... " << flush;

    oa->addDefaultServant(servant, "");

    r = oa->findDefaultServant("bar");
    test(r == 0);

    r = oa->findDefaultServant("");
    test(r == servant);

    for(idx = 0; idx < 5; ++idx)
    {
        identity.name = names[idx];
        prx = ICE_UNCHECKED_CAST(MyObjectPrx, oa->createProxy(identity));
        prx->ice_ping();
        test(prx->getName() == names[idx]);
    }

    cout << "ok" << endl;
}
Ejemplo n.º 29
0
int main(int argc , char* argv[])
{
	const bfs::path binPath(argv[0]);
	const bfs::path& homePath = system_complete(binPath).parent_path().parent_path();
	cout<<homePath.string();
	bpo::options_description desc("msgWait allowed options");
	desc.add_options()
		("help", "help message")
		("log_conf", bpo::value<string>(), "log4cplus configure file")
		("server_id", bpo::value<int>(), "The server id")
		("service_port", bpo::value<short>(), "The endpoint ice service port")
		("domain", bpo::value<string>(), "The server endpoint domain")
		("zk_servers", bpo::value<string>(), "The zookeeper servers list split with ','");

	string logConf;
	string domain;

	bpo::variables_map vm;
	string configFile = homePath.string() + "/conf/msgWait_config.cfg";
	ifstream configIFS(configFile.c_str());
	bpo::store(bpo::parse_config_file(configIFS, desc), vm);
	bpo::notify(vm);

	if(vm.count("help")){
		cout << desc << endl;
		return 0;
	}
	if(vm.count("log_conf")){
		logConf = vm["log_conf"].as<string>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("server_id")){
		serverId = vm["server_id"].as<int>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("service_port")){
		servicePort = vm["service_port"].as<short>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("domain")){
		domain = vm["domain"].as<string>();
	} else {
		cout << desc << endl;
		return 0;
	}
	if(vm.count("zk_servers")){
		zkServers = vm["zk_servers"].as<string>();
	} else {
		cout << desc << endl;
		return 0;
	}

	//configure log4cplus
	ConfigureAndWatchThread configureThread(LOG4CPLUS_TEXT(logConf), 5 * 1000);

	boost::shared_ptr<MessageWaitManager> messageWaitManagerPtr(new MessageWaitManager);
	messageWaitManagerPtr->init(serverId, servicePort, domain, zkServers);
	messageWaitManagerPtr->start();
    
    // init whitelist
    mtalk::utils::wl::InitWhiteList();

	Ice::CommunicatorPtr ic;

	try{
		ic = Ice::initialize();
		ostringstream os;
		os << "default -p " << servicePort;
		Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("TalkAdapter", os.str());
		Ice::ObjectPtr object = new msgwait::MessageWaitManagerServiceI( messageWaitManagerPtr );
		adapter->add(object, ic->stringToIdentity("MessageWaitManagerService"));
		adapter->activate();
		LOG_INFO("main => endpoint server started");
		cout << "==== Server Started ====" << endl;
		ic->waitForShutdown();
	} catch (const Ice::Exception& e) {
		cout << e << endl;
	} catch (const char* msg){
		cout << msg << endl;
	}
	messageWaitManagerPtr->stop();
	if(ic){
		ic->destroy();
	}

	return 0;
}