// -------------------------------------------------------------------------- CSeq_entry_Handle CAsn2FastaApp::ObtainSeqEntryFromSeqEntry( CObjectIStream& is) // -------------------------------------------------------------------------- { try { CRef<CSeq_entry> se(new CSeq_entry); is >> *se; if (se->Which() == CSeq_entry::e_not_set) { NCBI_THROW(CException, eUnknown, "provided Seq-entry is empty"); } return m_Scope->AddTopLevelSeqEntry(*se); } catch (CException& e) { if (! (is.GetFailFlags() & is.eEOF)) { ERR_POST(Error << e); } } return CSeq_entry_Handle(); }
const CBioseq_Handle& CAlnVec::GetBioseqHandle(TNumrow row) const { TBioseqHandleCache::iterator i = m_BioseqHandlesCache.find(row); if (i != m_BioseqHandlesCache.end()) { return i->second; } else { CBioseq_Handle bioseq_handle = GetScope().GetBioseqHandle(GetSeqId(row)); if (bioseq_handle) { return m_BioseqHandlesCache[row] = bioseq_handle; } else { string errstr = string("CAlnVec::GetBioseqHandle(): ") + "Seq-id cannot be resolved: " + GetSeqId(row).AsFastaString(); NCBI_THROW(CAlnException, eInvalidSeqId, errstr); } } }
bool CGeneInfoFileReader::x_GiToGeneId(int gi, list<int>& listGeneIds) { STwoIntRecord* pRecs; int nRecs; bool retval = false; if (s_GetMemFilePtrAndLength(m_memGi2GeneFile.get(), pRecs, nRecs)) { retval = s_SearchSortedArray(pRecs, nRecs, gi, 1, listGeneIds, false); } else { NCBI_THROW(CGeneInfoException, eFileNotFoundError, "Cannot access the memory-mapped file for " "Gi to Gene ID conversion."); } return retval; }
bool CJsonOverUTTPReader::x_AddNewNode(CJsonNode::TInstance new_node) { if (!m_CurrentNode) { m_CurrentNode = new_node; return false; } else if (m_HashValueIsExpected) { m_HashValueIsExpected = false; m_CurrentNode.SetByKey(m_HashKey, new_node); } else // The current node is either a JSON object or an array, // because if it was a non-container node then this method // wouldn't have been called. if (m_CurrentNode.IsArray()) m_CurrentNode.Append(new_node); else { NCBI_THROW(CJsonOverUTTPException, eObjectKeyMustBeString, "JSON-over-UTTP: Invalid object key type"); } return true; }
CObjectOStream* CObjectOStream::Open(ESerialDataFormat format, CNcbiOstream& outStream, bool bdeleteStream) { EOwnership deleteStream = bdeleteStream ? eTakeOwnership : eNoOwnership; switch ( format ) { case eSerial_AsnText: return OpenObjectOStreamAsn(outStream, deleteStream); case eSerial_AsnBinary: return OpenObjectOStreamAsnBinary(outStream, deleteStream); case eSerial_Xml: return OpenObjectOStreamXml(outStream, deleteStream); case eSerial_Json: return OpenObjectOStreamJson(outStream, deleteStream); default: break; } NCBI_THROW(CSerialException,eNotImplemented, "CObjectOStream::Open: unsupported format"); }
CAsnCache_DataLoader::SCacheInfo& CAsnCache_DataLoader::x_GetIndex() { if (m_IndexMap.empty()) { NCBI_THROW(CException, eUnknown, "setup failure: no cache objects available"); } CFastMutexGuard LOCK(m_Mutex); // hash to a pool of cache objects based on thread ID int id = CThread::GetSelf(); id %= m_IndexMap.size(); TIndexMap::iterator iter = m_IndexMap.begin() + id; if ( !iter->get() ) { iter->reset(new SCacheInfo); (*iter)->cache.Reset(new CAsnCache(m_DbPath)); } return **iter; }
CNetScheduleAPI CNetScheduleClientFactory::CreateInstance() { CConfig conf(m_Registry); const CConfig::TParamTree* param_tree = conf.GetTree(); const TPluginManagerParamTree* netschedule_tree = param_tree->FindSubNode(kNetScheduleAPIDriverName); if (netschedule_tree) { SNetScheduleAPIImpl* ret = m_PM_NetSchedule.CreateInstance( kNetScheduleAPIDriverName, TPMNetSchedule::GetDefaultDrvVers(), netschedule_tree); if (ret != NULL) return ret; } NCBI_THROW(CNSClientFactoryException, eNSClientIsNotCreated, "Couldn't create NetSchedule client. Check registry."); }
void CJsonOverUTTPWriter::SendOutputBuffer() { const char* output_buffer; size_t output_buffer_size; size_t bytes_written; do { m_UTTPWriter.GetOutputBuffer(&output_buffer, &output_buffer_size); for (;;) { if (m_Pipe.Write(output_buffer, output_buffer_size, &bytes_written) != eIO_Success) { NCBI_THROW(CIOException, eWrite, "Error while writing to the pipe"); } if (bytes_written == output_buffer_size) break; output_buffer += bytes_written; output_buffer_size -= bytes_written; } } while (m_UTTPWriter.NextOutputBuffer()); }
TMemberIndex CChoicePointerTypeInfo::GetPtrIndex(const CChoiceTypeInfo* choiceType, TConstObjectPtr choicePtr) { const CChoicePointerTypeInfo* choicePtrType = CTypeConverter<CChoicePointerTypeInfo>::SafeCast(choiceType); const CPointerTypeInfo* ptrType = choicePtrType->m_PointerTypeInfo; TConstObjectPtr classPtr = ptrType->GetObjectPointer(choicePtr); if ( !classPtr ) return choicePtrType->m_NullPointerIndex; const CClassTypeInfo* classType = CTypeConverter<CClassTypeInfo>::SafeCast(ptrType->GetPointedType()); const TVariantsByType& variants = choicePtrType->m_VariantsByType; TVariantsByType::const_iterator v = variants.find(classType->GetCPlusPlusTypeInfo(classPtr)); if ( v == variants.end() ) NCBI_THROW(CSerialException,eInvalidData, "incompatible CChoicePointerTypeInfo type"); return v->second; }
bool CGeneInfoFileReader::x_GeneIdToGi(int geneId, int iGiField, list<int>& listGis) { SMultiIntRecord<4>* pRecs; int nRecs; bool retval = false; if (s_GetMemFilePtrAndLength(m_memGene2GiFile.get(), pRecs, nRecs)) { retval = s_SearchSortedArray(pRecs, nRecs, geneId, iGiField, listGis, true); } else { NCBI_THROW(CGeneInfoException, eFileNotFoundError, "Cannot access the memory-mapped file for " "Gene ID to Gi conversion."); } return retval; }
void CBlastHitMatrixCGIApplication::x_GetSeqAnnot(CCgiContext& ctx) { const CNcbiRegistry & reg = ctx.GetConfig(); string blastURL = reg.Get("NetParams", "BlastURL"); string url = (string)blastURL + "?CMD=Get&RID=" + m_RID + "&FORMAT_TYPE=ASN.1&FORMAT_OBJECT=Alignment"; SConnNetInfo* net_info = ConnNetInfo_Create(NULL); // create HTTP connection CConn_HttpStream inHttp(url,net_info); try { m_Annot.Reset(new CSeq_annot); auto_ptr<CObjectIStream> is (CObjectIStream::Open(eSerial_AsnText, inHttp)); *is >> *m_Annot; } catch (CException& e) { m_Annot.Reset(); NCBI_THROW(CBlastHitMatrixCGIException, eInvalidSeqAnnot, "Exception reading SeqAnnot via url " + url + ", exception message: " + e.GetMsg()); } }
int CSeqDB::GetAmbigSeqAlloc(int oid, char ** buffer, int nucl_code, ESeqDBAllocType strategy, TSequenceRanges *masks) const { m_Impl->Verify(); if ((strategy != eMalloc) && (strategy != eNew)) { NCBI_THROW(CSeqDBException, eArgErr, "Invalid allocation strategy specified."); } int rv = m_Impl->GetAmbigSeq(oid, buffer, nucl_code, 0, strategy, masks); m_Impl->Verify(); return rv; }
CSeqDB::CSeqDB(const string & dbname, ESeqType seqtype, CSeqDBNegativeList * nlist) { if (dbname.size() == 0) { NCBI_THROW(CSeqDBException, eArgErr, "Database name is required."); } m_Impl = s_SeqDBInit(dbname, s_GetSeqTypeChar(seqtype), 0, 0, true, NULL, nlist); m_Impl->Verify(); }
pair<TMemberIndex, const CItemsInfo::TItemsByTag*> CItemsInfo::GetItemsByTagInfo(void) const { typedef pair<TMemberIndex, const TItemsByTag*> TReturn; TReturn ret(m_ZeroTagIndex, m_ItemsByTag.get()); if ( ret.first == kInvalidMember && ret.second == 0 ) { CFastMutexGuard GUARD(s_ItemsMapMutex); ret = TReturn(m_ZeroTagIndex, m_ItemsByTag.get()); if ( ret.first == kInvalidMember && ret.second == 0 ) { { CIterator i(*this); if ( i.Valid() ) { ret.first = *i-GetItemInfo(i)->GetId().GetTag(); for ( ++i; i.Valid(); ++i ) { if ( ret.first != *i-GetItemInfo(i)->GetId().GetTag() ) { ret.first = kInvalidMember; break; } } } } if ( ret.first != kInvalidMember ) { m_ZeroTagIndex = ret.first; } else { auto_ptr<TItemsByTag> items(new TItemsByTag); for ( CIterator i(*this); i.Valid(); ++i ) { const CItemInfo* itemInfo = GetItemInfo(i); TTag tag = itemInfo->GetId().GetTag(); if ( !items->insert(TItemsByTag::value_type(tag, *i)).second ) { NCBI_THROW(CSerialException,eInvalidData, "duplicate member tag"); } } ret.second = items.get(); m_ItemsByTag = items; } } } return ret; }
char* CDelta_ext_PackTarget::NewSegment(CSeqUtil::TCoding coding, TSeqPos length) { CRef<CDelta_seq> ds(new CDelta_seq); CSeq_literal& lit = ds->SetLiteral(); lit.SetLength(length); m_Obj.Set().push_back(ds); switch (coding) { case CSeqUtil::e_not_set: return NULL; #define CODING_CASE_EX(key, type, setter, len) \ case CSeqUtil::key: \ { \ type& dest = lit.SetSeq_data().setter(); \ dest.Set().resize(len); \ return &dest.Set()[0]; \ } #define CODING_CASE(name, type) \ CODING_CASE_EX(e_##name, type, Set##name, length) CODING_CASE_EX(e_Ncbi2na, CNCBI2na, SetNcbi2na, (length + 3) / 4) CODING_CASE_EX(e_Ncbi4na, CNCBI4na, SetNcbi4na, (length + 1) / 2) // case CSeqUtil::e_Ncbi4na_expand: // CODING_CASE(Ncbi8na, CNCBI8na) CODING_CASE(Iupacaa, CIUPACaa) CODING_CASE(Ncbi8aa, CNCBI8aa) CODING_CASE(Ncbieaa, CNCBIeaa) CODING_CASE(Ncbistdaa, CNCBIstdaa) #undef CODING_CASE #undef CODING_CASE_EX default: NCBI_THROW(CSeqUtilException, eInvalidCoding, "CDelta_ext_PackTarget: unexpected coding"); } }
CSeqDB::CSeqDB(const string & dbname, ESeqType seqtype, CSeqDBGiList * gi_list) { if (dbname.size() == 0) { NCBI_THROW(CSeqDBException, eArgErr, "Database name is required."); } char seq_type = s_GetSeqTypeChar(seqtype); m_Impl = s_SeqDBInit(dbname, seq_type, 0, 0, true, gi_list); m_Impl->Verify(); }
int CBlastHitMatrixCGIApplication::ProcessRequest(CCgiContext &ctx) { // retrieve our CGI rendering params x_GetCGIContextParams(ctx); x_InitAppData(ctx); bool success = true; if(m_BlastHitMatrix->IsFileOut()) { success = m_BlastHitMatrix->WriteToFile(); } else { string encoding("image/png"); CCgiResponse& response = ctx.GetResponse(); response.SetContentType(encoding); response.WriteHeader(); success = m_BlastHitMatrix->Display(response.out()); } if(!success) { NCBI_THROW(CBlastHitMatrixCGIException, eImageRenderError, "Exception occured, exception message: " + m_BlastHitMatrix->GetErrorMessage()); } return 0; }
CRef<CGC_Assembly> CGenomicCollectionsService::GetAssembly(const string& acc_, const string& mode) { string acc = NStr::TruncateSpaces(acc_); ValidateAsmAccession(acc); CGCClient_GetAssemblyBlobRequest req; CGCClientResponse reply; req.SetAccession(acc); req.SetMode(mode); LogRequest(req); try { return CCachedAssembly(AskGet_assembly_blob(req, &reply)).Assembly(); } catch (CException& ex) { if(reply.IsSrvr_error()) { NCBI_THROW(CException, eUnknown, reply.GetSrvr_error().GetDescription()); } throw; } }
CGeneInfoFileReader::CGeneInfoFileReader(const string& strGi2GeneFile, const string& strGene2OffsetFile, const string& strGi2OffsetFile, const string& strAllGeneDataFile, const string& strGene2GiFile, bool bGiToOffsetLookup) : m_strGi2GeneFile(strGi2GeneFile), m_strGene2OffsetFile(strGene2OffsetFile), m_strGi2OffsetFile(strGi2OffsetFile), m_strGene2GiFile(strGene2GiFile), m_strAllGeneDataFile(strAllGeneDataFile), m_bGiToOffsetLookup(bGiToOffsetLookup) { if (!OpenBinaryInputFile(m_strAllGeneDataFile, m_inAllData)) { NCBI_THROW(CGeneInfoException, eFileNotFoundError, "Cannot open the Gene Data file for reading: " + m_strAllGeneDataFile); } x_MapMemFiles(); }
void CSeqVector_CI::x_PrevCacheSeg() { _ASSERT(m_SeqMap); TSeqPos pos = x_CachePos(); if ( pos-- == 0 ) { // Can not go further NCBI_THROW(CSeqVectorException, eOutOfRange, "Can not update cache: iterator beyond start"); } TSeqPos size = x_GetSize(); // save current cache in backup x_SwapCache(); // update segment if needed if ( m_Seg.IsInvalid() ) { x_InitSeg(pos); } else { while ( m_Seg && m_Seg.GetPosition() > pos ) { x_DecSeg(); } } if ( !m_Seg ) { NCBI_THROW_FMT(CSeqVectorException, eDataError, "CSeqVector_CI: invalid sequence length: " <<pos<<" <> "<<size); } // Try to re-use backup cache if ( pos >= x_CachePos() && pos < x_CacheEndPos() ) { m_Cache = m_CacheData.get() + pos - x_CachePos(); } else { // can not use backup cache x_ResetCache(); x_UpdateCacheDown(pos); _ASSERT(GetPos() == pos); _ASSERT(x_CacheSize()); _ASSERT(x_CacheEndPos() == pos+1); } }
const CItemsInfo::TItemsByName& CItemsInfo::GetItemsByName(void) const { TItemsByName* items = m_ItemsByName.get(); if ( !items ) { CFastMutexGuard GUARD(s_ItemsMapMutex); items = m_ItemsByName.get(); if ( !items ) { auto_ptr<TItemsByName> keep(items = new TItemsByName); for ( CIterator i(*this); i.Valid(); ++i ) { const CItemInfo* itemInfo = GetItemInfo(i); const string& name = itemInfo->GetId().GetName(); if ( !items->insert(TItemsByName::value_type(name, *i)).second ) { if ( !name.empty() ) NCBI_THROW(CSerialException,eInvalidData, string("duplicate member name: ")+name); } } m_ItemsByName = keep; } } return *items; }
CTempString CBlastDbBlob::x_ReadString(EStringFormat fmt, int * offsetp) const { int sz = 0; if (fmt == eSize4) { sz = x_ReadIntFixed<int,4>(offsetp); } else if (fmt == eSizeVar) { sz = x_ReadVarInt(offsetp); } const char * datap = ""; if (fmt == eNUL) { CTempString ts = Str(); int zoffset = -1; for(size_t i = *offsetp; i < ts.size(); i++) { if (ts[i] == (char)0) { zoffset = i; break; } } if (zoffset == -1) { NCBI_THROW(CSeqDBException, eFileErr, "CBlastDbBlob::ReadString: Unterminated string."); } datap = ts.data() + *offsetp; sz = zoffset - *offsetp; *offsetp = zoffset+1; } else { datap = x_ReadRaw(sz, offsetp); } return CTempString(datap, sz); }
BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: // constructor CSeq_data::CSeq_data(const string& value, E_Choice index) { // Does value have to be validated // create seq type data holder switch (index) { case e_Iupacna: case e_Iupacaa: case e_Ncbieaa: DoConstruct (value, index); break; case e_Ncbi2na: case e_Ncbi4na: case e_Ncbi8na: case e_Ncbipna: case e_Ncbi8aa: case e_Ncbipaa: case e_Ncbistdaa: { vector< char > v; v.resize (value.size()); memcpy(&v[0], value.c_str(), value.size()); DoConstruct (v, index); break; } default: // throw error NCBI_THROW (CException, eUnknown, "CSeq_data constructor: Invalid E_Choice index"); } }
string CBlastDbFormatter::Write(const SSeqDBInitInfo& db_init_info) { CBlastDbMetadata dbmeta(db_init_info); vector<string> data2write; data2write.reserve(m_ReplacementTypes.size()); ITERATE(vector<char>, fmt, m_ReplacementTypes) { switch (*fmt) { case 'f': // file name data2write.push_back(dbmeta.GetFileName()); break; case 't': // title data2write.push_back(dbmeta.GetTitle()); break; case 'n': // number of sequences data2write.push_back(dbmeta.GetNumberOfSequences()); break; case 'l': // DB length data2write.push_back(dbmeta.GetDbLength()); break; case 'p': // molecule type data2write.push_back(dbmeta.GetMoleculeType()); break; case 'd': // date of last update data2write.push_back(dbmeta.GetDate()); break; case 'U': // Disk usage data2write.push_back(dbmeta.GetDiskUsage()); break; default: CNcbiOstrstream os; os << "Unrecognized format specification: '%" << *fmt << "'"; NCBI_THROW(CInvalidDataException, eInvalidInput, CNcbiOstrstreamToString(os)); } } return x_Replacer(data2write); }
void CPIDGuard::Release(void) { if ( !m_Path.empty() ) { // MT-Safe protect CFastMutexGuard LOCK(s_PidGuardMutex); // Read info TPid pid = 0; unsigned int ref = 0; CNcbiIfstream in(m_Path.c_str()); if ( in.good() ) { in >> pid >> ref; in.close(); if ( m_NewPID != pid ) { // We do not own this file more return; } if ( ref ) { ref--; } // Check reference counter if ( ref ) { // Write updated reference counter into the file CNcbiOfstream out(m_Path.c_str(), IOS_BASE::out | IOS_BASE::trunc); if ( out.good() ) { out << pid << endl << ref << endl; } if ( !out.good() ) { NCBI_THROW(CPIDGuardException, eWrite, "Unable to write into PID file " + m_Path +": " + _T_CSTRING(NcbiSys_strerror(errno))); } } else { // Remove the file CDirEntry(m_Path).Remove(); } }
ERR_Action Tokenize(const CTempString raw_line, vector<CTempString>& tokens) { if (!m_FieldNamesExtracted) { x_ExtractNames(raw_line); return eRR_Skip; } // The field names have been extracted so tokenize and check the data // consistency. // Note: the only action Tokenize() returns is eRR_Continue_Data TRowReaderStream_SingleTabDelimited::Tokenize(raw_line, tokens); if (tokens.size() != m_NumberOfFields) NCBI_THROW(CCRowReaderStream_IANA_TSV_Exception, eNumberOfFieldsMismatch, "Unexpected number of fields. The first line declared " + NStr::NumericToString(m_NumberOfFields) + "fields while the current line has " + NStr::NumericToString(tokens.size()) + " fields"); return eRR_Continue_Data; }
CSeqDB::CSeqDB(const vector<string> & dbs, ESeqType seqtype, CSeqDBGiList * gi_list) { string dbname; SeqDB_CombineAndQuote(dbs, dbname); if (dbname.size() == 0) { NCBI_THROW(CSeqDBException, eArgErr, "Database name is required."); } m_Impl = s_SeqDBInit(dbname, s_GetSeqTypeChar(seqtype), 0, 0, true, gi_list); m_Impl->Verify(); }
CSeqDB::CSeqDB(const string & dbname, ESeqType seqtype, int oid_begin, int oid_end, bool use_mmap, CSeqDBGiList * gi_list) { if (dbname.size() == 0) { NCBI_THROW(CSeqDBException, eArgErr, "Database name is required."); } m_Impl = s_SeqDBInit(dbname, s_GetSeqTypeChar(seqtype), oid_begin, oid_end, use_mmap, gi_list); m_Impl->Verify(); }
const CAuth_list& CPub::GetAuthors (void) const { switch (Which()) { case CPub::e_Gen : return (GetGen().GetAuthors()); case CPub::e_Sub : return (GetSub().GetAuthors()); case CPub::e_Article : return (GetArticle().GetAuthors()); case CPub::e_Book : return (GetBook().GetAuthors()); case CPub::e_Proc : return (GetProc().GetBook().GetAuthors()); case CPub::e_Patent : return (GetPatent().GetAuthors()); case CPub::e_Man : return (GetMan().GetCit().GetAuthors()); default : NCBI_THROW(CSerialException, eNotImplemented, "CPub::GetAuthors: unsupported entry type " + SelectionName(Which())); } }
string CGenomicCollectionsService::ValidateChrType(string chrType, string chrLoc) { CGCClient_ValidateChrTypeLocRequest req; CGCClientResponse reply; req.SetType(chrType); req.SetLocation(chrLoc); #ifdef _DEBUG ostringstream ostrstrm; ostrstrm << "Making request -" << MSerial_AsnText << req; LOG_POST(Info << ostrstrm.str()); #endif try { return AskGet_chrtype_valid(req, &reply); } catch (CException& ex) { if(reply.Which() == CGCClientResponse::e_Srvr_error) { NCBI_THROW(CException, eUnknown, reply.GetSrvr_error().GetDescription()); } throw; } }