Example #1
0
ECode CSizeF::ParseSizeF(
    /* [in] */ const String& string,
    /* [out] */ ISizeF** size)
{
    VALIDATE_NOT_NULL(size)
    *size = NULL;

    if (string.IsNull()) {
        return E_ILLEGAL_ARGUMENT_EXCEPTION;
    }
    //checkNotNull(string, "string must not be null");

    Int32 sep_ix = string.IndexOf('*');
    if (sep_ix < 0) {
        sep_ix = string.IndexOf('x');
    }
    if (sep_ix < 0) {
        // throw invalidSize(string);
        return E_NUMBER_FORMAT_EXCEPTION;
    }

    // try {
    Float w, h;
    FAIL_RETURN(StringUtils::Parse(string.Substring(0, sep_ix), &w))
    FAIL_RETURN(StringUtils::Parse(string.Substring(sep_ix + 1), &h))

    AutoPtr<CSizeF> s;
    CSizeF::NewByFriend(w, h, (CSizeF**)&s);
    *size = (ISizeF*)s.Get();
    REFCOUNT_ADD(*size)
    // } catch (NumberFormatException e) {
    //     throw invalidSize(string);
    // }
    return NOERROR;
}
Example #2
0
String UrlUtils::CanonicalizePath(
    /* [in] */ const String& _path,
    /* [in] */ Boolean discardRelativePrefix)
{
    String path = _path;
    // the first character of the current path segment
    Int32 segmentStart = 0;

    // the number of segments seen thus far that can be erased by sequences of '..'.
    Int32 deletableSegments = 0;

    for (Int32 i = 0; i <= path.GetLength(); ) {
        Int32 nextSegmentStart;
        if (i == path.GetLength()) {
            nextSegmentStart = i;
        } else if (path.GetChar(i) == '/') {
            nextSegmentStart = i + 1;
        } else {
            i++;
            continue;
        }

        /*
         * We've encountered either the end of a segment or the end of the
         * complete path. If the final segment was "." or "..", remove the
         * appropriate segments of the path.
         */
        if (i == segmentStart + 1 && path.RegionMatches(segmentStart, String("."), 0, 1)) {
            // Given "abc/def/./ghi", remove "./" to get "abc/def/ghi".
            String part = path.Substring(0, segmentStart);
            part += path.Substring(nextSegmentStart);
            path = part;
            i = segmentStart;
        }
        else if (i == segmentStart + 2 && path.RegionMatches(segmentStart, String(".."), 0, 2)) {
            if (deletableSegments > 0 || discardRelativePrefix) {
                // Given "abc/def/../ghi", remove "def/../" to get "abc/ghi".
                deletableSegments--;
                Int32 prevSegmentStart = path.LastIndexOf('/', segmentStart - 2) + 1;
                String part = path.Substring(0, prevSegmentStart);
                part += path.Substring(nextSegmentStart);
                path = part;
                i = segmentStart = prevSegmentStart;
            }
            else {
                // There's no segment to delete; this ".." segment must be retained.
                i++;
                segmentStart = i;
            }
        }
        else {
            if (i > 0) {
                deletableSegments++;
            }
            i++;
            segmentStart = i;
        }
    }
    return path;
}
ECode HttpURLConnection::GetResponseCode(
    /* [out] */ Int32* responseCode)
{
    VALIDATE_NOT_NULL(responseCode)

    // Call getInputStream() first since getHeaderField() doesn't return
    // exceptions
    AutoPtr<IInputStream> is;
    FAIL_RETURN(GetInputStream((IInputStream**)&is));
    String response;
    GetHeaderField(0, &response);
    if (response.IsNull()) {
        *responseCode = -1;
        return NOERROR;
    }
    response = response.Trim();
    Int32 mark = response.IndexOf(" ") + 1;
    if (mark == 0) {
        *responseCode = -1;
        return NOERROR;
    }
    Int32 last = mark + 3;
    if (last > response.GetLength()) {
        last = response.GetLength();
    }
    mResponseCode = StringUtils::ParseInt32(response.Substring(mark, last));
    if ((last + 1) <= response.GetLength()) {
        mResponseMessage = response.Substring(last + 1);
    }
    *responseCode = mResponseCode;
    return NOERROR;
}
Example #4
0
void CSplitClockView::UpdatePatterns()
{
    AutoPtr<IDateFormat> format;
    CDateFormat::AcquireSingleton((IDateFormat**)&format);
    String formatString;
    AutoPtr<IContext> context;
    GetContext((IContext**)&context);
    format->GetTimeFormatString(context, &formatString);
    Int32 index = GetAmPmPartEndIndex(formatString);
    String timeString;
    String amPmString;
    if (index == -1) {
        timeString = formatString;
        amPmString = "";
    } else {
        timeString = formatString.Substring(0, index);
        amPmString = formatString.Substring(index);
    }

    AutoPtr<ICharSequence> cs;
    CString::New(timeString, (ICharSequence**)&cs);
    mTimeView->SetFormat12Hour(cs);
    mTimeView->SetFormat24Hour(cs);

    cs = NULL;
    CString::New(amPmString, (ICharSequence**)&cs);
    mAmPmView->SetFormat12Hour(cs);
    mAmPmView->SetFormat24Hour(cs);
}
Example #5
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 #6
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 #7
0
bool LuaFile::LoadChunk(lua_State* luaState)
{
    if (hasLoaded_)
        return true;

    if (size_ == 0)
        return false;

    if (!luaState)
        return false;

    int top = lua_gettop(luaState);

    // Get file base name
    String name = GetName();
    unsigned extPos = name.FindLast('.');
    if (extPos != String::NPOS)
    {
        name = name.Substring(0, extPos);
    }

    int error = luaL_loadbuffer(luaState, data_, size_, name.CString());
    if (error)
    {
        const char* message = lua_tostring(luaState, -1);
        LOGERROR("Load Buffer failed for " + GetName() + ": " + String(message));
        lua_settop(luaState, top);
        return false;
    }

    LOGINFO("Loaded Lua script " + GetName());
    hasLoaded_ = true;

    return true;
}
Example #8
0
//==============================
// BitmapFontLocal::WordWrapText
void BitmapFontLocal::WordWrapText( String & inOutText, const float widthMeters, OVR::Array< OVR::String > wholeStrsList, const float fontScale ) const
{
	float const xScale = FontInfo.ScaleFactor * fontScale;
	const int32_t totalLength = inOutText.GetLengthI();
	int32_t lastWhitespaceIndex = -1;
	double lineWidthAtLastWhitespace = 0.0f;
	double lineWidth = 0.0f;
	int dontSplitUntilIdx = -1;
	for ( int32_t pos = 0; pos < totalLength; ++pos )
	{
		uint32_t charCode = inOutText.GetCharAt( pos );

		// Replace any existing character escapes with space as we recompute where to insert line breaks
		if ( charCode == '\r' || charCode == '\n' || charCode == '\t' )
		{
			inOutText.Remove( pos );
			inOutText.InsertCharAt( ' ', pos );
			charCode = ' ';
		}

		FontGlyphType const & g = GlyphForCharCode( charCode );
		lineWidth += g.AdvanceX * xScale;

		for ( int i = 0; i < wholeStrsList.GetSizeI(); ++i )
		{
			int curWholeStrLen = wholeStrsList[i].GetLengthI();
			int endPos = pos + curWholeStrLen;

			if ( endPos < totalLength )
			{
				String subInStr = inOutText.Substring( pos, endPos );
				if ( subInStr == wholeStrsList[i] )
				{
					dontSplitUntilIdx = Alg::Max(dontSplitUntilIdx, endPos);
				}
			}
		}

		if ( pos >= dontSplitUntilIdx )
		{
			if ( charCode == ' ' )
			{
				lastWhitespaceIndex = pos;
				lineWidthAtLastWhitespace = lineWidth;
			}

			// always check the line width and as soon as we exceed it, wrap the text at
			// the last whitespace. This ensure's the text always fits within the width.
			if ( lineWidth >= widthMeters && lastWhitespaceIndex >= 0 )
			{
				dontSplitUntilIdx = -1;
				inOutText.Remove( lastWhitespaceIndex );
				inOutText.InsertCharAt( '\n', lastWhitespaceIndex );
				// subtract the width after the last whitespace so that we don't lose any
				// of the accumulated width since then.
				lineWidth -= lineWidthAtLastWhitespace;
			}
		}
	}
}
Example #9
0
static status_t ExpandFilePathWildCardsAux(const String & curDir, const String & path, Queue<String> & outputPaths, bool isSimpleFormat)
{
   const char * fs = GetFilePathSeparator();
   const int32 sepIdx = path.IndexOf(fs);
   const String firstClause  = (sepIdx >= 0) ? path.Substring(0, sepIdx) : path;
   const String restOfString = (sepIdx >= 0) ? path.Substring(sepIdx+1) : GetEmptyString();

   StringMatcher sm(firstClause, isSimpleFormat);
   Directory dir(curDir());
   if (dir.IsValid())
   {
      if (CanWildcardStringMatchMultipleValues(firstClause))
      {
         while(1)
         {
            const char * fn = dir.GetCurrentFileName();
            if (fn)
            {
               if ((strcmp(fn, ".") != 0)&&(strcmp(fn, "..") != 0)&&((fn[0] != '.')||(firstClause.StartsWith(".")))&&(sm.Match(fn)))
               {
                  const String childPath = String(dir.GetPath())+fn;
                  if (restOfString.HasChars())
                  {
                     if (ExpandFilePathWildCardsAux(childPath, restOfString, outputPaths, isSimpleFormat) != B_NO_ERROR) return B_ERROR;
                  }
                  else if (outputPaths.AddTail(childPath) != B_NO_ERROR) return B_ERROR;
               } 
               dir++;
            }
            else break;
         }
      }
      else
      {
         const String childPath = String(dir.GetPath())+firstClause;
         if (FilePathInfo(childPath()).Exists())
         {
            if (restOfString.HasChars())
            {
               if (ExpandFilePathWildCardsAux(childPath, restOfString, outputPaths, isSimpleFormat) != B_NO_ERROR) return B_ERROR;
            }
            else if (outputPaths.AddTail(childPath) != B_NO_ERROR) return B_ERROR;
         }
      }
   }
   return B_NO_ERROR;
}
Example #10
0
ECode CJDBCConnection::constructor(
    /* [in] */ const String& url,
    /* [in] */ const String& enc,
    /* [in] */ const String& pwd,
    /* [in] */ const String& drep,
    /* [in] */ const String& vfs)
{
    ECode ec = NOERROR;
    if (url.StartWith("sqlite:/")) {
        mDbfile = url.Substring(0, 8);
    } else if (url.StartWith("jdbc:sqlite:/")) {
        mDbfile = url.Substring(0, 13);
    } else {
        return E_SQL_EXCEPTION;
    }

    this->mUrl = url;
    this->mEnc = enc;
    this->mVfs = vfs;

    ec = Open(mReadonly, (IDatabase**)&mDb);
    if (FAILED(ec)) {
        return E_SQL_EXCEPTION;
    }

    if (!pwd.IsNullOrEmpty()) {
        ec = mDb->Key(pwd);
        if (FAILED(ec)) {
            return E_SQL_EXCEPTION;
        }
    }

    IBusyHandler* hd = IBusyHandler::Probe(this);
    ec = mDb->BusyHandler(hd);
    //ec = mDb->BusyHandler(this);
    if (FAILED(ec)) {
        if (mDb != NULL) {
            mDb->Close();
        }
    }
    if (!drep.IsNull() && (drep.StartWith("j") || drep.StartWith("J"))) {
        mUseJulian = TRUE;
    }

    return NOERROR;
}
ECode BasicTokenIterator::CreateToken(
    /* [in] */ const String& value,
    /* [in] */ Int32 start,
    /* [in] */ Int32 end,
    /* [out] */ String* str)
{
    VALIDATE_NOT_NULL(str)
    *str = value.Substring(start, end);
    return NOERROR;
}
String WifiTile::RemoveDoubleQuotes(
    /* [in] */ const String& string)
{
    if (string == NULL) return String(NULL);
    const Int32 length = string.GetLength();
    if ((length > 1) && (string.GetChar(0) == '"') && (string.GetChar(length - 1) == '"')) {
        return string.Substring(1, length - 1);
    }
    return string;
}
Example #13
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 #14
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";
    }
}
String CBalloonView::GetLimitedLabelForDrawing(
    /* [in] */ const String& rawLabel,
    /* [in] */ Float widthToDraw)
{
    Int32 subLen = rawLabel.GetLength();
    if (subLen <= 1) return rawLabel;
    do {
        subLen--;
        Float width = 0.f;
        mPaintLabel->MeasureText(rawLabel, 0, subLen, &width);
        if (width + mSuspensionPointsWidth <= widthToDraw || 1 >= subLen) {
            return rawLabel.Substring(0, subLen) + SUSPENSION_POINTS;
        }
    } while (TRUE);
}
Example #16
0
ECode CWifiInfo::RemoveDoubleQuotes(
    /* [in] */ const String& str,
    /* [out] */ String* value)
{
    VALIDATE_NOT_NULL(value);

    if (str.IsNull()) return NOERROR;
    AutoPtr<ArrayOf<Char32> > charArray = str.GetChars();
    const Int32 length = charArray->GetLength();
    if ((length > 1) && ((*charArray)[0] == '"') && ((*charArray)[length - 1] == '"')) {
        *value = str.Substring(1, length - 1);
        return NOERROR;
    }
    *value = str;
    return NOERROR;
}
Example #17
0
bool Shader::ProcessSource(String& code, Deserializer& source)
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    
    // If the source if a non-packaged file, store the timestamp
    File* file = dynamic_cast<File*>(&source);
    if (file && !file->IsPackaged())
    {
        FileSystem* fileSystem = GetSubsystem<FileSystem>();
        String fullName = cache->GetResourceFileName(file->GetName());
        unsigned fileTimeStamp = fileSystem->GetLastModifiedTime(fullName);
        if (fileTimeStamp > timeStamp_)
            timeStamp_ = fileTimeStamp;
    }
    
    // Store resource dependencies for includes so that we know to reload if any of them changes
    if (source.GetName() != GetName())
        cache->StoreResourceDependency(this, source.GetName());
    
    while (!source.IsEof())
    {
        String line = source.ReadLine();
        
        if (line.StartsWith("#include"))
        {
            String includeFileName = GetPath(source.GetName()) + line.Substring(9).Replaced("\"", "").Trimmed();
            
            SharedPtr<File> includeFile = cache->GetFile(includeFileName);
            if (!includeFile)
                return false;
            
            // Add the include file into the current code recursively
            if (!ProcessSource(code, *includeFile))
                return false;
        }
        else
        {
            code += line;
            code += "\n";
        }
    }

    // Finally insert an empty line to mark the space between files
    code += "\n";
    
    return true;
}
ECode CIntentFilterAuthorityEntry::Match(
    /* [in] */ IUri* data,
    /* [out] */ Int32* result)
{
    VALIDATE_NOT_NULL(result)
    *result = IIntentFilter::NO_MATCH_DATA;

    String host;
    FAIL_RETURN(data->GetHost(&host))

    if (host.IsNull()) {
        return NOERROR;
    }

    if (FALSE) {
        Logger::V("IntentFilter", "Match host [%s] : [%s]", host.string(), mHost.string());
    }

    if (mWild) {
        if (host.GetLength() < mHost.GetLength()) {
            return NOERROR;
        }
        host = host.Substring(host.GetLength() - mHost.GetLength());
    }

    if (host.CompareIgnoreCase(mHost) != 0) {
        return NOERROR;
    }

    if (mPort >= 0) {
        Int32 port;
        FAIL_RETURN(data->GetPort(&port));
        if (mPort != port) {
            return NOERROR;
        }

        *result = IIntentFilter::MATCH_CATEGORY_PORT;
        return NOERROR;
    }

    *result = IIntentFilter::MATCH_CATEGORY_HOST;
    return NOERROR;
}
Example #19
0
String UrlUtils::GetSchemePrefix(
    /* [in] */const String& spec)
{
    Int32 colon = spec.IndexOf(':');

    if (colon < 1) {
        return String(NULL);
    }

    AutoPtr<ArrayOf<Char32> > char32Array = spec.GetChars();
    for (int i = 0; i < colon; i++) {
        if (!IsValidSchemeChar(i, (Byte)(*char32Array)[i])) {
            return String(NULL);
        }
    }

    String result = spec.Substring(0, colon).ToLowerCase();
    return result;
}
Example #20
0
ECode EcoFile::OpenEcoFile(
    /* [in] */ const String& sourceName,
    /* [out] */ IModuleInfo** ecoModule)
{
    String fileName = sourceName;
    Int32 start = fileName.LastIndexOf("/");
    Int32 end = fileName.LastIndexOf("-");
    fileName = fileName.Substring(start >= 0 ? start + 1 : 0, end >= 0 ? end : fileName.GetLength() - 4)  + String(".eco");
    String path = String("/data/elastos/") + fileName;
    AutoPtr<IModuleInfo> moduleInfo;
    if (FAILED(CReflector::AcquireModuleInfo(path.string(), (IModuleInfo**)&moduleInfo))) {
        *ecoModule = NULL;
        Slogger::E(TAG, "OpenEcoFile: Cann't Find the Instrumentation path is %s", path.string());
        return E_RUNTIME_EXCEPTION;
    }
    *ecoModule = moduleInfo;
    REFCOUNT_ADD(*ecoModule);
    return NOERROR;
}
ECode IntentTile::Create(
    /* [in] */ IQSTileHost* host,
    /* [in] */ const String& spec,
    /* [out] */ IQSTile** tile)
{
    VALIDATE_NOT_NULL(tile);
    if (spec == NULL || !spec.StartWith(PREFIX) || !spec.EndWith(")")) {
        tile = NULL;
        // throw new IllegalArgumentException("Bad intent tile spec: " + spec);
        return E_ILLEGAL_ARGUMENT_EXCEPTION;
    }
    const String action = spec.Substring(PREFIX.GetLength(), spec.GetLength() - 1);
    if (action.IsEmpty()) {
        tile = NULL;
        // throw new IllegalArgumentException("Empty intent tile spec action");
        return E_ILLEGAL_ARGUMENT_EXCEPTION;
    }
    *tile = new IntentTile(host, action);
    REFCOUNT_ADD(*tile);
    return NOERROR;
}
Example #22
0
ECode CURI::ValidateScheme(
    /* [in] */ const String& uri,
    /* [in] */ Int32 end,
    /* [out] */ String* result)
{
    VALIDATE_NOT_NULL(result)
    *result = String(NULL);

    if (end == 0) {
        return E_URI_SYNTAX_EXCEPTION;
    }

    AutoPtr<ArrayOf<Char32> > char32Array = uri.GetChars();
    for (Int32 i = 0; i < end; i++) {
        if (!UrlUtils::IsValidSchemeChar(i, (*char32Array)[i])) {
            return E_URI_SYNTAX_EXCEPTION;
        }
    }
    *result = uri.Substring(0, end);
    return NOERROR;
}
Example #23
0
ECode CURI::ParseAuthority(
    /* [in] */ Boolean forceServer)
{
    if (mAuthority.IsNull()) {
        return NOERROR;
    }

    String tempUserInfo;
    String temp = mAuthority;
    Int32 index = temp.IndexOf('@');
    Int32 hostIndex = 0;
    if (index != -1) {
        // remove user info
        tempUserInfo = temp.Substring(0, index);
        FAIL_RETURN(ValidateUserInfo(mAuthority, tempUserInfo, 0));
        temp = temp.Substring(index + 1); // host[:port] is left
        hostIndex = index + 1;
    }

    index = temp.LastIndexOf(':');
    Int32 endIndex = temp.IndexOf(']');

    String tempHost;
    Int32 tempPort = -1;
    if (index != -1 && endIndex < index) {
        // determine port and host
        tempHost = temp.Substring(0, index);

        Char32 firstPortChar = temp.GetChar(index + 1);
        if (firstPortChar >= '0' && firstPortChar <= '9') {
            // allow only digits, no signs
            ECode ec = StringUtils::Parse(temp.Substring(index + 1), &tempPort);
            if (ec == (ECode)E_NUMBER_FORMAT_EXCEPTION) {
                if (forceServer) {
                    ALOGE("%s Invalid port number %d", mAuthority.string(), hostIndex + index + 1);
                    return E_URI_SYNTAX_EXCEPTION;
                }
                return NOERROR;
            }
        } else {
            if (forceServer) {
                ALOGE("%s Invalid port number %d", mAuthority.string(), hostIndex + index + 1);
                return E_URI_SYNTAX_EXCEPTION;
            }
            return NOERROR;
        }
    }
    else {
        tempHost = temp;
    }

    if (tempHost.IsEmpty()) {
        if (forceServer) {
            return E_URI_SYNTAX_EXCEPTION;
        }
        return NOERROR;
    }

    Boolean isValid = FALSE;
    FAIL_RETURN(IsValidHost(forceServer, tempHost, &isValid));
    if (!isValid) {
        return NOERROR;
    }

    // this is a server based uri,
    // fill in the userInfo, host and port fields
    mUserInfo = tempUserInfo;
    mHost = tempHost;
    mPort = tempPort;
    mServerAuthority = TRUE;

    return NOERROR;
}
Example #24
0
bool ShaderVariation::Create()
{
    Release();

    if (!owner_)
    {
        compilerOutput_ = "Owner shader has expired";
        return false;
    }

    object_ = glCreateShader(type_ == VS ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER);
    if (!object_)
    {
        compilerOutput_ = "Could not create shader object";
        return false;
    }

    const String& originalShaderCode = owner_->GetSourceCode(type_);
    String shaderCode;

    // Check if the shader code contains a version define
    unsigned verStart = originalShaderCode.Find('#');
    unsigned verEnd = 0;
    if (verStart != String::NPOS)
    {
        if (originalShaderCode.Substring(verStart + 1, 7) == "version")
        {
            verEnd = verStart + 9;
            while (verEnd < originalShaderCode.Length())
            {
                if (IsDigit((unsigned)originalShaderCode[verEnd]))
                    ++verEnd;
                else
                    break;
            }
            // If version define found, insert it first
            String versionDefine = originalShaderCode.Substring(verStart, verEnd - verStart);
            shaderCode += versionDefine + "\n";
        }
    }
    // Force GLSL version 150 if no version define and GL3 is being used
    if (!verEnd && Graphics::GetGL3Support())
        shaderCode += "#version 150\n";

    // Distinguish between VS and PS compile in case the shader code wants to include/omit different things
    shaderCode += type_ == VS ? "#define COMPILEVS\n" : "#define COMPILEPS\n";

    // Add define for the maximum number of supported bones
    shaderCode += "#define MAXBONES " + String(Graphics::GetMaxBones()) + "\n";

    // Prepend the defines to the shader code
    Vector<String> defineVec = defines_.Split(' ');
    for (unsigned i = 0; i < defineVec.Size(); ++i)
    {
        // Add extra space for the checking code below
        String defineString = "#define " + defineVec[i].Replaced('=', ' ') + " \n";
        shaderCode += defineString;

        // In debug mode, check that all defines are referenced by the shader code
#ifdef _DEBUG
        String defineCheck = defineString.Substring(8, defineString.Find(' ', 8) - 8);
        if (originalShaderCode.Find(defineCheck) == String::NPOS)
            URHO3D_LOGWARNING("Shader " + GetFullName() + " does not use the define " + defineCheck);
#endif
    }

#ifdef RPI
    if (type_ == VS)
        shaderCode += "#define RPI\n";
#endif
#ifdef __EMSCRIPTEN__
    shaderCode += "#define WEBGL\n";
#endif
    if (Graphics::GetGL3Support())
        shaderCode += "#define GL3\n";

    // When version define found, do not insert it a second time
    if (verEnd > 0)
        shaderCode += (originalShaderCode.CString() + verEnd);
    else
        shaderCode += originalShaderCode;

    const char* shaderCStr = shaderCode.CString();
    glShaderSource(object_, 1, &shaderCStr, 0);
    glCompileShader(object_);

    int compiled, length;
    glGetShaderiv(object_, GL_COMPILE_STATUS, &compiled);
    if (!compiled)
    {
        glGetShaderiv(object_, GL_INFO_LOG_LENGTH, &length);
        compilerOutput_.Resize((unsigned)length);
        int outLength;
        glGetShaderInfoLog(object_, length, &outLength, &compilerOutput_[0]);
        glDeleteShader(object_);
        object_ = 0;
    }
    else
        compilerOutput_.Clear();

    return object_ != 0;
}
ECode CObjInfoList::AcquireDynamicEnumInfo(
    /* [in] */ const String& fullName,
    /* [in] */ ArrayOf<String>* itemNames,
    /* [in] */ ArrayOf<Int32>* itemValues,
    /* [out] */ IEnumInfo** enumInfo)
{
    if (fullName.IsNull() || itemNames == NULL
        || itemValues == NULL || !enumInfo
        || itemNames->GetLength() != itemValues->GetLength()) {
        return E_INVALID_ARGUMENT;
    }

    InfoLinkNode* node = mEnumInfoHead;
    String enumName;
    String enumNamespace;
    AutoPtr<CEnumInfo> enumInfoObj;
    Int32 count = 0, i = 0;

    LockHashTable(EntryType_Enum);
    for (; node; node = node->mNext) {
        enumInfoObj = (CEnumInfo *)node->mInfo;
        enumInfoObj->GetName(&enumName);
        enumInfoObj->GetNamespace(&enumNamespace);

        Int32 index = fullName.LastIndexOf(".");
        String name = index > 0 ? fullName.Substring(index + 1) : fullName;
        String nameSpace = index > 0 ? fullName.Substring(0, index - 1) : String("");
        if (name.Equals(enumName) && nameSpace.Equals(enumNamespace)) {
            enumInfoObj->GetItemCount(&count);
            if (count != itemNames->GetLength()) {
                if (!name.IsEmpty()) {
                    UnlockHashTable(EntryType_Enum);
                    return E_DATAINFO_EXIST;
                }
                else {
                    continue;
                }
            }

            AutoPtr< ArrayOf<String> > _itemNames = enumInfoObj->mItemNames;
            AutoPtr< ArrayOf<Int32> > _itemValues = enumInfoObj->mItemValues;
            for (i = 0; i < count; i++) {
                if (!(*itemNames)[i].Equals((*_itemNames)[i])) {
                    if (!name.IsEmpty()) {
                        UnlockHashTable(EntryType_Enum);
                        return E_DATAINFO_EXIST;
                    }
                    else {
                        continue;
                    }
                }
                if ((*itemValues)[i] != (*_itemValues)[i]) {
                    if (!name.IsEmpty()) {
                        UnlockHashTable(EntryType_Enum);
                        return E_DATAINFO_EXIST;
                    }
                    else {
                        continue;
                    }
                }
            }

            *enumInfo = enumInfoObj;
            (*enumInfo)->AddRef();
            return NOERROR;
        }
    }

    enumInfoObj = new CEnumInfo();
    if (enumInfoObj == NULL) {
        UnlockHashTable(EntryType_Enum);
        return E_OUT_OF_MEMORY;
    }

    ECode ec = enumInfoObj->InitDynamic(fullName, itemNames, itemValues);
    if (FAILED(ec)) {
        UnlockHashTable(EntryType_Enum);
        return ec;
    }

    ec = AddInfoNode(enumInfoObj, &mEnumInfoHead);
    if (FAILED(ec)) {
        UnlockHashTable(EntryType_Enum);
        return ec;
    }

    *enumInfo = enumInfoObj;
    (*enumInfo)->AddRef();

    UnlockHashTable(EntryType_Enum);

    return NOERROR;
}
Example #26
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 #27
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 #28
0
VariantMap Engine::ParseParameters(const Vector<String>& arguments)
{
    VariantMap ret;
    
    for (unsigned i = 0; i < arguments.Size(); ++i)
    {
        if (arguments[i][0] == '-' && arguments[i].Length() >= 2)
        {
            String argument = arguments[i].Substring(1).ToLower();
            
            if (argument == "headless")
                ret["Headless"] = true;
            else if (argument.Substring(0, 3) == "log")
            {
                argument = argument.Substring(3);
                int logLevel = GetStringListIndex(argument.CString(), logLevelPrefixes, -1);
                if (logLevel != -1)
                    ret["LogLevel"] = logLevel;
            }
            else if (argument == "nolimit")
                ret["FrameLimiter"] = false;
            else if (argument == "nosound")
                ret["Sound"] = false;
            else if (argument == "noip")
                ret["SoundInterpolation"] = false;
            else if (argument == "mono")
                ret["SoundStereo"] = false;
            else if (argument == "prepass")
                ret["RenderPath"] = "RenderPaths/Prepass.xml";
            else if (argument == "deferred")
                ret["RenderPath"] = "RenderPaths/Deferred.xml";
            else if (argument == "noshadows")
                ret["Shadows"] = false;
            else if (argument == "lqshadows")
                ret["LowQualityShadows"] = true;
            else if (argument == "nothreads")
                ret["WorkerThreads"] = false;
            else if (argument == "sm2")
                ret["ForceSM2"] = true;
            else
            {
                int value;
                if (argument.Length() > 1)
                    value = ToInt(argument.Substring(1));
                
                switch (tolower(argument[0]))
                {
                case 'x':
                    ret["WindowWidth"] = value;
                    break;
                    
                case 'y':
                    ret["WindowHeight"] = value;
                    break;
                
                case 'm':
                    ret["MultiSample"] = value;
                    break;
                    
                case 'b':
                    ret["SoundBuffer"] = value;
                    break;
                    
                case 'r':
                    ret["SoundMixRate"] = value;
                    break;
                    
                case 'v':
                    ret["VSync"] = true;
                    break;
                    
                case 't':
                    ret["TripleBuffer"] = true;
                    break;
                    
                case 'w':
                    ret["FullScreen"] = false;
                    break;
                        
                case 's':
                    ret["WindowResizable"] = true;
                    break;
                    
                case 'q':
                    ret["LogQuiet"] = true;
                    break;
                    
                case 'p':
                    ret["ResourcePaths"] = arguments[i].Substring(2);
                    break;
                }
            }
        }
    }
    
    return ret;
}
Example #29
0
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
bool VoidBot::PublicCommands(const char* SessionID, const String& Command)
{
// todo: these should all be busted out into their own functions

	// "Message For" command
	String keyword("message for");
	int32 pos = WholeWordPos(Command, keyword.Cstr());
	if( B_ERROR != pos )
	{
		if( 2048 < Command.Length() )
		{
			SendMessage(SessionID, "There is _no way_ I can remember all that, please phrase the message shorter.");
			return true;
		}

		pos += keyword.Length();
		String name(GetNick(Command, pos));
		if( 0 == name.Length() )
		{
			SendMessage(SessionID, "Please specify a nick!");
			return true;
		}

		if( B_ERROR != name.IndexOf(' ') )
		{
			// name with space, adjust for delimiter chars.
			pos += 2;
		}

		pos += name.Length() + 1;

		if( (int32)Command.Length() < (pos - 1) )
		{
			SendMessage(SessionID, "Please specify a message.");
			return true;
		}

		String message("Message from ");
		message += fData.UserByID(SessionID)->Name();
		message += " Left at";
		message += " [";
		message += Time();
		message += "]";
		message += ": ";
		message += Command.Substring(pos);
		fMessagesForName[name].push_back(message);
		SendPrivateMessage(SessionID, "Will there be anything else?.");
		fReportedNewMessages[name] = false;
		return true;
	}

	// "Seen" command
	keyword = "seen";
	pos = WholeWordPos(Command, keyword.Cstr());
	if( -1 != pos )
	{
		pos += keyword.Length();

		String name(GetNick(Command, pos));
		if( 0 == name.Length() )
		{
			SendMessage(SessionID, "Please specify a nick!");
			return true;
		}

		if( fLastWords.find(name.Cstr()) != fLastWords.end() )
		{
			String info(name);
			info += " was last seen ";
			info += fLastWords[name.Cstr()];
			SendMessage(SessionID, info.Cstr());
		}
		else
		{
			String negatory("No, I haven't seen ");
			negatory += name;
			SendMessage(SessionID, negatory.Cstr());
		}
		return true;
	}

		//*****************<FORTUNE ADDED BY MISZA>************************//
	pos = WholeWordPos(Command, "fortune");
	if(-1 != pos)
	{
		FILE *fp = popen ("fortune", "r");
		if(fp != NULL)
		{
			char ch;
			String cool= "\n";

			while((ch = fgetc(fp))!= EOF)
			{
				cool += ch;
			}

			fclose(fp);
			if(cool != "\n")
			{
				cool = cool.Substring(0,(cool.Length()-1));
				SendPrivateMessage(SessionID,cool.Cstr());
			}
		}
		return true;
	}
	//*****************</FORTUNE ADDED BY MISZA>************************//

	// "GMTime" command
	pos = WholeWordPos(Command, "gmtime");
	if( -1 != pos )
	{
		String info("The time is: ");
		info += Time();
		SendMessage(SessionID, info.Cstr());
		return true;
	}

	// "Time" command
	pos = WholeWordPos(Command, "time");
	if( -1 != pos )
	{
		String info("The time is: ");
		info += MyTime();
		SendMessage(SessionID, info.Cstr());
		return true;
	}

	// "iTime" command
	pos = WholeWordPos(Command, "itime");
	if( -1 != pos )
	{
		String info("The time is: ");
		info += NetTime();
		SendMessage(SessionID, info.Cstr());
		return true;
	}

	// "Atrus" Prevent messages to bebop
	keyword = "message for bebop";
	pos = WholeWordPos(Command, keyword.Cstr());
	if( B_ERROR != pos )
	{
		SendPrivateMessage(SessionID, "You didn't say the magic word...");

			return true;
	}

	// "Atrus" Prevent messages to Atrus
	keyword = "message for Atrus";
	pos = WholeWordPos(Command, keyword.Cstr());
	if( B_ERROR != pos )
	{
		SendPrivateMessage(SessionID, "You didn't say the magic word...");

			return true;
	}

	// "Atrus" Prevent messages to Bubbles
	keyword = "message for Bubbles";
	pos = WholeWordPos(Command, keyword.Cstr());
	if( B_ERROR != pos )
	{
		SendPrivateMessage(SessionID, "You didn't say the magic word...");

			return true;
	}

	// "Atrus" Prevent messages to FAQbot
	keyword = "message for FAQbot";
	pos = WholeWordPos(Command, keyword.Cstr());
	if( B_ERROR != pos )
	{
		SendPrivateMessage(SessionID, "You didn't say the magic word...");

			return true;
	}

	// "Messages" command
	pos = WholeWordPos(Command, "messages");
	if( B_ERROR != pos )
	{
		bool messages = false;
		uint32 quantity = 0;
		const char* name = fData.UserByID(SessionID)->Name();

		if( fMessagesForName.find(name) != fMessagesForName.end() )
		{
			quantity = fMessagesForName[name].size();

			if( quantity != 0 )
			{
				messages = true;
			}
		}

		if( true == messages )
		{
			for( uint32 i = 0; i < quantity; i++ )
			{
				SendPrivateMessage(SessionID, fMessagesForName[name][i].Cstr());
			}

			fMessagesForName[name].clear();
			fReportedNewMessages[name] = true;
		}
		else
		{
			String reply("Sorry ");
			reply += fData.UserByID(SessionID)->Name();
			reply += ", You get nothing and like it!";
			SendPrivateMessage(SessionID, reply.Cstr());
		}

		return true;
	}

	// "Version" command
	pos = WholeWordPos(Command, "version");
	if( B_ERROR != pos )
	{
		// The version string is made up of MAJOR_RELEASE.MINOR_RELEASE.BUG_FIXES
		SendPrivateMessage(SessionID, "I am at version 2.1 (MUSCLE " MUSCLE_VERSION_STRING ")");
		return true;
	}

	pos = WholeWordPos(Command, "catsup");
	if( B_ERROR != pos )
	{
		// Figure out how many lines of chat to return
		pos++;
		pos += strlen("catsup");

		uint32 lines;
		if( (uint32)pos < Command.Length() )
		{
			lines = (uint32)atoi(&(Command.Cstr()[pos]));
			if( 0 == lines )
			{
				lines = kDefaultChatHistory;
			}
		}
		else
		{
			lines = 25;
		}

		if( lines > fChatHistory.size() )
		{
			lines = fChatHistory.size();
		}

		String chatText("\n");
		for( uint32 i = lines; i > 0 ; i-- )
		{
			chatText += fChatHistory[i-1];
			chatText += "\n";
		}

		SendPrivateMessage(SessionID, chatText.Cstr());
		return true;
	}

	// "Email" command
	keyword = "email";
	pos = WholeWordPos(Command, keyword.Cstr());
	if( -1 != pos )
	{
		pos += keyword.Length();

		String name(GetNick(Command, pos));
		if( 0 == name.Length() )
		{
			SendPrivateMessage(SessionID, "Please specify a nick!");
			return true;
		}

		{
			String fullname(botPath);
			fullname += "/email/";
			fullname += name;
			if(!SendTextfile(SessionID, fullname.Cstr(), false))
			{
				SendPrivateMessage(SessionID, "No email address found for that nick!");
			}
			return true;
		}
	}

	// "Gimme" command (v.2)
	keyword = "gimme";
	pos = WholeWordPos(Command, keyword.Cstr());
	if( -1 != pos )
	{
		pos += keyword.Length();

		String name(GetNick(Command, pos));
		if( 0 == name.Length() )
		{
			SendPrivateMessage(SessionID, "Please specify help page!");
			return true;
		}

		{
			String fullname(botPath);
			fullname += "/faq/";
			fullname += name;
			return SendTextfile(SessionID, fullname.Cstr(), false);
		}
	}

	// Do all one word commands (aka send text file with same name to user)
	String name(Command.Substring( Command.IndexOf(" ") + 1));
	if ( 0 < name.Length() )
	{
		String fullname(botPath);
		fullname += "/commands/";
		fullname += name.Cstr();
		return SendTextfile(SessionID, fullname.Cstr(), false);
	}

	return false;
}
// Parses a string that the user typed in to stdin and creates a Message to send to the server.
static MessageRef ParseStdinCommand(const String & stdinCommand)
{
   if (stdinCommand.IsEmpty()) return MessageRef();

   StringTokenizer tok(stdinCommand(), " ");
   const String cmd  = tok();
   if ((cmd == "set") || (cmd == "s"))
   {
      const String theRest = String(tok.GetRemainderOfString());
      if (theRest.HasChars())
      {
         const int eqIdx = theRest.IndexOf('=');
         const String pathArg = (eqIdx >= 0) ? theRest.Substring(0, eqIdx).Trim() : theRest;
         const String dataArg = (eqIdx >= 0) ? theRest.Substring(eqIdx+1).Trim()  : "default";

         if (pathArg.StartsWith("/"))
         {
            LogTime(MUSCLE_LOG_ERROR, "PR_COMMAND_SETDATA paths cannot start with a slash (because you're only allowed to set nodes within your own session-folder!)\n");
         }
         else
         {
            LogTime(MUSCLE_LOG_INFO, "Sending PR_COMMAND_SETDATA to set node at subpath [%s] to contain a Message containing data string [%s]\n", pathArg(), dataArg());
            if (HasRegexTokens(pathArg)) LogTime(MUSCLE_LOG_WARNING, "Note: PR_COMMAND_SETDATA won't do pattern-matching on wildcard chars; rather they will become literal chars in the node-path!\n");

             MessageRef dataPayloadMsg = GetMessageFromPool();
             dataPayloadMsg()->AddString("User String", dataArg);

             MessageRef setDataMsg = GetMessageFromPool(PR_COMMAND_SETDATA);
             setDataMsg()->AddMessage(pathArg, dataPayloadMsg);

             return setDataMsg;
         }
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  set my_node_dir/my_node_file = some text to put in the node\n");
   }
   else if ((cmd == "get") || (cmd == "g"))
   {
      const String pathArg = tok();
      if (pathArg.HasChars())
      {
         LogTime(MUSCLE_LOG_INFO, "Sending PR_COMMAND_GETDATA to do a one-time download of nodes matching the following path: [%s]\n", pathArg());

         MessageRef getDataMsg = GetMessageFromPool(PR_COMMAND_GETDATA);
         getDataMsg()->AddString(PR_NAME_KEYS, pathArg);
         return getDataMsg;
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  get /*/*\n");
   }
   else if ((cmd == "delete") || (cmd == "d"))
   {
      const String pathArg = tok();
      if (pathArg.HasChars())
      {
         LogTime(MUSCLE_LOG_INFO, "Sending PR_COMMAND_REMOVEDATA to delete any nodes matching the following path: [%s]\n", pathArg());

         MessageRef deleteNodesMsg = GetMessageFromPool(PR_COMMAND_REMOVEDATA);
         deleteNodesMsg()->AddString(PR_NAME_KEYS, pathArg);
         return deleteNodesMsg;
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  delete *\n");
   }
   else if ((cmd == "subscribe") || (cmd == "S"))
   {
      const String pathArg = tok();
      if (pathArg.HasChars())
      {
         LogTime(MUSCLE_LOG_INFO, "Sending PR_COMMAND_SETPARAMETERS to set up a \"live\" subscription to any nodes matching the following path: [%s]\n", pathArg());

         MessageRef subscribeToNodesMsg = GetMessageFromPool(PR_COMMAND_SETPARAMETERS);
         subscribeToNodesMsg()->AddBool(String("SUBSCRIBE:%1").Arg(pathArg), true);
         return subscribeToNodesMsg;
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  subscribe /*/*\n");
   }
   else if ((cmd == "unsubscribe") || (cmd == "u"))
   {
      const String pathArg = tok();
      if (pathArg.HasChars())
      {
         LogTime(MUSCLE_LOG_INFO, "Sending PR_COMMAND_REMOVEPARAMETERS to get rid of any \"live\" subscriptions that match the following string: [SUBSCRIBE:%s]\n", pathArg());

         MessageRef unsubscribeFromNodesMsg = GetMessageFromPool(PR_COMMAND_REMOVEPARAMETERS);
         unsubscribeFromNodesMsg()->AddString(PR_NAME_KEYS, String("SUBSCRIBE:%1").Arg(pathArg));
         return unsubscribeFromNodesMsg;
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  unsubscribe /*/*\n");
   }
   else if ((cmd == "msg") || (cmd == "m"))
   {
      const String pathArg  = tok();
      if (pathArg.HasChars())
      {
         const String userText = tok.GetRemainderOfString();

         MessageRef chatMsg = GetMessageFromPool(1234);  // any non-PR_COMMAND_* message code will work here
         chatMsg()->AddString(PR_NAME_KEYS, pathArg);
         chatMsg()->AddString("chat_text", userText);
         return chatMsg;
      }
      else LogTime(MUSCLE_LOG_INFO, "Usage Example:  msg /*/* Hey guys!\n");
   }
   else if ((cmd == "help") || (cmd == "h"))
   {
      PrintHelp();
   }
   else LogTime(MUSCLE_LOG_ERROR, "Couldn't parse stdin command [%s].  Enter help to review the command-help-text.\n", stdinCommand());

   return MessageRef();  // nothing to send for now
}