Example #1
0
/**
 * Return the next command line option. This has a number of special cases
 * which closely, but not exactly, follow the POSIX command line options
 * patterns:
 *
 * <pre>
 * -- means to stop processing additional options
 * -z means option z
 * -z ARGS means option z with (non-optional) arguments ARGS
 * -zARGS means option z with (optional) arguments ARGS
 * --zz means option zz
 * --zz ARGS means option zz with (non-optional) arguments ARGS
 * </pre>
 *
 * Note that you cannot combine single letter options; -abc != -a -b -c
 *
 * @return Returns the option string, or null if there are no more options.
 */
String Monkey::NextOption()
{
    if (mNextArg >= mArgs->GetLength()) {
        return String();
    }
    String arg = (*mArgs)[mNextArg];
    if (!arg.StartWith("-")) {
        return String();
    }
    mNextArg++;
    if (arg.Equals("--")) {
        return String();
    }
    if (arg.GetLength() > 1 && arg.GetChar(1) != '-') {
        if (arg.GetLength() > 2) {
            mCurArgData = arg.Substring(2);
            return arg.Substring(0, 2);
        }
        else {
            mCurArgData = String();
            return arg;
        }
    }
    mCurArgData = String();
    return arg;
}
Example #2
0
ECode CExifInterface::GetAttributeDouble(
    /* [in] */ const String& tag,
    /* [in] */ Double defaultValue,
    /* [out] */ Double* result)
{
    VALIDATE_NOT_NULL(result);
    *result = defaultValue;

    HashMap<String, String>::Iterator it = mAttributes.Find(tag);
    if (it != mAttributes.End()) {
        String value = it->mSecond;
        if (value.IsNull()) {
            return NOERROR;
        }

        Int32 index = value.IndexOf("/");
        if (index == -1) {
            return NOERROR;
        }
        Double denom = StringUtils::ParseDouble(value.Substring(index + 1));
        if (denom == 0) {
            return NOERROR;
        }
        Double num = StringUtils::ParseDouble(value.Substring(0, index));
        *result = num / denom;
    }
    return NOERROR;
}
Example #3
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 #4
0
void Win32AllocateStdioConsole(const char * optArg)
{
   const String optOutFile = optArg;

   const char * conInStr  = optOutFile.HasChars() ? NULL         : "conin$";
   const char * conOutStr = optOutFile.HasChars() ? optOutFile() : "conout$";
   if (optOutFile.IsEmpty()) AllocConsole();  // no sense creating a DOS window if we're only outputting to a file anyway

   // Hopefully-temporary work-around for Windows not wanting to send stdout and stderr to the same file
   String conErrHolder;  // don't move this!  It needs to stay here
   const char * conErrStr = NULL;
   if (optOutFile.HasChars())
   {
      const int lastDotIdx = optOutFile.LastIndexOf('.');

      if (lastDotIdx > 0)
         conErrHolder = optOutFile.Substring(0, lastDotIdx) + "_stderr" + optOutFile.Substring(lastDotIdx);
      else
         conErrHolder = optOutFile + "_stderr.txt";

      conErrStr = conErrHolder();
   }
   else conErrStr = conOutStr;  // for the output-to-console-window case, where redirecting both stdout and stderr DOES work

# if __STDC_WANT_SECURE_LIB__
   FILE * junk;
   if (conInStr)  (void) freopen_s(&junk, conInStr,  "r", stdin);
   if (conOutStr) (void) freopen_s(&junk, conOutStr, "w", stdout);
   if (conErrStr) (void) freopen_s(&junk, conErrStr, "w", stderr);
# else
   if (conInStr)  (void) freopen(conInStr,  "r", stdin);
   if (conOutStr) (void) freopen(conOutStr, "w", stdout);
   if (conErrStr) (void) freopen(conErrStr, "w", stderr);
# endif
}
Example #5
0
void RemoveANSISequences(String & s)
{
   TCHECKPOINT;

   static const char _escapeBuf[] = {0x1B, '[', '\0'};
   static String _escape; if (_escape.IsEmpty()) _escape = _escapeBuf;

   while(true)
   {
      const int32 idx = s.IndexOf(_escape);  // find the next escape sequence
      if (idx >= 0)
      {
         const char * data = s()+idx+2;  // move past the ESC char and the [ char
         switch(data[0])
         {
            case 's': case 'u': case 'K':   // these are single-letter codes, so
               data++;                      // just skip over them and we are done
            break;

            case '=':
               data++;
            // fall through!
            default:
               // For numeric codes, keep going until we find a non-digit that isn't a semicolon
               while((muscleInRange(*data, '0', '9'))||(*data == ';')) data++;
               if (*data) data++;  // and skip over the trailing letter too.
            break;
         }
         s = s.Substring(0, idx) + s.Substring((uint32)(data-s()));  // remove the escape substring
      }
      else break;
   }
}
Example #6
0
void SplitPath(const String& fullPath, String& pathName, String& fileName, String& extension, bool lowercaseExtension)
{
    String fullPathCopy = GetInternalPath(fullPath);

    unsigned extPos = fullPathCopy.FindLast('.');
    unsigned pathPos = fullPathCopy.FindLast('/');

    if (extPos != String::NPOS && (pathPos == String::NPOS || extPos > pathPos))
    {
        extension = fullPathCopy.Substring(extPos);
        if (lowercaseExtension)
            extension = extension.ToLower();
        fullPathCopy = fullPathCopy.Substring(0, extPos);
    }
    else
        extension.Clear();

    pathPos = fullPathCopy.FindLast('/');
    if (pathPos != String::NPOS)
    {
        fileName = fullPathCopy.Substring(pathPos + 1);
        pathName = fullPathCopy.Substring(0, pathPos + 1);
    }
    else
    {
        fileName = fullPathCopy;
        pathName.Clear();
    }
}
Example #7
0
static String TranslateHTMLBreakTags( const String& s )
{
   String r;
   for ( size_type p0 = 0; ; )
   {
      size_type p = s.FindIC( "<br", p0 );
      if ( p == String::notFound )
      {
         r.Append( s.Substring( p0 ) );
         break;
      }

      if ( p != p0 )
         r.Append( s.Substring( p0, p-p0 ) );

      r.Append( '\n' );

      size_type p1 = s.Find( '>', p+1 );
      if ( p1 == String::notFound )
         break;
      p0 = p1 + 1;
   }

   return r;
}
ECode CHttpAuthHeader::ParseScheme(
    /* [in] */ const String& header,
    /* [out] */ String* scheme)
{
    if (header != NULL) {
        Int32 i = header.IndexOf(' ');
        if (i >= 0) {
            String localScheme = header.Substring(0, i).Trim();
            if (localScheme.EqualsIgnoreCase(DIGEST_TOKEN)) {
                mScheme = DIGEST;

                // md5 is the default algorithm!!!
                mAlgorithm = String("md5");
            } else {
                if (localScheme.EqualsIgnoreCase(BASIC_TOKEN)) {
                    mScheme = BASIC;
                }
            }

            *scheme = header.Substring(i + 1);
        }
    }

    *scheme = String(NULL);
    return NOERROR;
}
Example #9
0
// Joins the path of an RML or RCSS file with the path of a resource specified within the file.
void SystemInterface::JoinPath(String& translated_path, const String& document_path, const String& path)
{
	// If the path is absolute, strip the leading / and return it.
	if (path.Substring(0, 1) == "/")
	{
		translated_path = path.Substring(1);
		return;
	}

	// If the path is a Windows-style absolute path, return it directly.
	size_t drive_pos = path.Find(":");
	size_t slash_pos = Math::Min(path.Find("/"), path.Find("\\"));
	if (drive_pos != String::npos &&
		drive_pos < slash_pos)
	{
		translated_path = path;
		return;
	}

	// Strip off the referencing document name.
	translated_path = document_path;
	translated_path = translated_path.Replace("\\", "/");
	size_t file_start = translated_path.RFind("/");
	if (file_start != String::npos)
		translated_path.Resize(file_start + 1);
	else
		translated_path.Clear();

	// Append the paths and send through URL to removing any '..'.
	URL url(translated_path.Replace(":", "|") + path.Replace("\\", "/"));
	translated_path = url.GetPathedFileName().Replace("|", ":");
}
Example #10
0
String URLUtil::ComposeSearchUrl(
    /* [in] */ const String& inQuery,
    /* [in] */ const String& templateStr,
    /* [in] */ const String& queryPlaceHolder)
{
    Int32 placeHolderIndex = templateStr.IndexOf(queryPlaceHolder);
    if (placeHolderIndex < 0) {
        return String(NULL);
    }

    String query;
    StringBuilder buffer;
    buffer.AppendString(templateStr.Substring(0, placeHolderIndex));

    //try {
    //    query = java.net.URLEncoder.encode(inQuery, "utf-8");
    AutoPtr<IURLEncoder> URLEncoder;
    assert(0);
//    	CURLEncoder::New((IURLEncoder**)&URLEncoder);
    if (FAILED(URLEncoder->Encode(inQuery, String("utf-8"), &query))){
        return String(NULL);
    }
    buffer.AppendString(query);
    //} catch (UnsupportedEncodingException ex) {
    //    return null;
    //}

    buffer.AppendString(templateStr.Substring(
            placeHolderIndex + queryPlaceHolder.GetLength()));

    return buffer.ToString();
}
Example #11
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 #12
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;
}
ECode CHttpAuthHeader::ParseParameter(
    /* [in] */ const String& parameter)
{
    if (parameter != NULL) {
        // here, we are looking for the 1st occurence of '=' only!!!
        Int32 i = parameter.IndexOf('=');
        if (i >= 0) {
            String token = parameter.Substring(0, i).Trim();
            String value =
                TrimDoubleQuotesIfAny(parameter.Substring(i + 1).Trim());

            if (HttpLog::LOGV) {
                HttpLog::V(String("HttpAuthHeader.parseParameter(): token: ") + token
                    + String(" value: ") + value);
            }

            if (token.EqualsIgnoreCase(REALM_TOKEN)) {
                mRealm = value;
            } else {
                if (mScheme == DIGEST) {
                    ParseParameter(token, value);
                }
            }
        }
    }
    return NOERROR;
}
Example #15
0
ECode CQName::ValueOf(
    /* [in] */ String qNameAsString,
    /* [out] */  IQName** qName)
{
    // null is not valid
    if (qNameAsString == NULL) {
        // throw new IllegalArgumentException("cannot create QName from \"null\" or \"\" String");
        return E_ILLEGAL_ARGUMENT_EXCEPTION;
    }

    // "" local part is valid to preserve compatible behavior with QName 1.0
    if (qNameAsString.GetLength() == 0) {
        return CQName::New(
            IXMLConstants::NULL_NS_URI,
            qNameAsString,
            IXMLConstants::DEFAULT_NS_PREFIX,
            qName);
    }

    // local part only?
    if (qNameAsString.GetChar(0) != '{') {
        return CQName::New(
            IXMLConstants::NULL_NS_URI,
            qNameAsString,
            IXMLConstants::DEFAULT_NS_PREFIX,
            qName);
    }

    // Namespace URI improperly specified?
    if (qNameAsString.StartWith(String("{") + IXMLConstants::NULL_NS_URI + "}")) {
        // throw new IllegalArgumentException(
        //     "Namespace URI .equals(XMLConstants.NULL_NS_URI), "
        //     + ".equals(\"" + XMLConstants.NULL_NS_URI + "\"), "
        //     + "only the local part, "
        //     + "\"" + qNameAsString.substring(2 + XMLConstants.NULL_NS_URI.length()) + "\", "
        //     + "should be provided.");
        return E_ILLEGAL_ARGUMENT_EXCEPTION;
    }

    // Namespace URI and local part specified
    Int32 endOfNamespaceURI = qNameAsString.IndexOf('}');
    if (endOfNamespaceURI == -1) {
        return E_ILLEGAL_ARGUMENT_EXCEPTION;
        // throw new IllegalArgumentException(
        //     "cannot create QName from \""
        //         + qNameAsString
        //         + "\", missing closing \"}\"");
    }
    return CQName::New(
        qNameAsString.Substring(1, endOfNamespaceURI),
        qNameAsString.Substring(endOfNamespaceURI + 1),
        IXMLConstants::DEFAULT_NS_PREFIX,
        qName);
}
Example #16
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(" ");
}
/**
 * Convert a 32 char hex string into a Inet6Address.
 * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
 * made into an Inet6Address
 * @param addrHexString a 32 character hex string representing an IPv6 addr
 * @return addr an InetAddress representation for the string
 */
ECode NetworkUtils::HexToInet6Address(
    /* [in] */ const String& addrHexString,
    /* [out] */ IInetAddress** result)
{
    VALIDATE_NOT_NULL(result);
//    try {
    StringBuilder builder(addrHexString.Substring(0,4));
    builder += String(":");
    builder += addrHexString.Substring(4,8);
    builder += String(":");
    builder += addrHexString.Substring(8,12);
    builder += String(":");
    builder += addrHexString.Substring(12,16);
    builder += String(":");
    builder += addrHexString.Substring(16,20);
    builder += String(":");
    builder += addrHexString.Substring(20,24);
    builder += String(":");
    builder += addrHexString.Substring(24,28);
    builder += String(":");
    builder += addrHexString.Substring(28,32);
    AutoPtr<IInetAddress> inetaddress;
    NumericToInetAddress(builder.ToString(), (IInetAddress**)&inetaddress);

 //   }
//    catch (Exception e) {
//        Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
//        throw new IllegalArgumentException(e);
//    }
    *result = inetaddress;
    REFCOUNT_ADD(*result);
    return NOERROR;
}
//-------------------------------------------------------------------------------------
String OptionMenuItem::PopNamespaceFrom(OptionMenuItem* menuItem)
{
    String label = menuItem->Label;
    for (UInt32 i = 0; i < label.GetLength(); i++)
    {
        if (label.GetCharAt(i) == '.')
        {
            String ns = label.Substring(0, i);
            menuItem->Label = label.Substring(i + 1, label.GetLength());
            return ns;
        }
    }
    return "";
}
Example #19
0
String GetHumanReadableProgramNameFromArgv0(const char * argv0)
{
   String ret = argv0;

#ifdef __APPLE__
   ret = ret.Substring(0, ".app/");  // we want the user-visible name, not the internal name!
#endif

#ifdef __WIN32__
   ret = ret.Substring("\\").Substring(0, ".exe");
#else
   ret = ret.Substring("/");
#endif
   return ret;
}
Example #20
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 #21
0
String PropertyUtils::getElement( String keyString )
{
   size_t startpos1 = keyString.Find( '/', 1 );
   size_t startpos2 = keyString.Find( '/', startpos1+1 );
   size_t endpos    = keyString.Find( '/', startpos2+1 );
   return keyString.Substring( startpos2+1, endpos-startpos2 );
}
AssetStoragePtr HttpAssetProvider::TryCreateStorage(HashMap<String, String> &storageParams, bool fromNetwork)
{
    if (!storageParams.Contains("src") || !IsValidRef(storageParams["src"], ""))
        return AssetStoragePtr();
    if (storageParams.Contains("type") && storageParams["type"].Compare("HttpAssetStorage", false) != 0)
        return AssetStoragePtr();

    String baseUrl = storageParams["src"];
    if (!baseUrl.EndsWith("/") && baseUrl.Contains("/"))
        baseUrl = baseUrl.Substring(0, baseUrl.FindLast('/')+1);
    if (!baseUrl.EndsWith("/"))
        return AssetStoragePtr();

    String name = UniqueName(storageParams["name"]);

    // @todo liveupdate, liveupload, autodiscoverable etc. when actually needed
    AssetStoragePtr storage = StorageForBaseURL(baseUrl);
    if (!storage)
    {
        storage = AssetStoragePtr(new HttpAssetStorage(framework_->GetContext(), name, baseUrl, storageParams["localdir"]));
        httpStorages_.Push(storage);
    }

    storage->SetReplicated(Urho3D::ToBool(storageParams["replicated"]));
    return storage;
}
Example #23
0
Value FlagExpr::Evaluate(SymbolTable* scope, EvalContext& context, bool asbool)
{
	// When evaluating as a boolean, we want to use the "load flag" command, 07.
	// This is so an expression "flag <x>" can be used in normal expressions as
	// a flag number (e.g., set(myflag)) and in boolean conditions (e.g.,
	//  if myflag { }). Just sugar, really.
	// Thus, if statements and "and", "or", "not" expressions pass asbool=true.
	// All other nodes ignore this parameter, using the default value of false.
	//
	// Honestly, this feels like a hack, and it comes at the cost of some possibly
	// unintuitive behavior. However, it seems useful to allow the use of flags
	// in conditionals this way... Maybe there's a better alternative.

	String* value = new String();

	if(asbool) value->Code("07");

	Value flagval = expr->Evaluate(scope, context, false);

	String flagstr = flagval.ToCodeString();

	value->Append(flagstr.Substring(0,2));

	return Value(value);
}
Example #24
0
bool FileSystem::FileExists(const String& fileName) const
{
    if (!CheckAccess(GetPath(fileName)))
        return false;

    String fixedName = GetNativePath(RemoveTrailingSlash(fileName));

    #ifdef ANDROID
    if (fixedName.StartsWith("/apk/"))
    {
        SDL_RWops* rwOps = SDL_RWFromFile(fileName.Substring(5).CString(), "rb");
        if (rwOps)
        {
            SDL_RWclose(rwOps);
            return true;
        }
        else
            return false;
    }
    #endif

    #ifdef WIN32
    DWORD attributes = GetFileAttributesW(WString(fixedName).CString());
    if (attributes == INVALID_FILE_ATTRIBUTES || attributes & FILE_ATTRIBUTE_DIRECTORY)
        return false;
    #else
    struct stat st;
    if (stat(fixedName.CString(), &st) || st.st_mode & S_IFDIR)
        return false;
    #endif

    return true;
}
void GyroTempCalibration::TokenizeString(Array<String>* tokens, const String& str, char separator)
{
//	OVR_ASSERT(tokens != NULL);	// LDC - Asserts are currently not handled well on mobile.

	tokens->Clear();

	int tokenStart = 0;
	bool foundToken = false;
	
	for (int i=0; i <= str.GetLengthI(); i++)
	{
		if (i == str.GetLengthI() || str.GetCharAt(i) == separator)
		{
			if (foundToken)
			{
				// Found end of token.
				String token = str.Substring(tokenStart, i);
				tokens->PushBack(token);
				foundToken = false;
			}
		}
		else if (!foundToken)
		{
			foundToken = true;
			tokenStart = i;
		}
	}
}
Example #26
0
String URL::UrlDecode(const String &value)
{
	String decoded;

	decoded.Clear();

	const char *value_c = value.CString();
	String::size_type value_len = value.Length();
	for (String::size_type i = 0; i < value_len; i++) 
	{
		char c = value_c[i];
		if (c == '+')
		{
			decoded.Append(' ' );
		}
		else if (c == '%')
		{
			char *endp;
			String t = value.Substring(i+1, 2);
			int ch = strtol(t.CString(), &endp, 16);
			if (*endp == '\0')
				decoded.Append(char(ch));
			else
				decoded.Append(t);
			i += 2;
		}
		else
		{
			decoded.Append(c);
		}
	}

	return decoded;
}
Example #27
0
ECode CVideoPlayer::OnCreate(
    /* [in] */ IBundle* savedInstanceState)
{
    Activity::OnCreate(savedInstanceState);
    SetContentView(2130903046);//R.layout.videoplayer
    mVideoView = IVideoView::Probe(FindViewById(0x7f07000a));//R::Id::VideoView
    AutoPtr<IMediaController> mediaController;
//    FAIL_RETURN(CMediaController::New(this, (IMediaController**)&mediaController));
    mediaController->SetAnchorView(mVideoView);
    AutoPtr<IIntent> intent;
    FAIL_RETURN(GetIntent((IIntent**)&intent));
    AutoPtr<IUri> data;
    intent->GetData((IUri**)&data);
    if (data == NULL)
        return NOERROR;
    String spec;
    String scheme;
    data->GetScheme(&scheme) ;
    if (String("vnd.youtube").Equals(scheme)) {
        String ssp;
        data->GetSchemeSpecificPart(&ssp);
        String id = ssp.Substring(0, ssp.IndexOf('?'));
        FAIL_RETURN(GetSpecFromYouTubeVideoID(id, &spec));
    }
    if (spec == NULL)
        return NOERROR;
    AutoPtr<IUri> video;
//    FAIL_RETURN(Uri::Parse(spec, (IUri**)&video));
    FAIL_RETURN(mVideoView->SetMediaController(mediaController));
    FAIL_RETURN(mVideoView->SetVideoURI(video));
    FAIL_RETURN(IMediaPlayerControl::Probe(mVideoView)->Start());

    return NOERROR;
}
Example #28
0
AutoPtr<IClassInfo> Utils::GetClassInfo(
    /* [in] */ const String& className,
    /* [in] */ Int32 flag)
{
    if (flag == ELASTOS_DROID_CORE_ECO_FALG) {
        AutoPtr<IModuleInfo> m;
        ASSERT_SUCCEEDED(CReflector::AcquireModuleInfo(String("Elastos.Droid.Core.eco"), (IModuleInfo**)&m));
        AutoPtr<IClassInfo> classInfo;
        m->GetClassInfo(className, (IClassInfo**)&classInfo);
        assert(classInfo != NULL);
        return classInfo;
    }

    if (sModuleInfo == NULL) {
        ASSERT_SUCCEEDED(CReflector::AcquireModuleInfo(sModulePath, (IModuleInfo**)&sModuleInfo));
        assert(sModuleInfo != NULL);
    }

    String name = String("C") + className.Substring(className.LastIndexOf('.'));
    Logger::D(TAG, "the class name is [%s]", name.string());
    AutoPtr<IClassInfo> classInfo;
    sModuleInfo->GetClassInfo(className, (IClassInfo**)&classInfo);
    assert(classInfo != NULL);
    return classInfo;
}
Example #29
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;
			}
		}
	}
}
ECode WifiP2pServiceResponse::HexStr2Bin(
    /* [in] */ const String& hex,
    /* [out] */ ArrayOf<Byte>** array)
{
    VALIDATE_NOT_NULL(array);
    *array = NULL;

    Int32 sz = hex.GetLength() / 2;
    AutoPtr<ArrayOf<Byte> > b = ArrayOf<Byte>::Alloc(sz);
    if (b == NULL) return E_OUT_OF_MEMORY;

    String subStr;
    Int32 value;
    ECode ec = NOERROR;
    for (Int32 i = 0; i < sz; i++) {
        subStr = hex.Substring(i * 2, i * 2 + 2);
        ec = StringUtils::ParseInt32(subStr, 16, &value);
        if (FAILED(ec)) {
            Slogger::E("WifiP2pServiceResponse", "HexStr2Bin: failed to ParseInt32 %s", hex.string());
            return ec;
        }

        (*b)[i] = (Byte)value;
    }

    *array = b;
    REFCOUNT_ADD(*array);
    return NOERROR;
}