void OgreApp::setCommandLine(const Ogre::String &commandLine) { String configFile; mCommandLine = commandLine; if(!commandLine.empty()) { // splits command line in a vector without spliting text between quotes StringVector quoteSplit = Ogre::StringUtil::split(commandLine, "\""); // if the first char was a quote, split() ignored it. if(commandLine[0] == '\"') quoteSplit.insert(quoteSplit.begin(), " "); // insert a space in the list to reflect the presence of the first quote // insert a space instead of an empty string because the next split() will ingore the space but not the empty string // split(" ")->{} / split("")->{""} for(unsigned int i = 0; i < quoteSplit.size(); i++) { if(i&1) // odd elements : between quotes { mCommandLineArgs.push_back(quoteSplit[i]); } else // even elements : outside quotes { StringVector spaceSplit = Ogre::StringUtil::split(quoteSplit[i]); mCommandLineArgs.insert(mCommandLineArgs.end(), spaceSplit.begin(), spaceSplit.end()); } } } }
void CDirectoryManagerBase::AppendFileArray(const std::string& path, const std::string& fileExt, StringVector& fileArray)const { std::string filter = path + "*" + fileExt; StringVector tmp = WBSF::GetFilesList(filter, m_nameType); fileArray.insert(fileArray.begin(), tmp.begin(), tmp.end()); }
ModuleLinkerPass::StringVector ModuleLinkerPass::getAllSymbolsUsedByKernel( const std::string& kernelName) const { StringSet usedSymbols; usedSymbols.insert(kernelName); StringVector unprocessedSymbols = getAllSymbolsUsedByThisKernel( kernelName, _linkedModule); while(!unprocessedSymbols.empty()) { StringVector newSymbols; for(auto symbol = unprocessedSymbols.begin(); symbol != unprocessedSymbols.end(); ++symbol) { if(!usedSymbols.insert(*symbol).second) continue; if(!isKernelSymbol(_linkedModule, *symbol)) continue; StringVector kernelSymbols = getAllSymbolsUsedByThisKernel( *symbol, _linkedModule); newSymbols.insert(newSymbols.end(), kernelSymbols.begin(), kernelSymbols.end()); } unprocessedSymbols = std::move(newSymbols); } return StringVector(usedSymbols.begin(), usedSymbols.end()); }
StringVector Component::path() const { StringVector ret; if (hasParent()) { StringVector b = parent()->path(); ret.insert(ret.begin(), b.begin(), b.end()); } ret.push_back(name()); return ret; }
/* * 获取该规则期望过滤的域名 */ void FilterRule::getDomains(StringVector & domains) { if(!m_domains.empty()) { domains.insert(domains.end(),m_domains.begin(),m_domains.end()); return; } std::string s=parseDomain(m_reFilter); if(!s.empty()) domains.push_back(s); }
StringVector PME::GetStringVector ( ) { StringVector oStringVector; for ( int nCurrentMatch = 0; nCurrentMatch < nMatches; nCurrentMatch++ ) { oStringVector.insert ( oStringVector.end ( ), (*this)[nCurrentMatch] ); } return oStringVector; }
//************************************************************ // GetFileArray : obtain a list of file by serching in all directory //************************************************************ StringVector CDirectoryManager::GetFilesList()const { StringVector files; if (m_simpleExt) { files = CDirectoryManagerBase::GetFilesList(m_extensions); } else { StringVector extensions(m_extensions, "|"); for (size_t i = 0; i < extensions.size(); i++) { StringVector tmp = CDirectoryManagerBase::GetFilesList(extensions[i]); files.insert(files.end(), tmp.begin(), tmp.end()); } } return files; }
// Run dindel on a pair of samples DindelReturnCode DindelUtil::runDindelPairMatePair(const std::string& id, const StringVector& base_haplotypes, const StringVector& variant_haplotypes, const GraphCompareParameters& parameters, std::ostream& baseOut, std::ostream& variantOut, std::ostream& callsOut, DindelReadReferenceAlignmentVector* pReadAlignments) { PROFILE_FUNC("runDindelPairMatePair") StringVector inHaplotypes; inHaplotypes.insert(inHaplotypes.end(), base_haplotypes.begin(), base_haplotypes.end()); inHaplotypes.insert(inHaplotypes.end(), variant_haplotypes.begin(), variant_haplotypes.end()); // // First, extract the reads from the normal and variant data sets that match each haplotype // assert(inHaplotypes.size() > 0); // Get canidate alignments for the input haplotypes HapgenAlignmentVector candidateAlignments; // Choose the kmer size for alignment size_t align_kmer = 31; for(size_t i = 0; i < inHaplotypes.size(); ++i) { HapgenAlignmentVector thisCandidateAlignments; HapgenUtil::alignHaplotypeToReferenceKmer(align_kmer, inHaplotypes[i], parameters.referenceIndex, parameters.pRefTable, thisCandidateAlignments); candidateAlignments.insert(candidateAlignments.end(), thisCandidateAlignments.begin(), thisCandidateAlignments.end()); } // Remove duplicate or bad alignment pairs HapgenUtil::coalesceAlignments(candidateAlignments); if(Verbosity::Instance().getPrintLevel() > 3) printf("runDindel -- %zu candidate alignments found\n", candidateAlignments.size()); size_t MAX_ALIGNMENTS = 10; if(candidateAlignments.size() > MAX_ALIGNMENTS) return DRC_AMBIGUOUS_ALIGNMENT; // Join each haplotype with flanking sequence from the reference genome for each alignment // This function also adds a haplotype (with flanking sequence) for the piece of the reference int FLANKING_SIZE = 0; if (parameters.dindelRealignParameters.realignMatePairs) FLANKING_SIZE = 1000; StringVector flankingHaplotypes; // This vector contains the internal portion of the haplotypes, without the flanking sequence // It is used to extract reads StringVector candidateHaplotypes; for(size_t i = 0; i < candidateAlignments.size(); ++i) { HapgenUtil::makeFlankingHaplotypes(candidateAlignments[i], parameters.pRefTable, FLANKING_SIZE, inHaplotypes, flankingHaplotypes, candidateHaplotypes); } if(Verbosity::Instance().getPrintLevel() > 3) printf("runDindel -- made %zu flanking haplotypes\n", candidateHaplotypes.size()); // Normal reads SeqRecordVector normalReads; SeqRecordVector normalRCReads; // Remove non-unique candidate haplotypes std::sort(candidateHaplotypes.begin(), candidateHaplotypes.end()); StringVector::iterator haplotype_iterator = std::unique(candidateHaplotypes.begin(), candidateHaplotypes.end()); candidateHaplotypes.resize(haplotype_iterator - candidateHaplotypes.begin()); // Set the value to use for extracting reads that potentially match the haplotype // Do not use a kmer for extraction greater than this value size_t KMER_CEILING = 31; size_t extractionKmer = parameters.kmer < KMER_CEILING ? parameters.kmer : KMER_CEILING; bool extractOK = true; if(!parameters.bReferenceMode) { // Reads on the same strand as the haplotype extractOK = HapgenUtil::extractHaplotypeReads(candidateHaplotypes, parameters.baseIndex, extractionKmer, false, parameters.maxReads, parameters.maxExtractionIntervalSize, &normalReads, NULL); if(!extractOK) return DRC_OVER_DEPTH; // Reads on the reverse strand extractOK = HapgenUtil::extractHaplotypeReads(candidateHaplotypes, parameters.baseIndex, extractionKmer, true, parameters.maxReads, parameters.maxExtractionIntervalSize, &normalRCReads, NULL); if(!extractOK) return DRC_OVER_DEPTH; } // Variant reads SeqRecordVector variantReads; SeqRecordVector variantRCReads; extractOK = HapgenUtil::extractHaplotypeReads(candidateHaplotypes, parameters.variantIndex, extractionKmer, false, parameters.maxReads, parameters.maxExtractionIntervalSize, &variantReads, NULL); if(!extractOK) return DRC_OVER_DEPTH; extractOK = HapgenUtil::extractHaplotypeReads(candidateHaplotypes, parameters.variantIndex, extractionKmer, true, parameters.maxReads, parameters.maxExtractionIntervalSize, &variantRCReads, NULL); if(!extractOK) return DRC_OVER_DEPTH; size_t normal_reads = normalReads.size() + normalRCReads.size(); size_t variant_reads = variantReads.size() + variantRCReads.size(); size_t total_reads = normal_reads + variant_reads; if(Verbosity::Instance().getPrintLevel() > 3) printf("Extracted %zu normal reads, %zu variant reads\n", normal_reads, variant_reads); if(total_reads > parameters.maxReads) return DRC_OVER_DEPTH; if (total_reads == 0) return DRC_UNDER_DEPTH; // Generate the input haplotypes for dindel // We need at least 2 haplotypes (one is the reference) size_t totFlankingHaplotypes = flankingHaplotypes.size(); if(totFlankingHaplotypes < 2) return DRC_NO_ALIGNMENT; // Ensure the reference haplotype is a non-empty string if(flankingHaplotypes[0].size() == 0) return DRC_NO_ALIGNMENT; // Make Dindel referenceMappings StringVector dindelHaplotypes; std::set<DindelReferenceMapping> refMappings; // for(size_t i = 0; i < candidateAlignments.size(); ++i) { std::string upstream, defined, downstream; std::string refName = parameters.pRefTable->getRead(candidateAlignments[i].referenceID).id; HapgenUtil::extractReferenceSubstrings(candidateAlignments[i],parameters.pRefTable, FLANKING_SIZE, upstream, defined, downstream); std::string refSeq = upstream + defined + downstream; int refStart = candidateAlignments[i].position - int(upstream.size()) + 1; // Here the score is used as an estimate of how unique "defined" is in the reference sequence. // "defined" is not the reference sequence but a candidate haplotype. // It is conservative because the flanking sequence is not used in this estimation. DindelReferenceMapping rm(refName, refSeq, refStart, candidateAlignments[i].score+2*FLANKING_SIZE, candidateAlignments[i].isRC); std::set<DindelReferenceMapping>::iterator rmit = refMappings.find(rm); if(rmit == refMappings.end()) { refMappings.insert(rm); } else { if(rm.referenceAlignmentScore > rmit->referenceAlignmentScore) rmit->referenceAlignmentScore = rm.referenceAlignmentScore; } } // RESET MAPPING SCORES for(std::set<DindelReferenceMapping>::iterator it = refMappings.begin(); it != refMappings.end(); it++) it->referenceAlignmentScore = 1000; // make flankingHaplotypes unique std::set< std::string > setFlanking(flankingHaplotypes.begin(), flankingHaplotypes.end()); for(std::set< std::string >::const_iterator it = setFlanking.begin(); it != setFlanking.end(); it++) { dindelHaplotypes.push_back(*it); //dindelRefMappings[i] = std::vector<DindelReferenceMapping>(refMappings.begin(),refMappings.end()); } std::vector<DindelReferenceMapping> dRefMappings(refMappings.begin(),refMappings.end()); DindelWindow dWindow(dindelHaplotypes, dRefMappings); // // Run Dindel // // Initialize VCF collections VCFCollection vcfCollections[2]; // If in multisample mode, load the sample names into the VCFCollection if(parameters.variantIndex.pPopIdx != NULL) { for(size_t i = 0; i <= 1; ++i) vcfCollections[i].samples = parameters.variantIndex.pPopIdx->getSamples(); } size_t start_i = parameters.bReferenceMode ? 1 : 0; DindelRealignWindowResult *pThisResult = NULL; DindelRealignWindowResult *pPreviousResult = NULL; for(size_t i = start_i; i <= 1; ++i) { SeqRecordVector& fwdReads = (i == 0) ? normalReads : variantReads; SeqRecordVector& rcReads = (i == 0) ? normalRCReads : variantRCReads; const BWTIndexSet* indices = ¶meters.variantIndex; // Create dindel reads // Mates must be at the end of the array. std::vector<DindelRead> dReads; for(size_t j = 0; j < fwdReads.size(); ++j) dReads.push_back(convertToDindelRead(indices, fwdReads[j], true)); for(size_t j = 0; j < rcReads.size(); ++j) { rcReads[j].seq.reverseComplement(); std::reverse(rcReads[j].qual.begin(), rcReads[j].qual.end()); dReads.push_back(convertToDindelRead(indices, rcReads[j], false)); } pThisResult = new DindelRealignWindowResult(); std::stringstream out_ss; try { DindelRealignWindow dRealignWindow(&dWindow, dReads, parameters.dindelRealignParameters); dRealignWindow.run("hmm", vcfCollections[i], pReadAlignments, id, pThisResult, pPreviousResult, parameters.pRefTable); } catch(std::string e) { std::cerr << "Dindel Exception: " << e << "\n"; exit(DRC_EXCEPTION); } if(i == 0) pPreviousResult = pThisResult; } // Copy raw VCFRecords to output for(size_t i = 0; i <= 1; ++i) { std::ostream& curr_out = i == 0 ? baseOut : variantOut; for(size_t j = 0; j < vcfCollections[i].records.size(); ++j) curr_out << vcfCollections[i].records[j] << "\n"; } // Make comparative calls size_t VARIANT_IDX = 1; size_t BASE_IDX = 0; bool has_base_calls = !vcfCollections[BASE_IDX].records.empty(); for(size_t i = 0; i < vcfCollections[1].records.size(); ++i) { bool not_called_in_base = true; if(has_base_calls) not_called_in_base = vcfCollections[BASE_IDX].records[i].passStr == "NoCall" || vcfCollections[BASE_IDX].records[i].passStr == "NoSupp"; bool called_in_variant = vcfCollections[VARIANT_IDX].records[i].passStr == "PASS"; if(called_in_variant && not_called_in_base) callsOut << vcfCollections[VARIANT_IDX].records[i] << "\n"; } baseOut.flush(); variantOut.flush(); delete pThisResult; delete pPreviousResult; return DRC_OK; }
void NumericExpression::init() { _vars.clear(); _rpn.clear(); StringTokenizer variablesTokenizer( "", "" ); variablesTokenizer.addDelims( "[]", true ); variablesTokenizer.addQuotes( "'\"", true ); variablesTokenizer.keepEmpties() = false; StringTokenizer operandTokenizer( "", "" ); operandTokenizer.addDelims( ",()%*/+-", true ); operandTokenizer.addQuotes( "'\"", true ); operandTokenizer.keepEmpties() = false; StringVector variablesTokens; variablesTokenizer.tokenize( _src, variablesTokens ); StringVector t; bool invar = false; for( unsigned i=0; i<variablesTokens.size(); ++i ) { if ( variablesTokens[i] == "[" && !invar ) { // Start variable, add "[" token invar = true; t.push_back(variablesTokens[i]); } else if ( variablesTokens[i] == "]" && invar ) { // End variable, add "]" token invar = false; t.push_back(variablesTokens[i]); } else if ( invar ) { // Variable, add variable token t.push_back(variablesTokens[i]); } else { // Operands, tokenize it and add tokens StringVector operandTokens; operandTokenizer.tokenize( variablesTokens[i], operandTokens ); t.insert(t.end(), operandTokens.begin(), operandTokens.end()); } } // identify tokens: AtomVector infix; invar = false; for( unsigned i=0; i<t.size(); ++i ) { if ( t[i] == "[" && !invar ) { invar = true; } else if ( t[i] == "]" && invar ) { invar = false; infix.push_back( Atom(VARIABLE,0.0) ); _vars.push_back( Variable(t[i-1],0) ); } else if ( t[i] == "(" ) infix.push_back( Atom(LPAREN,0.0) ); else if ( t[i] == ")" ) infix.push_back( Atom(RPAREN,0.0) ); else if ( t[i] == "," ) infix.push_back( Atom(COMMA,0.0) ); else if ( t[i] == "%" ) infix.push_back( Atom(MOD,0.0) ); else if ( t[i] == "*" ) infix.push_back( Atom(MULT,0.0) ); else if ( t[i] == "/" ) infix.push_back( Atom(DIV,0.0) ); else if ( t[i] == "+" ) infix.push_back( Atom(ADD,0.0) ); else if ( t[i] == "-" ) infix.push_back( Atom(SUB,0.0) ); else if ( t[i] == "min" ) infix.push_back( Atom(MIN,0.0) ); else if ( t[i] == "max" ) infix.push_back( Atom(MAX,0.0) ); else if ( (t[i][0] >= '0' && t[i][0] <= '9') || t[i][0] == '.' ) infix.push_back( Atom(OPERAND,as<double>(t[i],0.0)) ); else if ( t[i] != "," && (i == 0 || t[i-1] != "[")) { std::string var = t[i]; // If this is a call to a script function, store the entire function // call in the variable string if (i < t.size() - 1 && t[i+1] == "(") { int parenCount = 0; do { ++i; var += t[i]; if (t[i] == "(") parenCount++; else if (t[i] == ")") parenCount--; } while (i < t.size() - 1 && parenCount > 0); } infix.push_back( Atom(VARIABLE, 0.0) ); _vars.push_back( Variable(var, 0) ); } // note: do nothing for a comma } // convert to RPN: // http://en.wikipedia.org/wiki/Shunting-yard_algorithm AtomStack s; unsigned var_i = 0; for( unsigned i=0; i<infix.size(); ++i ) { Atom& a = infix[i]; if ( a.first == LPAREN ) { s.push( a ); } else if ( a.first == RPAREN ) { while( s.size() > 0 ) { Atom top = s.top(); s.pop(); if ( top.first == LPAREN ) break; else _rpn.push_back( top ); } } else if ( a.first == COMMA ) { while( s.size() > 0 && s.top().first != LPAREN ) { _rpn.push_back( s.top() ); s.pop(); } } else if ( IS_OPERATOR(a) ) { if ( s.empty() || a.first > s.top().first ) { s.push( a ); } else { while( s.size() > 0 && a.first < s.top().first && IS_OPERATOR(s.top()) ) { _rpn.push_back( s.top() ); s.pop(); } s.push( a ); } } else if ( a.first == MIN || a.first == MAX ) { s.push( a ); } else if ( a.first == OPERAND ) { _rpn.push_back( a ); } else if ( a.first == VARIABLE ) { _rpn.push_back( a ); _vars[var_i++].second = _rpn.size()-1; // store the index } } while( s.size() > 0 ) { _rpn.push_back( s.top() ); s.pop(); } }
bool CConverToMK::WriteToMKFile() { filesystem::path kPath(m_pszMKFile); string strParentPath = kPath.parent_path().string(); StringVector kPathSet = m_kMKFileData; StringVector::iterator pkIterator = kPathSet.begin(); for (unsigned int i = 0;i < m_uiKeyStringPosition;i++) { pkIterator++; } kPathSet.insert(pkIterator,string("LOCAL_SRC_FILES := \\")); unsigned int uiPos = m_uiKeyStringPosition + 1; for (ModuleInfoMap::iterator it = m_kModuleInfoMap.begin(); it != m_kModuleInfoMap.end();it++) { ModuleInfo kInfo = it->second; StringVector kStringVector = m_kFilesPathData[string(kInfo.szModuleName)]; for (unsigned int uiIndex = 0;uiIndex < kStringVector.size();uiIndex++) { string strFullPath = kStringVector[uiIndex]; string strProcessedPath = ""; if (!ProcessPath(kInfo.szVCProjFile,strFullPath.c_str(),strProcessedPath)) { cout << "文件 " << strFullPath << " 找不到!请检查vcproj文件" << endl; continue; } replace_all(strProcessedPath,"\\","/"); if (uiIndex != kStringVector.size() - 1) { strProcessedPath = strProcessedPath + string(" \\"); } kPathSet.insert(kPathSet.begin() + uiPos,strProcessedPath); uiPos++; } } ofstream kOutStream("temp.mk"); cout << "正在写入到" << "temp.mk" << "文件里" << endl; progress_display kProgressDisplay(kPathSet.size()); for (unsigned int uiIndex = 0;uiIndex < kPathSet.size();uiIndex++) { kOutStream << kPathSet[uiIndex] << endl; ++kProgressDisplay; Sleep(20); } kOutStream.close(); cout << "已经写完并且关闭文件" << endl; return true; }
ERMsg CUIEnvCanRadar::GetRadarList(StringVector& radarList, CCallback& callback)const { ERMsg msg; //Interface attribute index to attribute index //sample for Québec //http://climate.weather.gc.ca/radar/index_e.html?site=XAM&year=2015&month=7&day=25&hour=13&minute=20&duration=2&image_type=PRECIPET_SNOW_WEATHEROFFICE //http://climate.weather.gc.ca/radar/index_e.html?site=XAM&sYear=2013&sMonth=7&sDay=15&sHour=22&sMin=00&Duration=2&ImageType=PRECIP_SNOW_WEATHEROFFICE&scale=14 static const char pageFormat[] = "radar/index_e.html?" "site=%s&" "year=%d&" "month=%d&" "day=%d&" "hour=%d&" "minute=00&" "duration=2&" "image_type=%s"; CCanadianRadar radar(Get(RADAR)); CTPeriod period = GetPeriod(); callback.PushTask(GetString(IDS_LOAD_FILE_LIST), radar.count() * period.size() / 2); size_t type = as<size_t>(TYPE); size_t prcpType = as<size_t>(PRCP_TYPE); CInternetSessionPtr pSession; CHttpConnectionPtr pConnection; msg = GetHttpConnection(SERVER_NAME[type], pConnection, pSession); if (!msg) return msg; ASSERT(period.GetTM().Type() == CTM::HOURLY); std::set<string> tmpList; //loop each 2 hours for (size_t i = 0; i < radar.size() && msg; i++) { if (radar.none() || radar[i]) { for (CTRef TRef = period.Begin(); TRef <= period.End() && msg; TRef += 2) { string URL = FormatA(pageFormat, CCanadianRadar::GetName(i,0).c_str(), TRef.GetYear(), TRef.GetMonth() + 1, TRef.GetDay() + 1, TRef.GetHour(), TYPE_NAME[prcpType]); URL.resize(strlen(URL.c_str())); string source; UtilWWW::GetPageText(pConnection, URL, source, true); //string::size_type posEnd = 0; string fileList = FindString(source, "blobArray = [", "]"); if (!fileList.empty()) { string::size_type posBegin = 0; while (posBegin != string::npos) { string image = FindString(fileList, "'", "'", posBegin); if (!image.empty()) tmpList.insert(image); posBegin = fileList.find(",", posBegin); } } msg += callback.StepIt(); } } } pConnection->Close(); pSession->Close(); radarList.insert(radarList.end(), tmpList.begin(), tmpList.end()); callback.AddMessage(GetString(IDS_NB_FILES_FOUND) + ToString(radarList.size())); callback.PopTask(); return msg; }
DdsEntitiesFactory::DdsEntitiesFactory(DdsEntitiesFactoryParameters const& params) : m_params(params), m_data(new Data()) { MIRO_LOG_CTOR("kn::DdsEntitiesFactory"); // for error reporting stringstream ostr; DDS::DomainParticipantFactory * dpf = DDS::DomainParticipantFactory::get_instance(); //--------------------------------------------------- // disable default locations for Qos policy lookup DDS::DomainParticipantFactoryQos dpfQos; DDS_DomainParticipantFactoryQos_initialize(&dpfQos); DDS::ReturnCode_t rc; if ((rc = dpf->get_qos(dpfQos)) != DDS_RETCODE_OK) { ostr << "DdsSupport::init() - Failed to query Qos (" << ((int)rc) << "): " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } // start participants disabled, so we can set discovery modules dpfQos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE; // if configuration file is given, disable all other config options if (!m_params.configFiles.empty()) { Miro::SearchPaths paths(KNDDS_INSTALL_PREFIX "/etc"); paths.addMiroEtcPaths(); dpfQos.profile.url_profile.maximum(m_params.configFiles.size()); dpfQos.profile.url_profile.length(m_params.configFiles.size()); dpfQos.profile.ignore_user_profile = true; dpfQos.profile.ignore_environment_profile = true; dpfQos.profile.ignore_resource_profile = true; for (unsigned int i = 0; i < m_params.configFiles.size(); ++i) { string absFilePath = paths.findFile(m_params.configFiles[i]); if (absFilePath.empty()) { ostr << "DdsSupport::init() - DDS config file given not found (" << m_params.configFiles[i] << ")"; throw Miro::Exception(ostr.str()); } dpfQos.profile.url_profile[i] = DDS_String_dup(("file://" + absFilePath).c_str()); } if ((rc = dpf->set_qos(dpfQos)) != DDS_RETCODE_OK) { ostr << "DdsSupport::init() - Failed to set Qos: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } } if (!m_params.defaultLibrary.empty() && (rc = dpf->set_default_library(m_params.defaultLibrary.c_str())) != DDS_RETCODE_OK) { ostr << "DdsSupport::init() - Failed to set default library: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } if (!m_params.defaultProfile.empty() && (rc = dpf->set_default_profile(m_params.defaultLibrary.c_str(), m_params.defaultProfile.c_str())) != DDS_RETCODE_OK) { ostr << "DdsSupport::init() - Failed to set default library: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } //------------------------------------------- // create all participants // (default is 1) DdsDomainParticipantRepository * partRepo = DdsDomainParticipantRepository::instance(); DdsTypeRegistratorRepository * typeRepo = DdsTypeRegistratorRepository::instance(); { ParticipantVector::const_iterator first, last = m_params.participants.end(); for (first = m_params.participants.begin(); first != last; ++first) { // create one participant char const * library = first->library.empty() ? NULL : first->library.c_str(); char const * profile = first->profile.empty() ? NULL : first->profile.c_str(); DDS::DomainParticipantQos qos; DDS_DomainParticipantQos_initialize(&qos); if (profile == NULL && (m_params.defaultLibrary.empty() || m_params.defaultProfile.empty())) { DDS::ReturnCode_t rc = dpf->get_default_participant_qos(qos); if (rc != DDS_RETCODE_OK) { ostr << "Get default participant Qos profile: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } } else { DDS::ReturnCode_t rc = dpf->get_participant_qos_from_profile(qos, library, profile); if (rc != DDS_RETCODE_OK) { ostr << "Load participant Qos profile: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } } // set participant name from Miro parameters if (!first->participantName.empty()) { qos.participant_name.name = DDS_String_dup(first->participantName.c_str()); } // handle discovery-peers processing // just print the stuff as a first step... if (!first->discoveryPeersFiles.empty()) { DDS_DiscoveryQosPolicy& discovery = qos.discovery; StringVector peers; StringVector::const_iterator f, l = first->discoveryPeersFiles.end(); for (f = first->discoveryPeersFiles.begin(); f != l; ++f) { StringVector const p = parseDiscoveryPeersFile(*f); peers.insert(peers.end(), p.begin(), p.end()); } // set peers list in qos if (discovery.initial_peers.maximum() < (int)peers.size()) { discovery.initial_peers.maximum(peers.size()); } discovery.initial_peers.length(peers.size()); for (int i = 0; i < discovery.initial_peers.length(); ++i) { assert (peers[i].length() < 100); DDS_String_free(discovery.initial_peers[i]); discovery.initial_peers[i] = DDS_String_dup(peers[i].c_str()); } MIRO_LOG_OSTR(LL_NOTICE, "DDS Initial peers layout for " << qos.participant_name.name); for (int i = 0; i < qos.discovery.initial_peers.length(); ++i) { MIRO_LOG_OSTR(LL_NOTICE, qos.discovery.initial_peers[i]); } } #ifdef KNDDS_HAS_DDS_Monitor if (first->enableMonitor) { int rc; rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "rti.monitor.library", "rtimonintoring", DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); char valueBuffer[17]; sprintf(valueBuffer, "%p", RTIDefaultMonitor_create); rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "rti.monitor.create_function_ptr", valueBuffer, DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); int monitorId = (first->monitorDomainId >= 0) ? first->monitorDomainId : first->domainId + 1; sprintf(valueBuffer, "%i", monitorId); rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "rti.monitor.config.new_participant_domain_id", valueBuffer, DDS_BOOLEAN_FALSE); if (!first->monitorLibrary.empty()) { rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "rti.monitor.config.qos_library", first->monitorLibrary.c_str(), DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "rti.monitor.config.qos_profile", first->monitorProfile.c_str(), DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); } } #endif #if defined(KNDDS_HAS_RTI_DistLogger) if(m_params.enableDistLogger) { // Initialize the distributed logger. If distLoggerDomainId is less than // 0, use the domain of the first participant int loggerId = (m_params.distLoggerDomainId >= 0) ? m_params.distLoggerDomainId : first->domainId; RTI_DLDistLogger* dl = NULL; RTI_DLOptions dlOptions; // RTI_DLOptions API changed in RTI DDS 5.1.0 #if (RTI_DDS_VERSION_MAJOR >= 5 && RTI_DDS_VERSION_MINOR > 0) rc = dlOptions.setDomainId(loggerId); assert (rc == DDS_RETCODE_OK); rc = dlOptions.setApplicationKind(qos.participant_name.name); assert (rc == DDS_RETCODE_OK); #else dlOptions.setDomainId(loggerId); dlOptions.setApplicationKind(qos.participant_name.name); #endif RTI_DLDistLogger::setOptions(dlOptions); dl = RTI_DLDistLogger::getInstance(); if(dl) { dl->info("DdsEntitiesFactory initialized RTI Distributed Logger"); } else { KN_ERROR("RTI Distributed Logger - getInstance() returned NULL"); } } #endif #if defined(KNDDS_HAS_DDS_LBPlugin) && defined(RTIDDS_LB_BETA_VERSION) // disable simple-endpoind discovery if static discovery modules are specified // we need to double-check if they can coexist peacefully... if (!first->lbpdFile.empty()) { qos.discovery_config.builtin_discovery_plugins &= ~DDS_DISCOVERYCONFIG_BUILTIN_SPDP; } if (!first->lbedFile.empty()) { qos.discovery_config.builtin_discovery_plugins &= ~DDS_DISCOVERYCONFIG_BUILTIN_SEDP; } #endif DDS::DomainParticipant * participant = dpf->create_participant(first->domainId, qos, NULL /* listener */, DDS::STATUS_MASK_NONE); if (participant == NULL) { throw Miro::Exception("DdsSupport::init() - Failed to create participant."); } // set default library/profile if (library != NULL && (rc = participant->set_default_library(library)) != DDS_RETCODE_OK) { ostr << "DdsSupport::init() - Failed to set participant default library: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } if (profile != NULL && (rc = participant->set_default_profile(library, profile)) != DDS_RETCODE_OK) { ostr << "DdsSupport::init() - Failed to set participant default profile: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } #if defined(KNDDS_HAS_DDS_LBPlugin) // add static discovery modules if specified if (!first->lbpdFile.empty()) { MIRO_LOG(LL_NOTICE, "DDS Static Participant Discovery"); # if defined(RTIDDS_LB_BETA_VERSION) DDSLBPDiscoveryPlugin *pPlugin = new DDSLBPDiscoveryPlugin(); pPlugin->parseXmlFile(first->lbpdFile.c_str()); pPlugin->registerPlugin(participant); # else rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "dds.discovery.participant.lbpdiscovery.library", "rtilbpdisc", DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "dds.discovery.participant.lbpdiscovery.create_function", "DDS_LBPDiscoveryPlugin_create", DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "dds.discovery.participant.lbpdiscovery.config_file", first->lbpdFile.c_str(), DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "dds.discovery.participant.load_plugin", "dds.discovery.endpoint.lbpdiscovery", DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); char valueBuffer[18]; sprintf(valueBuffer, "%i", first->lbedLogVerbosity); rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "dds.discovery.participant.lbpdiscovery.verbosity", valueBuffer, DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); # endif } if (!first->lbedFile.empty()) { MIRO_LOG(LL_NOTICE, "DDS Static Endpoint Discovery"); # if defined(RTIDDS_LB_BETA_VERSION) DDSLBEDiscoveryPlugin *ePlugin = new DDSLBEDiscoveryPlugin(); ePlugin->parseXmlFile(first->lbedFile.c_str()); ePlugin->registerPlugin(participant); # else rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "dds.discovery.endpoint.lbediscovery.library", "rtilbedisc", DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "dds.discovery.endpoint.lbediscovery.create_function", "DDS_LBEDiscoveryPlugin_create", DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "dds.discovery.endpoint.lbediscovery.config_file", first->lbedFile.c_str(), DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "dds.discovery.endpoint.load_plugin", "dds.discovery.endpoint.lbediscovery", DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); char valueBuffer[18]; sprintf(valueBuffer, "%i", first->lbedLogVerbosity); rc = DDS_PropertyQosPolicyHelper_add_property(&qos.property, "dds.discovery.endpoint.lbediscovery.verbosity", valueBuffer, DDS_BOOLEAN_FALSE); assert (rc == DDS_RETCODE_OK); # endif } #endif // enable participant rc = participant->enable(); if (rc != DDS_RETCODE_OK) { ostr << "DdsSupport::init() - Failed to enable participant: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } try { partRepo->add(first->name, participant); } catch (Miro::RepositoryBase::EAlreadyRegistered const&) { throw Miro::Exception("DdsSupport::init() - Duplicate name for participant at repo."); } //------------------------------------------------- // register all relevant types with the participant // by default assume, that all types are for all domains if (first->types.empty()) { DdsTypeRegistratorRepository::InstanceMap const& types = typeRepo->getMap(); DdsTypeRegistratorRepository::InstanceMap::const_iterator f, l = types.end(); for (f = types.begin(); f != l; ++f) { try { f->second->registerType(participant); } catch (Miro::Exception const& e) { ostr << "Error registering type" << f->first << " at participant " << first->name << ": " << e.what(); throw Miro::Exception(ostr.str()); } } } else { StringVector::const_iterator f, l = first->types.end(); for (f = first->types.begin(); f != l; ++f) { try { DdsTypeRegistratorBase * tReg = typeRepo->get(*f); tReg->registerType(participant); } catch (Miro::Exception const& e) { ostr << "Error registering type" << *f << " at participant " << first->name << ": " << e.what(); throw Miro::Exception(ostr.str()); } } } //------------------------------------------------- // create all flow controllers configured for the participant vector<DdsFlowControllerParameters>::const_iterator f, l = first->flowControllers.end(); for (f = first->flowControllers.begin(); f != l; ++f) { DDS::FlowControllerProperty_t property; property.scheduling_policy = (f->schedulingPolicy == "DDS_RR_FLOW_CONTROLLER_SCHED_POLICY")? DDS_RR_FLOW_CONTROLLER_SCHED_POLICY : DDS_EDF_FLOW_CONTROLLER_SCHED_POLICY; property.token_bucket.max_tokens = (f->tokenBucket.maxTokens < 0)? DDS_LENGTH_UNLIMITED : f->tokenBucket.maxTokens; property.token_bucket.tokens_added_per_period = (f->tokenBucket.tokensAddedPerPeriod < 0)? DDS_LENGTH_UNLIMITED : f->tokenBucket.tokensAddedPerPeriod; property.token_bucket.tokens_leaked_per_period = (f->tokenBucket.tokensLeakedPerPeriod < 0)? DDS_LENGTH_UNLIMITED : f->tokenBucket.tokensLeakedPerPeriod; if (f->tokenBucket.period > ACE_Time_Value::zero) { property.token_bucket.period.sec = f->tokenBucket.period.sec(); property.token_bucket.period.nanosec = f->tokenBucket.period.usec() * 1000; } else { property.token_bucket.period = DDS_DURATION_INFINITE; } property.token_bucket.bytes_per_token = (f->tokenBucket.bytesPerToken < 0)? DDS_LENGTH_UNLIMITED : f->tokenBucket.bytesPerToken; participant->create_flowcontroller(DDS::String_dup(f->name.c_str()), property); } DDS_DomainParticipantQos_finalize(&qos); } } //------------------------------------------------- // create all publishers in configuration file // (default is 1) DdsPublisherRepository * pubRepo = DdsPublisherRepository::instance(); { NodeVector::const_iterator first, last = m_params.publishers.end(); for (first = m_params.publishers.begin(); first != last; ++first) { // per publisher DDS::DomainParticipant * participant = NULL; try { participant = partRepo->get(first->participant); } catch (Miro::Exception const&) { ostr << "Publisher specified unknown participant: " << first->participant; throw Miro::Exception(ostr.str()); } char const * profile = first->profile.empty() ? NULL : first->profile.c_str(); char const * library = first->library.empty() ? NULL : first->library.c_str(); DDS::PublisherQos qos; DDS_PublisherQos_initialize(&qos); if (profile == NULL && (m_params.defaultLibrary.empty() || m_params.defaultProfile.empty())) { DDS::ReturnCode_t rc = participant->get_default_publisher_qos(qos); if (rc != DDS_RETCODE_OK) { ostr << "Get default publisher Qos profile: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } } else { DDS::ReturnCode_t rc = dpf->get_publisher_qos_from_profile(qos, library, profile); if (rc != DDS_RETCODE_OK) { ostr << "Load publisher Qos profile: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } } char const * partition = (first->partition.empty() || first->partition == "<NONE>")? NULL : first->partition.c_str(); if (partition != NULL) { qos.partition.name.maximum(1); qos.partition.name.length(1); qos.partition.name[0] = DDS_String_dup(partition); } DDS::Publisher * publisher = participant->create_publisher(qos, NULL /* listener */, DDS::STATUS_MASK_NONE); if (publisher == NULL) { throw Miro::Exception("Failed to create publisher."); } // set default library/profile if (library != NULL && (rc = publisher->set_default_library(library)) != DDS_RETCODE_OK) { ostr << "DdsSupport::init() - Failed to set publisher default library: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } if (profile != NULL && (rc = publisher->set_default_profile(library, profile)) != DDS_RETCODE_OK) { ostr << "DdsSupport::init() - Failed to set publisher default profile: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } try { pubRepo->add(first->name, publisher); } catch (Miro::RepositoryBase::EAlreadyRegistered const&) { throw Miro::Exception("DdsSupport::init() - Duplicate name for publisher at repo."); } DDS_PublisherQos_finalize(&qos); } } //------------------------------------------------- // create all subscribers in configuration file // (default is 2) DdsSubscriberRepository * subRepo = DdsSubscriberRepository::instance(); { NodeVector::const_iterator first, last = m_params.subscribers.end(); for (first = m_params.subscribers.begin(); first != last; ++first) { // per subscriber DDS::DomainParticipant * participant = NULL; try { participant = partRepo->get(first->participant); } catch (Miro::Exception const&) { ostr << "Subscriber specified unknown participant: " << first->participant; throw Miro::Exception(ostr.str()); } char const * profile = first->profile.empty() ? NULL : first->profile.c_str(); char const * library = first->library.empty() ? NULL : first->library.c_str(); DDS::SubscriberQos qos; DDS_SubscriberQos_initialize(&qos); if (profile == NULL && (m_params.defaultLibrary.empty() || m_params.defaultProfile.empty())) { DDS::ReturnCode_t rc = participant->get_default_subscriber_qos(qos); if (rc != DDS_RETCODE_OK) { ostr << "Get default subscriber Qos profile: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } } else { DDS::ReturnCode_t rc = dpf->get_subscriber_qos_from_profile(qos, library, profile); if (rc != DDS_RETCODE_OK) { ostr << "Load subscriber Qos profile: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } } char const * partition = (first->partition.empty() || first->partition == "<NONE>")? NULL : first->partition.c_str(); if (partition != NULL) { if (strcmp("<TEAM>", partition) == 0) { Miro::RobotParameters * rp = Miro::RobotParameters::instance(); if (!rp->teamMembers.empty()) { qos.partition.name.maximum(rp->teamMembers.size()); qos.partition.name.length(rp->teamMembers.size()); for (unsigned int i = 0; i < rp->teamMembers.size(); ++i) { qos.partition.name[i] = DDS_String_dup(rp->teamMembers[i].c_str()); } } else { MIRO_LOG(LL_WARNING, "Team partition requested, but RobotParameters::teamMembers is empty, assuming ALL."); qos.partition.name.maximum(1); qos.partition.name.length(1); qos.partition.name[0] = DDS_String_dup("*"); } } else { qos.partition.name.maximum(1); qos.partition.name.length(1); qos.partition.name[0] = DDS_String_dup(partition); } } DDS::Subscriber * subscriber = participant->create_subscriber(qos, NULL /* listener */, DDS::STATUS_MASK_NONE); if (subscriber == NULL) { throw Miro::Exception("Failed to create subscriber."); } // set default library/profile if (library != NULL && (rc = subscriber->set_default_library(library)) != DDS_RETCODE_OK) { ostr << "DdsSupport::init() - Failed to set subscriber default library: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } if (profile != NULL && (rc = subscriber->set_default_profile(library, profile)) != DDS_RETCODE_OK) { ostr << "DdsSupport::init() - Failed to set subscriber default profile: " << DdsSupport::getError(rc); throw Miro::Exception(ostr.str()); } try { subRepo->add(first->name, subscriber); } catch (Miro::RepositoryBase::EAlreadyRegistered const&) { throw Miro::Exception("DdsSupport::init() - Duplicate name for subscriber at repo."); } DDS_SubscriberQos_finalize(&qos); } } //------------------------------------------------- // create all topics in configuration file // (default is 0) { TopicVector::const_iterator first, last = m_params.topics.end(); for (first = m_params.topics.begin(); first != last; ++first) { DDS::DomainParticipant * participant = NULL; try { participant = partRepo->get(first->participant); } catch (Miro::Exception const&) { ostr << "Topic specified unknown participant: " << first->participant; throw Miro::Exception(ostr.str()); } char const * profile = first->profile.empty() ? NULL : first->profile.c_str(); char const * library = first->library.empty() ? NULL : first->library.c_str(); DDS::Topic * topic = (profile || (!m_params.defaultLibrary.empty() && !m_params.defaultProfile.empty())) ? participant->create_topic_with_profile(first->name.c_str(), first->typeName.c_str(), library, profile, NULL /* listener */, DDS::STATUS_MASK_NONE) : participant->create_topic(first->name.c_str(), first->typeName.c_str(), DDS_TOPIC_QOS_DEFAULT, NULL /* listener */, DDS::STATUS_MASK_NONE); if (topic == NULL) { throw Miro::Exception("Failed to create topic."); } } } }