Example #1
0
static std::vector<String> GetLogLevelCompletionSuggestions(const String& arg)
{
	std::vector<String> result;
	
	String debugLevel = "debug";
	if (debugLevel.Find(arg) == 0)
		result.push_back(debugLevel);

	String noticeLevel = "notice";
	if (noticeLevel.Find(arg) == 0)
		result.push_back(noticeLevel);

	String informationLevel = "information";
	if (informationLevel.Find(arg) == 0)
		result.push_back(informationLevel);

	String warningLevel = "warning";
	if (warningLevel.Find(arg) == 0)
		result.push_back(warningLevel);

	String criticalLevel = "critical";
	if (criticalLevel.Find(arg) == 0)
		result.push_back(criticalLevel);

	return result;
}
Example #2
0
   /// Returns true if the supplied UNC path contains a Share name.
   bool 
   FileUtilities::IsValidUNCFolder(const String &sPath)
   {
      if (!IsUNCPath(sPath))
         return false;

      // We have at least \\server

      int shareStartPos = sPath.Find(_T("\\"), 3);
      if (shareStartPos < 0)
         return false;

      // We have at least \\server\

      int folderStartPos = sPath.Find(_T("\\"), shareStartPos + 1);
      if (folderStartPos < 0)
         return false;

      // We have at least \\server\share\

      int length = sPath.GetLength();
      if (folderStartPos == length-1)
         return false;

      // We have something after \\server\share. That is a folder.
      return true;
   }
Example #3
0
void DatabaseDemo::HandleInput(const String& input)
{
    // Echo input string to stdout
    Print(input);
    row_ = 0;
    if (input == "quit" || input == "exit")
        engine_->Exit();
    else if (input.StartsWith("set") || input.StartsWith("get"))
    {
        // We expect a key/value pair for 'set' command
        Vector<String> tokens = input.Substring(3).Split(' ');
        String setting = tokens.Size() ? tokens[0] : "";
        if (input.StartsWith("set") && tokens.Size() > 1)
        {
            if (setting == "maxrows")
                maxRows_ = Max(ToUInt(tokens[1]), 1U);
            else if (setting == "connstr")
            {
                String newConnectionString(input.Substring(input.Find(" ", input.Find("connstr")) + 1));
                Database* database = GetSubsystem<Database>();
                DbConnection* newConnection = database->Connect(newConnectionString);
                if (newConnection)
                {
                    database->Disconnect(connection_);
                    connection_ = newConnection;
                }
            }
        }
        if (tokens.Size())
        {
            if (setting == "maxrows")
                Print(ToString("maximum rows is set to %d", maxRows_));
            else if (setting == "connstr")
                Print(ToString("connection string is set to %s", connection_->GetConnectionString().CString()));
            else
                Print(ToString("Unrecognized setting: %s", setting.CString()));
        }
        else
            Print("Missing setting paramater. Recognized settings are: maxrows, connstr");
    }
    else
    {
        // In this sample demo we use the dbCursor event to loop through each row as it is being fetched
        // Regardless of this event is being used or not, all the fetched rows will be made available in the DbResult object,
        //   unless the dbCursor event handler has instructed to filter out the fetched row from the final result
        DbResult result = connection_->Execute(input, true);

        // Number of affected rows is only meaningful for DML statements like insert/update/delete
        if (result.GetNumAffectedRows() != -1)
            Print(ToString("Number of affected rows: %d", result.GetNumAffectedRows()));
    }
    Print(" ");
}
Example #4
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 #5
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 #6
0
static void AddSuggestion(std::vector<String>& matches, const String& word, const String& suggestion)
{
    if (suggestion.Find(word) != 0)
        return;

    matches.push_back(suggestion);
}
Example #7
0
//-----------------------------------------------------------------------------------------------------------------------------------------------------
VOID Configuration::LoadConfigFile(LPCTSTR Filename)
{
  TextStream T(File::Open(Filename, FileMode::OPEN));

  while(!T.EndOfStream())
  {
    String L = T.ReadLine();
    if (L.BeginsWith("#"))
      continue;

    String::Iterator i = L.Find('=');
    if (i != L.End())
    {
      String Name = L.Substr(L.Begin(), i);
      String Value = L.Substr(i+1, L.End());

      if (m_Schema.Contains(Name))
      {
        Item I = m_Schema.Get(Name);
        if ((I.m_Source & ConfigurationSource::FILE) == 0)
          continue;
        I.m_Present = TRUE;
      }

      m_ConfigValues.Add(Name,Value);
    }
  }
}
Example #8
0
   IMAPResult
   IMAPCommandStore::ExecuteCommand(shared_ptr<IMAPConnection> pConnection, shared_ptr<IMAPCommandArgument> pArgument)
   {


      String sTag = pArgument->Tag();
      String sCommand = pArgument->Command();

      if (!pConnection->IsAuthenticated())
         return IMAPResult(IMAPResult::ResultNo, "Authenticate first");

      if (!pConnection->GetCurrentFolder())
         return IMAPResult(IMAPResult::ResultNo, "No folder selected.");


      shared_ptr<IMAPStore> pStore = shared_ptr<IMAPStore>(new IMAPStore());
      pStore->SetIsUID(false);

      String sResponse; 
      long lMailNoStart = 6;
      long lMailNoEnd = sCommand.Find(_T(" "), lMailNoStart);
      long lMailNoLen = lMailNoEnd - lMailNoStart;
      String sMailNo = sCommand.Mid(lMailNoStart, lMailNoLen);
      String sShowPart = sCommand.Mid(lMailNoEnd);

      pArgument->Command(sShowPart);

      IMAPResult result = pStore->DoForMails(pConnection, sMailNo, pArgument);

      if (result.GetResult() == IMAPResult::ResultOK)
         pConnection->SendAsciiData(pArgument->Tag() + " OK STORE completed\r\n");

      return result;
   }
Example #9
0
///////////////////////////////////////////////////////////////////////////////
// Checks if a file name matches this joker.
///////////////////////////////////////////////////////////////////////////////
bool Joker::Matches(const String& fileName) const
{
	int empty = 0;

	int leftIndex = 0;
	if( m_left.GetLength() > 0 )
	{
		leftIndex = fileName.Find(m_left, 0);
		if( leftIndex != 0 )
		{
			return false;
		}
	}
	else
	{
		empty = 1;
	}

	int rightIndex = 0;
	if( m_right.GetLength() > 0 )
	{
		rightIndex = fileName.Find(m_right, leftIndex + m_left.GetLength());
		if( rightIndex < 0 )
		{
			return false;
		}
		int wantedIndex = fileName.GetLength() - m_right.GetLength();
		if( rightIndex != wantedIndex )
		{
			return false;
		}
	}
	else
	{
		empty |= 2;
	}

	if( empty == 3 && m_str != "*" )
	{
		// Exact match
		return m_str == fileName;
	}
	return true;
}
Example #10
0
   bool
   MailImporter::GetRootLevelDirectory_(const String &fullPath, String &rootLevel)
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Takes an input parameter such as C:\DataDir\Account\Sub1\Sub2\Test.eml and
   // returns the root of that hierarcy, such as C:\Datadir\Account in this case.
   //---------------------------------------------------------------------------()
   {
      // The file must be located in the data directory. Make sure this is the case.
      const String dataDirectory = IniFileSettings::Instance()->GetDataDirectory();

      if (!fullPath.StartsWith(dataDirectory))
         return false;

      int currentTrimPosition = dataDirectory.GetLength() + 1;

      const String publicFolderName = IMAPConfiguration::GetPublicFolderDiskName();

      // Is the file located in the public folder?
      if (fullPath.FindNoCase(publicFolderName, currentTrimPosition) == currentTrimPosition)
      {
         // The file is located in the public folder.
         currentTrimPosition += publicFolderName.GetLength() + 1;
      }
      else
      {
         // The file is either located in the queue folder or in an account folder.
         int slashPosition = fullPath.Find(_T("\\"), currentTrimPosition);
         if (slashPosition < 0)
            return false;

         int accountSlashPosition = fullPath.Find(_T("\\"), slashPosition+1);

         if (accountSlashPosition > 0)
         {
            // The file is locate din the queue folder.
            currentTrimPosition = accountSlashPosition+1;
         }
      }

      rootLevel = fullPath.Mid(0, currentTrimPosition);
      return true;
   }
Example #11
0
   bool
   StringParser::AnyOfCharsExists_(const String &sChars, const String &sLookIn)
   {

      for (int i = 0; i < sChars.GetLength(); i++)
      {
         if (sLookIn.Find(sChars.GetAt(i)) >= 0)
            return true;
      }
      return false;
   }
Example #12
0
   bool
   StringParser::ValidateString(const String &sString, const String &sAllowedChars)
   {
      for (int i = 0; i < sString.GetLength(); i++)
      {
         if (sAllowedChars.Find(sString.GetAt(i)) < 0)
            return false;
      }

      return true;   
   }
Example #13
0
//задание цвета строки
void AnimeList::RowColor(int row)
{
	Date release;
	Array<CellSeries> array;
	Date today = GetSysDate();
	String xml = listName.Get(row, SeriesRelease);
	String number, date;
	int ep = listName.Get(row, Episodes);
	int ser;
	if(xml.GetCount() > 0)
	{
		int pos;
		while(xml.GetCount() > 0){ 
			pos = xml.Find("-");
			if(pos > 0)
			{
				number = String(xml, pos);
				xml.Remove(0, pos + 1);
				date = String(xml, 10);
				xml.Remove(0, 11);
				series.number = StrInt(number);
				StrToDate(series.release, date);
				array.Add(series);
			}
		}
		release = array[array.GetCount()-1].release;
		if((ep == array[array.GetCount()-1].number) & (today < release))
			ser = array[array.GetCount()-1].number - 1;
		else
			ser = ((today - release) / 7) + array[array.GetCount()-1].number;
	} else
	{
		release = listName.Get(row, Release);
		ser = ((today - release) / 7) + 1;
	}
	int views = listName.Get(row, Views);
	if(views == ep) //полностью просмотрено
		for(int i=0;i<listName.GetColumnCount();i++)
			listName.SetDisplay(row, i, Single<ColumnBlue>());
	else
		if((views < ep) & (views != 0) & (views == ser)) //нет новых серий, в просмотре
			for(int i=0;i<listName.GetColumnCount();i++)
				listName.SetDisplay(row, i, Single<ColumnGreen>());
		else
			if((views < ep) & (views != 0) & (views < ser)) //есть новые серии, в просмотре
				for(int i=0;i<listName.GetColumnCount();i++)
					listName.SetDisplay(row, i, Single<ColumnRed>());
			else
				if(views == 0) //нет просмотренных серий
					for(int i=0;i<listName.GetColumnCount();i++)
						listName.SetDisplay(row, i, Single<ColumnDefault>());
}
void LegacyTimePeriod::ParseTimeRange(const String& timerange, tm *begin, tm *end, int *stride, tm *reference)
{
	String def = timerange;

	/* Figure out the stride. */
	size_t pos = def.FindFirstOf('/');

	if (pos != String::NPos) {
		String strStride = def.SubStr(pos + 1).Trim();
		*stride = Convert::ToLong(strStride);

		/* Remove the stride parameter from the definition. */
		def = def.SubStr(0, pos);
	} else {
		*stride = 1; /* User didn't specify anything, assume default. */
	}

	/* Figure out whether the user has specified two dates. */
	pos = def.Find("- ");

	if (pos != String::NPos) {
		String first = def.SubStr(0, pos).Trim();

		String second = def.SubStr(pos + 1).Trim();

		ParseTimeSpec(first, begin, NULL, reference);

		/* If the second definition starts with a number we need
		 * to add the first word from the first definition, e.g.:
		 * day 1 - 15 --> "day 15" */
		bool is_number = true;
		size_t xpos = second.FindFirstOf(' ');
		String fword = second.SubStr(0, xpos);

		try {
			Convert::ToLong(fword);
		} catch (...) {
			is_number = false;
		}

		if (is_number) {
			xpos = first.FindFirstOf(' ');
			ASSERT(xpos != String::NPos);
			second = first.SubStr(0, xpos + 1) + second;
		}

		ParseTimeSpec(second, NULL, end, reference);
	} else {
		ParseTimeSpec(def, begin, end, reference);
	}
}
Example #15
0
   bool
   StringParser::IsNumeric(const String &sInput)
   {

      String sNumbers = "1234567890";
      int l = sInput.GetLength();
      for (int i = 0; i < l; i++)
      {
         if (sNumbers.Find(sInput.GetAt(i)) < 0)
            return false;
      }

      return true;
   }
Example #16
0
static int StringFind(const std::vector<Value>& args)
{
	ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
	String self = vframe->Self;

	if (args.empty())
		BOOST_THROW_EXCEPTION(std::invalid_argument("Too few arguments"));

	String::SizeType result;

	if (args.size() > 1) {
		if (static_cast<double>(args[1]) < 0)
			BOOST_THROW_EXCEPTION(std::invalid_argument("String index is out of range"));

		result = self.Find(args[0], args[1]);
	} else
		result = self.Find(args[0]);

	if (result == String::NPos)
		return -1;
	else
		return result;
}
Example #17
0
void B3EInterface::__EditCompleted_bkg( Edit& sender )
{
   try
   {
      String id = sender.Text().Trimmed();
      if ( id == TARGET_IMAGE )
         id.Clear();
      if ( !id.IsEmpty() )
      {
         bool valid;
         size_type p = id.Find( "->" );
         if ( p == String::notFound )
            valid = id.IsValidIdentifier();
         else
            valid = id.Left( p ).IsValidIdentifier() && id.Substring( p+2 ).IsValidIdentifier();
         if ( !valid )
            throw Error( "Invalid view identifier: " + id );
      }

      if ( sender == GUI->BackgroundReferenceView1_Edit )
      {
         instance.p_inputView[0].backgroundReferenceViewId = id;
         sender.SetText( BACKGROUND_REFERENCE_ID1 );
      }
      else if ( sender == GUI->BackgroundReferenceView2_Edit )
      {
         instance.p_inputView[1].backgroundReferenceViewId = id;
         sender.SetText( BACKGROUND_REFERENCE_ID2 );
      }
      return;
   }

   catch ( ... )
   {
      if ( sender == GUI->BackgroundReferenceView1_Edit )
         sender.SetText( BACKGROUND_REFERENCE_ID1 );
      else if ( sender == GUI->BackgroundReferenceView2_Edit )
         sender.SetText( BACKGROUND_REFERENCE_ID2 );

      try
      {
         throw;
      }
      ERROR_HANDLER

      sender.SelectAll();
      sender.Focus();
   }
}
Example #18
0
void Application::HandleLogMessage(StringHash eventType, VariantMap& eventData)
{
    using namespace LogMessage;

    if (eventData[P_LEVEL].GetInt() == LOG_ERROR)
    {
        // Strip the timestamp if necessary
        String error = eventData[P_MESSAGE].GetString();
        unsigned bracketPos = error.Find(']');
        if (bracketPos != String::NPOS)
            error = error.Substring(bracketPos + 2);

        startupErrors_ += error + "\n";
    }
}
Example #19
0
//выбор в главном массиве
void AnimeList::Change()
{
	if(listName.IsCursor()) {
		infoTab.complete.SetLabel(AsString(listName.Get(Complete)));
		infoTab.name.SetLabel(AsString(listName.Get(Named)));
		infoTab.nameRus.SetLabel(AsString(listName.Get(NamedRus)));
		infoTab.episodes.SetLabel(AsString(listName.Get(Episodes)));
		infoTab.views.SetLabel(AsString(listName.Get(Views)));
		infoTab.dateRelease.SetLabel(AsString(listName.Get(Release)));
		test.testStr.SetText(AsString((listName.Get(SeriesRelease))));
		
		if(parameters.checkSave)
		{
			String text;
			int v = listName.Get(Views);
			v++;
			text = Format(AsString(listName.Get(Named))+ " %d", v);
			copy.SetText(text);
			copy.SelectAll();
			copy.Copy();
		};
		
		seriesArray.Clear();
		test.testList.Clear();
		//заполнение массива релизов серий из поля SeriesRelease главного массива (парсер строки)
		String xml = listName.Get(SeriesRelease);
		String number, date;
		int pos;
		while(xml.GetCount() > 0){ 
			pos = xml.Find("-");
			if(pos > 0)
			{
			number = String(xml, pos);
			xml.Remove(0, pos + 1);
			date = String(xml, 10);
			xml.Remove(0, 11);
			series.number = StrInt(number);
			StrToDate(series.release, date);
			seriesArray.Add(series);
			}
		}
			
		if(listName.Get(Complete) != "Yes")
			AnimeSeries();
		else
			seriesDate.Clear();
	}
}
Example #20
0
bool HelpWin::GoTo0(const String& link, bool find) {
	int q = link.Find('#');
	if(q >= 0) {
		topic = link.Mid(0, q);
		label = link.Mid(q + 1);
	}
	else {
		topic = link;
		label = Null;
	}
	Topic t = AcquireTopic(topic);
	if(!IsNull(t.text)) {
		Title(t.title.ToWString());
		view = t.text;
		view.GotoLabel(label, true);
		tree.FindSetCursor(topic);
		return true;
	}
	return false;
}
Example #21
0
void InvoiceFormatter::formatBillPrice(StringBuffer &buf, InvoiceData &invoice)
{
	buf.Cat("[*A1 " + AsString(t_("Amount payed:")) + " -|-|");
	buf.Cat(fixFuckedLinuxFormating(ConvertMoney().Format(invoice.summary_price)));
	buf.Cat(" " + AsString(t_("CUR")) + "]&");
	buf.Cat("[A1 " + AsString(t_("Amount in words:")) + " ");
	
	String xxx = AsString(invoice.summary_price);
	int idx = xxx.Find('.');
	int d;
	String s = xxx;
	if (idx > 0)
		s = xxx.Left(idx);
	sscanf(~s, "%d", &d);
	
	NumberToTextConverter *converter = new SlovakNumberToTextConverter();
	buf.Cat(converter->convert(d));
	delete ((SlovakNumberToTextConverter *)converter);
	
	buf.Cat(" " + AsString(t_("CUR")) + "] ");
}
Example #22
0
std::vector<String> icinga::GetFieldCompletionSuggestions(const Type::Ptr& type, const String& word)
{
	std::vector<String> result;

	for (int i = 0; i < type->GetFieldCount(); i++) {
		Field field = type->GetFieldInfo(i);

		if (!(field.Attributes & FAConfig) || field.Attributes & FAInternal)
			continue;

		if (strcmp(field.TypeName, "int") != 0 && strcmp(field.TypeName, "double") != 0
		    && strcmp(field.TypeName, "bool") != 0 && strcmp(field.TypeName, "String") != 0)
			continue;

		String fname = field.Name;

		String suggestion = fname + "=";

		if (suggestion.Find(word) == 0)
			result.push_back(suggestion);
	}

	return result;
}
Example #23
0
void CommentOutFunction(String& code, const String& signature)
{
    unsigned startPos = code.Find(signature);
    unsigned braceLevel = 0;
    if (startPos == String::NPOS)
        return;
    
    code.Insert(startPos, "/*");
    
    for (unsigned i = startPos + 2 + signature.Length(); i < code.Length(); ++i)
    {
        if (code[i] == '{')
            ++braceLevel;
        else if (code[i] == '}')
        {
            --braceLevel;
            if (braceLevel == 0)
            {
                code.Insert(i + 1, "*/");
                return;
            }
        }
    }
}
Example #24
0
SceneEditor3D ::SceneEditor3D(Context* context, const String &fullpath, UITabContainer *container) :
    ResourceEditor(context, fullpath, container)
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    scene_ = new Scene(context_);
    SharedPtr<File> xmlFile = cache->GetFile(fullpath);

    if (GetExtension(fullpath) == ".scene")
        scene_->LoadXML(*xmlFile);
    else
        scene_->Load(*xmlFile);

    scene_->SetUpdateEnabled(false);

    sceneView_ = new SceneView3D(context_, this);

    // EARLY ACCESS
    if (fullpath.Find(String("ToonTown")) != String::NPOS)
    {
          sceneView_->GetCameraNode()->SetWorldPosition(Vector3(-119.073f, 76.1121f, 16.47763f));
          Quaternion q(0.55f, 0.14f,  0.8f, -0.2f);
          sceneView_->SetYaw(q.YawAngle());
          sceneView_->SetPitch(q.PitchAngle());
          sceneView_->GetCameraNode()->SetWorldRotation(q);
    }
    else
    {
        Node* playerSpawn = scene_->GetChild("PlayerInfoStart", true);
        if (playerSpawn)
        {
            sceneView_->GetCameraNode()->SetPosition(playerSpawn->GetPosition());
            sceneView_->SetYaw(playerSpawn->GetRotation().EulerAngles().y_);
        }

    }

    sceneView_->SetGravity(UI_GRAVITY_ALL);

    rootContentWidget_->AddChild(sceneView_);

    gizmo3D_ = new Gizmo3D(context_);
    gizmo3D_->SetView(sceneView_);
    gizmo3D_->Show();

    SubscribeToEvent(E_UPDATE, HANDLER(SceneEditor3D, HandleUpdate));
    SubscribeToEvent(E_EDITORACTIVENODECHANGE, HANDLER(SceneEditor3D, HandleEditorActiveNodeChange));

    SubscribeToEvent(E_GIZMOEDITMODECHANGED, HANDLER(SceneEditor3D, HandleGizmoEditModeChanged));

    // FIXME: Set the size at the end of setup, so all children are updated accordingly
    // future size changes will be handled automatically
    IntRect rect = container_->GetContentRoot()->GetRect();
    rootContentWidget_->SetSize(rect.Width(), rect.Height());

    SubscribeToEvent(E_EDITORPLAYSTARTED, HANDLER(SceneEditor3D, HandlePlayStarted));
    SubscribeToEvent(E_EDITORPLAYSTOPPED, HANDLER(SceneEditor3D, HandlePlayStopped));

    SubscribeToEvent(scene_, E_NODEREMOVED, HANDLER(SceneEditor3D, HandleNodeRemoved));

}
Example #25
0
void main ()
{
String child = String("child");
String child2 = String("child");
String car = String("car");
String testString = String();


// Test = operator
// Test 1
testString = child; 
cout << testString << endl;
// Test 2
testString = car; 
cout << testString << endl;


// Test "==" operator
// Test 1
cout << (child == child2) << endl;
// Test 2
cout << (child == car) << endl; 


// Test "!=" operator
// Test 1
cout << (child != child2) << endl; 
// Test 2
cout << (child != car) << endl; 


// Test "+" operator
// Test 1
testString = child + child2;
cout << testString << endl;
// Test 2
testString = child + car;
cout << testString << endl;


// Test Find()
try
{
	// Test 1
	cout << child.Find('x', 2) << endl;
	// Test 2
	cout << testString.Find('c', 3) << endl;
	// Test 3
	cout << testString.Find('c', 20) << endl;
}
catch ( String error )
{
	cout << "Error occured: " << error << endl;
}


// Test SubString()
// Test Find()
try
{
	// Test 1
	cout << child.Substring(2, 2) << endl;
	// Test 2
	cout << testString.Substring(1, 5) << endl;
	// Test 3
	cout << testString.Substring(10, 5) << endl;
}
catch ( String error )
{
	cout << "Error occured: " << error << endl;
}


system ("pause");
}
Example #26
0
   IMAPResult
   IMAPCommandUID::ExecuteCommand(shared_ptr<IMAPConnection> pConnection, shared_ptr<IMAPCommandArgument> pArgument)
   {
      if (!pConnection->IsAuthenticated())
         return IMAPResult(IMAPResult::ResultNo, "Authenticate first");

      String sTag = pArgument->Tag();
      String sCommand = pArgument->Command();

      if (!pConnection->GetCurrentFolder())
         return IMAPResult(IMAPResult::ResultNo, "No folder selected.");

      shared_ptr<IMAPSimpleCommandParser> pParser = shared_ptr<IMAPSimpleCommandParser>(new IMAPSimpleCommandParser());

      pParser->Parse(pArgument);
      
      if (pParser->WordCount() < 2)
         return IMAPResult(IMAPResult::ResultBad, "Command requires at least 1 parameter.");

      String sTypeOfUID = pParser->Word(1)->Value();

      if (sTypeOfUID.CompareNoCase(_T("FETCH")) == 0)
      {
         if (pParser->WordCount() < 4)
            return IMAPResult(IMAPResult::ResultBad, "Command requires at least 3 parameters.");

         command_ = shared_ptr<IMAPFetch>(new IMAPFetch());
      }
      else if (sTypeOfUID.CompareNoCase(_T("COPY")) == 0)
      {

         if (pParser->WordCount() < 4)
            return IMAPResult(IMAPResult::ResultBad, "Command requires at least 3 parameters.");

         command_ = shared_ptr<IMAPCopy>(new IMAPCopy());
      }
      else if (sTypeOfUID.CompareNoCase(_T("STORE")) == 0)
      {
         if (pParser->WordCount() < 4)
            return IMAPResult(IMAPResult::ResultBad, "Command requires at least 3 parameters.");

         command_ = shared_ptr<IMAPStore>(new IMAPStore());
      }
      else if (sTypeOfUID.CompareNoCase(_T("SEARCH")) == 0)
      {
         shared_ptr<IMAPCommandSEARCH> pCommand = shared_ptr<IMAPCommandSEARCH> (new IMAPCommandSEARCH(false));
         pCommand->SetIsUID();
         IMAPResult result = pCommand->ExecuteCommand(pConnection, pArgument);

         if (result.GetResult() == IMAPResult::ResultOK)
            pConnection->SendAsciiData(sTag + " OK UID completed\r\n");

         return result;
      }
      else if (sTypeOfUID.CompareNoCase(_T("SORT")) == 0)
      {
         shared_ptr<IMAPCommandSEARCH> pCommand = shared_ptr<IMAPCommandSEARCH> (new IMAPCommandSEARCH(true));
         pCommand->SetIsUID();
         IMAPResult result = pCommand->ExecuteCommand(pConnection, pArgument);
         
         if (result.GetResult() == IMAPResult::ResultOK)
            pConnection->SendAsciiData(sTag + " OK UID completed\r\n");

         return result;
      }


      if (!command_)
         return IMAPResult(IMAPResult::ResultBad, "Bad command.");

      command_->SetIsUID(true);

      // Copy the first word containing the message sequence
      long lSecWordStartPos = sCommand.Find(_T(" "), 5) + 1;
      long lSecWordEndPos = sCommand.Find(_T(" "), lSecWordStartPos);
      long lSecWordLength = lSecWordEndPos - lSecWordStartPos;
      String sMailNo = sCommand.Mid(lSecWordStartPos, lSecWordLength);
      
      // Copy the second word containing the actual command.
      String sShowPart = sCommand.Mid(lSecWordEndPos + 1);

      if (sMailNo.IsEmpty())
         return IMAPResult(IMAPResult::ResultBad, "No mail number specified");

      if (!StringParser::ValidateString(sMailNo, "01234567890,.:*"))
         return IMAPResult(IMAPResult::ResultBad, "Incorrect mail number");

      // Set the command to execute as argument
      pArgument->Command(sShowPart);

      // Execute the command. If we have gotten this far, it means that the syntax
      // of the command is correct. If we fail now, we should return NO. 
      IMAPResult result = command_->DoForMails(pConnection, sMailNo, pArgument);

      if (result.GetResult() == IMAPResult::ResultOK)
         pConnection->SendAsciiData(pArgument->Tag() + " OK UID completed\r\n");

      return result;
   }
Example #27
0
void CLICommand::ShowCommands(int argc, char **argv, po::options_description *visibleDesc,
    po::options_description *hiddenDesc,
    ArgumentCompletionCallback globalArgCompletionCallback,
    bool autocomplete, int autoindex)
{
	boost::mutex::scoped_lock lock(GetRegistryMutex());

	typedef std::map<std::vector<String>, CLICommand::Ptr>::value_type CLIKeyValue;

	std::vector<String> best_match;
	int arg_begin = 0;
	CLICommand::Ptr command;

	BOOST_FOREACH(const CLIKeyValue& kv, GetRegistry()) {
		const std::vector<String>& vname = kv.first;

		arg_begin = 0;

		for (int i = 0, k = 1; i < vname.size() && k < argc; i++, k++) {
			if (strcmp(argv[k], "--no-stack-rlimit") == 0 || strcmp(argv[k], "--autocomplete") == 0 || strcmp(argv[k], "--scm") == 0) {
				i--;
				arg_begin++;
				continue;
			}

			if (autocomplete && i >= autoindex - 1)
				break;

			if (vname[i] != argv[k])
				break;

			if (i >= best_match.size()) {
				best_match.push_back(vname[i]);
			}

			if (i == vname.size() - 1) {
				command = kv.second;
				break;
			}
		}
	}

	String aword;

	if (autocomplete) {
		if (autoindex < argc)
			aword = argv[autoindex];

		if (autoindex - 1 > best_match.size() && !command)
			return;
	} else
		std::cout << "Supported commands: " << std::endl;

	BOOST_FOREACH(const CLIKeyValue& kv, GetRegistry()) {
		const std::vector<String>& vname = kv.first;

		if (vname.size() < best_match.size())
			continue;

		bool match = true;

		for (int i = 0; i < best_match.size(); i++) {
			if (vname[i] != best_match[i]) {
				match = false;
				break;
			}
		}

		if (!match)
			continue;

		if (autocomplete) {
			String cname;

			if (autoindex - 1 < vname.size()) {
				cname = vname[autoindex - 1];

				if (cname.Find(aword) == 0)
					std::cout << cname << "\n";
			}
		} else
			std::cout << "  * " << boost::algorithm::join(vname, " ") << " (" << kv.second->GetShortDescription() << ")" << std::endl;
	}

	if (!autocomplete)
		std::cout << std::endl;

	if (command && autocomplete) {
		String aname, prefix, pword;
		const po::option_description *odesc;
	
		if (autoindex - 2 >= 0 && strcmp(argv[autoindex - 1], "=") == 0 && strstr(argv[autoindex - 2], "--") == argv[autoindex - 2]) {
			aname = argv[autoindex - 2] + 2;
			pword = aword;
		} else if (autoindex - 1 >= 0 && argv[autoindex - 1][0] == '-' && argv[autoindex - 1][1] == '-') {
			aname = argv[autoindex - 1] + 2;
			pword = aword;
			
			if (pword == "=")
				pword = "";
		} else if (aword.GetLength() > 1 && aword[0] == '-' && aword[1] != '-') {
			aname = aword.SubStr(1, 1);
			prefix = aword.SubStr(0, 2);
			pword = aword.SubStr(2);
		} else {
			goto complete_option;
		}

		odesc = visibleDesc->find_nothrow(aname, false);

		if (!odesc)
			return;

		if (odesc->semantic()->min_tokens() == 0)
			goto complete_option;

		BOOST_FOREACH(const String& suggestion, globalArgCompletionCallback(aname, pword)) {
			std::cout << prefix << suggestion << "\n";
		}
Example #28
0
   bool
   MailImporter::Import (const String &originalFullPath, int iAccountID, const String &sIMAPFolder)
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Imports a message located in the data directory into the queue or into an account.
   // If the message is located into an account, the ID of that account must be supplied.
   // hMailServer could determine this automatically, but we're lazy.
   //---------------------------------------------------------------------------()
   {
      // Check so that the file really exists.
      if (!FileUtilities::Exists(originalFullPath))
         return false;

      // The message must be located in the data directory.
      String dataDirectory = IniFileSettings::Instance()->GetDataDirectory();

      // Retrieve the ID of the message.
      __int64 messageID;
      bool isPartialFileName = false;
      if (!PersistentMessage::GetMessageID(originalFullPath, messageID, isPartialFileName))
         return false;

      // Check so that this message isn't already referenced in the database.
      if (messageID > 0)
      {
         // The file apparently already exists. But if the full path is stored in the database,
         // we should replace that with the partial file name.
         if (isPartialFileName)
            return true;
         else
         {
            bool result = ReplaceMessagePath_(messageID, originalFullPath);
            
            if (iAccountID > 0 && result)
               IMAPFolderContainer::Instance()->UncacheAccount(iAccountID);

            return result;

         }
      }

      String newFullPath = originalFullPath;

      // Construct a partial file name.
      String partialFileName;
      if (!PersistentMessage::GetPartialFilename(newFullPath, partialFileName))
      {
         // It was not possible to construct a partial file name from the full path.
         String movedFile;
         if (!MoveToNamedSubdirectory_(originalFullPath, partialFileName, newFullPath))
            return false;
      }

      if (iAccountID > 0)
      {
         // Make sure we're really placing the file into an account.
         int domainSlashPos = originalFullPath.Find(_T("\\"), dataDirectory.GetLength()+1);

         if (domainSlashPos < 0)
            return false;

         int accountSlashPos = originalFullPath.Find(_T("\\"), domainSlashPos+1);

         if (accountSlashPos < 0)
            return false;
      }
      else
      {
         // Make sure the file is placed into the data directory root.
         int invalidSlash = originalFullPath.Find(_T("\\"), dataDirectory.GetLength()+1);
         
         if (invalidSlash > 0)
         {
            // The message doesn't appear to be placed into the data directory.
            return false;
         }
      }

      shared_ptr<Message> pMessage = shared_ptr<Message> (new Message);
      pMessage->SetPartialFileName(partialFileName);

      // Set message size
      pMessage->SetSize(FileUtilities::FileSize(newFullPath));

      shared_ptr<MessageData> pMsgData = shared_ptr<MessageData>(new MessageData());
      if (!pMsgData->LoadFromMessage(newFullPath, pMessage))
         return false;

      // Check what we should set the internal date to.
      String sReceivedHeader = GetInternalDate_(pMsgData);
      pMessage->SetCreateTime(sReceivedHeader);
   
      // Parse out the From-address
      shared_ptr<AddresslistParser> pFromParser = shared_ptr<AddresslistParser>(new AddresslistParser());
      std::vector<shared_ptr<Address> > vecAddresses = pFromParser->ParseList(pMsgData->GetFrom());
      std::vector<shared_ptr<Address> >::iterator iterElement = vecAddresses.begin();

      if (iterElement != vecAddresses.end())
      {
         String sAddress = (*iterElement)->sMailboxName + "@" + (*iterElement)->sDomainName;
         pMessage->SetFromAddress(sAddress);
      }

      if (iAccountID == 0)
      {
         // Since this message is supposed to be delivered, we need
         // to parse the sender and recipients
         shared_ptr<AddresslistParser> pToParser = shared_ptr<AddresslistParser>(new AddresslistParser());
         std::vector<shared_ptr<Address> > vecAddresses = pToParser->ParseList(pMsgData->GetTo());
         std::vector<shared_ptr<Address> >::iterator iterElement = vecAddresses.begin();

         RecipientParser recipientParser;
         while (iterElement != vecAddresses.end())
         {
            String sAddress = (*iterElement)->sMailboxName + "@" + (*iterElement)->sDomainName;
            bool recipientOK = false;
            recipientParser.CreateMessageRecipientList(sAddress, pMessage->GetRecipients(), recipientOK);
            iterElement++;
         }

         // Since this message is supposed to be delivered, we need
         // to parse the sender and recipients
         pToParser = shared_ptr<AddresslistParser>(new AddresslistParser());
         vecAddresses = pToParser->ParseList(pMsgData->GetCC());
         iterElement = vecAddresses.begin();

         while (iterElement != vecAddresses.end())
         {
            String sAddress = (*iterElement)->sMailboxName + "@" + (*iterElement)->sDomainName;
            bool recipientOK = false;
            recipientParser.CreateMessageRecipientList(sAddress, pMessage->GetRecipients(), recipientOK);
            iterElement++;
         }

         pMessage->SetState(Message::Delivering);

         // Remove all non-local recipients to prevent duplicate email from being sent.
         pMessage->GetRecipients()->RemoveNonLocalAccounts();

         if (pMessage->GetRecipients()->GetCount() == 0)
            return false;
      }
      else
      {
         pMessage->SetAccountID(iAccountID);
         pMessage->SetState(Message::Delivered);

         // Check if we should move it to an IMAP folder
         if (!sIMAPFolder.IsEmpty())
         {
            __int64 iResultAccount = 0;
            __int64 iResultFolder = 0;
            MessageUtilities::MoveToIMAPFolder(pMessage, iAccountID, sIMAPFolder, true, true, iResultAccount, iResultFolder);
         }
         else
         {
            __int64 inboxID = CacheContainer::Instance()->GetInboxIDCache().GetUserInboxFolder(iAccountID);
            if (inboxID == 0)
               return false;

            pMessage->SetFolderID(inboxID);
         }
      }

      // Add the object to the database.
      if (!PersistentMessage::SaveObject(pMessage))
         return false;

      return true;
   }
Example #29
0
void HttpRequest::ThreadFunction()
{
#ifndef UWP //TODO: fix UWP
    String protocol = "http";
    String host;
    String path = "/";
    int port = 80;

    unsigned protocolEnd = url_.Find("://");
    if (protocolEnd != String::NPOS)
    {
        protocol = url_.Substring(0, protocolEnd);
        host = url_.Substring(protocolEnd + 3);
    }
    else
        host = url_;

    unsigned pathStart = host.Find('/');
    if (pathStart != String::NPOS)
    {
        path = host.Substring(pathStart);
        host = host.Substring(0, pathStart);
    }

    unsigned portStart = host.Find(':');
    if (portStart != String::NPOS)
    {
        port = ToInt(host.Substring(portStart + 1));
        host = host.Substring(0, portStart);
    }

    char errorBuffer[ERROR_BUFFER_SIZE];
    memset(errorBuffer, 0, sizeof(errorBuffer));

    String headersStr;
    for (unsigned i = 0; i < headers_.Size(); ++i)
    {
        // Trim and only add non-empty header strings
        String header = headers_[i].Trimmed();
        if (header.Length())
            headersStr += header + "\r\n";
    }

    // Initiate the connection. This may block due to DNS query
    /// \todo SSL mode will not actually work unless Civetweb's SSL mode is initialized with an external SSL DLL
    mg_connection* connection = 0;
    if (postData_.Empty())
    {
        connection = mg_download(host.CString(), port, protocol.Compare("https", false) ? 0 : 1, errorBuffer, sizeof(errorBuffer),
            "%s %s HTTP/1.0\r\n"
            "Host: %s\r\n"
            "%s"
            "\r\n", verb_.CString(), path.CString(), host.CString(), headersStr.CString());
    }
    else
    {
        connection = mg_download(host.CString(), port, protocol.Compare("https", false) ? 0 : 1, errorBuffer, sizeof(errorBuffer),
            "%s %s HTTP/1.0\r\n"
            "Host: %s\r\n"
            "%s"
            "Content-Length: %d\r\n"
            "\r\n"
            "%s", verb_.CString(), path.CString(), host.CString(), headersStr.CString(), postData_.Length(), postData_.CString());
    }

    {
        MutexLock lock(mutex_);
        state_ = connection ? HTTP_OPEN : HTTP_ERROR;

        // If no connection could be made, store the error and exit
        if (state_ == HTTP_ERROR)
        {
            error_ = String(&errorBuffer[0]);
            return;
        }
    }

    // Loop while should run, read data from the connection, copy to the main thread buffer if there is space
    while (shouldRun_)
    {
        // Read less than full buffer to be able to distinguish between full and empty ring buffer. Reading may block
        int bytesRead = mg_read(connection, httpReadBuffer_.Get(), READ_BUFFER_SIZE / 4);
        if (bytesRead <= 0)
            break;

        mutex_.Acquire();

        // Wait until enough space in the main thread's ring buffer
        for (;;)
        {
            unsigned spaceInBuffer = READ_BUFFER_SIZE - ((writePosition_ - readPosition_) & (READ_BUFFER_SIZE - 1));
            if ((int)spaceInBuffer > bytesRead || !shouldRun_)
                break;

            mutex_.Release();
            Time::Sleep(5);
            mutex_.Acquire();
        }

        if (!shouldRun_)
        {
            mutex_.Release();
            break;
        }

        if (writePosition_ + bytesRead <= READ_BUFFER_SIZE)
            memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), (size_t)bytesRead);
        else
        {
            // Handle ring buffer wrap
            unsigned part1 = READ_BUFFER_SIZE - writePosition_;
            unsigned part2 = bytesRead - part1;
            memcpy(readBuffer_.Get() + writePosition_, httpReadBuffer_.Get(), part1);
            memcpy(readBuffer_.Get(), httpReadBuffer_.Get() + part1, part2);
        }

        writePosition_ += bytesRead;
        writePosition_ &= READ_BUFFER_SIZE - 1;

        mutex_.Release();
    }

    // Close the connection
    mg_close_connection(connection);

    {
        MutexLock lock(mutex_);
        state_ = HTTP_CLOSED;
    }
#endif
}
Example #30
0
bool HttpsClient::ProxyConnect()
{
	if(use_proxy) {
		int start_time = msecs();
		int end_time = msecs() + timeout_msecs;
		while(!socket.PeekWrite(1000)) {
			int time = msecs();
			if(time >= end_time) {
				error = NFormat(t_("%s:%d: connecting to host timed out"), socket_host, socket_port);
				Close();
				return false;
			}
		}
		String host_port = host;
		if(port)
			host_port << ':' << port;
		else
			host_port << ":443";
		String request;
		request << "CONNECT " << host_port << " HTTP/1.1\r\n"
		        << "Host: " << host_port << "\r\n";
		if(!IsNull(proxy_username))
			request << "Proxy-Authorization: Basic "
			        << Base64Encode(proxy_username + ':' + proxy_password) << "\r\n";
		request << "\r\n";
		LLOG(request);
		int written = 0;
		while(msecs() - end_time < 0) {
			int nwrite = socket.WriteWait(request.GetIter(written), min(request.GetLength() - written, 1000), 1000);
			if(socket.IsError()) {
				error = Socket::GetErrorText();
				Close();
				return false;
			}
			if((written += nwrite) >= request.GetLength())
				break;
		}
		if(written < request.GetLength()) {
			error = NFormat(t_("%s:%d: timed out sending request to server"), host, port);
			Close();
			return false;
		}
		String line = ReadUntilProgress('\n', start_time, end_time, false);
		LLOG("P< " << line);
		if(socket.IsError()) {
			error = Socket::GetErrorText();
			Close();
			return false;
		}
		if(!line.StartsWith("HTTP") || line.Find(" 2") < 0) {
			error = "Invalid proxy reply: " + line;
			Close();
			return false;
		}
		while(line.GetCount()) {
			line = ReadUntilProgress('\n', start_time, end_time, false);
			if(*line.Last() == '\r')
				line.Trim(line.GetCount() - 1);
			LLOG("P< " << line << " len " << line.GetCount());
			if(socket.IsError()) {
				error = Socket::GetErrorText();
				Close();
				return false;
			}
		}
		use_proxy = false;
		while(!socket.PeekWrite(1000)) {
			int time = msecs();
			if(time >= end_time) {
				error = NFormat(t_("%s:%d: connecting to host timed out"), socket_host, socket_port);
				Close();
				return false;
			}
		}
	}
	return true;
}