Version::Version(const String& string) { String delim(Text(".")); String part; SizeT start = 0; auto pos = string.Split(delim, part, start); while (-1 != pos) { SizeT value = 0; auto raw = part.GetBuffer(); if (nullptr != raw) { while (*raw != Text('\0') && !_istdigit(*raw)) { raw++; } value = _tcstoul(raw, NULL, 10); } m_parts.push_back(value); pos = string.Split(delim, part, start); } }
bool EditorMode::PlayProject(String addArgs, bool debug) { ToolEnvironment* env = GetSubsystem<ToolEnvironment>(); ToolSystem* tsystem = GetSubsystem<ToolSystem>(); const String& editorBinary = env->GetEditorBinary(); Project* project = tsystem->GetProject(); if (!project) return false; Vector<String> paths; paths.Push(env->GetCoreDataDir()); paths.Push(env->GetPlayerDataDir()); paths.Push(project->GetResourcePath()); // fixme: this is for loading from cache paths.Push(project->GetProjectPath()); paths.Push(project->GetProjectPath() + "Cache"); String resourcePaths; resourcePaths.Join(paths, "!"); Vector<String> vargs; String args = ToString("--player --project \"%s\"", AddTrailingSlash(project->GetProjectPath()).CString()); vargs = args.Split(' '); if (debug) vargs.Insert(0, "--debug"); if (addArgs.Length() > 0) vargs.Insert(0, addArgs.Split(' ')); String dump; dump.Join(vargs, " "); LOGINFOF("Launching Broker %s %s", editorBinary.CString(), dump.CString()); IPC* ipc = GetSubsystem<IPC>(); playerBroker_ = ipc->SpawnWorker(editorBinary, vargs); if (playerBroker_) { SubscribeToEvent(playerBroker_, E_IPCJSERROR, HANDLER(EditorMode, HandleIPCJSError)); SubscribeToEvent(playerBroker_, E_IPCWORKEREXIT, HANDLER(EditorMode, HandleIPCWorkerExit)); SubscribeToEvent(playerBroker_, E_IPCWORKERLOG, HANDLER(EditorMode, HandleIPCWorkerLog)); } return playerBroker_.NotNull(); }
void InFtpAnalyzerStream::ProcessLine(const AString& line) { FtpAnalyzer *fa = (FtpAnalyzer*)m_analyzer; cmatch m; if (regex_search((const char*)line.begin(), (const char*)line.end(), m, s_reFtpResponse)) { int code = atoi(String(m[1])); switch (code) { case 220: { ASCIIEncoding enc; String s = enc.GetChars(line); vector<String> vec = s.Split(); if (vec.size() >= 2 && vec[1].Find(".") != -1) fa->ServerName = vec[1]; } break; case 227: fa->PrepareEndpoint(ASCIIEncoding().GetChars(line)); break; case 230: if (fa->UserName!="anonymous" && !fa->m_user) (fa->m_user=FtpUser::FindByServerLogin(fa->m_ci->DstEndPoint, fa->UserName))->SetPassword(fa->Password); break; } } }
bool LicenseSystem::ValidateKey(const String& key) { if (!key.StartsWith("ATOMIC-")) return false; Vector<String> elements = key.Split('-'); if (elements.Size() != 5) return false; for (unsigned i = 1; i < elements.Size(); i++) { String element = elements[i]; if (element.Length() != 4) return false; for (unsigned j = 0; j < 4; j++) { char c = element[j]; if ((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) continue; return false; } } return true; }
void Settings::Load() { Directory appDataDir = GetAppDataDir(); if (appDataDir.Exists()) { File config; config.SetLocation(appDataDir.Location().OriginalString() + "/config.txt"); FileStream fs; if (config.Exists()) { AutoPointerArray<UInt8> buf(new UInt8[config.Size()], config.Size()); if (fs.Open(config.Location(), FileAccessMode::Read, FileAccessPriority::ReadThroughput)) { fs.Read(buf.Get(), 0, buf.Size()); fs.Close(); for (Size i = 0, s = 0; i < buf.Size(); ++i) if (buf[i] == '\n') { String line = String(reinterpret_cast<const char*>(&buf[s]), i - s); AutoPointerArray<String> keyValue = line.Split(String("=")); if (keyValue.Count() == 2) { const char* key = StringCache::Find(keyValue[0]); if (key == 0) key = keyValue[0].c_str(); m_PImpl->m_Data[key] = keyValue[1]; } s = i+1; } } } } }
void ConfigObject::DumpModifiedAttributes(const std::function<void(const ConfigObject::Ptr&, const String&, const Value&)>& callback) { for (const Type::Ptr& type : Type::GetAllTypes()) { auto *dtype = dynamic_cast<ConfigType *>(type.get()); if (!dtype) continue; for (const ConfigObject::Ptr& object : dtype->GetObjects()) { Dictionary::Ptr originalAttributes = object->GetOriginalAttributes(); if (!originalAttributes) continue; ObjectLock olock(originalAttributes); for (const Dictionary::Pair& kv : originalAttributes) { String key = kv.first; Type::Ptr type = object->GetReflectionType(); std::vector<String> tokens = key.Split("."); String fieldName = tokens[0]; int fid = type->GetFieldId(fieldName); Value currentValue = object->GetField(fid); Value modifiedValue; if (tokens.size() > 1) { Value current = currentValue; for (std::vector<String>::size_type i = 1; i < tokens.size() - 1; i++) { if (!current.IsObjectType<Dictionary>()) BOOST_THROW_EXCEPTION(std::invalid_argument("Value must be a dictionary.")); Dictionary::Ptr dict = current; const String& key = tokens[i]; if (!dict->Contains(key)) break; current = dict->Get(key); } if (!current.IsObjectType<Dictionary>()) BOOST_THROW_EXCEPTION(std::invalid_argument("Value must be a dictionary.")); Dictionary::Ptr dict = current; const String& key = tokens[tokens.size() - 1]; modifiedValue = dict->Get(key); } else modifiedValue = currentValue; callback(object, key, modifiedValue); } } } }
bool LogLinearModel::LoadWeights (const char* _zName) { cout << "Loading weights for log linear model : " << _zName << endl; // LogLinearModelFeatures::LoadIndices (_zName); String sName; sName << _zName << ":weights_file"; File file; if (false == file.Open ((config)sName)) return false; String sLine; if (false == file.ReadLastLine (sLine)) return false; String_dq_t dqValues; sLine.Split (dqValues, ','); i_Features = dqValues.size (); vec_Weights.Resize (i_Features, 0); for (int i = 0; i < i_Features; ++ i) vec_Weights [i] = dqValues [i]; return true; }
void PlayCmd::Run() { LOGINFOF("Playing project"); ToolSystem* tsystem = GetSubsystem<ToolSystem>(); ToolEnvironment* env = GetSubsystem<ToolCore::ToolEnvironment>(); Project* project = tsystem->GetProject(); const String& editorBinary = env->GetEditorBinary(); Vector<String> paths; paths.Push(env->GetCoreDataDir()); paths.Push(env->GetPlayerDataDir()); paths.Push(project->GetResourcePath()); // fixme: this is for loading from cache paths.Push(project->GetProjectPath()); paths.Push(project->GetProjectPath() + "Cache"); String resourcePaths; resourcePaths.Join(paths, "!"); Vector<String> vargs; String args = ToString("--player --project \"%s\"", AddTrailingSlash(project->GetProjectPath()).CString()); vargs = args.Split(' '); //vargs.Insert(0, "--player"); // TODO: use IPC (maybe before this set log location/access the log and output it, we need access to errors) LaunchPlayerProcess(editorBinary, vargs, ""); Finished(); }
void BuildAndroid::RunADBStartActivity() { SubprocessSystem* subs = GetSubsystem<SubprocessSystem>(); String adbCommand = platformAndroid_->GetADBCommand(); ToolSystem* toolSystem = GetSubsystem<ToolSystem>(); Project* project = toolSystem->GetProject(); AndroidBuildSettings* settings = project->GetBuildSettings()->GetAndroidBuildSettings(); String stringArgs; const char* cpackage = settings->GetPackageName().CString(); stringArgs.AppendWithFormat("shell am start -n %s/%s.AtomicGameEngine",cpackage, cpackage); Vector<String> args = stringArgs.Split(' '); currentBuildPhase_ = ADBStartActivity; Subprocess* subprocess = subs->Launch(adbCommand, args, buildPath_); if (!subprocess) { FailBuild("StartActivity operation did not launch successfully."); return; } VariantMap buildOutput; buildOutput[BuildOutput::P_TEXT] = "\n\n<color #D4FB79>Starting Android Activity</color>\n\n"; SendEvent(E_BUILDOUTPUT, buildOutput); SubscribeToEvent(subprocess, E_SUBPROCESSCOMPLETE, ATOMIC_HANDLER(BuildAndroid, HandleADBStartActivityComplete)); SubscribeToEvent(subprocess, E_SUBPROCESSOUTPUT, ATOMIC_HANDLER(BuildBase, HandleSubprocessOutputEvent)); }
void PlatformAndroid::HandleRefreshAndroidTargetsEvent(StringHash eventType, VariantMap& eventData) { if (eventType == E_SUBPROCESSOUTPUT) { targetOutput_ += eventData[SubprocessOutput::P_TEXT].GetString(); } else if (eventType == E_SUBPROCESSCOMPLETE) { refreshAndroidTargetsProcess_ = 0; androidTargets_.Clear(); MemoryBuffer reader(targetOutput_.CString(), targetOutput_.Length() + 1); while (!reader.IsEof()) { String line = reader.ReadLine(); if (line.StartsWith("id:")) { //id: 33 or "Google Inc.:Google APIs (x86 System Image):19" Vector<String> elements = line.Split('\"'); if (elements.Size() == 2) { String api = elements[1]; androidTargets_.Push(api); } } } SendEvent(E_ANDROIDTARGETSREFRESHED); } }
static Array::Ptr StringSplit(const String& delims) { ScriptFrame *vframe = ScriptFrame::GetCurrentFrame(); String self = vframe->Self; std::vector<String> tokens = self.Split(delims.CStr()); return Array::FromVector(tokens); }
Array* CreateArguments(Engine* eng, const char* cstr) { GCPAUSE_NORUN( eng ); String* str = eng->AllocString(cstr ? cstr : ""); String* delm = eng->AllocString(" \t\n\r"); return str->Split(delm); }
void Scene::SetVarNamesAttr(String value) { Vector<String> varNames = value.Split(';'); varNames_.Clear(); for (Vector<String>::ConstIterator i = varNames.Begin(); i != varNames.End(); ++i) varNames_[*i] = *i; }
int LicenseSystem::ParseResponse(const String& response, LicenseParse& parse) { ATOMIC_LOGINFOF("%s", response.CString()); if (response.StartsWith("AC_ACTIVATIONSEXCEEDED")) { return 1; } if (response.StartsWith("AC_IDNOTACTIVATED")) { return 4; } if (response.StartsWith("AC_FAILED")) { return 2; } if (!response.StartsWith("WINDOWS")) { ATOMIC_LOGERRORF("Error Parsing Server Response %s", response.CString()); return 3; } String codes = response; codes.Replace("\n", ""); codes.Replace("\r", ""); Vector<String> cvector = codes.Split(' '); for (unsigned i = 0; i < cvector.Size(); i++) { Vector<String> feature = cvector[i].Split('='); if (feature.Size() != 2) continue; if (feature[0] == "WINDOWS") parse.licenseWindows_ = !feature[1].StartsWith("0"); else if (feature[0] == "MAC") parse.licenseMac_ = !feature[1].StartsWith("0"); else if (feature[0] == "ANDROID") parse.licenseAndroid_ = !feature[1].StartsWith("0"); else if (feature[0] == "IOS") parse.licenseIOS_ = !feature[1].StartsWith("0"); else if (feature[0] == "HTML5") parse.licenseHTML5_ = !feature[1].StartsWith("0"); else if (feature[0] == "THREED") parse.licenseModule3D_ = !feature[1].StartsWith("0"); } return 0; }
void UberShaderPreprocessor::SetShader(ShaderStageType stage, const String& source, const String& shaderFlags, const String& requiredFlags) { CachedShader& shader = m_shaders[stage]; shader.present = true; shader.source = source; // On extrait les flags de la chaîne std::vector<String> flags; shaderFlags.Split(flags, ' '); for (String& flag : flags) { auto it = m_flags.find(flag); if (it == m_flags.end()) m_flags[flag] = 1U << m_flags.size(); auto it2 = shader.flags.find(flag); if (it2 == shader.flags.end()) shader.flags[flag] = 1U << shader.flags.size(); } // On construit les flags requis pour l'activation du shader shader.requiredFlags = 0; flags.clear(); requiredFlags.Split(flags, ' '); for (String& flag : flags) { UInt32 flagVal; auto it = m_flags.find(flag); if (it == m_flags.end()) { flagVal = 1U << m_flags.size(); m_flags[flag] = flagVal; } else flagVal = it->second; shader.requiredFlags |= flagVal; } }
String::StrPtrVec* TextFile::ReadLines(CStr fileName, Exception* out_ex) { //Here \r\n is used instead of NewLine so that Linux can see lines from a Windows text file ASSERT_PARAMETER(fileName); String text; if(ReadAll(fileName, text, out_ex)) return text.Split(text, text.Length(), Text("\r\n")); else return new String::StrPtrVec(); }
void AS_Load::Run() { String fileContent = String::Read(m_name); Array<String> params = fileContent.Split("\n"); if (params.Size() == EXPECTED_PARAMS_SIZE) { Game::Instance().SetLevelInfo(params); SetWantedState(AS_PLAYING); } else SetWantedState(AS_START_MENU); }
void ParseCommand(String input, String &command, StringVector ¶meters) { input = input.Trimmed(); if (input.Empty()) return; uint parenPos = input.Find('(', 0); uint spacePos = input.Find(' ', 0); if (parenPos == String::NPOS && spacePos == String::NPOS) { command = input; return; } StringVector parts; if (parenPos != String::NPOS && parenPos < spacePos) { uint parenEndPos = input.FindLast(')'); String insideParens = (parenEndPos != String::NPOS ? input.Substring(parenPos+1, parenEndPos-parenPos-1).Trimmed() : input.Substring(parenPos+1).Trimmed()); command = input.Substring(0, parenPos).Trimmed(); // "one, two, three", "one,two,three" and "one two three" parts = insideParens.Contains(',') ? insideParens.Split(',') : insideParens.Split(' '); } else { command = input.Substring(0, spacePos).Trimmed(); String remaining = input.Substring(spacePos+1).Trimmed(); // "one, two, three", "one,two,three" and "one two three" parts = remaining.Contains(',') ? remaining.Split(',') : remaining.Split(' '); } for(StringVector::Iterator iter=parts.Begin(); iter!=parts.End(); ++iter) { String part = (*iter).Trimmed(); if (part.EndsWith(",")) part = part.Substring(0, part.Length()-1); if (!part.Empty()) parameters.Push(part); } }
String FormatValue(const Double& value, const String& format) { String prefix; String suffix; Integer left = 0; Integer right = 0; Boolean dot = false; Integer length = format.Length(); for (Integer i = 0; i < length; i++) { const Char c = format[i]; if (c == '#') { if (dot) right++; else left++; } else if (c == '.') dot = true; else if (c == '|') break; else if (dot) suffix += c; else prefix += c; } Double v = Abs(value); if (v < 0.00001) v = 0; if (left == 0 && right == 0) return prefix + AnyToStr(v) + suffix; String s = AnyToStr(v); String n = value < 0 ? "-" : String::Empty; auto pair = s.Split("."); if (pair.Length() < 2) pair.Add(String::Empty); if (left < 1) left = 1; pair[0] = pair[0].PadLeft('0', left); if (right == 0) return prefix + n + pair[0] + suffix; pair[1] = pair[1].PadRight('0', right); return prefix + n + pair[0] + String(".") + pair[1].SubString(0, right) + suffix; }
Dictionary::Ptr ScheduledDowntimeNameComposer::ParseName(const String& name) const { std::vector<String> tokens = name.Split("!"); if (tokens.size() < 2) BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid ScheduledDowntime name.")); Dictionary::Ptr result = new Dictionary(); result->Set("host_name", tokens[0]); if (tokens.size() > 2) { result->Set("service_name", tokens[1]); result->Set("name", tokens[2]); } else { result->Set("name", tokens[1]); } return result; }
bool LuaScript::PushScriptFunction(const String& functionName, bool silentIfNotFound) { Vector<String> splitedNames = functionName.Split('.'); String currentName = splitedNames.Front(); lua_getglobal(luaState_, currentName.CString()); if (splitedNames.Size() > 1) { if (!lua_istable(luaState_, -1)) { LOGERROR("Could not find Lua table: Table name = '" + currentName + "'"); return false; } for (unsigned i = 1; i < splitedNames.Size() - 1; ++i) { currentName = currentName + "." + splitedNames[i]; lua_getfield(luaState_, -1, splitedNames[i].CString()); if (!lua_istable(luaState_, -1)) { LOGERROR("Could not find Lua table: Table name = '" + currentName + "'"); return false; } } currentName = currentName + "." + splitedNames.Back().CString(); lua_getfield(luaState_, -1, splitedNames.Back().CString()); } if (!lua_isfunction(luaState_, -1)) { if (!silentIfNotFound) LOGERROR("Could not find Lua function: Function name = '" + currentName + "'"); return false; } return true; }
bool LuaScript::PushLuaFunction(lua_State* L, const String& functionName) { Vector<String> splitNames = functionName.Split('.'); String currentName = splitNames.Front(); lua_getglobal(L, currentName.CString()); if (splitNames.Size() > 1) { for (unsigned i = 0; i < splitNames.Size() - 1; ++i) { if (i) { currentName = currentName + "." + splitNames[i]; lua_getfield(L, -1, splitNames[i].CString()); lua_replace(L, -2); } if (!lua_istable(L, -1)) { lua_pop(L, 1); lua_pushstring(L, ("Could not find Lua table: Table name = '" + currentName + "'").CString()); return false; } } currentName = currentName + "." + splitNames.Back(); lua_getfield(L, -1, splitNames.Back().CString()); lua_replace(L, -2); } if (!lua_isfunction(L, -1)) { lua_pop(L, 1); lua_pushstring(L, ("Could not find Lua function: Function name = '" + currentName + "'").CString()); return false; } return true; }
/////////////////////////////////////////////////////////////////////////////// // [in] fullPath : true to get paths as dir+name instead of name only StringArray Directory::GetFileNames(const String& dirPath, const String& joker, bool fullPaths) { StringArray filePaths; StringArray jokerPatterns; Array<Joker> jokers; if( !joker.IsEmpty() ) { jokerPatterns = joker.Split('|'); } else { jokerPatterns.Add("*"); } jokers.EnsureCapacity(jokerPatterns.GetSize()); foreach(jokerPatterns, i) { jokers.Add( Joker(jokerPatterns[i]) ); }
bool XPathQuery::SetQuery(const String& queryString, const String& variableString, bool bind) { if (!variableString.Empty()) { Clear(); variables_ = new pugi::xpath_variable_set(); // Parse the variable string having format "name1:type1,name2:type2,..." where type is one of "Bool", "Float", "String", "ResultSet" Vector<String> vars = variableString.Split(','); for (Vector<String>::ConstIterator i = vars.Begin(); i != vars.End(); ++i) { Vector<String> tokens = i->Trimmed().Split(':'); if (tokens.Size() != 2) continue; pugi::xpath_value_type type; if (tokens[1] == "Bool") type = pugi::xpath_type_boolean; else if (tokens[1] == "Float") type = pugi::xpath_type_number; else if (tokens[1] == "String") type = pugi::xpath_type_string; else if (tokens[1] == "ResultSet") type = pugi::xpath_type_node_set; else return false; if (!variables_->add(tokens[0].CString(), type)) return false; } } queryString_ = queryString; if (bind) Bind(); return true; }
void NagiosCheckTask::ProcessCheckOutput(const Dictionary::Ptr& result, String& output) { String text; String perfdata; vector<String> lines = output.Split(is_any_of("\r\n")); BOOST_FOREACH (const String& line, lines) { size_t delim = line.FindFirstOf("|"); if (!text.IsEmpty()) text += "\n"; if (delim != String::NPos) { text += line.SubStr(0, delim); if (!perfdata.IsEmpty()) perfdata += " "; perfdata += line.SubStr(delim + 1, line.GetLength()); } else { text += line; } }
STDMETHODIMP C_FloodedFill::Retrieve(I_Archive *arc) { C_STLException::install(); try { BSTR bs = NULL; if (S_OK != arc->RetrieveString(&bs)) { return E_FAIL; } String s(bs); String::FreeBSTR(&bs); static String enditem(_T("/mmp:item")); static String fill(_T("mmp:floodfill")); static String endfill(_T("/mmp:floodfill")); while (!s.toLower().Find(endfill).isValid()) { StringPtr ptrItem = s.Find(enditem); if (ptrItem.isValid()) { arc->Rollback(); break; } StringPtr ptrStart = s.Find(fill); if (ptrStart.isValid()) { StringPtr ptrStyle = s.Find(_T("colours")); StringPtr ptrLeft = s.Find(_T("\""), ptrStyle); if (ptrLeft.isValid()) { ptrLeft++; StringPtr ptrRight = s.Find(_T("\""), ptrLeft); if (ptrRight.isValid()) { String style = s.Mid(ptrLeft.Index(), ptrRight.Index() - ptrLeft.Index()); if (style.GetLength() > 0) { T_PointerArray<String> sa; style.Split(_T(':'), &sa); m_nCount = sa.GetLength(); m_saColours.ReDim(m_nCount); for (int n = 0; n < m_nCount; n++) { *m_saColours[n] = sa[n]->toInteger(); } } } } } else { arc->Rollback(); EatTag(arc); } if (S_OK != arc->RetrieveString(&bs)) { return E_FAIL; } s = bs; String::FreeBSTR(&bs); } } catch (C_STLNonStackException const &exception) { exception.Log(_T("Exception in C_floodFill::Retrieve")); } return S_OK; }
void ConfigObject::RestoreAttribute(const String& attr, bool updateVersion) { Type::Ptr type = GetReflectionType(); std::vector<String> tokens = attr.Split("."); String fieldName = tokens[0]; int fid = type->GetFieldId(fieldName); Value currentValue = GetField(fid); Dictionary::Ptr original_attributes = GetOriginalAttributes(); if (!original_attributes) return; Value oldValue = original_attributes->Get(attr); Value newValue; if (tokens.size() > 1) { newValue = currentValue.Clone(); Value current = newValue; if (current.IsEmpty()) BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot restore non-existent object attribute")); String prefix = tokens[0]; for (std::vector<String>::size_type i = 1; i < tokens.size() - 1; i++) { if (!current.IsObjectType<Dictionary>()) BOOST_THROW_EXCEPTION(std::invalid_argument("Value must be a dictionary.")); Dictionary::Ptr dict = current; const String& key = tokens[i]; prefix += "." + key; if (!dict->Contains(key)) BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot restore non-existent object attribute")); current = dict->Get(key); } if (!current.IsObjectType<Dictionary>()) BOOST_THROW_EXCEPTION(std::invalid_argument("Value must be a dictionary.")); Dictionary::Ptr dict = current; const String& key = tokens[tokens.size() - 1]; prefix += "." + key; std::vector<String> restoredAttrs; { ObjectLock olock(original_attributes); for (const auto& kv : original_attributes) { std::vector<String> originalTokens = String(kv.first).Split("."); if (tokens.size() > originalTokens.size()) continue; bool match = true; for (std::vector<String>::size_type i = 0; i < tokens.size(); i++) { if (tokens[i] != originalTokens[i]) { match = false; break; } } if (!match) continue; Dictionary::Ptr dict; if (tokens.size() == originalTokens.size()) dict = current; else { Value currentSub = current; for (std::vector<String>::size_type i = tokens.size() - 1; i < originalTokens.size() - 1; i++) { dict = currentSub; currentSub = dict->Get(originalTokens[i]); if (!currentSub.IsObjectType<Dictionary>()) { currentSub = new Dictionary(); dict->Set(originalTokens[i], currentSub); } } dict = currentSub; } dict->Set(originalTokens[originalTokens.size() - 1], kv.second); restoredAttrs.push_back(kv.first); } } for (const String& attr : restoredAttrs) original_attributes->Remove(attr); } else { newValue = oldValue; } original_attributes->Remove(attr); SetField(fid, newValue); if (updateVersion) SetVersion(Utility::GetTime()); }
Dictionary::Ptr LivestatusLogUtility::GetAttributes(const String& text) { Dictionary::Ptr bag = new Dictionary(); /* * [1379025342] SERVICE NOTIFICATION: contactname;hostname;servicedesc;WARNING;true;foo output */ unsigned long time = atoi(text.SubStr(1, 11).CStr()); Log(LogDebug, "LivestatusLogUtility") << "Processing log line: '" << text << "'."; bag->Set("time", time); size_t colon = text.FindFirstOf(':'); size_t colon_offset = colon - 13; String type = String(text.SubStr(13, colon_offset)).Trim(); String options = String(text.SubStr(colon + 1)).Trim(); bag->Set("type", type); bag->Set("options", options); std::vector<String> tokens = options.Split(";"); /* set default values */ bag->Set("class", LogEntryClassInfo); bag->Set("log_type", 0); bag->Set("state", 0); bag->Set("attempt", 0); bag->Set("message", text); /* used as 'message' in log table, and 'log_output' in statehist table */ if (type.Contains("INITIAL HOST STATE") || type.Contains("CURRENT HOST STATE") || type.Contains("HOST ALERT")) { if (tokens.size() < 5) return bag; bag->Set("host_name", tokens[0]); bag->Set("state", Host::StateFromString(tokens[1])); bag->Set("state_type", tokens[2]); bag->Set("attempt", atoi(tokens[3].CStr())); bag->Set("plugin_output", tokens[4]); if (type.Contains("INITIAL HOST STATE")) { bag->Set("class", LogEntryClassState); bag->Set("log_type", LogEntryTypeHostInitialState); } else if (type.Contains("CURRENT HOST STATE")) { bag->Set("class", LogEntryClassState); bag->Set("log_type", LogEntryTypeHostCurrentState); } else { bag->Set("class", LogEntryClassAlert); bag->Set("log_type", LogEntryTypeHostAlert); } return bag; } else if (type.Contains("HOST DOWNTIME ALERT") || type.Contains("HOST FLAPPING ALERT")) { if (tokens.size() < 3) return bag; bag->Set("host_name", tokens[0]); bag->Set("state_type", tokens[1]); bag->Set("comment", tokens[2]); if (type.Contains("HOST FLAPPING ALERT")) { bag->Set("class", LogEntryClassAlert); bag->Set("log_type", LogEntryTypeHostFlapping); } else { bag->Set("class", LogEntryClassAlert); bag->Set("log_type", LogEntryTypeHostDowntimeAlert); } return bag; } else if (type.Contains("INITIAL SERVICE STATE") || type.Contains("CURRENT SERVICE STATE") || type.Contains("SERVICE ALERT")) { if (tokens.size() < 6) return bag; bag->Set("host_name", tokens[0]); bag->Set("service_description", tokens[1]); bag->Set("state", Service::StateFromString(tokens[2])); bag->Set("state_type", tokens[3]); bag->Set("attempt", atoi(tokens[4].CStr())); bag->Set("plugin_output", tokens[5]); if (type.Contains("INITIAL SERVICE STATE")) { bag->Set("class", LogEntryClassState); bag->Set("log_type", LogEntryTypeServiceInitialState); } else if (type.Contains("CURRENT SERVICE STATE")) { bag->Set("class", LogEntryClassState); bag->Set("log_type", LogEntryTypeServiceCurrentState); } else { bag->Set("class", LogEntryClassAlert); bag->Set("log_type", LogEntryTypeServiceAlert); } return bag; } else if (type.Contains("SERVICE DOWNTIME ALERT") || type.Contains("SERVICE FLAPPING ALERT")) { if (tokens.size() < 4) return bag; bag->Set("host_name", tokens[0]); bag->Set("service_description", tokens[1]); bag->Set("state_type", tokens[2]); bag->Set("comment", tokens[3]); if (type.Contains("SERVICE FLAPPING ALERT")) { bag->Set("class", LogEntryClassAlert); bag->Set("log_type", LogEntryTypeServiceFlapping); } else { bag->Set("class", LogEntryClassAlert); bag->Set("log_type", LogEntryTypeServiceDowntimeAlert); } return bag; } else if (type.Contains("TIMEPERIOD TRANSITION")) { if (tokens.size() < 4) return bag; bag->Set("class", LogEntryClassState); bag->Set("log_type", LogEntryTypeTimeperiodTransition); bag->Set("host_name", tokens[0]); bag->Set("service_description", tokens[1]); bag->Set("state_type", tokens[2]); bag->Set("comment", tokens[3]); } else if (type.Contains("HOST NOTIFICATION")) { if (tokens.size() < 6) return bag; bag->Set("contact_name", tokens[0]); bag->Set("host_name", tokens[1]); bag->Set("state_type", tokens[2].CStr()); bag->Set("state", Service::StateFromString(tokens[3])); bag->Set("command_name", tokens[4]); bag->Set("plugin_output", tokens[5]); bag->Set("class", LogEntryClassNotification); bag->Set("log_type", LogEntryTypeHostNotification); return bag; } else if (type.Contains("SERVICE NOTIFICATION")) { if (tokens.size() < 7) return bag; bag->Set("contact_name", tokens[0]); bag->Set("host_name", tokens[1]); bag->Set("service_description", tokens[2]); bag->Set("state_type", tokens[3].CStr()); bag->Set("state", Service::StateFromString(tokens[4])); bag->Set("command_name", tokens[5]); bag->Set("plugin_output", tokens[6]); bag->Set("class", LogEntryClassNotification); bag->Set("log_type", LogEntryTypeServiceNotification); return bag; } else if (type.Contains("PASSIVE HOST CHECK")) { if (tokens.size() < 3) return bag; bag->Set("host_name", tokens[0]); bag->Set("state", Host::StateFromString(tokens[1])); bag->Set("plugin_output", tokens[2]); bag->Set("class", LogEntryClassPassive); return bag; } else if (type.Contains("PASSIVE SERVICE CHECK")) { if (tokens.size() < 4) return bag; bag->Set("host_name", tokens[0]); bag->Set("service_description", tokens[1]); bag->Set("state", Host::StateFromString(tokens[2])); bag->Set("plugin_output", tokens[3]); bag->Set("class", LogEntryClassPassive); return bag; } else if (type.Contains("EXTERNAL COMMAND")) { bag->Set("class", LogEntryClassCommand); /* string processing not implemented in 1.x */ return bag; } else if (type.Contains("LOG VERSION")) { bag->Set("class", LogEntryClassProgram); bag->Set("log_type", LogEntryTypeVersion); return bag; } else if (type.Contains("logging initial states")) { bag->Set("class", LogEntryClassProgram); bag->Set("log_type", LogEntryTypeInitialStates); return bag; } else if (type.Contains("starting... (PID=")) { bag->Set("class", LogEntryClassProgram); bag->Set("log_type", LogEntryTypeProgramStarting); return bag; } /* program */ else if (type.Contains("restarting...") || type.Contains("shutting down...") || type.Contains("Bailing out") || type.Contains("active mode...") || type.Contains("standby mode...")) { bag->Set("class", LogEntryClassProgram); return bag; } return bag; }
SharedPtr<Resource> LevelLoader::Load(Stream& source) { String line; List<String> list; SharedPtr<TextReader> reader(new TextReader(&source)); line = reader->ReadLine(); list = line.Split(' '); if (list.Count() < 2) return SharedPtr<Resource>::EMPTY; const Vector2i size(list[0].ToInt(), list[1].ToInt()); auto data = _context->NewObject<Level>(); auto cache = _context->GetModule<ResourceCache>(); List<SharedPtr<Model>> prefabs; prefabs.Add(SharedPtr<Model>(cache->Load<Model>("Data/Models/floor.obj"))); prefabs.Add(SharedPtr<Model>(cache->Load<Model>("Data/Models/wall.obj"))); bool** map = new bool*[size.x]; for (int x = 0; x < size.x; x++) map[x] = new bool[size.y]; for (int y = 0; y < size.y; y++) { line = reader->ReadLine(); if (line.Count() != size.x) { for (int x = 0; x < size.x; x++) map[x][y] = false; continue; } for (int x = 0; x < size.x; x++) map[x][y] = line[x] == '#'; } for (int x = 0; x < size.x; x++) for (int y = 0; y < size.y; y++) { const Vector2i index(x / LevelChunk::SIDE, y / LevelChunk::SIDE); const Vector2i pos(x - index.x * LevelChunk::SIDE, y - index.y * LevelChunk::SIDE); auto chunk = data->GetChunk(index); auto& cell = chunk->GetCell(pos); cell.Clear(); if (map[x][y]) continue; cell.SetFloor(0); if (x > 0 && map[x - 1][y]) cell.SetWall(DIR_WEST, 1); if (x + 1 < size.x && map[x + 1][y]) cell.SetWall(DIR_EAST, 1); if (y > 0 && map[x][y - 1]) cell.SetWall(DIR_NORTH, 1); if (y + 1 < size.y && map[x][y + 1]) cell.SetWall(DIR_SOUTH, 1); } for (int x = 0; x < size.x; x++) delete[] map[x]; delete[] map; data->SetPrefabs(prefabs); return DynamicCast<Resource>(data); }
int ConsoleCommand::RunScriptConsole(ScriptFrame& scriptFrame, const String& connectAddr, const String& session, const String& commandOnce, const String& commandOnceFileName, bool syntaxOnly) { std::map<String, String> lines; int next_line = 1; #ifdef HAVE_EDITLINE String homeEnv = Utility::GetFromEnvironment("HOME"); String historyPath; std::fstream historyfp; if (!homeEnv.IsEmpty()) { historyPath = String(homeEnv) + "/.icinga2_history"; historyfp.open(historyPath.CStr(), std::fstream::in); String line; while (std::getline(historyfp, line.GetData())) add_history(line.CStr()); historyfp.close(); } #endif /* HAVE_EDITLINE */ l_ScriptFrame = &scriptFrame; l_Session = session; while (std::cin.good()) { String fileName; if (commandOnceFileName.IsEmpty()) fileName = "<" + Convert::ToString(next_line) + ">"; else fileName = commandOnceFileName; next_line++; bool continuation = false; std::string command; incomplete: std::string line; if (commandOnce.IsEmpty()) { #ifdef HAVE_EDITLINE std::ostringstream promptbuf; std::ostream& os = promptbuf; #else /* HAVE_EDITLINE */ std::ostream& os = std::cout; #endif /* HAVE_EDITLINE */ os << fileName; if (!continuation) os << " => "; else os << " .. "; #ifdef HAVE_EDITLINE String prompt = promptbuf.str(); char *cline; cline = readline(prompt.CStr()); if (!cline) break; if (commandOnce.IsEmpty() && cline[0] != '\0') { add_history(cline); if (!historyPath.IsEmpty()) { historyfp.open(historyPath.CStr(), std::fstream::out | std::fstream::app); historyfp << cline << "\n"; historyfp.close(); } } line = cline; free(cline); #else /* HAVE_EDITLINE */ std::getline(std::cin, line); #endif /* HAVE_EDITLINE */ } else line = commandOnce; if (!line.empty() && line[0] == '$') { if (line == "$continue" || line == "$quit" || line == "$exit") break; else if (line == "$help") std::cout << "Welcome to the Icinga 2 debug console.\n" "Usable commands:\n" " $continue Continue running Icinga 2 (script debugger).\n" " $quit, $exit Stop debugging and quit the console.\n" " $help Print this help.\n\n" "For more information on how to use this console, please consult the documentation at https://icinga.com/docs\n"; else std::cout << "Unknown debugger command: " << line << "\n"; continue; } if (!command.empty()) command += "\n"; command += line; std::unique_ptr<Expression> expr; try { lines[fileName] = command; Value result; /* Local debug console. */ if (connectAddr.IsEmpty()) { expr = ConfigCompiler::CompileText(fileName, command); /* This relies on the fact that - for syntax errors - CompileText() * returns an AST where the top-level expression is a 'throw'. */ if (!syntaxOnly || dynamic_cast<ThrowExpression *>(expr.get())) { if (syntaxOnly) std::cerr << " => " << command << std::endl; result = Serialize(expr->Evaluate(scriptFrame), 0); } else result = true; } else { /* Remote debug console. */ try { result = ExecuteScript(l_Session, command, scriptFrame.Sandboxed); } catch (const ScriptError&) { /* Re-throw the exception for the outside try-catch block. */ boost::rethrow_exception(boost::current_exception()); } catch (const std::exception& ex) { Log(LogCritical, "ConsoleCommand") << "HTTP query failed: " << ex.what(); #ifdef HAVE_EDITLINE /* Ensures that the terminal state is reset */ rl_deprep_terminal(); #endif /* HAVE_EDITLINE */ return EXIT_FAILURE; } } if (commandOnce.IsEmpty()) { std::cout << ConsoleColorTag(Console_ForegroundCyan); ConfigWriter::EmitValue(std::cout, 1, result); std::cout << ConsoleColorTag(Console_Normal) << "\n"; } else { std::cout << JsonEncode(result) << "\n"; break; } } catch (const ScriptError& ex) { if (ex.IsIncompleteExpression() && commandOnce.IsEmpty()) { continuation = true; goto incomplete; } DebugInfo di = ex.GetDebugInfo(); if (commandOnceFileName.IsEmpty() && lines.find(di.Path) != lines.end()) { String text = lines[di.Path]; std::vector<String> ulines = text.Split("\n"); for (decltype(ulines.size()) i = 1; i <= ulines.size(); i++) { int start, len; if (i == (decltype(i))di.FirstLine) start = di.FirstColumn; else start = 0; if (i == (decltype(i))di.LastLine) len = di.LastColumn - di.FirstColumn + 1; else len = ulines[i - 1].GetLength(); int offset; if (di.Path != fileName) { std::cout << di.Path << ": " << ulines[i - 1] << "\n"; offset = 2; } else offset = 4; if (i >= (decltype(i))di.FirstLine && i <= (decltype(i))di.LastLine) { std::cout << String(di.Path.GetLength() + offset, ' '); std::cout << String(start, ' ') << String(len, '^') << "\n"; } } } else { ShowCodeLocation(std::cout, di); } std::cout << ex.what() << "\n"; if (!commandOnce.IsEmpty()) return EXIT_FAILURE; } catch (const std::exception& ex) { std::cout << "Error: " << DiagnosticInformation(ex) << "\n"; if (!commandOnce.IsEmpty()) return EXIT_FAILURE; } } return EXIT_SUCCESS; }