status_t RuleRunner::RunRule(FilerRule *rule, entry_ref &ref) { if (!rule) return B_ERROR; bool pass; printf("Running rule '%s'\n",rule->GetDescription()); if (rule->GetRuleMode() == FILER_RULE_ANY) { pass = false; for (int32 i = 0; i < rule->CountTests(); i++) { BMessage *test = rule->TestAt(i); if (IsMatch(*test,ref)) { pass = true; break; } } } else // And mode { pass = true; for (int32 i = 0; i < rule->CountTests(); i++) { BMessage *test = rule->TestAt(i); if (!IsMatch(*test,ref)) { pass = false; break; } } } if (pass) { entry_ref realref; BEntry(&ref,true).GetRef(&realref); for (int32 i = 0; i < rule->CountActions(); i++) { BMessage *action = rule->ActionAt(i); // Note that this call passes the same ref object from one call to the // next. This allows the user to chain actions together. The only thing // required to do this is for the particular action to change the ref // passed to it. status_t status = RunAction(*action,realref); if (status != B_OK) return status; } } return B_OK; }
HTTPRequestHandler* AcquisitionRequestFactoryAction::createRequestHandler(const HTTPServerRequest& request, DatabaseContext context, Logger& logger_) { string URI = request.getURI(); logger_.information("[rest/Factory] Handling request: " + URI); if (request.getMethod() == HTTPRequest::HTTP_GET) { if (IsMatch(URI, constant::station_request_pattern) || IsMatch(URI, constant::station_info_request_pattern)) { return new GetStation(URI, { context.db_handler }); } else if (IsMatch(URI, constant::meteo_request_pattern) || IsMatch(URI, constant::meteo_station_uid_request_pattern) || IsMatch(URI, constant::meteo_station_uid_request_pattern + constant::uri_query_vars_pattern) || IsMatch(URI, constant::meteo_station_uid_ts_request_pattern)) { return new GetMeteo(URI, { context.db_handler }); } else if (IsMatch(URI, constant::meteo_element_request_pattern) || IsMatch(URI, constant::meteo_element_info_request_pattern)) { return new GetMetrics(URI, { context.db_handler }); } else if (IsMatch(URI, constant::info_request_pattern)) { return new GetInfo(URI, { context.db_handler }); } else { return net::CreateRequestBad_(URI); } } else { return net::CreateRequestBad_(URI); } }
BOOL CDiskImageDos::IsMyType(int hFile, const char* szExt ) { // 확장자로 확인 if ( IsMatch( "dsk;do", szExt ) ) return TRUE; if (IsMatch("po;nib;apl;iie;prg", szExt)) return FALSE; // 모르는 확장자 인경우 내용 확인 // check for a dos order image of a dos diskette return CheckImage( hFile, sg_abyLogicalOrder ); }
int main() { assert(!IsMatch("aa", "a")); assert(IsMatch("aa","aa")); assert(!IsMatch("aaa", "aa")); assert(IsMatch("aa","*")); assert(IsMatch("aa","a*")); assert(IsMatch("aa","a**")); assert(IsMatch("ab","?*")); assert(IsMatch("hi","*?")); assert(!IsMatch("aab", "c*a*b")); return 0; }
/// <summary> /// Test the ending bytes of the string against the given pattern. /// </summary> /// <param name="str">The string to compare.</param> /// <param name="pattern">The pattern to test the string against.</param> /// <returns>True if the end of the string exactly matches the pattern; False if the end of the string does not exactly match the pattern.</returns> Bool String_EndsWith(const String str, const String pattern) { const struct StringInt *s, *p; s = (const struct StringInt *)str; p = (const struct StringInt *)pattern; return p->length <= s->length && IsMatch(s->text, p->text, s->length - p->length, p->length); }
void FvValueMaskNotifier::OnModified(const FvUInt32 oldValue, const FvUInt32 newValue) { if(GetState() == NO_MATCH) { if(IsMatch(newValue)) { _SetState(MATCH); _OnMatch(); } } else { if(!IsMatch(newValue)) { _SetState(NO_MATCH); _OnNoMatch(); } } }
int main() { char *s1 = (char *)"12345"; char *s2 = (char *)"42321"; if (IsMatch(s1, s2)) std::cout << "match!" << std::endl; else std::cout << "not match!" << std::endl; return 0; }
void FvValueRangeNotifier::OnModified(const FvInt32 iOldValue, const FvInt32 iNewValue) { m_iValue = iNewValue; if(GetState() == NO_MATCH) { if(IsMatch(iNewValue)) { _SetState(MATCH); _OnMatch(); } } else { if(!IsMatch(iNewValue)) { _SetState(NO_MATCH); _OnNoMatch(); } } }
/* todo: - destination coding if blank then it should use the extension of the source file if *.* then it should use the extension from the source file if *.png then it should store it as a png file if *.jpg then it should store it as a jpg file etc.. */ FileList::FileList(std::string src, std::string dest, std::string append) { FileInfo* info; std::string newName; std::string srcExt; std::string destExt; FileType destType; std::string tmpBase; std::cout << "FileList::FileList(src) == " << src << "\n"; tmpBase = GetBasePath( src ); if( tmpBase == src ) { GetCWD(tmpBase); // no wildcard or filename information was provided //return; } std::cout << "FileList::FileList.tmpBase == " << tmpBase << "\n"; // open the basepath dir DIR * dir; dir = opendir(tmpBase.c_str()); //TODO : need to see if the open dir fails!! dirent* de; std::string tmpName; tmpName = GetFilename(src); while((de = readdir(dir)) != NULL) { if( de->d_type == DT_REG) { // we need to see if it matches the filename/wildcard stuff? if( IsMatch( tmpName, de->d_name ) == true ) { std::cout << "file match found\n"; info = GetInfo(de, src, dest, append); mFiles.push_back( info ); } } } }
void FvValueMaskNotifier::Init(const FvUInt32 uiCurState, const FvUInt32 uiMatchMask) { m_uiMatchMask = uiMatchMask; if(IsMatch(uiCurState)) { _SetState(MATCH); } else { _SetState(NO_MATCH); } }
SceNetAdhocMatchingMemberInternal* findMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac) { if (context == NULL || mac == NULL) return NULL; SceNetAdhocMatchingMemberInternal * peer = context->peerlist; while (peer != NULL) { if (IsMatch(peer->mac, *mac)) return peer; peer = peer->next; } return NULL; }
SceNetAdhocctlScanInfo * findGroup(SceNetEtherAddr * MAC) { if (MAC == NULL) return NULL; // Group Reference SceNetAdhocctlScanInfo * group = networks; // Count Groups for (; group != NULL; group = group->next) { if (IsMatch(group->bssid.mac_addr, *MAC)) break; } // Return Network Count return group; }
bool ShouldProcess(wregex* ignorePattern, const CString& path) { if (!ignorePattern) { return true; } bool ignore = IsMatch(ignorePattern, path); if (ignore) { CString message; message.Format(TEXT("Ignoring %s"), path); OutputWriter::WriteLine(message); } return !ignore; }
void FvValueRangeNotifier::Init(const FvInt32 iCurrentValue, const FvInt32 iMin, const FvInt32 iMax) { FV_ASSERT_WARNING(iMin <= iMax); m_iMin = iMin; m_iMax = FvMathTool::Max(iMax, iMin); m_iValue = iCurrentValue; if(IsMatch(iCurrentValue)) { _SetState(MATCH); } else { _SetState(NO_MATCH); } }
int main(int argc, char* argv[]) { std::vector<std::unique_ptr<IVisitable>> objects; objects.push_back(std::unique_ptr<A>(new A(1))); objects.push_back(std::unique_ptr<B>(new B(2))); objects.push_back(std::unique_ptr<C>(new C(3))); auto b2Matcher = make_matcher<B>([](const B& b) { return b.B_ID() == 2; }); for (auto& p : objects) { if (b2Matcher.IsMatch(*p)) std::cout << "Matched a B with id 2" << std::endl; } }
/// <summary> /// Search forward through the given string looking for the given pattern. /// </summary> /// <param name="str">The string to search through.</param> /// <param name="pattern">The pattern to test the string against.</param> /// <param name="start">The offset within the text to start comparing (usually zero).</param> /// <returns>The first (leftmost) index within the string that matches the pattern, if any; if no part of the /// string matches, this returns -1.</returns> Int String_IndexOf(const String str, const String pattern, Int start) { const struct StringInt *s, *p; Int end; s = (const struct StringInt *)str; p = (const struct StringInt *)pattern; if (p->length > s->length) return -1; if (start < 0) start = 0; for (end = s->length - p->length; start <= end; start++) { if (IsMatch(s->text, p->text, start, p->length)) return start; } return -1; }
String UEventObserver::NativeWaitForNextEvent() { char buffer[1024]; for (;;) { int length = uevent_next_event(buffer, sizeof(buffer) - 1); if (length <= 0) { return String(NULL); } buffer[length] = '\0'; // Logger::V("Received uevent message: %s", buffer); if (IsMatch(buffer, length)) { // Assume the message is ASCII. return String(buffer); } } }
static int GetSingleFile( struct dirent *dir ) { for( ;; ) { if( RdosReadDir( dir->d_handle, dir->d_entry_nr, NAME_MAX, dir->d_name, &dir->d_size, &dir->d_attr, &dir->d_msb_time, &dir->d_lsb_time ) ) { if( IsMatch( dir, dir->d_name ) ) return( 1 ); else dir->d_entry_nr++; } else return( 0 ); } }
void deleteMember(SceNetAdhocMatchingContext * context, SceNetEtherAddr * mac) { if (context == NULL || mac == NULL) return; // Previous Peer Reference SceNetAdhocMatchingMemberInternal * prev = NULL; // Peer Pointer SceNetAdhocMatchingMemberInternal * peer = context->peerlist; // Iterate Peers for (; peer != NULL; peer = peer->next) { // Found Peer if (IsMatch(context->mac, *mac)) { // Multithreading Lock //context->peerlock.lock(); // Unlink Left (Beginning) if (prev == NULL) context->peerlist = peer->next; // Unlink Left (Other) else prev->next = peer->next; // Multithreading Unlock //context->peerlock.unlock(); // Free Memory free(peer); // Stop Search break; } // Set Previous Reference prev = peer; } }
/// <summary> /// Search backward through the given string looking for the given pattern. /// </summary> /// <param name="str">The string to search through.</param> /// <param name="pattern">The pattern to test the string against.</param> /// <param name="start">The start character index within the string where the search should begin (usually the length of the string). /// If passed 'n', the first substring comparison will be against the characters at (n - pattern.length) through (n - 1), inclusive.</param> /// <returns>The last (rightmost) index within the string that matches the pattern, if any; if no part of the /// string matches, this returns -1.</returns> Int String_LastIndexOf(const String str, const String pattern, Int start) { const struct StringInt *s, *p; Int slength, plength; s = (const struct StringInt *)str; p = (const struct StringInt *)pattern; slength = s->length; plength = p->length; if (plength > slength || start < plength) return -1; start -= plength; if (start >= slength - plength) { start = slength - plength; } for (; start >= 0; start--) { if (IsMatch(s->text, p->text, start, plength)) return start; } return -1; }
Element* LiveNodeList::traverseToLastElement() const { return ElementTraversal::lastWithin(rootNode(), IsMatch(*this)); }
HTTPRequestHandler* StorageRequestFactoryAction::createRequestHandler(const HTTPServerRequest& request, DatabaseContext context, Logger& logger_) { auto db_storage = context.db_storage; auto db_aggregation = context.db_aggregate; string URI = request.getURI(); logger_.information("[rest/Factory] Handling request: " + URI); if (request.getMethod() == HTTPRequest::HTTP_GET) { if (IsMatch(URI, constant::station_request_pattern) || IsMatch(URI, constant::station_info_request_pattern)) { return new net::GetStation(URI, { db_storage, db_aggregation }); } else if (IsMatch(URI, constant::aggregate_request_pattern) || IsMatch(URI, constant::aggregate_station_uid_request_pattern) || IsMatch(URI, constant::aggregate_station_period_request_pattern) || IsMatch(URI, constant::aggregate_station_period_request_pattern + constant::uri_query_vars_pattern) || IsMatch(URI, constant::aggregate_station_period_time_request_pattern)) { return new net::GetAggregate(URI, { db_storage, db_aggregation }); } else if (IsMatch(URI, constant::meteo_request_pattern) || IsMatch(URI, constant::meteo_station_uid_request_pattern) || IsMatch(URI, constant::meteo_station_uid_request_pattern + constant::uri_query_vars_pattern) || IsMatch(URI, constant::meteo_station_uid_ts_request_pattern)) { return new net::GetMeteo(URI, { db_storage, db_aggregation }); } else if (IsMatch(URI, constant::info_request_pattern)) { return new net::GetInfo(URI, { db_storage, db_aggregation }); } else if (IsMatch(URI, constant::meteo_element_request_pattern) || IsMatch(URI, constant::meteo_element_info_request_pattern)) { return new net::GetMetrics(URI, { db_storage, db_aggregation }); } else if (IsMatch(URI, constant::export_request_pattern) || IsMatch(URI, constant::export_station_uid_request_pattern) || IsMatch(URI, constant::export_station_uid_request_pattern + constant::uri_query_vars_pattern)) { return new net::GetExport(URI, { db_storage, db_aggregation }); } else if (IsMatch(URI, constant::operation_request_pattern)) { return new net::GetOperation(URI, { db_storage, db_aggregation }); } else if (IsMatch(URI, constant::period_request_pattern)) { return new net::GetPeriod(URI, { db_storage, db_aggregation }); } else { return net::CreateRequestBad_(URI); } } else { return net::CreateRequestBad_(URI); } }
const char *BadWords::Filter(const char *input, int *cch_back) { // Filter only if turned on (on is the default). if (cch_back != NULL) { *cch_back = -1; } if (!on_ || nodes_.size() == 0) { strncpyz(buffer_, input, sizeof(buffer_)); return buffer_; } // Traverse the match graph, looking for matches. Handle non-alpha // wildcards and insertions, like f*k vs. fu*k. std::list<Match> matches; std::list<MatchEntry> progress; const char *pch = input; for (; *pch != 0; pch++) { // Ignore whitespace, but track it since it will cancel some matches char ch = *pch; // Treat newlines specially. This marks the boundary between // entered chat. This is tracked. if (ch == '\n') { std::list<MatchEntry>::iterator it = progress.begin(); for (; it != progress.end(); it++) { it->has_newline = true; it->char_index_last = -1; } continue; } if (isspace(ch)) { std::list<MatchEntry>::iterator it = progress.begin(); while (it != progress.end()) { it->last_space = pch - input; if (it->match) { it->char_index_last = -1; } it++; } continue; } if (ch >= 'A' && ch <= 'Z') { ch += 'a' - 'A'; } // If it is a letter, match against the match graph. if (ch >= 'a' && ch <= 'z') { int char_index = ch - 'a'; // Examine in-progress matches. std::list<MatchEntry>::iterator it = progress.begin(); while (it != progress.end()) { // Match a trailing repeated char. MatchEntry& entry = *it; if (entry.match) { if (entry.char_index_last == char_index) { entry.end = pch - input; if (*(pch + 1) != 0) { it++; continue; } } if (IsMatch(input, entry)) { matches.push_back(Match(entry.start, entry.end)); } it = progress.erase(it); continue; } entry.char_count++; // Not matched yet. Is it a match now? dword *next_index = &nodes_[entry.current_index].indexes[char_index]; if (*next_index & kfMatMatch) { if ((!entry.has_newline && entry.wildcard_replacements == 0) || (*next_index & kfMatWildcards) != 0) { // Add a new entry that is the match, ahead of the // iterator, so it gets processed even if this is the // last char. MatchEntry new_entry = entry; new_entry.end = pch - input; new_entry.char_index_last = char_index; new_entry.standalone = (*next_index & kfMatStandalone) != 0; new_entry.standalone |= (new_entry.last_space != -1); new_entry.standalone |= ((new_entry.wildcard_count) != 0); new_entry.match = true; progress.insert(boost::next(it), new_entry); } } // Follow this char_index to the next node, if there one if (*next_index & kfMatIndex) { entry.end = pch - input; entry.current_index = (*next_index & kfMatIndex); entry.char_index_last = char_index; it++; continue; } // No next node; allow the entry to persist if it is letter // doubling. if (entry.char_index_last == char_index) { entry.end = pch - input; entry.char_count--; it++; continue; } // Remove the entry it = progress.erase(it); } // Start a new match, if there is one dword node_index = nodes_[0].indexes[char_index] & kfMatIndex; if (node_index != 0) { MatchEntry entry(pch - input, pch - input, node_index, char_index); entry.char_count = 1; progress.push_back(entry); } continue; } // Not a-z, handle skip and insertion. Insertion is easy, just // preserve existing MatchEntrys. Skips require wildcarding: // clone existing MatchEntrys, and step them for each next node. // Add new match entries for all first char matches. std::list<MatchEntry>::iterator it = progress.begin(); int next_indexes[26]; int index_count; // Start new wildcard match entries only if this is a whitespace // boundary. Otherwise it is easy to cause an explosion of match // entries by simply typing "***************". if (pch == input || isspace(*(pch - 1))) { index_count = GetNextCharIndexes(0, next_indexes); for (int i = 0; i < index_count; i++) { // Push to the front so these entries aren't enumerated again dword *next_index = &nodes_[0].indexes[next_indexes[i]]; MatchEntry entry(pch - input, pch - input, (*next_index & kfMatIndex), -1); entry.wildcard_count = 1; entry.wildcard_replacements = 1; progress.push_front(entry); } } // Handle wildcarding in existing entries while (it != progress.end()) { // Don't span existing matched entries over wildcard chars. MatchEntry& entry = *it; if (entry.match) { if (IsMatch(input, entry)) { matches.push_back(Match(entry.start, entry.end)); } it = progress.erase(it); continue; } entry.wildcard_count++; // Enumerate next nodes, and make new stepped MatchEntrys for each. index_count = GetNextCharIndexes(entry.current_index, next_indexes); for (int i = 0; i < index_count; i++) { dword *next_index = &nodes_[entry.current_index].indexes[next_indexes[i]]; // Only match if there is a trailing whitespace boundary if (*(pch + 1) == 0 || isspace(*(pch + 1))) { if ((*next_index & (kfMatMatch | kfMatWildcards)) == (kfMatMatch | kfMatWildcards)) { // And there is more string to be evaled if (*(pch + 1) != 0) { // Add a floating MatchEntry, in order to suck up // repeated chars of the match. MatchEntry new_entry = entry; new_entry.end = pch - input; // Standalone, because since there is a wildcard, // the entry is by definition standalone only. new_entry.standalone = true; new_entry.match = true; new_entry.wildcard_replacements++; progress.insert(it, new_entry); } else { // There is a wildcard, so by definition, it is // standalone only. MatchEntry new_entry = entry; new_entry.standalone = true; new_entry.end = pch - input; new_entry.wildcard_replacements++; if (IsMatch(input, new_entry)) { matches.push_back(Match(new_entry.start, new_entry.end)); } } } } // If there is a child at this char (already know there is) if (*next_index & kfMatIndex) { // And there has been kcWildcardsEntryMax wildcards only if (entry.wildcard_count <= kcWildcardsEntryMax) { // Then add a new match entry to track this path. MatchEntry new_entry = entry; new_entry.current_index = (*next_index & kfMatIndex); new_entry.end = pch - input; new_entry.wildcard_replacements++; progress.insert(it, new_entry); } } } it++; } } if (matches.size() > 1) { // See if the matches overlap; if so clean them up. bool overlap = false; std::list<Match>::iterator it = matches.begin(); for (; it != matches.end(); it++) { std::list<Match>::iterator it_next = boost::next(it); if (it_next != matches.end()) { if ((*it).end >= (*it_next).start) { overlap = true; break; } } } if (overlap) { CleanupMatches(matches); } } // Find the earliest starting entry that spans the end. // If this overlaps a match, start from the match. if (cch_back != NULL) { int earliest = -1; std::list<MatchEntry>::iterator it = progress.begin(); for (; it != progress.end(); it++) { if (earliest == -1 || (*it).start < earliest) { earliest = (*it).start; } } if (earliest != -1) { std::list<Match>::iterator itm = matches.begin(); for (; itm != matches.end(); itm++) { if (itm->end >= earliest) { earliest = itm->start; } } *cch_back = (pch - input) - earliest; } } // Any matches? If not, return the original line if (matches.size() == 0) { strncpyz(buffer_, input, sizeof(buffer_)); return buffer_; } // Finally, build the new string. return BuildResult(input, matches); }
// GetFilesRecurse //------------------------------------------------------------------------------ /*static*/ void FileIO::GetFilesRecurseEx( AString & pathCopy, const Array< AString > * patterns, Array< FileInfo > * results ) { const uint32_t baseLength = pathCopy.GetLength(); #if defined( __WINDOWS__ ) pathCopy += '*'; // don't want to use wildcard to filter folders // recurse into directories WIN32_FIND_DATA findData; HANDLE hFind = FindFirstFileEx( pathCopy.Get(), FindExInfoBasic, &findData, FindExSearchLimitToDirectories, nullptr, 0 ); if ( hFind == INVALID_HANDLE_VALUE) { return; } do { if ( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { // ignore magic '.' and '..' folders // (don't need to check length of name, as all names are at least 1 char // which means index 0 and 1 are valid to access) if ( findData.cFileName[ 0 ] == '.' && ( ( findData.cFileName[ 1 ] == '.' ) || ( findData.cFileName[ 1 ] == '\000' ) ) ) { continue; } pathCopy.SetLength( baseLength ); pathCopy += findData.cFileName; pathCopy += NATIVE_SLASH; GetFilesRecurseEx( pathCopy, patterns, results ); } } while ( FindNextFile( hFind, &findData ) != 0 ); FindClose( hFind ); // do files in this directory pathCopy.SetLength( baseLength ); pathCopy += '*'; hFind = FindFirstFileEx( pathCopy.Get(), FindExInfoBasic, &findData, FindExSearchNameMatch, nullptr, 0 ); if ( hFind == INVALID_HANDLE_VALUE) { return; } do { if ( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { continue; } if ( IsMatch( patterns, findData.cFileName ) ) { pathCopy.SetLength( baseLength ); pathCopy += findData.cFileName; if ( results->GetSize() == results->GetCapacity() ) { results->SetCapacity( results->GetSize() * 2 ); } results->SetSize( results->GetSize() + 1 ); FileInfo & newInfo = results->Top(); newInfo.m_Name = pathCopy; newInfo.m_Attributes = findData.dwFileAttributes; newInfo.m_LastWriteTime = (uint64_t)findData.ftLastWriteTime.dwLowDateTime | ( (uint64_t)findData.ftLastWriteTime.dwHighDateTime << 32 ); newInfo.m_Size = (uint64_t)findData.nFileSizeLow | ( (uint64_t)findData.nFileSizeHigh << 32 ); } } while ( FindNextFile( hFind, &findData ) != 0 ); FindClose( hFind ); #elif defined( __LINUX__ ) || defined( __APPLE__ ) DIR * dir = opendir( pathCopy.Get() ); if ( dir == nullptr ) { return; } for ( ;; ) { dirent * entry = readdir( dir ); if ( entry == nullptr ) { break; // no more entries } // dir? if ( ( entry->d_type & DT_DIR ) == DT_DIR ) { // ignore . and .. if ( entry->d_name[ 0 ] == '.' ) { if ( ( entry->d_name[ 1 ] == 0 ) || ( ( entry->d_name[ 1 ] == '.' ) && ( entry->d_name[ 2 ] == 0 ) ) ) { continue; } } // regular dir pathCopy.SetLength( baseLength ); pathCopy += entry->d_name; pathCopy += NATIVE_SLASH; GetFilesRecurseEx( pathCopy, patterns, results ); continue; } // file - does it match wildcard? if ( IsMatch( patterns, entry->d_name ) ) { pathCopy.SetLength( baseLength ); pathCopy += entry->d_name; if ( results->GetSize() == results->GetCapacity() ) { results->SetCapacity( results->GetSize() * 2 ); } results->SetSize( results->GetSize() + 1 ); FileInfo & newInfo = results->Top(); newInfo.m_Name = pathCopy; // get additional info struct stat info; VERIFY( stat( pathCopy.Get(), &info ) == 0 ); newInfo.m_Attributes = info.st_mode; #if defined( __APPLE__ ) newInfo.m_LastWriteTime = ( ( (uint64_t)info.st_mtimespec.tv_sec * 1000000000ULL ) + (uint64_t)info.st_mtimespec.tv_nsec ); #else newInfo.m_LastWriteTime = ( ( (uint64_t)info.st_mtim.tv_sec * 1000000000ULL ) + (uint64_t)info.st_mtim.tv_nsec ); #endif newInfo.m_Size = info.st_size; } } closedir( dir ); #else #error Unknown platform #endif }
// GetFilesNoRecurseEx //------------------------------------------------------------------------------ /*static*/ void FileIO::GetFilesNoRecurseEx( const char * path, const Array< AString > * patterns, Array< FileInfo > * results ) { AStackString< 256 > pathCopy( path ); PathUtils::EnsureTrailingSlash( pathCopy ); const uint32_t baseLength = pathCopy.GetLength(); #if defined( __WINDOWS__ ) pathCopy += '*'; WIN32_FIND_DATA findData; HANDLE hFind = FindFirstFileEx( pathCopy.Get(), FindExInfoBasic, &findData, FindExSearchNameMatch, nullptr, 0 ); if ( hFind == INVALID_HANDLE_VALUE) { return; } do { if ( findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { continue; } if ( IsMatch( patterns, findData.cFileName ) ) { pathCopy.SetLength( baseLength ); pathCopy += findData.cFileName; if ( results->GetSize() == results->GetCapacity() ) { results->SetCapacity( results->GetSize() * 2 ); } results->SetSize( results->GetSize() + 1 ); FileInfo & newInfo = results->Top(); newInfo.m_Name = pathCopy; newInfo.m_Attributes = findData.dwFileAttributes; newInfo.m_LastWriteTime = (uint64_t)findData.ftLastWriteTime.dwLowDateTime | ( (uint64_t)findData.ftLastWriteTime.dwHighDateTime << 32 ); newInfo.m_Size = (uint64_t)findData.nFileSizeLow | ( (uint64_t)findData.nFileSizeHigh << 32 ); } } while ( FindNextFile( hFind, &findData ) != 0 ); FindClose( hFind ); #elif defined( __LINUX__ ) || defined( __APPLE__ ) DIR * dir = opendir( pathCopy.Get() ); if ( dir == nullptr ) { return; } for ( ;; ) { dirent * entry = readdir( dir ); if ( entry == nullptr ) { break; // no more entries } // dir? if ( ( entry->d_type & DT_DIR ) == DT_DIR ) { // ingnore dirs continue; } // file - does it match wildcard? if ( IsMatch( patterns, entry->d_name ) ) { pathCopy.SetLength( baseLength ); pathCopy += entry->d_name; if ( results->GetSize() == results->GetCapacity() ) { results->SetCapacity( results->GetSize() * 2 ); } results->SetSize( results->GetSize() + 1 ); FileInfo & newInfo = results->Top(); newInfo.m_Name = pathCopy; // get additional info struct stat info; VERIFY( stat( pathCopy.Get(), &info ) == 0 ); newInfo.m_Attributes = info.st_mode; #if defined( __APPLE__ ) newInfo.m_LastWriteTime = ( ( (uint64_t)info.st_mtimespec.tv_sec * 1000000000ULL ) + (uint64_t)info.st_mtimespec.tv_nsec ); #else newInfo.m_LastWriteTime = ( ( (uint64_t)info.st_mtim.tv_sec * 1000000000ULL ) + (uint64_t)info.st_mtim.tv_nsec ); #endif newInfo.m_Size = info.st_size; } } closedir( dir ); #else #error Unknown platform #endif }
Element* LiveNodeList::traverseBackwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset) const { return traverseMatchingElementsBackwardToOffset(currentElement, &rootNode(), offset, currentOffset, IsMatch(*this)); }
int LookupStringInFixedSet(const unsigned char* graph, size_t length, const char* key, size_t key_length) { const unsigned char* pos = graph; const unsigned char* end = graph + length; const unsigned char* offset = pos; const char* key_end = key + key_length; const char* multibyte_start = 0; while (GetNextOffset(&pos, end, &offset)) { /*char <char>+ end_char offsets * char <char>+ return value * char end_char offsets * char return value * end_char offsets * return_value */ int did_consume = 0; if (key != key_end && !IsEOL(offset, end)) { /* Leading <char> is not a match. Don't dive into this child */ if (!IsMatch(offset, end, key, multibyte_start)) continue; did_consume = 1; NextPos(&offset, &key, &multibyte_start); /* Possible matches at this point: * <char>+ end_char offsets * <char>+ return value * end_char offsets * return value */ /* Remove all remaining <char> nodes possible */ while (!IsEOL(offset, end) && key != key_end) { if (!IsMatch(offset, end, key, multibyte_start)) return -1; NextPos(&offset, &key, &multibyte_start); } } /* Possible matches at this point: * end_char offsets * return_value * If one or more <char> elements were consumed, a failure * to match is terminal. Otherwise, try the next node. */ if (key == key_end) { int return_value; if (GetReturnValue(offset, end, multibyte_start, &return_value)) return return_value; /* The DAFSA guarantees that if the first char is a match, all * remaining char elements MUST match if the key is truly present. */ if (did_consume) return -1; continue; } if (!IsEndCharMatch(offset, end, key, multibyte_start)) { if (did_consume) return -1; /* Unexpected */ continue; } NextPos(&offset, &key, &multibyte_start); pos = offset; /* Dive into child */ } return -1; /* No match */ }
// Depth-first traversal of sub-tree (below root_elem) xmlNodePtr ProtoXml::IterFinder::GetNext() { //TRACE("enter ProtoXml::IterFinder::GetNext() prev_elem:%s\n", prev_elem ? (const char*)prev_elem->name : "(null)"); if(NULL == prev_elem) { return NULL; } else if (prev_elem != root_elem) { // We need to skip the subtree of the prev_elem // This involves moving right or up and right xmlNodePtr nextElem = prev_elem->next; while (NULL == nextElem) { prev_elem = prev_elem->parent; // move up iter_depth--; if (prev_elem != root_elem) nextElem = prev_elem->next; // move right else break; // we're done (returned to root_elem) } prev_elem = nextElem; // Check for match before descending if (NULL != nextElem) { if (!UpdateCurrentPath(iter_depth, (const char*)nextElem->name)) PLOG(PL_WARN, "ProtoXml::IterFinder::GetNext() error: unable to update current path\n"); else if (IsMatch()) return nextElem; // found match, done for now } } // Descend down or across tree while (NULL != prev_elem) { // First, try to move down or the right of the tree xmlNodePtr nextElem = prev_elem->xmlChildrenNode; if (NULL == nextElem) { if (prev_elem != root_elem) { nextElem = prev_elem->next; // no children, try next sibling } else { prev_elem = NULL; // done, root_elem had no children return NULL; } } else if (prev_elem != root_elem) { iter_depth++; } // Second, if needed, move back up the tree and to the right while (NULL == nextElem) { // No child or sibling, so move up a level // and right to parent's next sibling prev_elem = prev_elem->parent; // move up iter_depth--; if (prev_elem != root_elem) nextElem = prev_elem->next; // move right else break; // we're done (returned to root_elem) } prev_elem = nextElem; if (NULL != nextElem) { if (!UpdateCurrentPath(iter_depth, (const char*)nextElem->name)) { PLOG(PL_WARN, "ProtoXml::IterFinder::GetNext() error: unable to update current path\n"); continue; } if (IsMatch()) break; // found match, done for now } } return prev_elem; } // end ProtoXml::IterFinder::GetNext()
void MSSMessage::Add(unsigned char *p, size_t len) { for (size_t i = 0; i < len; i++ ) { mInput.push_back(p[i]); } while (true) { { if (mInput.size() >= mHeaderSize) { if (IsMatch(mHeader, mHeaderSize)) { if (mDiscard > 0) Debug::PrintLine(Debug::MSSMSG, "Found the header (discarded %d bytes)", mDiscard); else Debug::PrintLine(Debug::MSSMSG, "Found the header"); mDiscard = 0; // erase the matched bytes, step to next state mInput.erase(mInput.begin(), mInput.begin() + mHeaderSize); mState = HEADERBODY; // match - move to next state //Debug::PrintLine(Debug::MSSMSG, "current state is %d", mState); } else { // discard the first character mDiscard++; mInput.erase(mInput.begin()); } } else break; } if (mState == HEADERBODY) { if (mInput.size() >= sizeof(DWORD) + sizeof(DWORD) + sizeof(DWORD)) // enough bytes in the buffer for 3 words ? { mMessageLength = ConvertWord(true, 0); // get and convert the message length mInput.erase(mInput.begin(), mInput.begin() + sizeof(DWORD)); mMessageType = ConvertWord(true, 0); // get and convert the message type mInput.erase(mInput.begin(), mInput.begin() + sizeof(DWORD)); mMessageId = ConvertWord(false, 0); // get the message ID mInput.erase(mInput.begin(), mInput.begin() + sizeof(DWORD)); Debug::PrintLine(Debug::MSSMSG, "type = %d, length = %d, id = 0x%08x", mMessageType, mMessageLength, mMessageId); mState = HEADERSTOP; //Debug::PrintLine(Debug::MSSMSG, "current state is %d", mState); } else break; } if (mState == HEADERSTOP) { if (mInput.size() >= mFooterSize) { if (IsMatch(mFooter, mFooterSize)) { if (mDiscard > 0) Debug::PrintLine(Debug::MSSMSG, "Found the footer (discarded %d bytes)", mDiscard); else Debug::PrintLine(Debug::MSSMSG, "Found the footer"); mDiscard = 0; mInput.erase(mInput.begin(), mInput.begin() + mFooterSize); mState = MESSAGEBODY; //Debug::PrintLine(Debug::MSSMSG, "current state is %d", mState); } else { // discard the first character mDiscard++; mInput.erase(mInput.begin()); } } else break; } if (mState == MESSAGEBODY) { // Parse the message. // On return, either the message was OK and input bytes will have been consumed, // or the message was garbled and any unread input is still in the buffer (mInput). // In either case, start looking for the next message header (set mState to HEADERSTART) switch (mMessageType) { case CAPTURECOMPLETE: DoCaptureComplete(true); break; case CAPTUREFAIL: DoCaptureComplete(false); break; case ACKNOWLEDGE: DoAcknowledge(); break; case STATUS: DoStatusReply(); break; default: // message garbled Debug::PrintLine(Debug::MSSMSG, "message type unknown - type = %d", mMessageType); break; } mState = HEADERSTART; //Debug::PrintLine(Debug::MSSMSG, "current state is %d", mState); } } //Debug::PrintLine(Debug::MSSMSG, "current state is %d", mState); }
RESULTCODE CsvImportProcessorImpl::Execute() { GError *pError = augeGetErrorInstance(); GLogger *pLogger = augeGetLoggerInstance(); char csvDrv[AUGE_DRV_MAX]; char csvDir[AUGE_PATH_MAX]; char csvName[AUGE_NAME_MAX]; char csvPath[AUGE_PATH_MAX]; char constr[AUGE_PATH_MAX]; memset(csvDrv, 0, AUGE_DRV_MAX); memset(csvDir, 0, AUGE_PATH_MAX); memset(csvName, 0, AUGE_NAME_MAX); memset(csvPath, 0, AUGE_PATH_MAX); memset(constr,0,AUGE_PATH_MAX); auge_split_path(m_csv_path.c_str(), csvDrv, csvDir,csvName,NULL); auge_make_path(csvPath, csvDrv,csvDir,NULL,NULL); g_sprintf(constr,"DATABASE=%s",csvPath); DataEngine* pDataEngine = NULL; DataEngineManager* pDataEngineManager = augeGetDataEngineManagerInstance(); pDataEngine = pDataEngineManager->GetEngine("CsvFile"); if(pDataEngine==NULL) { pLogger->Error(pError->GetLastError(),__FILE__,__LINE__); return AG_FAILURE; } RESULTCODE rc = AG_FAILURE; Workspace* pcsvWorkspace = pDataEngine->CreateWorkspace(); pcsvWorkspace->SetConnectionString(constr); rc = pcsvWorkspace->Open(); if(rc!=AG_SUCCESS) { pLogger->Error(pError->GetLastError(),__FILE__,__LINE__); pcsvWorkspace->Release(); return AG_FAILURE; } FeatureWorkspace* pobjWorkspace = NULL; ConnectionManager* pConnectionManager = augeGetConnectionManagerInstance(); pobjWorkspace = dynamic_cast<FeatureWorkspace*>(pConnectionManager->GetWorkspace(m_user, m_source_name.c_str())); if(pobjWorkspace==NULL) { pLogger->Error(pError->GetLastError(),__FILE__,__LINE__); pcsvWorkspace->Release(); return AG_FAILURE; } FeatureClass* pFeatureClass = NULL; pFeatureClass = pobjWorkspace->OpenFeatureClass(m_dataset_name.c_str()); if(pFeatureClass==NULL) { pLogger->Error(pError->GetLastError(),__FILE__,__LINE__); pcsvWorkspace->Release(); return AG_FAILURE; } AttributeDataSet* pcsvDataset = static_cast<AttributeDataSet*>(pcsvWorkspace->OpenDataSet(csvName)); GFields* pcsvFields = pcsvDataset->GetFields(); GFields* pobjFields = pFeatureClass->GetFields(); if(!IsMatch(pcsvFields,pobjFields)) { const char* msg = "Field is not matched"; pError->SetError(msg); pLogger->Error(msg, __FILE__, __LINE__); pFeatureClass->Release(); pcsvDataset->Release(); pcsvWorkspace->Release(); return AG_FAILURE; } FeatureInsertCommand* cmd = pFeatureClass->CreateInsertCommand(); Row* pRow = NULL; Cursor* pCursor = pcsvDataset->GetRows(); while((pRow=pCursor->NextRow())!=NULL) { AddFeature(pRow, pFeatureClass,cmd); pRow->Release(); } cmd->Commit(); cmd->Release(); pCursor->Release(); pFeatureClass->Refresh(); pFeatureClass->Release(); pcsvDataset->Release(); pcsvWorkspace->Release(); return AG_SUCCESS; }