Example #1
0
   String
   ScriptServer::_Compile(const String &sLanguage, const String &sFilename)
   {
      String sContents = FileUtilities::ReadCompleteTextFile(sFilename);

      if (sContents.IsEmpty())
         return "";

      // Create an instance of the script engine and execute the script.
      CComObject<CScriptSiteBasic>* pBasic;
      CComObject<CScriptSiteBasic>::CreateInstance(&pBasic);

      CComQIPtr<IActiveScriptSite> spUnk;

      if (!pBasic)
         return "ScriptServer:: Failed to create instance of script site.";

      spUnk = pBasic; // let CComQIPtr tidy up for us
      pBasic->Initiate(sLanguage, NULL);
      // pBasic->SetObjectContainer(pObjects);
      pBasic->AddScript(sContents);
      pBasic->Run();
      pBasic->Terminate();

      String sErrorMessage = pBasic->GetLastError();

      if (!sErrorMessage.IsEmpty())
         sErrorMessage = "File: " + sFilename + "\r\n" + sErrorMessage;

      return sErrorMessage;

   }
Example #2
0
   String 
   MailImporter::GetInternalDate_(shared_ptr<MessageData> pMsgData)
   {

      String sReceivedHeader = pMsgData->GetFieldValue("Received");
      if (!sReceivedHeader.IsEmpty())
      {
         DateTime dtTime = Utilities::GetDateTimeFromReceivedHeader(sReceivedHeader);
         
         if (dtTime.GetYear() > 1980 && dtTime.GetYear() < 2040)
         {
            return GetInternalDate_DatePlusTimeZone(dtTime);
         }
      }        

      // We could not determine the date by looking at the Received header, check
      // the Date header insetad.
      String sDateHeader = pMsgData->GetFieldValue("Date");
      if (!sDateHeader.IsEmpty())
      {
         DateTime dtTime = Time::GetDateTimeFromMimeHeader(sDateHeader);
         
         if (dtTime.GetYear() > 1980 && dtTime.GetYear() < 2040)
         {
            return GetInternalDate_DatePlusTimeZone(dtTime);
         }
      }

      // We didn't find it in the Date header either. Use the current date.
      String sCurrentTime = Time::GetCurrentDateTime();
      return sCurrentTime;
      
   }
Example #3
0
String Base64::Decode(const String& input)
{
	BIO *biomem = BIO_new_mem_buf(
		const_cast<char*>(input.CStr()), input.GetLength());
	BIO *bio64 = BIO_new(BIO_f_base64());
	BIO_push(bio64, biomem);
	BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL);

	auto *outbuf = new char[input.GetLength()];

	size_t len = 0;
	int rc;

	while ((rc = BIO_read(bio64, outbuf + len, input.GetLength() - len)) > 0)
		len += rc;

	String ret = String(outbuf, outbuf + len);
	BIO_free_all(bio64);
	delete [] outbuf;

	if (ret.IsEmpty() && !input.IsEmpty())
		throw std::invalid_argument("Not a valid base64 string");

	return ret;
}
Example #4
0
	static inline ExpressionResult For(ScriptFrame& frame, const String& fkvar, const String& fvvar, const Value& value, Expression *expression, const DebugInfo& debugInfo = DebugInfo())
	{
		if (value.IsObjectType<Array>()) {
			if (!fvvar.IsEmpty())
				BOOST_THROW_EXCEPTION(ScriptError("Cannot use dictionary iterator for array.", debugInfo));

			Array::Ptr arr = value;

			for (Array::SizeType i = 0; i < arr->GetLength(); i++) {
				frame.Locals->Set(fkvar, arr->Get(i));
				ExpressionResult res = expression->Evaluate(frame);
				CHECK_RESULT_LOOP(res);
			}
		} else if (value.IsObjectType<Dictionary>()) {
			if (fvvar.IsEmpty())
				BOOST_THROW_EXCEPTION(ScriptError("Cannot use array iterator for dictionary.", debugInfo));

			Dictionary::Ptr dict = value;
			std::vector<String> keys;

			{
				ObjectLock olock(dict);
				BOOST_FOREACH(const Dictionary::Pair& kv, dict) {
					keys.push_back(kv.first);
				}
			}

			BOOST_FOREACH(const String& key, keys) {
				frame.Locals->Set(fkvar, key);
				frame.Locals->Set(fvvar, dict->Get(key));
				ExpressionResult res = expression->Evaluate(frame);
				CHECK_RESULT_LOOP(res);
			}
Example #5
0
void ObjectListCommand::PrintObject(std::ostream& fp, bool& first, const String& message, std::map<String, int>& type_count, const String& name_filter, const String& type_filter)
{
	Dictionary::Ptr object = JsonDecode(message);

	Dictionary::Ptr properties = object->Get("properties");

	String internal_name = properties->Get("__name");
	String name = object->Get("name");
	String type = object->Get("type");

	if (!name_filter.IsEmpty() && !Utility::Match(name_filter, name) && !Utility::Match(name_filter, internal_name))
		return;
	if (!type_filter.IsEmpty() && !Utility::Match(type_filter, type))
		return;

	if (first)
		first = false;
	else
		fp << "\n";

	Dictionary::Ptr debug_hints = object->Get("debug_hints");

	fp << "Object '" << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << internal_name << ConsoleColorTag(Console_Normal) << "'";
	fp << " of type '" << ConsoleColorTag(Console_ForegroundMagenta | Console_Bold) << type << ConsoleColorTag(Console_Normal) << "':\n";

	PrintProperties(fp, properties, debug_hints, 2);

	type_count[type]++;
}
Example #6
0
// Read and save messages and their attachments
void ReadMessageTest(MAPIEx& mapi, const String &folderName = "") {
	puts("\nRead and save message test");
	MAPIFolder folder;
	if (folderName.IsEmpty()) {
		if(!mapi.OpenInbox(folder))
			return;
	} else {
		if(!mapi.OpenFolder(folderName, folder)) 		// Instead of Inbox open selected folder
			return;
	}
	
	// use SortContents to sort the messages, default is ascending by PR_MESSAGE_DELIVERY_TIME
	folder.SortContents(TABLE_SORT_DESCEND);
	//mapi.SetUnreadOnly();		
	
	MAPIMessage message;
	while(folder.GetNextMessage(message)) {
		Time receivedTime = message.GetReceivedTime();
		Time submitTime = message.GetSubmitTime();
		Time modifTime = message.GetLastModificationTime();
		String recipients;
		if (message.GetRecipients()) {
			String name, email;
			int type;
			while (message.GetNextRecipient(name, email, type)) {
				if (!recipients.IsEmpty())
					recipients += "; ";
				String stype; 
				if (type == MAPI_TO)
					stype = "TO";
				else if (type == MAPI_CC)
					stype = "CC";
				else if (type == MAPI_BCC)
					stype = "BCC";
				else
					stype = "Unknown!";
				recipients += Format("'%s' (%s)(%s)", name, email, stype.Begin());
			}
		}
		puts(Format("Message from '%s' (%s) to %s subject '%s', received time: %s, "
				"sent time: %s, modif time: %s", message.GetSenderName(), 
				message.GetSenderEmail(), recipients, message.GetSubject(), 
				Format(receivedTime), Format(submitTime), Format(modifTime)));
		puts(Format("Body: %s", message.GetBody(false)));
		//puts(Format("HTML: %s", message.GetHTML()));
		if(message.GetAttachmentCount()) {
			printf(Format("Saving attachments to %s...", MSG_ATTACHMENT_FOLDER));
			message.SaveAttachment(MSG_ATTACHMENT_FOLDER);
			puts("done");
		}
		static int num;
		String fileName = "c:\\temp\\" + FormatInt(num) + ".msg";
		printf(Format("Saving message to %s ...", fileName.Begin()));
		message.SaveToFile(fileName);
		num++;
		puts("done");
	}
}
Example #7
0
void __fastcall TfrmRetrieveMain::AddClick( TObject *Sender ) {
	if( !OpenDialog1->Execute( ) ) {
		return;
	}
	Screen->Cursor = crSQLWait;
	progress->Position = 0;
	std::unique_ptr < TStrings > lines( new TStringList );
	lines->LoadFromFile( OpenDialog1->FileName );
	progress->Max = lines->Count;
	std::unique_ptr < TStrings > fields( new TStringList );
	bool expectPos = (rgDestOrder->ItemIndex == FROM_FILE);
	bool finished = false;
	for( int line = 0; line < lines->Count; ) {
		fields->CommaText = lines->Strings[ line ++ ];
		int pos;
		String warning;
		switch( fields->Count ) {
			case 0:
				continue;
			case 1:
				if( expectPos ) {
					warning = "No position";
				} else {
					pos = rows.size() + 1;
				}
				break;
			case 2:
				if( expectPos ) {
					pos = fields->Strings[ 1 ].ToIntDef( -1 );
					if( pos < 1 ) {
						warning = "Invalid position";
					}
					break;
				}
			default:
				warning = "Extra characters";
		}

		if( warning.IsEmpty() ) {
			warning = addCryovials( fields->Strings[ 0 ], pos );
		}
		if( !warning.IsEmpty() ) {
			warning = warning + " on line " + String( line );
			if( Application->MessageBox( warning.c_str(), L"Warning", MB_OKCANCEL | MB_ICONWARNING) != IDOK ) {
				rows.clear( );
				break;
			}
		}
		progress->StepIt( );
		fillGrid( );
		Application->ProcessMessages( );
	}
	Screen->Cursor = crDefault;
	sortList.clear( );
	updateDisplay();
}
Example #8
0
String Comment::AddComment(const Checkable::Ptr& checkable, CommentType entryType, const String& author,
    const String& text, double expireTime, const String& id, const MessageOrigin::Ptr& origin)
{
	String fullName;

	if (id.IsEmpty())
		fullName = checkable->GetName() + "!" + Utility::NewUniqueID();
	else
		fullName = id;

	Dictionary::Ptr attrs = new Dictionary();

	attrs->Set("author", author);
	attrs->Set("text", text);
	attrs->Set("expire_time", expireTime);
	attrs->Set("entry_type", entryType);
	attrs->Set("entry_time", Utility::GetTime());

	Host::Ptr host;
	Service::Ptr service;
	tie(host, service) = GetHostService(checkable);

	attrs->Set("host_name", host->GetName());
	if (service)
		attrs->Set("service_name", service->GetShortName());

	String zone = checkable->GetZoneName();

	if (!zone.IsEmpty())
		attrs->Set("zone", zone);

	String config = ConfigObjectUtility::CreateObjectConfig(Comment::TypeInstance, fullName, true, Array::Ptr(), attrs);

	Array::Ptr errors = new Array();

	if (!ConfigObjectUtility::CreateObject(Comment::TypeInstance, fullName, config, errors)) {
		ObjectLock olock(errors);
		for (const String& error : errors) {
			Log(LogCritical, "Comment", error);
		}

		BOOST_THROW_EXCEPTION(std::runtime_error("Could not create comment."));
	}

	Comment::Ptr comment = Comment::GetByName(fullName);

	if (!comment)
		BOOST_THROW_EXCEPTION(std::runtime_error("Could not create comment."));

	Log(LogNotice, "Comment")
	    << "Added comment '" << comment->GetName() << "'.";

	return fullName;
}
Example #9
0
void HttpUtility::SendJsonError(HttpResponse& response, const int code,
    const String& info, const String& diagnosticInformation)
{
	Dictionary::Ptr result = new Dictionary();
	response.SetStatus(code, HttpUtility::GetErrorNameByCode(code));
	result->Set("error", code);
	if (!info.IsEmpty())
		result->Set("status", info);
	if (!diagnosticInformation.IsEmpty())
		result->Set("diagnostic information", diagnosticInformation);
	HttpUtility::SendJsonBody(response, result);
}
   bool 
   SignatureAdder::GetMessageIsReply_(std::shared_ptr<MessageData> &message_data)
   {
      String sHeader = message_data->GetFieldValue("References");
      if (!sHeader.IsEmpty())
         return true; // Contains Reference header - It's a reply.

      sHeader = message_data->GetFieldValue("In-Reply-To");
      if (!sHeader.IsEmpty())
         return true; // Contains In-Reply-To header - It's a reply.

      return false;
   }
Example #11
0
String UrlUtils::AuthoritySafePath(
    /* [in] */ const String& authority,
    /* [in] */ const String& path)
{
    if (!authority.IsNull() &&
            !authority.IsEmpty() &&
            !path.IsEmpty() &&
            !path.StartWith(String("/")))
    {
        return String("/") + path;
    }
    return path;
}
Example #12
0
   std::vector<String>
   StringParser::SplitString(const String &sInput, const String &sSeperators)
   {
      // Previously, this code used boost::tokenizer to split
      // the contents of string, but I did some tests and it
      // showed that the below code was 50% faster. Not so 
      // unexpected since tokenizer is much more advanced.

      std::vector<String> vecResult;
      int iBeginning = 0;
      int iEnd = sInput.Find(sSeperators);

      if (iEnd == -1)
      {
         // The separator was not found in the string. 
         // We should put the entire string in the result.
         if (!sInput.IsEmpty())
            vecResult.push_back(sInput);

      }

      int iSeperatorLen = sSeperators.GetLength();

      while (iEnd >= 0)
      {
         int iSubStrLength = iEnd - iBeginning;
         
         String sSubString;
         sSubString = sInput.Mid(iBeginning, iSubStrLength);
         
         vecResult.push_back(sSubString);

         // Skip to the position where the next substring
         // can start
         iBeginning = iEnd + iSeperatorLen;
         iEnd = sInput.Find(sSeperators, iBeginning);   
      }

      if (iBeginning > 0)
      {
         String sSubString = sInput.Mid(iBeginning);
         if (!sSubString.IsEmpty())
            vecResult.push_back(sSubString);
      }

      return vecResult;
    
  
   }
Example #13
0
   void LoadFiltersFromGlobalString( const IsoString& globalKey )
   {
      filters.Clear();

      String s = PixInsightSettings::GlobalString( globalKey  );
      if ( !s.IsEmpty() )
      {
         for ( size_type p = 0; ; )
         {
            size_type p1 = s.Find( '(', p );
            if ( p1 == String::notFound )
               break;

            size_type p2 = s.Find( ')', p1 );
            if ( p2 == String::notFound )
               break;

            String extStr = s.Substring( p1, p2-p1 );
            if ( !extStr.IsEmpty() )
            {
               StringList extLst;
               extStr.Break( extLst, ' ', true );
               if ( !extLst.IsEmpty() )
               {
                  FileFilter filter;

                  for ( StringList::const_iterator i = extLst.Begin(); i != extLst.End(); ++i )
                  {
                     size_type d = i->Find( '.' );
                     if ( d != String::notFound )
                        filter.AddExtension( i->Substring( d ) );
                  }

                  if ( !filter.Extensions().IsEmpty() )
                  {
                     String desc = s.Substring( p, p1-p );
                     desc.Trim();
                     filter.SetDescription( desc );

                     filters.Add( filter );
                  }
               }
            }

            p = p2 + 1;
         }
      }
   }
Example #14
0
INT_PTR CALLBACK IVALoginProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_INITDIALOG:
    {
        LocalizeWindow(hwnd);

        CTSTR lpName = g_pCloudData->GetLoginName();
        SetWindowText(GetDlgItem(hwnd, IDC_LOGINNAME), lpName);
        CTSTR lpPassword = g_pCloudData->GetLoginPassword();
        SetWindowText(GetDlgItem(hwnd, IDC_LOGINPASSWORD), lpPassword);
        return 1;
    }

    case WM_COMMAND:
    {
        switch (LOWORD(wParam))
        {
        case IDOK:
        {
            String strName = GetEditText(GetDlgItem(hwnd, IDC_LOGINNAME));
            if (strName.IsEmpty())
            {
                OBSMessageBox(hwnd, L"请输入用户名", NULL, 0);
                break;
            }

            String strPassword = GetEditText(GetDlgItem(hwnd, IDC_LOGINPASSWORD));
            if (strPassword.IsEmpty())
            {
                OBSMessageBox(hwnd, L"密码不能为空", NULL, 0);
                break;
            }

            g_pCloudData->SetLoginName(strName);
            g_pCloudData->SetLoginPassword(strPassword);
        }
        case IDCANCEL:
            EndDialog(hwnd, LOWORD(wParam));
            break;
        }
        break;
    }
    }

    return 0;
}
void ScheduledDowntime::EvaluateApplyRuleInstance(const Checkable::Ptr& checkable, const String& name, VMFrame& frame, const ApplyRule& rule)
{
	DebugInfo di = rule.GetDebugInfo();

	Log(LogDebug, "ScheduledDowntime")
		<< "Applying scheduled downtime '" << rule.GetName() << "' to object '" << checkable->GetName() << "' for rule " << di;

	ConfigItemBuilder::Ptr builder = new ConfigItemBuilder(di);
	builder->SetType("ScheduledDowntime");
	builder->SetName(name);
	builder->SetScope(frame.Locals);

	Host::Ptr host;
	Service::Ptr service;
	tie(host, service) = GetHostService(checkable);

	builder->AddExpression(new SetExpression(MakeIndexer("host_name"), OpSetLiteral, MakeLiteral(host->GetName()), false, di));

	if (service)
		builder->AddExpression(new SetExpression(MakeIndexer("service_name"), OpSetLiteral, MakeLiteral(service->GetShortName()), false, di));

	String zone = checkable->GetZone();

	if (!zone.IsEmpty())
		builder->AddExpression(new SetExpression(MakeIndexer("zone"), OpSetLiteral, MakeLiteral(zone), false, di));

	builder->AddExpression(new OwnedExpression(rule.GetExpression()));

	ConfigItem::Ptr downtimeItem = builder->Compile();
	downtimeItem->Commit();
}
Example #16
0
Dictionary::Ptr HttpUtility::FetchRequestParameters(HttpRequest& request)
{
	Dictionary::Ptr result;

	String body;
	char buffer[1024];
	size_t count;

	while ((count = request.ReadBody(buffer, sizeof(buffer))) > 0)
		body += String(buffer, buffer + count);

	if (!body.IsEmpty()) {
#ifdef I2_DEBUG
		Log(LogDebug, "HttpUtility")
		    << "Request body: '" << body << "'";
#endif /* I2_DEBUG */
		result = JsonDecode(body);
	}

	if (!result)
		result = new Dictionary();

	typedef std::pair<String, std::vector<String> > kv_pair;
	BOOST_FOREACH(const kv_pair& kv, request.RequestUrl->GetQuery()) {
		result->Set(kv.first, Array::FromVector(kv.second));
	}

	return result;
}
Example #17
0
AutoPtr<ITimeZone> TimeZone::GetDefault()
{
    if (sDefaultTimeZone == NULL) {
        AutoPtr<ITimeZoneGetter> tzGetter = TimeZoneGetter::GetInstance();
        String zoneName;
        if (tzGetter != NULL) {
            tzGetter->GetId(&zoneName);
        }
        if (!zoneName.IsNull()) {
            zoneName = zoneName.Trim();
        }
        if (!zoneName.IsNull() || zoneName.IsEmpty()) {
            // try {
                // On the host, we can find the configured timezone here.
            ECode ec = IoUtils::ReadFileAsString(String("/etc/timezone"), &zoneName);
            // } catch (IOException ex) {
                // "vogar --mode device" can end up here.
                // TODO: give libcore access to Android system properties and read "persist.sys.timezone".
            if (FAILED(ec)) {
                zoneName = String("GMT");
            }
            // }
        }
        TimeZone::GetTimeZone(zoneName, (ITimeZone**)&sDefaultTimeZone);
    }

    AutoPtr<ITimeZone> tz;
    sDefaultTimeZone->Clone((ITimeZone**)&tz);
    return tz;
}
Example #18
0
bool Gdb_MI2::SetBreakpoint(const String& filename, int line, const String& bp)
{
	String file = Filter(host->GetHostPath(NormalizePath(filename)), CharFilterReSlash2);
	
	// gets all breakpoints
	MIValue bps = GetBreakpoints();
	
	// line should start from 1...
	line++;
	
	// check wether we've got already a breakpoint here
	// and remove it
	MIValue brk = pick(bps.FindBreakpoint(file, line));
	if(!brk.IsEmpty())
		if(!MICmd(Format("break-delete %s", brk["number"].Get())))
		{
			Exclamation(t_("Couldn't remove breakpoint"));
			return false;
		}
	
	if(bp.IsEmpty())
		return true;
	else if(bp[0] == 0xe)
		return MICmd(Format("break-insert %s:%d", file, line));
	else
		return MICmd(Format("break-insert -c \"%s\" %s:%d", bp, file, line));
}
Example #19
0
bool DriveOpenClose(String drive, bool open)
{
	int operation;
	if (open)
		operation = IOCTL_STORAGE_EJECT_MEDIA;
	else
		operation = IOCTL_STORAGE_LOAD_MEDIA;
	if (drive.IsEmpty())
		return false;
	else if (drive.GetCount() == 1)
		drive += ":";
	else {
		drive = drive.Left(2);
		if (drive[1] != ':')
			return false;
	}
	HANDLE hDrive;
	hDrive = CreateFile("\\\\.\\" + drive, GENERIC_READ || GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
	if (hDrive == INVALID_HANDLE_VALUE)
		return false;
	bool ret = false;
	DWORD dummyBytesReturned;
	if (DeviceIoControl(hDrive, operation, 0, 0, 0, 0, &dummyBytesReturned, 0))
		ret = true;
  	CloseHandle(hDrive);
  	return ret;
}
Example #20
0
void
Accelerometer::Run(const String& command) {
	if (!command.IsEmpty()) {
		Uri commandUri;
		commandUri.SetUri(command);
		String method = commandUri.GetHost();
		StringTokenizer strTok(commandUri.GetPath(), L"/");
		if(strTok.GetTokenCount() == 1) {
			strTok.GetNextToken(callbackId);
			AppLogDebug("Method %S, CallbackId: %S", method.GetPointer(), callbackId.GetPointer());
		}
		if(method == L"com.cordova.Accelerometer.watchAcceleration" && !callbackId.IsEmpty() && !IsStarted()) {
			StartSensor();
		}
		if(method == L"com.cordova.Accelerometer.clearWatch" && IsStarted()) {
			StopSensor();
		}
		if(method == L"com.cordova.Accelerometer.getCurrentAcceleration" && !callbackId.IsEmpty() && !IsStarted()) {
			GetLastAcceleration();
		}
		AppLogDebug("Acceleration command %S completed", command.GetPointer());
	} else {
		AppLogDebug("Can't run empty command");
	}
}
Example #21
0
//-----------------------------------------------------------------------------
void Profile::CopyItems(JSON* root, String prefix)
{
    JSON* item = root->GetFirstItem();
    while (item)
    {
        String item_name;
        if (prefix.IsEmpty())
            item_name = item->Name;
        else
            item_name = prefix + "." + item->Name;

        if (item->Type == JSON_Object)
        {   // recursively copy the children
            
            CopyItems(item, item_name);
        }
        else
        {
            //Settings.Set(item_name, item->Value);
            SetValue(item);
        }

        item = root->GetNextItem(item);
    }
}
Example #22
0
FileFormat::FileFormat( const String& nameExtOrMime, bool toRead, bool toWrite ) :
   FileFormatBase()
{
   if ( nameExtOrMime.IsEmpty() )
      throw Error( "FileFormat: Empty format name, file extension or MIME type specified" );

   m_data = new FileFormatPrivate;

   if ( nameExtOrMime.Contains( '/' ) )
   {
      IsoString mimeType( nameExtOrMime );
      m_data->handle = (*API->FileFormat->GetFileFormatByMimeType)( ModuleHandle(), mimeType.c_str(), toRead, toWrite );
      if ( m_data->handle == nullptr )
         throw Error( "FileFormat: No installed image file format was found "
                      "for the specified MIME type \'" + nameExtOrMime + "\' and access conditions" );
   }
   else if ( nameExtOrMime.StartsWith( '.' ) )
   {
      m_data->handle = (*API->FileFormat->GetFileFormatByFileExtension)( ModuleHandle(), nameExtOrMime.c_str(), toRead, toWrite );
      if ( m_data->handle == nullptr )
         throw Error( "FileFormat: No installed image file format was found "
                      "for the specified file extension \'" + nameExtOrMime + "\'and access conditions" );
   }
   else
   {
      IsoString id( nameExtOrMime );
      m_data->handle = (*API->FileFormat->GetFileFormatByName)( ModuleHandle(), id.c_str() );
      if ( m_data->handle == nullptr )
         throw Error( "FileFormat: No installed image file format was found "
                      "with the specified identifier \'" + nameExtOrMime + '\'' );
   }

   m_data->GetCapabilities();
}
Example #23
0
void InfluxdbWriter::SendMetric(const Dictionary::Ptr& tmpl, const String& label, const Dictionary::Ptr& fields, double ts)
{
	std::ostringstream msgbuf;
	msgbuf << EscapeKeyOrTagValue(tmpl->Get("measurement"));

	Dictionary::Ptr tags = tmpl->Get("tags");
	if (tags) {
		ObjectLock olock(tags);
		for (const Dictionary::Pair& pair : tags) {
			// Empty macro expansion, no tag
			if (!pair.second.IsEmpty()) {
				msgbuf << "," << EscapeKeyOrTagValue(pair.first) << "=" << EscapeKeyOrTagValue(pair.second);
			}
		}
	}

	// Label may be empty in the case of metadata
	if (!label.IsEmpty())
		msgbuf << ",metric=" << EscapeKeyOrTagValue(label);

	msgbuf << " ";

	{
		bool first = true;

		ObjectLock fieldLock(fields);
		for (const Dictionary::Pair& pair : fields) {
			if (first)
				first = false;
			else
				msgbuf << ",";

			msgbuf << EscapeKeyOrTagValue(pair.first) << "=" << EscapeValue(pair.second);
		}
	}

	msgbuf << " " <<  static_cast<unsigned long>(ts);

#ifdef I2_DEBUG
	Log(LogDebug, "InfluxdbWriter")
		<< "Add to metric list: '" << msgbuf.str() << "'.";
#endif /* I2_DEBUG */

	// Buffer the data point
	m_DataBuffer.emplace_back(msgbuf.str());

	// Flush if we've buffered too much to prevent excessive memory use
	if (static_cast<int>(m_DataBuffer.size()) >= GetFlushThreshold()) {
		Log(LogDebug, "InfluxdbWriter")
			<< "Data buffer overflow writing " << m_DataBuffer.size() << " data points";

		try {
			Flush();
		} catch (...) {
			/* Do nothing. */
		}
	}
}
Example #24
0
//---------------------------------------------------------------------------
//
//---------------------------------------------------------------------------
int __fastcall  ASMessageAdapterEditAfterSave::Generate()
{
   String lsID = fEditor->DataSets[0]->Values[fIDExp];
   if(!lsID.IsEmpty())
   {
	   return GenerateMessage(lsID);
   }
   return 0;
}
Example #25
0
void Ide::OnBreakpoint(int i)
{
	if(!editfile.IsEmpty() && !designer && debugger) {
		String q = editor.GetBreakpoint(i);
		if(q[0] != 0xe && !debugger->SetBreakpoint(editfile, i, q))
			if(!q.IsEmpty())
				editor.SetBreakpoint(i, "\xe");
	}
}
	bool LuaState::Execute(const String& code, int errorHandler)
	{
		if (code.IsEmpty())
			return true;

		if (!Load(code))
			return false;

		return CallWithHandler(errorHandler, 0);
	}
Example #27
0
//	  TUpdateStatusSet lStatus;
//	  lStatus << usInserted <<usModified;
//---------------------------------------------------------------------------
//<COL COLCODE="flowinstid" REFCOLCODE="flowinstid" SOURCE=''/>
__fastcall ASEditRefValues::ASEditRefValues(ASEditDataSet *aTargetDS,_di_IXMLNode aDefNode):PCObject(NULL){
	fTargetDS = aTargetDS;
	fSourceFieldName = BLNODEATT(aDefNode,"REFCOLCODE");
	fTargetFieldName = BLNODEATT(aDefNode,"COLCODE");
	String lsIndex = BLNODEATT(aDefNode,"SOURCE").Trim();
	if(lsIndex.IsEmpty())
		fSourceIndex   =0;
	else
	   fSourceIndex  =StrToInt(lsIndex) -1;
}
Example #28
0
///////////////////
// Execute removal
void ActionRemove::Execute()
{
	// Find the section to remote it from
	String sect = section;
	if (sect.IsEmpty()) THROW_ATHENA_EXCEPTION(Exception::TODO); // TODO
	Section section = GetSection(sect);

	// Remove the line
	section->RemoveEntryByIndex(lineNumber);
}
Example #29
0
/////////////////////
// Execute insertion
void ActionInsert::Execute()
{
	// Find the section to insert it on
	String sectionName = section;
	if (sectionName.IsEmpty()) sectionName = entry->GetDefaultGroup();
	Section sect = GetSection(sectionName);

	// Insert the line
	sect->AddEntry(entry,lineNumber);
}
Example #30
0
ECode CKXmlSerializer::GetPrefix(
    /* [in] */ const String& ns,
    /* [in] */ Boolean includeDefault,
    /* [in] */ Boolean create,
    /* [out] */ String* prefix)
{
    assert(prefix != NULL);

    for (Int32 i = (*mNspCounts)[mDepth + 1] * 2 - 2; i >= 0; i -= 2) {
        if ((*mNspStack)[i + 1].Equals(ns)
            && (includeDefault || !(*mNspStack)[i].IsEmpty())) {
            String cand = (*mNspStack)[i];
            for (Int32 j = i + 2; j < (*mNspCounts)[mDepth + 1] * 2; j++) {
                if ((*mNspStack)[j].Equals(cand)) {
                    cand = NULL;
                    break;
                }
            }
            if (!cand.IsNull()) {
                *prefix = cand;
                return NOERROR;
            }
        }
    }

    if (!create) {
        *prefix = NULL;
        return NOERROR;
    }

    String _prefix;

    if (ns.IsEmpty()) {
        _prefix = "";
    }
    else {
        do {
            _prefix = "n" + (mAuto++);
            for (Int32 i = (*mNspCounts)[mDepth + 1] * 2 - 2; i >= 0; i -= 2) {
                if (_prefix.Equals((*mNspStack)[i])) {
                    _prefix = NULL;
                    break;
                }
            }
        }
        while (_prefix.IsNull());
    }

    Boolean p = mPending;
    mPending = FALSE;
    FAIL_RETURN(SetPrefix(_prefix, ns));
    mPending = p;
    *prefix = _prefix;
    return NOERROR;
}