NodeI::NodeI(const Ice::ObjectAdapterPtr& adapter, NodeSessionManager& sessions, const ActivatorPtr& activator, const IceUtil::TimerPtr& timer, const TraceLevelsPtr& traceLevels, const NodePrx& proxy, const string& name, const UserAccountMapperPrx& mapper, const string& instanceName) : _communicator(adapter->getCommunicator()), _adapter(adapter), _sessions(sessions), _activator(activator), _timer(timer), _traceLevels(traceLevels), _name(name), _proxy(proxy), _redirectErrToOut(false), _allowEndpointsOverride(false), _waitTime(0), _instanceName(instanceName), _userAccountMapper(mapper), _platform("IceGrid.Node", _communicator, _traceLevels), _fileCache(new FileCache(_communicator)), _serial(1), _consistencyCheckDone(false) { Ice::PropertiesPtr props = _communicator->getProperties(); const_cast<string&>(_dataDir) = _platform.getDataDir(); const_cast<string&>(_serversDir) = _dataDir + "/servers"; const_cast<string&>(_tmpDir) = _dataDir + "/tmp"; const_cast<Ice::Int&>(_waitTime) = props->getPropertyAsIntWithDefault("IceGrid.Node.WaitTime", 60); const_cast<string&>(_outputDir) = props->getProperty("IceGrid.Node.Output"); const_cast<bool&>(_redirectErrToOut) = props->getPropertyAsInt("IceGrid.Node.RedirectErrToOut") > 0; const_cast<bool&>(_allowEndpointsOverride) = props->getPropertyAsInt("IceGrid.Node.AllowEndpointsOverride") > 0; // // Parse the properties override property. // vector<string> overrides = props->getPropertyAsList("IceGrid.Node.PropertiesOverride"); if(!overrides.empty()) { for(vector<string>::iterator p = overrides.begin(); p != overrides.end(); ++p) { if(p->find("--") != 0) { *p = "--" + *p; } } Ice::PropertiesPtr p = Ice::createProperties(); p->parseCommandLineOptions("", overrides); Ice::PropertyDict propDict = p->getPropertiesForPrefix(""); for(Ice::PropertyDict::const_iterator q = propDict.begin(); q != propDict.end(); ++q) { _propertiesOverride.push_back(createProperty(q->first, q->second)); } } }
TrustManager::TrustManager(const Ice::CommunicatorPtr& communicator) : _communicator(communicator) { Ice::PropertiesPtr properties = communicator->getProperties(); _traceLevel = properties->getPropertyAsInt("IceSSL.Trace.Security"); string key; try { key = "IceSSL.TrustOnly"; _all = parse(properties->getProperty(key)); key = "IceSSL.TrustOnly.Client"; _client = parse(properties->getProperty(key)); key = "IceSSL.TrustOnly.Server"; _allServer = parse(properties->getProperty(key)); Ice::PropertyDict dict = properties->getPropertiesForPrefix("IceSSL.TrustOnly.Server."); for(Ice::PropertyDict::const_iterator p = dict.begin(); p != dict.end(); ++p) { string name = p->first.substr(string("IceSSL.TrustOnly.Server.").size()); key = p->first; _server[name] = parse(p->second); } } catch(const ParseException& e) { Ice::PluginInitializationException ex(__FILE__, __LINE__); ex.reason = "IceSSL: invalid property " + key + ":\n" + e.reason; throw ex; } }
LaserI::LaserI(Ice::PropertiesPtr prop) { std::string model = prop->getProperty("Laser.Model"); if ("Hokuyo"==model || "hokuyo"==model){ std::string deviceId = prop->getProperty("Laser.DeviceId"); double min = (double)prop->getPropertyAsInt("Laser.MinAng"); double max = (double)prop->getPropertyAsInt("Laser.MaxAng"); int clustering = prop->getPropertyAsInt("Laser.Clustering"); int faceup = prop->getPropertyAsInt("Laser.FaceUp"); double min_ang = min*M_PI/180; double max_ang = max*M_PI/180; this->manager = new hokuyo::HokuyoManager(deviceId, min_ang, max_ang, clustering, -1, faceup); }else{ throw std::invalid_argument( model + " laser is not allowed" ); } }
TraceLevels::TraceLevels(const string name, const Ice::PropertiesPtr& properties, const Ice::LoggerPtr& theLogger) : topicMgr(0), topicMgrCat("TopicManager"), topic(0), topicCat("Topic"), subscriber(0), subscriberCat("Subscriber"), election(0), electionCat("Election"), replication(0), replicationCat("Replication"), logger(theLogger) { const string keyBase = name + ".Trace."; const_cast<int&>(topicMgr) = properties->getPropertyAsInt(keyBase + topicMgrCat); const_cast<int&>(topic) = properties->getPropertyAsInt(keyBase + topicCat); const_cast<int&>(subscriber) = properties->getPropertyAsInt(keyBase + subscriberCat); const_cast<int&>(election) = properties->getPropertyAsInt(keyBase + electionCat); }
int Server::run(int argc, char* argv[]) { Ice::StringSeq args = Ice::argsToStringSeq(argc, argv); Ice::PropertiesPtr properties = communicator()->getProperties(); args = properties->parseCommandLineOptions("", args); Ice::stringSeqToArgs(args, argc, argv); if(properties->getPropertyAsInt("FailOnStartup") > 0) { return EXIT_FAILURE; } Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("TestAdapter"); TestI* test = new TestI(); Ice::ObjectPtr obj = test; adapter->add(test, communicator()->stringToIdentity(properties->getProperty("Ice.Admin.ServerId"))); int delay = properties->getPropertyAsInt("ActivationDelay"); if(delay > 0) { IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(delay)); } shutdownOnInterrupt(); try { adapter->activate(); } catch(const Ice::ObjectAdapterDeactivatedException&) { } communicator()->waitForShutdown(); ignoreInterrupt(); delay = properties->getPropertyAsInt("DeactivationDelay"); if(delay > 0) { IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(delay)); } return test->isFailed() ? EXIT_FAILURE : EXIT_SUCCESS; }
int LibraryServer::run(int argc, char*[]) { if(argc > 1) { cerr << appName() << ": too many arguments" << endl; return EXIT_FAILURE; } Ice::PropertiesPtr properties = communicator()->getProperties(); // // Create an object adapter // Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Library"); // // Create an evictor for books. // Freeze::EvictorPtr evictor = Freeze::createBackgroundSaveEvictor(adapter, _envName, "books"); Ice::Int evictorSize = properties->getPropertyAsInt("EvictorSize"); if(evictorSize > 0) { evictor->setSize(evictorSize); } // // Use the evictor as servant Locator. // adapter->addServantLocator(evictor, "book"); // // Create the library, and add it to the object adapter. // LibraryIPtr library = new LibraryI(communicator(), _envName, "authors", evictor); adapter->add(library, Ice::stringToIdentity("library")); // // Create and install a factory for books. // Ice::ValueFactoryPtr bookFactory = new BookFactory(library); communicator()->getValueFactoryManager()->add(bookFactory, Demo::Book::ice_staticId()); // // Everything ok, let's go. // shutdownOnInterrupt(); adapter->activate(); communicator()->waitForShutdown(); ignoreInterrupt(); return EXIT_SUCCESS; }
TraceLevels::TraceLevels(const Ice::CommunicatorPtr& communicator, const string& prefix) : admin(0), adminCat("Admin"), application(0), applicationCat("Application"), node(0), nodeCat("Node"), replica(0), replicaCat("Replica"), server(0), serverCat("Server"), adapter(0), adapterCat("Adapter"), object(0), objectCat("Object"), activator(0), activatorCat("Activator"), patch(0), patchCat("Patch"), locator(0), locatorCat("Locator"), session(0), sessionCat("Session"), logger(communicator->getLogger()) { Ice::PropertiesPtr properties = communicator->getProperties(); string keyBase = prefix + ".Trace."; const_cast<int&>(admin) = properties->getPropertyAsInt(keyBase + adminCat); const_cast<int&>(application) = properties->getPropertyAsInt(keyBase + applicationCat); const_cast<int&>(node) = properties->getPropertyAsInt(keyBase + nodeCat); const_cast<int&>(replica) = properties->getPropertyAsInt(keyBase + replicaCat); const_cast<int&>(server) = properties->getPropertyAsInt(keyBase + serverCat); const_cast<int&>(adapter) = properties->getPropertyAsInt(keyBase + adapterCat); const_cast<int&>(object) = properties->getPropertyAsInt(keyBase + objectCat); const_cast<int&>(activator) = properties->getPropertyAsInt(keyBase + activatorCat); const_cast<int&>(patch) = properties->getPropertyAsInt(keyBase + patchCat); const_cast<int&>(locator) = properties->getPropertyAsInt(keyBase + locatorCat); const_cast<int&>(session) = properties->getPropertyAsInt(keyBase + sessionCat); }
void ServiceI::start(const string& name, const CommunicatorPtr& communicator, const StringSeq& args) { Ice::PropertiesPtr properties = communicator->getProperties(); Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter(name); if(properties->getPropertyAsInt(name + ".Freeze") > 0) { // // We do this to ensure the dbenv directory exists. // Freeze::createConnection(communicator, name); } Ice::ObjectPtr object = new TestI(adapter, properties); adapter->add(object, communicator->stringToIdentity(properties->getProperty(name + ".Identity"))); adapter->activate(); }
TrustManager::TrustManager(const Ice::CommunicatorPtr& communicator) : _communicator(communicator) { Ice::PropertiesPtr properties = communicator->getProperties(); _traceLevel = properties->getPropertyAsInt("IceSSL.Trace.Security"); string key; try { key = "IceSSL.TrustOnly"; parse(properties->getProperty(key), _rejectAll, _acceptAll); key = "IceSSL.TrustOnly.Client"; parse(properties->getProperty(key), _rejectClient, _acceptClient); key = "IceSSL.TrustOnly.Server"; parse(properties->getProperty(key), _rejectAllServer, _acceptAllServer); Ice::PropertyDict dict = properties->getPropertiesForPrefix("IceSSL.TrustOnly.Server."); for(Ice::PropertyDict::const_iterator p = dict.begin(); p != dict.end(); ++p) { string name = p->first.substr(string("IceSSL.TrustOnly.Server.").size()); key = p->first; list<DistinguishedName> reject, accept; parse(p->second, reject, accept); if(!reject.empty()) { _rejectServer[name] = reject; } if(!accept.empty()) { _acceptServer[name] = accept; } } } catch(const ParseException& e) { Ice::PluginInitializationException ex(__FILE__, __LINE__); ex.reason = "IceSSL: invalid property " + key + ":\n" + e.reason; throw ex; } }
void MyUtil::initialize() { ServiceI& service = ServiceI::instance(); // 注册SubjectObserver service.getAdapter()->add(&SubjectObserverI::instance(), service.createIdentity("SO", "")); // 注册AdminConsole // AdminConsoleManagerI::instance().registerComponent("ClusterController", "CC", &ControllerManagerI::instance()); // service.getAdapter()->add(&AdminConsoleManagerI::instance(), service.createIdentity("ACM", "")); // 注册Controller service.getAdapter()->add(&ControllerManagerI::instance(), service.createIdentity("M", "")); // Controller初始化&开始运行 Ice::PropertiesPtr prop = service.getCommunicator()->getProperties(); int intervalFetch = prop->getPropertyAsIntWithDefault("Fetch.Interval", 5); int intervalNotify = prop->getPropertyAsIntWithDefault("Notify.Interval", 120); int cluster = prop->getPropertyAsInt("Server.Cluster"); // cluster改为在controller设置 -- 090727 by zhanghan ControllerManagerI::instance().initialize(cluster, intervalFetch, intervalNotify); ServiceMonitorManager::instance().start(); }
int CasinoServer::run(int argc, char*[]) { if(argc > 1) { cerr << appName() << ": too many arguments" << endl; return EXIT_FAILURE; } // // Initialize pseudo-random number generator // srand((unsigned int)IceUtil::Time::now().toMicroSeconds()); Ice::PropertiesPtr properties = communicator()->getProperties(); _bankEdge = properties->getPropertyAsInt("Bank.Edge"); if(_bankEdge < 1) { _bankEdge = 1; } cout << "Bank edge is " << _bankEdge << endl; // // Create an object adapter // Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Casino"); // // Register factories // communicator()->addValueFactory(new ValueFactory<BankI>, CasinoStore::PersistentBank::ice_staticId()); communicator()->addValueFactory(new ValueFactory<PlayerI>, CasinoStore::PersistentPlayer::ice_staticId()); communicator()->addValueFactory(new ValueFactory<BetI>, CasinoStore::PersistentBet::ice_staticId()); // // Create evictors; each type gets its own type-specific evictor // // // Bank evictor // class BankInitializer : public Freeze::ServantInitializer { public: BankInitializer(CasinoServer& server) : _server(server) { } virtual void initialize(const Ice::ObjectAdapterPtr& /*adapter*/, const Ice::Identity& /*identity*/, const string& /*facet*/, const Ice::ObjectPtr& servant) { BankI* bank = dynamic_cast<BankI*>(servant.get()); bank->init(_server._bankPrx, _server._bankEvictor, _server._playerEvictor, _server._betEvictor, _server._betResolver, _server._bankEdge); } private: BankInitializer& operator=(const BankInitializer&) { return *this; } CasinoServer& _server; }; _bankEvictor = Freeze::createTransactionalEvictor(adapter, _envName, "bank", createTypeMap(CasinoStore::PersistentBank::ice_staticId()), new BankInitializer(*this)); int size = properties->getPropertyAsInt("Bank.EvictorSize"); if(size > 0) { _bankEvictor->setSize(size); } adapter->addServantLocator(_bankEvictor, "bank"); // // Player evictor // class PlayerInitializer : public Freeze::ServantInitializer { public: PlayerInitializer(CasinoServer& server) : _server(server) { } virtual void initialize(const Ice::ObjectAdapterPtr& adptr, const Ice::Identity& identity, const string& /*facet*/, const Ice::ObjectPtr& servant) { CasinoStore::PersistentPlayerPrx prx = CasinoStore::PersistentPlayerPrx::uncheckedCast(adptr->createProxy(identity)); PlayerI* player = dynamic_cast<PlayerI*>(servant.get()); player->init(prx, _server._playerEvictor, _server._bankPrx); } private: PlayerInitializer& operator=(const PlayerInitializer&) { return *this; } CasinoServer& _server; }; _playerEvictor = Freeze::createTransactionalEvictor(adapter, _envName, "player", createTypeMap(CasinoStore::PersistentPlayer::ice_staticId()), new PlayerInitializer(*this)); size = properties->getPropertyAsInt("Player.EvictorSize"); if(size > 0) { _playerEvictor->setSize(size); } adapter->addServantLocator(_playerEvictor, "player"); // // Bet evictor // class BetInitializer : public Freeze::ServantInitializer { public: BetInitializer(CasinoServer& server) : _server(server) { } virtual void initialize(const Ice::ObjectAdapterPtr& /*adapter*/, const Ice::Identity& /*identity*/, const string& /*facet*/, const Ice::ObjectPtr& servant) { BetI* bet = dynamic_cast<BetI*>(servant.get()); bet->init(_server._betEvictor, _server._bankEdge); } private: BetInitializer& operator=(const BetInitializer&) { return *this; } CasinoServer& _server; }; _betEvictor = Freeze::createTransactionalEvictor(adapter, _envName, "bet", createTypeMap(CasinoStore::PersistentBet::ice_staticId()), new BetInitializer(*this)); size = properties->getPropertyAsInt("Bet.EvictorSize"); if(size > 0) { _betEvictor->setSize(size); } adapter->addServantLocator(_betEvictor, "bet"); // // Prepare startup // try { _betResolver.start(); // // Retrieve / create the bank // Ice::Identity bankId = communicator()->stringToIdentity("bank/Montecito"); _bankPrx = CasinoStore::PersistentBankPrx::uncheckedCast(adapter->createProxy(bankId)); if(!_bankEvictor->hasObject(bankId)) { _bankEvictor->add(new BankI(_bankPrx, _bankEvictor, _playerEvictor, _betEvictor, _betResolver, _bankEdge), bankId); } // // reload existing bets into the bet resolver // _bankPrx->reloadBets(); // // Create players / recreate missing players missing players using a transaction // (the transaction is not really necessary here, but a good demo) // const string players[] = { "al", "bob", "charlie", "dave", "ed", "fred", "gene", "herb", "irvin", "joe", "ken", "lance" }; Freeze::ConnectionPtr connection = Freeze::createConnection(communicator(), _envName); Freeze::TransactionPtr tx = connection->beginTransaction(); _playerEvictor->setCurrentTransaction(tx); for(size_t i = 0; i < 12; ++i) { Ice::Identity ident = { players[i], "player" }; if(!_playerEvictor->hasObject(ident)) { _playerEvictor->add(new PlayerI, ident); } } tx->commit(); assert(_playerEvictor->getCurrentTransaction() == 0); connection = 0; // // Everything is ready, activate // adapter->activate(); shutdownOnInterrupt(); communicator()->waitForShutdown(); _betResolver.destroy(); } catch(...) { _betResolver.destroy(); throw; } return 0; }
int PhoneBookCollocated::run(int argc, char* argv[]) { Ice::PropertiesPtr properties = communicator()->getProperties(); // // Create and install a factory for contacts. // ContactFactoryPtr contactFactory = new ContactFactory(); communicator()->addObjectFactory(contactFactory, Demo::Contact::ice_staticId()); // // Create the name index. // NameIndexPtr index = new NameIndex("name"); vector<Freeze::IndexPtr> indices; indices.push_back(index); // // Create an object adapter, use the evictor as servant locator. // Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("PhoneBook"); // // Create an evictor for contacts. // // When Freeze.Evictor.db.contacts.PopulateEmptyIndices is not 0 // and the Name index is empty, Freeze will traverse the database // to recreate the index during createXXXEvictor(). Therefore the // factories for the objects stored in evictor (contacts here) // must be registered before the call to createXXXEvictor(). // Freeze::EvictorPtr evictor = Freeze::createBackgroundSaveEvictor(adapter, _envName, "contacts", 0, indices); adapter->addServantLocator(evictor, "contact"); Ice::Int evictorSize = properties->getPropertyAsInt("EvictorSize"); if(evictorSize > 0) { evictor->setSize(evictorSize); } // // Completes the initialization of the contact factory. Note that ContactI/ // ContactFactoryI uses this evictor only when a Contact is destroyed, // which cannot happen during createXXXEvictor(). // contactFactory->setEvictor(evictor); // // Create the phonebook, and add it to the Object Adapter. // PhoneBookIPtr phoneBook = new PhoneBookI(evictor, contactFactory, index); adapter->add(phoneBook, communicator()->stringToIdentity("phonebook")); // // Everything ok, let's go. // int runParser(int, char*[], const Ice::CommunicatorPtr&); int status = runParser(argc, argv, communicator()); adapter->destroy(); return status; }
int main(int argc, char** argv){ 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::Pose3DPrx> pose3dprx; 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 std::vector<recorder::poolWriteImages*> poolImages; int nConsumidores; int poolSize; //lasers std::vector<recorder::poolWriteLasers*> poolLasers; //pose3dencoders std::vector<recorder::poolWritePose3dEncoders*> poolPose3dEncoders; //pose3d std::vector<recorder::poolWritePose3d*> poolPose3d; //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 fileFormat; 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"); } Ice::PropertiesPtr prop; ic = Ice::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); if (nCameras > 0 ){ struct stat buf; char dire[]="./data/images/"; if( stat( dire, &buf ) == -1 ) { system("mkdir ./data/images/"); } fileFormat=prop->getProperty("Recorder.FileFormat"); if (fileFormat.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 (fileFormat.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 "File format is not valid"; } nConsumidores=prop->getPropertyAsIntWithDefault("Recorder.nConsumers",2); poolSize=prop->getPropertyAsIntWithDefault("Recorder.poolSize",10); } 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"; 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); std::stringstream sFormat; std::string imageFormat; sFormat << "Recorder.Camera" << i+1 << ".Format"; imageFormat = prop->getProperty(sFormat.str()); //pool recorder::poolWriteImages *temp = new recorder::poolWriteImages(cprxAux, Hz,poolSize,i+1,imageFormat ,fileFormat ,compression_params); poolImages.push_back(temp); for (int j=i*nConsumidores; j< i*nConsumidores+nConsumidores; j++){ pthread_create(&consumerThreads[j], &attr, camera_pool_consumer_thread,temp); totalConsumers++; } pthread_create(&producerThreads[i], &attr, camera_pool_producer_thread,temp); totalProducers++; } 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++; } nPose3d= prop->getPropertyAsInt("Recorder.nPose3d"); if (nPose3d > 0){ struct stat buf; char dire[]="./data/pose3d/"; if( stat( dire, &buf ) == -1 ) { system("mkdir data/pose3d/"); } } for (int i=0; i< nPose3d; i++){ struct stat buf; std::stringstream claserPath; claserPath << "./data/pose3d/pose3d" << i+1; if( stat( claserPath.str().c_str(), &buf ) == -1 ) { std::stringstream instruction; instruction << "mkdir " << claserPath.str(); system(instruction.str().c_str()); } // Contact to POSE3D interface std::stringstream sProxy; sProxy << "Recorder.Pose3D" << i+1 << ".Proxy"; Ice::ObjectPrx base = ic->propertyToProxy(sProxy.str()); if (0==base) throw "Could not create proxy with pose3d"; // Cast to Pose3DPrx jderobot::Pose3DPrx prx = jderobot::Pose3DPrx::checkedCast(base); if (0== prx) throw "Invalid proxy Mycomponent.pose3d.Proxy"; pose3dprx.push_back(prx); recorder::poolWritePose3d*temp = new recorder::poolWritePose3d(prx, Hz,poolSize,i+1); poolPose3d.push_back(temp); pthread_create(&consumerThreads[totalConsumers], &attr, pose3d_pool_consumer_thread,temp); totalConsumers++; pthread_create(&producerThreads[totalProducers], &attr, pose3d_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; 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; }
Sensors::Sensors(Ice::CommunicatorPtr ic) { this-> ic = ic; Ice::PropertiesPtr prop = ic->getProperties(); ////////////////////////////// ENCODERS ////////////////////////////// // Contact to ENCODERS interface Ice::ObjectPrx baseEncoders = ic->propertyToProxy("introrob.Encoders.Proxy"); if (0 == baseEncoders) throw "Could not create proxy with encoders"; // Cast to encoders eprx = jderobot::EncodersPrx::checkedCast(baseEncoders); if (0 == eprx) throw "Invalid proxy introrob.Encoders.Proxy"; ////////////////////////////// CAMERA1 /////////////////////////////2 Ice::ObjectPrx baseCamera1 = ic->propertyToProxy("introrob.Camera1.Proxy"); if (0==baseCamera1) throw "Could not create proxy"; /*cast to CameraPrx*/ camera1 = jderobot::CameraPrx::checkedCast(baseCamera1); if (0==camera1) throw "Invalid proxy"; jderobot::ImageDataPtr data = camera1->getImageData(camera1->getImageFormat().at(0)); image1.create(data->description->height, data->description->width, CV_8UC3); ////////////////////////////// CAMERA2 /////////////////////////////2 Ice::ObjectPrx baseCamera2 = ic->propertyToProxy("introrob.Camera2.Proxy"); if (0==baseCamera2) throw "Could not create proxy"; /*cast to CameraPrx*/ camera2 = jderobot::CameraPrx::checkedCast(baseCamera2); if (0==camera2) throw "Invalid proxy"; data = camera2->getImageData(camera2->getImageFormat().at(0)); image2.create(data->description->height, data->description->width, CV_8UC3); ////////////////////////////// LASER ////////////////////////////// boolLaser = prop->getPropertyAsInt("introrob.Laser"); std::cout << "Laser " << boolLaser << std::endl; if(boolLaser){ // Contact to LASER interface Ice::ObjectPrx laserICE = ic->propertyToProxy("introrob.Laser.Proxy"); if (0 == laserICE) throw "Could not create proxy with Laser"; // Cast to LASER laserprx = jderobot::LaserPrx::checkedCast(laserICE); if (0 == laserprx){ throw std::string("Invalid proxy introrob.Laser.Proxy"); } } }
/*********************************************************** connect to the server ***********************************************************/ int ServerConnectionHandler::Connect(const std::string &user, const std::string &password, bool &ircon, std::string & reason) { Disconnect(); Ice::RouterPrx defaultRouter = _communicator->getDefaultRouter(); if(!defaultRouter) { LogHandler::getInstance()->LogToFile(std::string("Can not connect: no default router set")); return 0; } try { _router = Glacier2::RouterPrx::checkedCast(defaultRouter); } catch(const IceUtil::Exception& ex) { LogHandler::getInstance()->LogToFile(std::string("Exception connecting to the server: ") + ex.what()); return 0; } catch(...) { LogHandler::getInstance()->LogToFile(std::string("Unknown exception connecting to the server. ")); return 0; } if(!_router) { LogHandler::getInstance()->LogToFile(std::string("Can not connect: configured router is not a Glacier2 router")); return 0; } try { _session = LbaNet::ClientSessionPrx::uncheckedCast(_router->createSession(user, password)); } catch(const Glacier2::PermissionDeniedException& ex) { LogHandler::getInstance()->LogToFile(std::string("Permission denied: ") + ex.what()); LogHandler::getInstance()->InformUser("Permission denied."); reason = ex.reason; return -1; } try { std::string verS = _session->GetVersion(); Ice::PropertiesPtr prop = _communicator->getProperties(); std::string serverV = prop->getPropertyWithDefault("LbanetServerVersion", "v0"); if(verS != serverV) { reason = "Server version mismatch - please update your game."; Disconnect(); return -1; } } catch(const Ice::Exception& ex) { LogHandler::getInstance()->LogToFile(std::string("Error getting server version: ") + ex.what()); return 0; } try { _adapter = _communicator->createObjectAdapter("LbaNetClient"); _adapter->activate(); } catch(const Ice::Exception& ex) { LogHandler::getInstance()->LogToFile(std::string("Error creating adapter: ") + ex.what()); return 0; } // clear online list ThreadSafeWorkpile::JoinEvent evcl; evcl.ListName = "online"; evcl.Clear = true; ThreadSafeWorkpile::getInstance()->HappenedJoinEvent(evcl); // fill it with already connected people if(_session) { Ice::Long ownid = -1; LbaNet::ConnectedL listco = _session->GetConnected(ownid); ThreadSafeWorkpile::getInstance()->SetPlayerId(ownid); LbaNet::ConnectedL::const_iterator it = listco.begin(); LbaNet::ConnectedL::const_iterator end = listco.end(); for(;it != end; ++it) { ThreadSafeWorkpile::JoinEvent ev; ev.ListName = "online"; ev.Joined = true; ev.Clear = false; ev.Nickname = it->first; ev.Status = it->second.Status; ev.Color = it->second.NameColor; ThreadSafeWorkpile::getInstance()->HappenedJoinEvent(ev); ThreadSafeWorkpile::getInstance()->ChatColorChanged(ev.Nickname, ev.Color); } //synchronize time with server //SynchronizedTimeHandler::getInstance()->Initialize(session); } IceUtil::ThreadPtr t = new SendingLoopThread(_adapter, _session, _router->getServerProxy()->ice_getIdentity().category, user); _tc = t->start(); _thread_started = true; //--------------------------------------------------------------- // start the irc thread Ice::PropertiesPtr prop = _communicator->getProperties(); _ircOn = (prop->getPropertyAsInt("IrcOn") == 1); std::string IrcServer = prop->getProperty("IrcServer"); std::string IrcChannel = "#" + prop->getProperty("IrcChannel"); if(_ircOn) { ircon = true; IrcThread::IrcCoInfo coi; coi.Server = IrcServer; coi.Nickname = user; coi.Channel = IrcChannel; _ircth = new IrcThread(coi); _tcirc = _ircth->start(); } else ircon = false; return 1; }
Freeze::ObjectStoreBase::ObjectStoreBase(const string& facet, const string& facetType, bool createDb, EvictorIBase* evictor, const vector<IndexPtr>& indices, bool populateEmptyIndices) : _facet(facet), _evictor(evictor), _indices(indices), _communicator(evictor->communicator()), _encoding(evictor->encoding()), _keepStats(false) { if(facet == "") { _dbName = EvictorIBase::defaultDb; } else { _dbName = facet; } if(!facetType.empty()) { // // Create a sample servant with this type // ValueFactoryPtr factory = _communicator->getValueFactoryManager()->find(facetType); if(factory == 0) { throw DatabaseException(__FILE__, __LINE__, "No object factory registered for type-id '" + facetType + "'"); } _sampleServant = factory->create(facetType); } ConnectionPtr catalogConnection = createConnection(_communicator, evictor->dbEnv()->getEnvName()); Catalog catalog(catalogConnection, catalogName()); Catalog::iterator p = catalog.find(evictor->filename()); if(p != catalog.end()) { if(p->second.evictor) { // // empty means the value is ::Freeze::ObjectRecord // _keepStats = p->second.value.empty(); } else { DatabaseException ex(__FILE__, __LINE__); ex.message = evictor->filename() + " is not an evictor database"; throw ex; } } DbEnv* dbEnv = evictor->dbEnv()->getEnv(); try { _db.reset(new Db(dbEnv, 0)); Ice::PropertiesPtr properties = evictor->communicator()->getProperties(); string propPrefix = "Freeze.Evictor." + evictor->filename() + "."; int btreeMinKey = properties->getPropertyAsInt(propPrefix + _dbName + ".BtreeMinKey"); if(btreeMinKey > 2) { if(evictor->trace() >= 1) { Trace out(evictor->communicator()->getLogger(), "Freeze.Evictor"); out << "Setting \"" << evictor->filename() + "." + _dbName << "\"'s btree minkey to " << btreeMinKey; } _db->set_bt_minkey(btreeMinKey); } bool checksum = properties->getPropertyAsInt(propPrefix + "Checksum") > 0; if(checksum) { if(evictor->trace() >= 1) { Trace out(evictor->communicator()->getLogger(), "Freeze.Evictor"); out << "Turning checksum on for \"" << evictor->filename() << "\""; } _db->set_flags(DB_CHKSUM); } int pageSize = properties->getPropertyAsInt(propPrefix + "PageSize"); if(pageSize > 0) { if(evictor->trace() >= 1) { Trace out(evictor->communicator()->getLogger(), "Freeze.Evictor"); out << "Setting \"" << evictor->filename() << "\"'s pagesize to " << pageSize; } _db->set_pagesize(pageSize); } TransactionPtr tx = catalogConnection->beginTransaction(); DbTxn* txn = getTxn(tx); u_int32_t flags = DB_THREAD; if(createDb) { flags |= DB_CREATE; } // // Berkeley DB expects file paths to be UTF8 encoded. We keep // _dbName as a native string here, while it might have // been better to convert it to UTF-8, changing this isn't // possible without potentially breaking backward compatibility // with deployed databases. // _db->open(txn, nativeToUTF8(evictor->filename(), getProcessStringConverter()).c_str(), _dbName.c_str(), DB_BTREE, flags, FREEZE_DB_MODE); for(size_t i = 0; i < _indices.size(); ++i) { _indices[i]->_impl->associate(this, txn, createDb, populateEmptyIndices); } if(p == catalog.end()) { CatalogData catalogData; catalogData.evictor = true; catalogData.key = "Ice::Identity"; catalogData.value = "Object"; catalog.put(Catalog::value_type(evictor->filename(), catalogData)); } tx->commit(); } catch(const DbException& dx) { TransactionPtr tx = catalogConnection->currentTransaction(); if(tx != 0) { try { tx->rollback(); } catch(...) { } } if(dx.get_errno() == ENOENT) { NotFoundException ex(__FILE__, __LINE__); ex.message = dx.what(); throw ex; } else { DatabaseException ex(__FILE__, __LINE__); ex.message = dx.what(); throw ex; } } catch(...) { TransactionPtr tx = catalogConnection->currentTransaction(); if(tx != 0) { try { tx->rollback(); } catch(...) { } } throw; } }
void Freeze::IndexI::associate(ObjectStoreBase* store, DbTxn* txn, bool createDb, bool populateIndex) { assert(txn != 0); _store = store; _index._communicator = store->communicator(); _index._encoding = store->encoding(); _db.reset(new Db(store->evictor()->dbEnv()->getEnv(), 0)); _db->set_flags(DB_DUP | DB_DUPSORT); _db->set_app_private(this); _dbName = EvictorIBase::indexPrefix + store->dbName() + "." + _index.name(); Ice::PropertiesPtr properties = store->communicator()->getProperties(); string propPrefix = "Freeze.Evictor." + store->evictor()->filename() + "."; int btreeMinKey = properties->getPropertyAsInt(propPrefix + _dbName + ".BtreeMinKey"); if(btreeMinKey > 2) { if(store->evictor()->trace() >= 1) { Trace out(store->evictor()->communicator()->getLogger(), "Freeze.Evictor"); out << "Setting \"" << store->evictor()->filename() + "." + _dbName << "\"'s btree minkey to " << btreeMinKey; } _db->set_bt_minkey(btreeMinKey); } bool checksum = properties->getPropertyAsInt(propPrefix + "Checksum") > 0; if(checksum) { // // No tracing on purpose // _db->set_flags(DB_CHKSUM); } // // pagesize can't change // u_int32_t flags = 0; if(createDb) { flags = DB_CREATE; } // // // Berkeley DB expects file paths to be UTF8 encoded. We keep // _dbName as a native string here, while it might have // been better to convert it to UTF-8, changing this isn't // possible without potentially breaking backward compatibility // with deployed databases. // _db->open(txn, IceUtil::nativeToUTF8(store->evictor()->filename(), IceUtil::getProcessStringConverter()).c_str(), _dbName.c_str(), DB_BTREE, flags, FREEZE_DB_MODE); flags = 0; if(populateIndex) { flags = DB_CREATE; } store->db()->associate(txn, _db.get(), callback, flags); }
Freeze::SharedDbEnv::SharedDbEnv(const std::string& envName, const Ice::CommunicatorPtr& communicator, DbEnv* env) : _env(env), _envName(envName), _communicator(communicator), _refCount(0) { Ice::PropertiesPtr properties = _communicator->getProperties(); _trace = properties->getPropertyAsInt("Freeze.Trace.DbEnv"); if(_env == 0) { _envHolder.reset(new DbEnv(0)); _env = _envHolder.get(); if(_trace >= 1) { Trace out(_communicator->getLogger(), "Freeze.DbEnv"); out << "opening database environment \"" << envName << "\""; } string propertyPrefix = string("Freeze.DbEnv.") + envName; try { _env->set_errpfx(reinterpret_cast<char*>(this)); _env->set_errcall(dbErrCallback); #ifdef _WIN32 // // Berkeley DB may use a different C++ runtime // _env->set_alloc(::malloc, ::realloc, ::free); #endif // // Deadlock detection // _env->set_lk_detect(DB_LOCK_YOUNGEST); u_int32_t flags = DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN; if(properties->getPropertyAsInt(propertyPrefix + ".DbRecoverFatal") != 0) { flags |= DB_RECOVER_FATAL | DB_CREATE; } else { flags |= DB_RECOVER | DB_CREATE; } if(properties->getPropertyAsIntWithDefault(propertyPrefix + ".DbPrivate", 1) != 0) { flags |= DB_PRIVATE; } /* // // Does not seem to work reliably in 4.1.25 // time_t timeStamp = properties->getPropertyAsIntWithDefault(propertyPrefix + ".TxTimestamp", 0); if(timeStamp != 0) { try { set_tx_timestamp(&timeStamp); } catch(const ::DbException& dx) { DatabaseException ex(__FILE__, __LINE__); ex.message = dx.what(); throw ex; } } */ // // Maybe we can deprecate this property since it can be set in the DB_CONFIG file // bool autoDelete = (properties->getPropertyAsIntWithDefault( propertyPrefix + ".OldLogsAutoDelete", 1) != 0); if(autoDelete) { _env->set_flags(DB_LOG_AUTOREMOVE, 1); } // // Threading // flags |= DB_THREAD; string dbHome = properties->getPropertyWithDefault( propertyPrefix + ".DbHome", envName); _env->open(dbHome.c_str(), flags, FREEZE_DB_MODE); } catch(const ::DbException& dx) { DatabaseException ex(__FILE__, __LINE__); ex.message = dx.what(); throw ex; } // // Default checkpoint period is every 120 seconds // Int checkpointPeriod = properties->getPropertyAsIntWithDefault( propertyPrefix + ".CheckpointPeriod", 120); Int kbyte = properties->getPropertyAsIntWithDefault(propertyPrefix + ".PeriodicCheckpointMinSize", 0); if(checkpointPeriod > 0) { _thread = new CheckpointThread(*this, Time::seconds(checkpointPeriod), kbyte, _trace); } } // // Get catalog // _catalog = SharedDb::openCatalog(*this); }
IceInternal::LocatorManager::LocatorManager(const Ice::PropertiesPtr& properties) : _background(properties->getPropertyAsInt("Ice.BackgroundLocatorCacheUpdates") > 0), _tableHint(_table.end()) { }
Freeze::MapIndexI::MapIndexI(const ConnectionIPtr& connection, MapDb& db, DbTxn* txn, bool createDb, const MapIndexBasePtr& index) : _index(index) { assert(txn != 0); _db.reset(new Db(connection->dbEnv()->getEnv(), 0)); _db->set_flags(DB_DUP | DB_DUPSORT); u_int32_t flags = 0; if(createDb) { flags = DB_CREATE; } _dbName = db.dbName() + "." + _index->name(); _db->set_app_private(this); if(index->compareEnabled()) { _db->set_bt_compare(&customIndexCompare); } Ice::PropertiesPtr properties = connection->communicator()->getProperties(); string propPrefix = "Freeze.Map." + _dbName + "."; int btreeMinKey = properties->getPropertyAsInt(propPrefix + "BtreeMinKey"); if(btreeMinKey > 2) { if(connection->trace() >= 1) { Trace out(connection->communicator()->getLogger(), "Freeze.Map"); out << "Setting \"" << _dbName << "\"'s btree minkey to " << btreeMinKey; } _db->set_bt_minkey(btreeMinKey); } bool checksum = properties->getPropertyAsInt(propPrefix + "Checksum") > 0; if(checksum) { if(connection->trace() >= 1) { Trace out(connection->communicator()->getLogger(), "Freeze.Map"); out << "Turning checksum on for \"" << _dbName << "\""; } _db->set_flags(DB_CHKSUM); } int pageSize = properties->getPropertyAsInt(propPrefix + "PageSize"); if(pageSize > 0) { if(connection->trace() >= 1) { Trace out(connection->communicator()->getLogger(), "Freeze.Map"); out << "Setting \"" << _dbName << "\"'s pagesize to " << pageSize; } _db->set_pagesize(pageSize); } if(connection->trace() >= 1) { Trace out(connection->communicator()->getLogger(), "Freeze.Map"); out << "Opening index \"" << _dbName << "\""; } // // Berkeley DB expects file paths to be UTF8 encoded. // _db->open(txn, nativeToUTF8(_dbName, getProcessStringConverter()).c_str(), 0, DB_BTREE, flags, FREEZE_DB_MODE); // // To populate empty indices // flags = DB_CREATE; db.associate(txn, _db.get(), callback, flags); // // Note: caller catch and translates exceptions // }
void PluginI::initialize() { Ice::PropertiesPtr properties = _communicator->getProperties(); bool ipv4 = properties->getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0; bool preferIPv6 = properties->getPropertyAsInt("Ice.PreferIPv6Address") > 0; string address; if(ipv4 && !preferIPv6) { address = properties->getPropertyWithDefault("IceDiscovery.Address", "239.255.0.1"); } else { address = properties->getPropertyWithDefault("IceDiscovery.Address", "ff15::1"); } int port = properties->getPropertyAsIntWithDefault("IceDiscovery.Port", 4061); string interface = properties->getProperty("IceDiscovery.Interface"); if(properties->getProperty("IceDiscovery.Multicast.Endpoints").empty()) { ostringstream os; os << "udp -h \"" << address << "\" -p " << port; if(!interface.empty()) { os << " --interface \"" << interface << "\""; } properties->setProperty("IceDiscovery.Multicast.Endpoints", os.str()); } if(properties->getProperty("IceDiscovery.Reply.Endpoints").empty()) { ostringstream os; os << "udp"; if(!interface.empty()) { os << " -h \"" << interface << "\""; } properties->setProperty("IceDiscovery.Reply.Endpoints", os.str()); } if(properties->getProperty("IceDiscovery.Locator.Endpoints").empty()) { properties->setProperty("IceDiscovery.Locator.AdapterId", IceUtil::generateUUID()); } _multicastAdapter = _communicator->createObjectAdapter("IceDiscovery.Multicast"); _replyAdapter = _communicator->createObjectAdapter("IceDiscovery.Reply"); _locatorAdapter = _communicator->createObjectAdapter("IceDiscovery.Locator"); // // Setup locatory registry. // LocatorRegistryIPtr locatorRegistry = new LocatorRegistryI(_communicator); Ice::LocatorRegistryPrx locatorRegistryPrx = Ice::LocatorRegistryPrx::uncheckedCast(_locatorAdapter->addWithUUID(locatorRegistry)); string lookupEndpoints = properties->getProperty("IceDiscovery.Lookup"); if(lookupEndpoints.empty()) { ostringstream os; os << "udp -h \"" << address << "\" -p " << port; if(!interface.empty()) { os << " --interface \"" << interface << "\""; } lookupEndpoints = os.str(); } Ice::ObjectPrx lookupPrx = _communicator->stringToProxy("IceDiscovery/Lookup -d:" + lookupEndpoints); lookupPrx = lookupPrx->ice_collocationOptimized(false); // No collocation optimization for the multicast proxy! try { // Ensure we can establish a connection to the multicast proxy // but don't block. Ice::AsyncResultPtr result = lookupPrx->begin_ice_getConnection(); if(result->sentSynchronously()) { lookupPrx->end_ice_getConnection(result); } } catch(const Ice::LocalException& ex) { ostringstream os; os << "IceDiscovery is unable to establish a multicast connection:\n"; os << "proxy = " << lookupPrx << '\n'; os << ex; throw Ice::PluginInitializationException(__FILE__, __LINE__, os.str()); } // // Add lookup and lookup reply Ice objects // _lookup = new LookupI(locatorRegistry, LookupPrx::uncheckedCast(lookupPrx), properties); _multicastAdapter->add(_lookup, _communicator->stringToIdentity("IceDiscovery/Lookup")); Ice::ObjectPrx lookupReply = _replyAdapter->addWithUUID(new LookupReplyI(_lookup))->ice_datagram(); _lookup->setLookupReply(LookupReplyPrx::uncheckedCast(lookupReply)); // // Setup locator on the communicator. // Ice::ObjectPrx loc = _locatorAdapter->addWithUUID(new LocatorI(_lookup, locatorRegistryPrx)); _communicator->setDefaultLocator(Ice::LocatorPrx::uncheckedCast(loc)); _multicastAdapter->activate(); _replyAdapter->activate(); _locatorAdapter->activate(); }