void SubInfoRecordUpdater::Logd(
    /* [in] */ const String& message)
{
    Logger::E("SubInfoRecordUpdater", "[SubInfoRecordUpdater]:%s\n", message.string());
}
Example #2
0
ECode CNotificationGroup::FromXml(
    /* [in] */ IXmlPullParser* xpp,
    /* [in] */ IContext* context,
    /* [out] */ INotificationGroup** group)
{
    VALIDATE_NOT_NULL(group);

    String value;
    xpp->GetAttributeValue(String(NULL), String("nameres"), &value);

    Int32 nameResId = -1;
    String name;
    AutoPtr<IUUID> uuid;

    if (!value.IsNull()) {
        AutoPtr<IResources> res;
        context->GetResources((IResources**)&res);
        res->GetIdentifier(value, String("string"), String("android"), &nameResId);
        if (nameResId > 0) {
            res->GetString(nameResId, &name);
        }
    }

    if (name.IsNull()) {
        xpp->GetAttributeValue(String(NULL), String("name"), &name);
    }

    xpp->GetAttributeValue(String(NULL), String("uuid"), &value);
    if (!value.IsNull()) {
        // try {
        AutoPtr<IUUIDHelper> helper;
        CUUIDHelper::AcquireSingleton((IUUIDHelper**)&helper);
        ECode ec = helper->FromString(value, (IUUID**)&uuid);
        if (FAILED(ec)) {
            Logger::W(TAG, "UUID not recognized for %s, using new one.", name.string());
        }
        // } catch (IllegalArgumentException e) {
        //     Log.w(TAG, "UUID not recognized for " + name + ", using new one.");
        // }
    }

    AutoPtr<CNotificationGroup> notificationGroup;
    CNotificationGroup::NewByFriend(name, nameResId, uuid, (CNotificationGroup**)&notificationGroup);
    Int32 event;
    xpp->Next(&event);
    while (event != IXmlPullParser::END_TAG || (xpp->GetName(&name), !name.Equals("notificationGroup"))) {
        if (event == IXmlPullParser::START_TAG) {
            if (xpp->GetName(&name), name.Equals("package")) {
                String pkg;
                xpp->NextText(&pkg);
                notificationGroup->AddPackage(pkg);
            }
        }
        xpp->Next(&event);
    }

    /* we just loaded from XML, no need to save */
    notificationGroup->mDirty = FALSE;

    *group = (INotificationGroup*)notificationGroup.Get();
    REFCOUNT_ADD(*group);
    return NOERROR;
}
Example #3
0
boolean UniqueString::operator ==(const String& s) const {
    return string() == s.string() && length() == s.length();
}
Example #4
0
void testStringBuilder()
{
    printf("\n- - - - testStringBuilder- - - \n");
    StringBuilder str("和路由器一样,Binder驱动虽然默默无闻,却是通信的核心。");
    Int32 charCount = str.GetLength();
    Int32 end = charCount;
    Int32 start = 0;
    String subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    end = charCount - 1;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    end = charCount - 2;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    end = charCount;
    start = 6;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 7;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 8;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 9;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 12;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 13;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 14;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 14;
    end = charCount - 1;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 14;
    end = charCount - 2;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    end = charCount - 15;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    end = charCount - 16;
    subStr = str.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
}
Example #5
0
/**
 * Using the restrictions provided (categories & packages), generate a list
 * of activities that we can actually switch to.
 *
 * @return Returns TRUE if it could successfully build a list of target
 *         activities
 */
Boolean Monkey::GetMainApps()
{
    AutoPtr<IUserHandleHelper> helper;
    CUserHandleHelper::AcquireSingleton((IUserHandleHelper**)&helper);
    Int32 myUserId;
    helper->GetMyUserId(&myUserId);

    List<String>::Iterator it = mMainCategories->Begin();
    const Int32 N = mMainCategories->GetSize();
    for (; it != mMainCategories->End(); ++it) {
        String category = *it;
        AutoPtr<IIntent> intent;
        CIntent::New(IIntent::ACTION_MAIN, (IIntent**)&intent);
        if (!category.IsNullOrEmpty()) {
            intent->AddCategory(category);
        }

        AutoPtr<IObjectContainer> mainApps;
        mPm->QueryIntentActivities(intent, String(), 0, myUserId, (IObjectContainer**)&mainApps);
        Int32 count;
        if (!mainApps || (mainApps->GetObjectCount(&count), count == 0)) {
            PFL_EX("// Warning: no activities found for category %s", category.string());
            continue;
        }
        if (mVerbose >= 2) { // very verbose
            PFL_EX("// Selecting main activities from category %s", category.string());
        }

        AutoPtr<IObjectEnumerator> enumerator;
        mainApps->GetObjectEnumerator((IObjectEnumerator**)&enumerator);
        Boolean hasNext = FALSE;
        while (enumerator->MoveNext(&hasNext), hasNext) {
            AutoPtr<IInterface> element;
            enumerator->Current((IInterface**)&element);
            AutoPtr<IResolveInfo> r = IResolveInfo::Probe(element);
            String packageName;
            AutoPtr<IActivityInfo> act;
            r->GetActivityInfo((IActivityInfo**)&act);
            AutoPtr<IApplicationInfo> appInfo;
            act->GetApplicationInfo((IApplicationInfo**)&appInfo);
            appInfo->GetPackageName(&packageName);
            String actName;
            act->GetName(&actName);

            if (CheckEnteringPackage(packageName)) {
                if (mVerbose >= 2) { // very verbose
                    PFL_EX("//   + Using main activity %s (from package %s)", actName.string(), packageName.string());
                }
                AutoPtr<IComponentName> ele;
                CComponentName::New(packageName, actName, (IComponentName**)&ele);
                mMainApps->PushBack(ele);
            }
            else {
                if (mVerbose >= 3) { // very very verbose
                    PFL_EX("//   - NOT USING main activity %s (from package %s)",
                            actName.string(), packageName.string());
                }
            }
        } //end while
    }

    if (mMainApps->IsEmpty()) {
        PFL_EX("** No activities found to run, monkey aborted.");
        return FALSE;
    }

    return TRUE;
}
void RegisteredServicesCache::GenerateServicesMap(
    /* [in] */ Int32 userId)
{
    Slogger::D(TAG, "generateServicesMap() for %d", userId);

    AutoPtr<IPackageManager> pm;
    mContext->GetPackageManager((IPackageManager**)&pm);
    List<AutoPtr<IRegisteredServicesCacheServiceInfo> > serviceInfos;
    AutoPtr<IList> resolveInfos;
    AutoPtr<IIntent> intent;
    CIntent::New(mInterfaceName, (IIntent**)&intent);
    ASSERT_SUCCEEDED(pm->QueryIntentServicesAsUser(intent, IPackageManager::GET_META_DATA, userId,
            (IList**)&resolveInfos));
    AutoPtr<IIterator> it;
    resolveInfos->GetIterator((IIterator**)&it);
    Boolean hasNext;
    while (it->HasNext(&hasNext), hasNext) {
        AutoPtr<IInterface> current;
        it->GetNext((IInterface**)&current);
        AutoPtr<IResolveInfo> resolveInfo = IResolveInfo::Probe(current);
        // try {
        AutoPtr<IRegisteredServicesCacheServiceInfo> info;
        ECode ec = ParseServiceInfo(resolveInfo, (IRegisteredServicesCacheServiceInfo**)&info);
        if (FAILED(ec)) {
            String s;
            resolveInfo->ToString(&s);
            Slogger::W(TAG, "Unable to load service info %s ec = 0x%08x", s.string(), ec);
            continue;
        }
        serviceInfos.PushBack(info);
        // } catch (XmlPullParserException e) {
        //     Log.w(TAG, "Unable to load service info " + resolveInfo.toString(), e);
        // } catch (IOException e) {
        //     Log.w(TAG, "Unable to load service info " + resolveInfo.toString(), e);
        // }
    }

    AutoLock lock(mServicesLock);

    AutoPtr<UserServices> user = FindOrCreateUserLocked(userId);
    Boolean firstScan = user->mServices == NULL;
    if (firstScan) {
        user->mServices = new HashMap<AutoPtr<IInterface>, AutoPtr<IRegisteredServicesCacheServiceInfo> >();
    }
    else {
        user->mServices->Clear();
    }

    StringBuilder changes;
    Boolean changed = FALSE;
    ServiceInfo* info;
    List<AutoPtr<IRegisteredServicesCacheServiceInfo> >::Iterator itr = serviceInfos.Begin();
    for (Int32 i = 0; itr != serviceInfos.End(); ++itr, ++i) {
        info = (ServiceInfo*)(*itr).Get();
        // four cases:
        // - doesn't exist yet
        //   - add, notify user that it was added
        // - exists and the UID is the same
        //   - replace, don't notify user
        // - exists, the UID is different, and the new one is not a system package
        //   - ignore
        // - exists, the UID is different, and the new one is a system package
        //   - add, notify user that it was added
        AutoPtr<IInteger32> previousUid;
        HashMap<AutoPtr<IInterface>, AutoPtr<IInteger32> >::Iterator it = user->mPersistentServices.Find(info->mType);
        if (it != user->mPersistentServices.End()) {
            previousUid = it->mSecond;
        }
        if (previousUid == NULL) {
            if (Logger::IsLoggable(TAG, Logger::VERBOSE)) {
                changes += "  New service added: ";
                changes += Object::ToString(info);
                changes += "\n";
            }

            changed = TRUE;
            (*user->mServices)[info->mType] = info;
            AutoPtr<IInteger32> iuid;
            CInteger32::New(info->mUid, (IInteger32**)&iuid);
            (user->mPersistentServices)[info->mType] = iuid;
            if (!(mPersistentServicesFileDidNotExist && firstScan)) {
                NotifyListener(info->mType, userId, FALSE /* removed */);
            }
        }
        else {
            Int32 pUid;
            previousUid->GetValue(&pUid);
            if (pUid == info->mUid) {
                if (Logger::IsLoggable(TAG, Logger::VERBOSE)) {
                    changes += "  Existing service (nop): ";
                    changes += Object::ToString(info);
                    changes += "\n";
                }
                (*user->mServices)[info->mType] = info;
            }
            else if (InSystemImage(info->mUid)
                    || !ContainsTypeAndUid(&serviceInfos, info->mType, pUid)) {
                if (InSystemImage(info->mUid)) {
                    if (Logger::IsLoggable(TAG, Logger::VERBOSE)) {
                        changes += ("  System service replacing existing: ");
                        changes += Object::ToString(info);
                        changes += ("\n");
                    }
                }
                else {
                    if (Logger::IsLoggable(TAG, Logger::VERBOSE)) {
                        changes += ("  Existing service replacing a removed service: ");
                        changes += Object::ToString(info);
                        changes += ("\n");
                    }
                }
                (*user->mServices)[info->mType] = info;
                AutoPtr<IInteger32> iuid;
                CInteger32::New(info->mUid, (IInteger32**)&iuid);
                (user->mPersistentServices)[info->mType] = iuid;
                NotifyListener(info->mType, userId, FALSE /* removed */);
            }
            else {
                if (Logger::IsLoggable(TAG, Logger::VERBOSE)) {
                    // ignore
                    changes += ("  Existing service with new uid ignored: ");
                    changes += Object::ToString(info);
                    changes += ("\n");
                }
            }
        }
    }

    List<AutoPtr<IInterface> > toBeRemoved;
    HashMap<AutoPtr<IInterface>, AutoPtr<IInteger32> >::Iterator item = user->mPersistentServices.Begin();
    for (; item != user->mPersistentServices.End(); ++item) {
        AutoPtr<IInterface> v1 = item->mFirst;
        if (!ContainsType(&serviceInfos, v1)) {
            toBeRemoved.PushBack(v1);
        }
    }
    List<AutoPtr<IInterface> >::Iterator toBeRemItr = toBeRemoved.Begin();
    for (; toBeRemItr != toBeRemoved.End(); ++toBeRemItr) {
        AutoPtr<IInterface> v1 = *toBeRemItr;
        user->mPersistentServices.Erase(v1);
        NotifyListener(v1, userId, TRUE /* removed */);
        changed = TRUE;

        if (Logger::IsLoggable(TAG, Logger::VERBOSE)) {
            changes += ("  Service removed: ");
            changes += Object::ToString(v1);
            changes += ("\n");
        }
    }

    if (Logger::IsLoggable(TAG, Logger::VERBOSE)) {
        if (changes.GetLength() > 0) {
            Logger::D(TAG, "generateServicesMap(%s): %d services:%s\n",
                    mInterfaceName.string(), serviceInfos.GetSize(), changes.ToString().string());
        }
        else {
            Logger::D(TAG, "generateServicesMap(%s): %d services unchanged",
                    mInterfaceName.string(), serviceInfos.GetSize());
        }
    }

    if (changed) {
        WritePersistentServicesLocked();
    }
}
Example #7
0
void assertEquals(const String& aspect, const String& test)
{
    printf("aspect: [%s], test: [%s]\n", aspect.string(), test.string());
    assert(aspect.Equals(test));
}
ECode CLocaleBuilder::SetExtension(
    /* [in] */ Char32 key,
    /* [in] */ const String& value)
{
    AutoPtr<IChar32> keyObj;
    CChar32::New(key, (IChar32**)&keyObj);
    if (value.IsNullOrEmpty()) {
        mExtensions->Remove(keyObj->Probe(EIID_IInterface));
        return NOERROR;
    }

    String normalizedValue = value.ToLowerCase();//ToLowerCase(Locale.ROOT)
    normalizedValue = normalizedValue.Replace('_', '-');
    AutoPtr<ArrayOf<String> > subtags;
    StringUtils::Split(normalizedValue, String("-"), (ArrayOf<String>**)&subtags);

    // Lengths for subtags in the private use extension should be [1, 8] chars.
    // For all other extensions, they should be [2, 8] chars.
    //
    // http://www.rfc-editor.org/rfc/bcp/bcp47.txt
    Int32 minimumLength = (key == ILocale::PRIVATE_USE_EXTENSION) ? 1 : 2;
    for (Int32 i = 0; i < subtags->GetLength(); ++i) {
        String subtag = (*subtags)[i];
        if (!CLocale::IsValidBcp47Alphanum(subtag, minimumLength, 8)) {
            ALOGE("CLocaleBuilder::SetExtension: IllformedLocaleException, Invalid private use extension : %s", value.string());
            return E_ILLFORMED_LOCALE_EXCEPTION;
        }
    }

    // We need to take special action in the case of unicode extensions,
    // since we claim to understand their keywords and mAttributes->
    if (key == ILocale::UNICODE_LOCALE_EXTENSION) {
        // First clear existing attributes and mKeywords->
        mExtensions->Clear();
        mAttributes->Clear();

        CLocale::ParseUnicodeExtension(subtags, mKeywords, mAttributes);
    }
    else {
        AutoPtr<ICharSequence> csq;
        CString::New(normalizedValue, (ICharSequence**)&csq);
        mExtensions->Put(keyObj, TO_IINTERFACE(csq));
    }
    return NOERROR;
}
ECode CLocaleBuilder::SetUnicodeLocaleKeyword(
    /* [in] */ const String& key,
    /* [in] */ const String& type)
{
    if (key.IsNull()) {
        return E_NULL_POINTER_EXCEPTION;
    }

    if (type.IsNull() && mKeywords != NULL) {
        AutoPtr<ICharSequence> csq;
        CString::New(key, (ICharSequence**)&csq);
        mKeywords->Remove(TO_IINTERFACE(csq));
        return NOERROR;
    }

    String lowerCaseKey = key.ToLowerCase();//ToLowerCase(Locale.ROOT)
    // The key must be exactly two alphanumeric characters.
    if (lowerCaseKey.GetLength() != 2 || !CLocale::IsAsciiAlphaNum(lowerCaseKey)) {
        ALOGE("CLocaleBuilder::SetExtension: IllformedLocaleException, Invalid unicode locale keyword : %s", key.string());
        return E_ILLFORMED_LOCALE_EXCEPTION;
    }

    // The type can be one or more alphanumeric strings of length [3, 8] characters,
    // separated by a separator char, which is one of "_" or "-". Though the spec
    // doesn't require it, we normalize all "_" to "-" to make the rest of our
    // processing easier.
    String lowerCaseType = type.ToLowerCase();//ToLowerCase(Locale.ROOT)
    lowerCaseType = lowerCaseType.Replace('_', '-');
    if (!CLocale::IsValidTypeList(lowerCaseType)) {
        ALOGE("CLocaleBuilder::SetExtension: IllformedLocaleException, Invalid unicode locale type : %s", type.string());
        return E_ILLFORMED_LOCALE_EXCEPTION;
    }

    // Everything checks out fine, add the <key, type> mapping to the list.
    AutoPtr<ICharSequence> keycsq = CoreUtils::Convert(lowerCaseKey);
    AutoPtr<ICharSequence> typecsq = CoreUtils::Convert(lowerCaseType);
    mKeywords->Put(TO_IINTERFACE(keycsq), TO_IINTERFACE(typecsq));
    return NOERROR;
}
ECode CLocaleBuilder::AddUnicodeLocaleAttribute(
    /* [in] */ const String& attribute)
{
    if (attribute.IsNull()) {
        return E_NULL_POINTER_EXCEPTION;
    }

    String lowercaseAttribute = attribute.ToLowerCase();//toLowerCase(Locale.ROOT);
    if (!CLocale::IsValidBcp47Alphanum(lowercaseAttribute, 3, 8)) {
        ALOGE("CLocaleBuilder::AddUnicodeLocaleAttribute: IllformedLocaleException, Invalid attribute: %s", attribute.string());
        return E_ILLFORMED_LOCALE_EXCEPTION;
    }

    AutoPtr<ICharSequence> csq;
    CString::New(lowercaseAttribute, (ICharSequence**)&csq);
    return mAttributes->Add(csq->Probe(EIID_IInterface));
}
ECode CLocaleBuilder::RemoveUnicodeLocaleAttribute(
    /* [in] */ const String& attribute)
{
    if (attribute.IsNull()) {
        return E_NULL_POINTER_EXCEPTION;
    }

    // Weirdly, remove is specified to check whether the attribute
    // is valid, so we have to perform the full alphanumeric check here.
    String lowercaseAttribute = attribute.ToLowerCase();//toLowerCase(Locale.ROOT);
    if (!CLocale::IsValidBcp47Alphanum(lowercaseAttribute, 3, 8)) {
        ALOGE("CLocaleBuilder::RemoveUnicodeLocaleAttribute: IllformedLocaleException, Invalid attribute: %s", attribute.string());
        return E_ILLFORMED_LOCALE_EXCEPTION;
    }

    AutoPtr<ICharSequence> csq;
    CString::New(lowercaseAttribute, (ICharSequence**)&csq);
    return mAttributes->Remove(csq->Probe(EIID_IInterface));
}
ECode CLocaleBuilder::NormalizeAndValidateScript(
    /* [in] */ const String& script,
    /* [in] */ Boolean strict,
    /* [out] */ String* str)
{
    VALIDATE_NOT_NULL(str)
    *str = String("");
    if (script.IsNullOrEmpty()) {
        return NOERROR;
    }

    if (!CLocale::IsValidBcp47Alpha(script, 4, 4)) {
        if (strict) {
            ALOGE("CLocaleBuilder::NormalizeAndValidateScript: IllformedLocaleException, Invalid script: %s", script.string());
            return E_ILLFORMED_LOCALE_EXCEPTION;
        }
        else {
            return NOERROR;
        }
    }

    return CLocale::TitleCaseAsciiWord(script, str);
}
ECode CLocaleBuilder::NormalizeAndValidateVariant(
    /* [in] */ const String& variant,
    /* [out] */ String* str)
{
    VALIDATE_NOT_NULL(str)
    *str = String("");

    if (variant.IsNullOrEmpty()) {
        return NOERROR;
    }

    // Note that unlike extensions, we canonicalize to lower case alphabets
    // and underscores instead of hyphens.
    String normalizedVariant = variant.Replace('-', '_');
    AutoPtr<ArrayOf<String> > subTags;
    StringUtils::Split(normalizedVariant, String("_"), (ArrayOf<String>**)&subTags);

    for (Int32 i = 0; i < subTags->GetLength(); ++i) {
        if (!IsValidVariantSubtag((*subTags)[i])) {
            ALOGE("CLocaleBuilder::NormalizeAndValidateVariant: IllformedLocaleException, Invalid variant: %s", variant.string());
            return E_ILLFORMED_LOCALE_EXCEPTION;
        }
    }

    *str = normalizedVariant;
    return NOERROR;
}
ECode MyActivityController::Run()
{
    PrintMessageForState();

    mHost->GetAm()->SetActivityController(this);
    mState = STATE_NORMAL;

    AutoPtr<IInputStreamReader> converter;
    AutoPtr<IBufferedReader> in;

    AutoPtr<ISystem> system;
    Elastos::Core::CSystem::AcquireSingleton((ISystem**)&system);
    AutoPtr<IInputStream> systemIn;
    system->GetIn((IInputStream**)&systemIn);
    CInputStreamReader::New(systemIn, (IInputStreamReader**)&converter);
    CBufferedReader::New(converter, (IBufferedReader**)&in);
    String line;
    while (!(in->ReadLine(&line), line).IsNull()) {
        Boolean addNewline = TRUE;
        if (line.GetLength() <= 0) {
            addNewline = FALSE;
        }
        else if (line.Equals("q") || line.Equals("quit")) {
            ResumeController(RESULT_DEFAULT);
            break;
        }
        else if (mState == STATE_CRASHED) {
            if (line.Equals("c") || line.Equals("continue")) {
                ResumeController(RESULT_CRASH_DIALOG);
            }
            else if (line.Equals("k") || line.Equals("kill")) {
                ResumeController(RESULT_CRASH_KILL);
            }
            else {
                PFL_EX("Invalid command: %s", line.string());
            }
        }
        else if (mState == STATE_ANR) {
            if (line.Equals("c") || line.Equals("continue")) {
                ResumeController(RESULT_ANR_DIALOG);
            }
            else if (line.Equals("k") || line.Equals("kill")) {
                ResumeController(RESULT_ANR_KILL);
            }
            else if (line.Equals("w") || line.Equals("wait")) {
                ResumeController(RESULT_ANR_WAIT);
            }
            else {
                PFL_EX("Invalid command: %s", line.string());
            }
        }
        else if (mState == STATE_EARLY_ANR) {
            if (line.Equals("c") || line.Equals("continue")) {
                ResumeController(RESULT_EARLY_ANR_CONTINUE);
            }
            else if (line.Equals("k") || line.Equals("kill")) {
                ResumeController(RESULT_EARLY_ANR_KILL);
            }
            else {
                PFL_EX("Invalid command: %s", line.string());
            }
        }
        else {
            PFL_EX("Invalid command: %s", line.string());
        }

        AutoLock lock(mLock);
        if (addNewline) {
            PFL_EX("");
        }
        PrintMessageForState();
    }

    return mHost->GetAm()->SetActivityController(NULL);
}
Example #15
0
ECode WebVttTrack::OnCueParsed(
    /* [in] */ ITextTrackCue* cue)
{
    {
        AutoLock syncLock(mParser);
        String regionId;
        cue->GetRegionId(&regionId);
        // resolve region
        if (regionId.GetLength() != 0) {
            AutoPtr<ITextTrackRegion> region = mRegions[regionId];
            cue->SetRegion(region.Get());
        }

        if (DEBUG) Slogger::V(TAG, "adding cue %p", cue);

        // tokenize text track string-lines into lines of spans
        mTokenizer->Reset();
        AutoPtr<ArrayOf<ICharSequence*> > strings;
        cue->GetStrings((ArrayOf<ICharSequence*>**)&strings);
        Int32 len = strings->GetLength();
        for (Int32 i = 0; i < len; i++) {
            AutoPtr<ICharSequence> cs = (*strings)[i];
            String s;
            cs->ToString(&s);
            mTokenizer->Tokenize(s);
        }
        AutoPtr<ArrayOf<IArrayOf*> > lines;
        mExtractor->GetText((ArrayOf<IArrayOf*>**)&lines);
        cue->SetLines(lines);
        AutoPtr<IStringBuilder> sbr;
        AutoPtr<IStringBuilder> osb;
        cue->AppendStringsToBuilder(sbr, (IStringBuilder**)&osb);
        osb->Append(String(" simplified to: "));
        AutoPtr<IStringBuilder> fosb;
        cue->AppendLinesToBuilder(osb, (IStringBuilder**)&fosb);
        String string;
        ICharSequence::Probe(fosb)->ToString(&string);

        if (DEBUG) Slogger::V(TAG, string.string());

        // extract inner timestamps
        AutoPtr<ArrayOf<IArrayOf*> > lines_;
        cue->GetLines((ArrayOf<IArrayOf*>**)&lines_);
        Int32 size = lines_->GetLength();
        for (Int32 i = 0; i < size; ++i) {
            AutoPtr<IArrayOf> line = (*lines_)[i];
            Int32 length;
            line->GetLength(&length);
            for (Int32 j = 0; i < length; ++j) {
                AutoPtr<IInterface> obj;
                line->Get(j, (IInterface**)&obj);
                AutoPtr<ITextTrackCueSpan> span = ITextTrackCueSpan::Probe(obj);
                Int64 timestampMs;
                span->GetTimeStampMs(&timestampMs);
                Int64 startTimeMs;
                ISubtitleTrackCue::Probe(cue)->GetStartTimeMs(&startTimeMs);
                Int64 endTimeMs;
                ISubtitleTrackCue::Probe(cue)->GetEndTimeMs(&endTimeMs);
                AutoPtr<IInteger64> tsms;
                CoreUtils::Convert(timestampMs);
                Boolean flag = FALSE;
                mTimestamps->Contains(tsms.Get(), &flag);
                if(timestampMs > startTimeMs &&
                    timestampMs < endTimeMs && !flag) {
                    mTimestamps->Add(tsms.Get());
                }
            }
        }

        mTimestamps->GetSize(&size);
        if (size > 0) {
            AutoPtr<ArrayOf<Int64> > innerTimesMs = ArrayOf<Int64>::Alloc(size);
            for (Int32 ix=0; ix < size; ++ix) {
                AutoPtr<IInterface> obj;
                mTimestamps->Get(ix, (IInterface**)&obj);
                AutoPtr<IInteger64> obj_ = IInteger64::Probe(obj);
                Int64 value;
                obj_->GetValue(&value);
                innerTimesMs->Set(ix, value);
                ISubtitleTrackCue::Probe(cue)->SetInnerTimesMs(innerTimesMs);
            }
            mTimestamps->Clear();
        } else {
            ISubtitleTrackCue::Probe(cue)->SetInnerTimesMs(NULL);
        }

        ISubtitleTrackCue::Probe(cue)->SetRunID(mCurrentRunID);
    }

    Boolean ret = FALSE;
    return SubtitleTrack::AddCue(ISubtitleTrackCue::Probe(cue), &ret);
}
Example #16
0
ECode DigestScheme::CreateMessageDigest(
    /* [in] */ const String& digAlg,
    /* [out] */ IMessageDigest** digest)
{
    VALIDATE_NOT_NULL(digest)
    // try {
    AutoPtr<IMessageDigestHelper> helper;
    CMessageDigestHelper::AcquireSingleton((IMessageDigestHelper**)&helper);
    ECode ec = helper->GetInstance(digAlg, digest);
    if (FAILED(ec)) {
        *digest = NULL;
        Logger::E("DigestScheme", "Unsupported algorithm in HTTP Digest authentication: %s", digAlg.string());
        return E_UNSUPPORTED_ALGORITHM_IN_HTTP_DIGEST_AUTHENTICATION;
    }
    return NOERROR;
    // } catch (Exception e) {
    //     throw new UnsupportedDigestAlgorithmException(
    //       "Unsupported algorithm in HTTP Digest authentication: "
    //        + digAlg);
    // }
}
ECode RecoverySystem::RebootWipeUserData(
    /* [in] */ IContext* context,
    /* [in] */ Boolean shutdown,
    /* [in] */ const String& reason,
    /* [in] */ Boolean wipeMedia)
{
    AutoPtr<IInterface> service;
    FAIL_RETURN(context->GetSystemService(IContext::USER_SERVICE, (IInterface**)&service));
    IUserManager* um = IUserManager::Probe(service);
    Boolean hasUR = FALSE;
    um->HasUserRestriction(IUserManager::DISALLOW_FACTORY_RESET, &hasUR);
    if (hasUR) {
        // throw new SecurityException("Wiping data is not allowed for this user.");
        return E_SECURITY_EXCEPTION;
    }

    AutoPtr<IConditionVariable> condition = new ConditionVariable();

    AutoPtr<IIntent> intent;
    FAIL_RETURN(CIntent::New(
            String("android.intent.action.MASTER_CLEAR_NOTIFICATION"), (IIntent**)&intent));
    intent->AddFlags(IIntent::FLAG_RECEIVER_FOREGROUND);
    AutoPtr<IUserHandle> owner;
    AutoPtr<IUserHandleHelper> helper;
    CUserHandleHelper::AcquireSingleton((IUserHandleHelper**)&helper);
    helper->GetOWNER((IUserHandle**)&owner);
    AutoPtr<OpenConditionBroadcastReceiver> receiver = new OpenConditionBroadcastReceiver(condition);
    context->SendOrderedBroadcastAsUser(intent, owner,
            Elastos::Droid::Manifest::permission::MASTER_CLEAR,
            receiver, NULL, 0, String(NULL), NULL);

    // Block until the ordered broadcast has completed.
    condition->Block();

    String shutdownArg;
    if (shutdown) {
        shutdownArg = "--shutdown_after";
    }

    String reasonArg;
    if (!reason.IsEmpty()) {
        reasonArg = String("--reason=") + SanitizeArg(reason);
    }

    String localeArg("--locale=");
    AutoPtr<ILocale> locale;
    AutoPtr<ILocaleHelper> localeHelper;
    CLocaleHelper::AcquireSingleton((ILocaleHelper**)&localeHelper);
    localeHelper->GetDefault((ILocale**)&locale);
    String defLocal;
    locale->ToString(&defLocal);
    localeArg += defLocal;

    String cmd("--wipe_data\n");
    if (wipeMedia) {
        cmd += "--wipe_media\n";
    }

    return BootCommand(context, 4, shutdownArg.string(),
            cmd.string(), reasonArg.string(), localeArg.string());
}
Example #18
0
ECode CGestureStore::SaveEx(
    /* [in] */ IOutputStream * stream,
    /* [in] */ Boolean closeStream)
{
    VALIDATE_NOT_NULL(stream);
    /*
	AutoPtr<IBufferedOutputStream> outs;
	if (FAILED(CBufferedOutputStream::New(stream,
			                               GestureConstants::IO_BUFFER_SIZE,
			                               (IBufferedOutputStream **) &outs)))
	{
		return E_RUNTIME_EXCEPTION;
	}
	*/

    AutoPtr<IDataOutputStream> out;
    if (FAILED(CDataOutputStream::New(stream,(IDataOutputStream **) &out)))
    {
        return E_RUNTIME_EXCEPTION;
    }

    Int64 start;
    if (PROFILE_LOADING_SAVING) {
        start = SystemClock::GetElapsedRealtime();
    }

    HashMap<String, List<IGesture*> *> *maps = mNamedGestures;

    IDataOutput *dout=IDataOutput::Probe(out);
    // Write version number
    dout->WriteInt16(FILE_FORMAT_VERSION);
    // Write number of entries
    dout->WriteInt32(maps->GetSize());

    HashMap<String, List<IGesture*> *>::Iterator iter = maps->Begin();
    for (Int32 i=0; iter!=maps->End(); ++iter, ++i) {
        String key= iter->mFirst;
        List<IGesture*> *examples= iter->mSecond;
        Int32 count = examples->GetSize();

        // Write entry name
        ArrayOf<Byte>* utf = StringToByteArray(key);
        dout->WriteBytes(*utf); //??no WriteUTF api
        ArrayOf<Byte>::Free(utf);

        // Write number of examples for this entry
        dout->WriteInt32(count);

        for (Int32 j = 0; j < count; j++) {
            ((IGesture*)((*examples)[i]))->Serialize(out);
        }
    }
    stream->Flush(); //no Flush api

    if (PROFILE_LOADING_SAVING) {
        Int64 end = SystemClock::GetElapsedRealtime();
        Int64 diff= end - start;
        String tmp = String::FromInt64(diff);
        String log = String("Saving gestures library = ") + tmp + String(" ms");
        Logger::D(LOG_TAG,log.string());
    }

    mChanged = FALSE;
    if (closeStream) {
        CGestureUtils::CloseStream((ICloseable *)stream);
    }

    return NOERROR;

}
ECode RegisteredServicesCache::ParseServiceInfo(
    /* [in] */ IResolveInfo* service,
    /* [out] */ IRegisteredServicesCacheServiceInfo** info)
{
    VALIDATE_NOT_NULL(info);
    *info = NULL;

    AutoPtr<IServiceInfo> si;
    service->GetServiceInfo((IServiceInfo**)&si);
    AutoPtr<IComponentName> componentName;
    String packageName, name;
    IPackageItemInfo::Probe(si)->GetPackageName(&packageName);
    IPackageItemInfo::Probe(si)->GetName(&name);
    CComponentName::New(packageName, name, (IComponentName**)&componentName);

    AutoPtr<IPackageManager> pm;
    mContext->GetPackageManager((IPackageManager**)&pm);

    AutoPtr<IXmlResourceParser> parser;
    // try {
    IPackageItemInfo::Probe(si)->LoadXmlMetaData(pm, mMetaDataName, (IXmlResourceParser**)&parser);
    if (parser == NULL) {
        Slogger::E(TAG, "No %s meta-data", mMetaDataName.string());
        *info = NULL;
        return E_XML_PULL_PARSER_EXCEPTION;
        // throw new XmlPullParserException("No " + mMetaDataName + " meta-data");
    }

    IXmlPullParser* xpp = IXmlPullParser::Probe(parser);
    AutoPtr<IAttributeSet> attrs = Xml::AsAttributeSet(IXmlPullParser::Probe(xpp));

    Int32 type;
    while (xpp->Next(&type), type != IXmlPullParser::END_DOCUMENT
            && type != IXmlPullParser::START_TAG) {
    }

    String nodeName;
    xpp->GetName(&nodeName);
    if (!mAttributesName.Equals(nodeName)) {
        Slogger::E(TAG, "Meta-data does not start with %s tag", mAttributesName.string());
        if (parser != NULL) ICloseable::Probe(parser)->Close();
        return E_XML_PULL_PARSER_EXCEPTION;
        // throw new XmlPullParserException(
        //         "Meta-data does not start with " + mAttributesName +  " tag");
    }

    AutoPtr<IApplicationInfo> appInfo;
    IComponentInfo::Probe(si)->GetApplicationInfo((IApplicationInfo**)&appInfo);
    AutoPtr<IResources> resources;
    pm->GetResourcesForApplication(appInfo, (IResources**)&resources);
    String pkgName;
    IPackageItemInfo::Probe(si)->GetPackageName(&pkgName);
    AutoPtr<IInterface> v;
    ECode ec = ParseServiceAttributes(resources, pkgName, attrs, (IInterface**)&v);
    if (ec == (ECode)E_NAME_NOT_FOUND_EXCEPTION) {
        Slogger::E(TAG, "Unable to load resources for pacakge %s", pkgName.string());
        if (parser != NULL) parser->Close();
        return E_XML_PULL_PARSER_EXCEPTION;
        // throw new XmlPullParserException(
        //             "Unable to load resources for pacakge " + si.packageName);
    }
    else if (FAILED(ec)) {
        if (parser != NULL) parser->Close();
        return ec;
    }

    if (v == NULL) {
        if (parser != NULL) parser->Close();
        return NOERROR;
    }
    AutoPtr<IServiceInfo> serviceInfo;
    service->GetServiceInfo((IServiceInfo**)&serviceInfo);
    AutoPtr<IApplicationInfo> applicationInfo;
    IComponentInfo::Probe(serviceInfo)->GetApplicationInfo((IApplicationInfo**)&applicationInfo);
    Int32 uid;
    applicationInfo->GetUid(&uid);
    CRegisteredServicesCacheServiceInfo::New(v, componentName, uid, info);

    if (parser != NULL) parser->Close();

    return NOERROR;
    // } catch (NameNotFoundException e) {
    //     throw new XmlPullParserException(
    //             "Unable to load resources for pacakge " + si.packageName);
    // } finally {
    //     if (parser != null) parser.close();
    // }
}
static void assertEquals(const String& aspect, const String& test)
{
    printf("aspect: [%s], test: [%s]\n", aspect.string(), test.string());
    assert(aspect.Equals(test) && "result not equals aspect!");
}
Example #21
0
void testSubstring()
{
    printf("\n- - - testSubstring()- - - \n");

    String str("0123456789");
    String subStr = str.Substring(0, 10);
    printf(" > str.Substring(0, 10): [%s]\n", subStr.string());
    subStr = str.Substring(1, 10);
    printf(" > str.Substring(1, 10): [%s]\n", subStr.string());
    subStr = str.Substring(8, 10);
    printf(" > str.Substring(8, 10): [%s]\n", subStr.string());
    subStr = str.Substring(9, 10);
    printf(" > str.Substring(9, 10): [%s]\n", subStr.string());
    subStr = str.Substring(10, 10);
    printf(" > str.Substring(10, 10): [%s]\n", subStr.string());

    subStr = str.Substring(0, 9);
    printf(" > str.Substring(0, 9): [%s]\n", subStr.string());
    subStr = str.Substring(1, 9);
    printf(" > str.Substring(1, 9): [%s]\n", subStr.string());
    subStr = str.Substring(8, 9);
    printf(" > str.Substring(8, 9): [%s]\n", subStr.string());
    subStr = str.Substring(9, 9);
    printf(" > str.Substring(9, 9): [%s]\n", subStr.string());

    String zhStr("和路由器一样,Binder驱动虽然默默无闻,却是通信的核心。");
    Int32 charCount = zhStr.GetLength();
    Int32 end = charCount;
    Int32 start = 0;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    end = charCount - 1;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    end = charCount - 2;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    end = charCount;
    start = 6;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 7;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 8;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 9;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 12;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 13;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 14;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 14;
    end = charCount - 1;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    start = 14;
    end = charCount - 2;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    end = charCount - 15;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
    end = charCount - 16;
    subStr = zhStr.Substring(start, end);
    printf(" > str.Substring(%d, %d): [%s]\n", start, end, subStr.string());
}
bool NativeAuthListenerInternal::RequestCredentials(
    /* [in] */ const char* authMechanism,
    /* [in] */ const char* authPeer,
    /* [in] */ uint16_t authCount,
    /* [in] */ const char* userName,
    /* [in] */ uint16_t credMask,
    /* [in] */ Credentials& credentials)
{
    /*
     * Take the authentication changed lock to prevent clients from changing the
     * authListener out from under us while we are calling out into it.
     */
    AutoPtr<ICredentials> cs;
    {
        AutoLock lock(mBusPtr->mBaAuthenticationChangeLock);

        AutoPtr<IAuthListenerInternal> al;
        mAuthListener->Resolve(EIID_IAuthListenerInternal, (IInterface**)&al);
        if (al == NULL) {
            Logger::E("NativeAuthListenerInternal", "RequestCredentials(): Can't get new local reference to AuthListener");
            return false;
        }

        al->RequestCredentials(String(authMechanism), String(authPeer),
                (Int32)authCount, String(userName), (Int32)credMask, (ICredentials**)&cs);
    }

    if (cs == NULL) {
        Logger::E("NativeAuthListenerInternal", "RequestCredentials(): Null return from method");
        return false;
    }

    AutoPtr< ArrayOf<Byte> > password;
    cs->GetPassword((ArrayOf<Byte>**)&password);
    if (password != NULL) {
        credentials.SetPassword(qcc::String((const char*)password->GetPayload(), password->GetLength()));
    }

    String strUserName;
    cs->GetUserName(&strUserName);
    if (!strUserName.IsNull()) {
        credentials.SetUserName(strUserName.string());
    }

    String certificateChain;
    cs->GetCertificateChain(&certificateChain);
    if (!certificateChain.IsNull()) {
        credentials.SetCertChain(certificateChain.string());
    }

    String privateKey;
    cs->GetPrivateKey(&privateKey);
    if (!privateKey.IsNull()) {
        credentials.SetPrivateKey(privateKey.string());
    }

    AutoPtr< ArrayOf<Byte> > logonEntry;
    cs->GetLogonEntry((ArrayOf<Byte>**)&logonEntry);
    if (logonEntry != NULL) {
        credentials.SetLogonEntry(qcc::String((const char*)logonEntry->GetPayload(), logonEntry->GetLength()));
    }

    AutoPtr<IInteger32> expiration;
    cs->GetExpiration((IInteger32**)&expiration);
    if (expiration != NULL) {
        Int32 seconds;
        expiration->GetValue(&seconds);
        credentials.SetExpiration(seconds);
    }

    return true;
}
Example #23
0
/**
 * Process the command-line options
 *
 * @return Returns TRUE if options were parsed with no apparent errors.
 */
Boolean Monkey::ProcessOptions()
{
    // quick (throwaway) check for unadorned command
    if (mArgs->GetLength() < 1) {
        ShowUsage();
        return FALSE;
    }

    String opt;
    while (!((opt = NextOption()).IsNull())) {
        if (opt.Equals("-s")) {
            mSeed = NextOptionLong("Seed");
        } else if (opt.Equals("-p")) {
            mValidPackages->Insert(NextOptionData());
        } else if (opt.Equals("-c")) {
            mMainCategories->PushBack(NextOptionData());
        } else if (opt.Equals("-v")) {
            mVerbose += 1;
        } else if (opt.Equals("--ignore-crashes")) {
            mIgnoreCrashes = TRUE;
        } else if (opt.Equals("--ignore-timeouts")) {
            mIgnoreTimeouts = TRUE;
        } else if (opt.Equals("--ignore-security-exceptions")) {
            mIgnoreSecurityExceptions = TRUE;
        } else if (opt.Equals("--monitor-native-crashes")) {
            mMonitorNativeCrashes = TRUE;
        } else if (opt.Equals("--ignore-native-crashes")) {
            mIgnoreNativeCrashes = TRUE;
        } else if (opt.Equals("--kill-process-after-error")) {
            mKillProcessAfterError = TRUE;
        } else if (opt.Equals("--hprof")) {
            mGenerateHprof = TRUE;
        } else if (opt.Equals("--pct-touch")) {
            Int32 i = IMonkeySourceRandom::FACTOR_TOUCH;
            (*mFactors)[i] = -NextOptionLong("touch events percentage");
        } else if (opt.Equals("--pct-motion")) {
            Int32 i = IMonkeySourceRandom::FACTOR_MOTION;
            (*mFactors)[i] = -NextOptionLong("motion events percentage");
        } else if (opt.Equals("--pct-trackball")) {
            Int32 i = IMonkeySourceRandom::FACTOR_TRACKBALL;
            (*mFactors)[i] = -NextOptionLong("trackball events percentage");
        } else if (opt.Equals("--pct-rotation")) {
            Int32 i = IMonkeySourceRandom::FACTOR_ROTATION;
            (*mFactors)[i] = -NextOptionLong("screen rotation events percentage");
        } else if (opt.Equals("--pct-syskeys")) {
            Int32 i = IMonkeySourceRandom::FACTOR_SYSOPS;
            (*mFactors)[i] = -NextOptionLong("system (key) operations percentage");
        } else if (opt.Equals("--pct-nav")) {
            Int32 i = IMonkeySourceRandom::FACTOR_NAV;
            (*mFactors)[i] = -NextOptionLong("nav events percentage");
        } else if (opt.Equals("--pct-majornav")) {
            Int32 i = IMonkeySourceRandom::FACTOR_MAJORNAV;
            (*mFactors)[i] = -NextOptionLong("major nav events percentage");
        } else if (opt.Equals("--pct-appswitch")) {
            Int32 i = IMonkeySourceRandom::FACTOR_APPSWITCH;
            (*mFactors)[i] = -NextOptionLong("app switch events percentage");
        } else if (opt.Equals("--pct-flip")) {
            Int32 i = IMonkeySourceRandom::FACTOR_FLIP;
            (*mFactors)[i] = -NextOptionLong("keyboard flip percentage");
        } else if (opt.Equals("--pct-anyevent")) {
            Int32 i = IMonkeySourceRandom::FACTOR_ANYTHING;
            (*mFactors)[i] = -NextOptionLong("any events percentage");
        } else if (opt.Equals("--pct-pinchzoom")) {
            Int32 i = IMonkeySourceRandom::FACTOR_PINCHZOOM;
            (*mFactors)[i] = -NextOptionLong("pinch zoom events percentage");
        } else if (opt.Equals("--pkg-blacklist-file")) {
            mPkgBlacklistFile = NextOptionData();
        } else if (opt.Equals("--pkg-whitelist-file")) {
            mPkgWhitelistFile = NextOptionData();
        } else if (opt.Equals("--throttle")) {
            mThrottle = NextOptionLong("delay (in milliseconds) to wait between events");
        } else if (opt.Equals("--randomize-throttle")) {
            mRandomizeThrottle = TRUE;
        } else if (opt.Equals("--wait-dbg")) {
            // do nothing - it's caught at the very start of run()
        } else if (opt.Equals("--dbg-no-events")) {
            mSendNoEvents = TRUE;
        } else if (opt.Equals("--port")) {
            mServerPort = (Int32) NextOptionLong("Server port to listen on for commands");
        } else if (opt.Equals("--setup")) {
            mSetupFileName = NextOptionData();
        } else if (opt.Equals("-f")) {
            mScriptFileNames->Set(mScriptFileNames->GetLength(), NextOptionData());
        } else if (opt.Equals("--profile-wait")) {
            mProfileWaitTime = NextOptionLong("Profile delay" \
                        " (in milliseconds) to wait between user action");
        } else if (opt.Equals("--device-sleep-time")) {
            mDeviceSleepTime = NextOptionLong("Device sleep time" \
                                              "(in milliseconds)");
        } else if (opt.Equals("--randomize-script")) {
            mRandomizeScript = TRUE;
        } else if (opt.Equals("--script-log")) {
            mScriptLog = TRUE;
        } else if (opt.Equals("--bugreport")) {
            mRequestBugreport = TRUE;
        } else if (opt.Equals("--periodic-bugreport")){
            mGetPeriodicBugreport = TRUE;
            mBugreportFrequency = NextOptionLong("Number of iterations");
        } else if (opt.Equals("-h")) {
            ShowUsage();
            return FALSE;
        } else {
            PFL_EX("** Error: Unknown option: %s", opt.string());
            ShowUsage();
            return FALSE;
        }
    } //end while

    // If a server port hasn't been specified, we need to specify
    // a count
    if (mServerPort == -1) {
        String countStr = NextArg();
        if (countStr.IsNull()) {
            PFL_EX("** Error: Count not specified");
            ShowUsage();
            return FALSE;
        }
        StringUtils::ParseInt32(countStr, &mCount);
    }

    return TRUE;
}
ECode CInstrumentationTestRunner::OnStart()
{
    PrepareLooper();

    if (mJustCount) {
        mResults->PutString(IInstrumentation::REPORT_KEY_IDENTIFIER, IInstrumentationTestRunner::REPORT_VALUE_ID);
        mResults->PutInt32(IInstrumentationTestRunner::REPORT_KEY_NUM_TOTAL, mTestCount);
        Finish(IActivity::RESULT_OK, mResults);
    }
    else {
        if (mDebug) {
            // TODO:
            // Debug.waitForDebugger();
        }

        AutoPtr<IByteArrayOutputStream> byteArrayOutputStream;
        CByteArrayOutputStream::New((IByteArrayOutputStream**)&byteArrayOutputStream);
        AutoPtr<IPrintStream> writer;
        CPrintStream::New(byteArrayOutputStream.Get(), (IPrintStream**)&writer);
        // try {
        AutoPtr<StringResultPrinter> resultPrinter = new StringResultPrinter(writer);

        mTestRunner->AddTestListener(resultPrinter);

        AutoPtr<ISystem> system;
        Elastos::Core::CSystem::AcquireSingleton((ISystem**)&system);
        Int64 startTime;
        system->GetCurrentTimeMillis(&startTime);
        ECode ec = mTestRunner->RunTest();
        if (FAILED(ec)) {
            // TODO:
            // writer.println(String.format("Test run aborted due to unexpected exception: %s",
            //             t.getMessage()));
            // t.printStackTrace(writer);
        }
        Int64 runTime;
        system->GetCurrentTimeMillis(&runTime);
        runTime = runTime - startTime;

        AutoPtr<ITestResult> testResult;
        mTestRunner->GetTestResult((ITestResult**)&testResult);
        resultPrinter->Print(testResult, runTime);
        // } catch (Throwable t) {
        //     // catch all exceptions so a more verbose error message can be outputted
        //     writer.println(String.format("Test run aborted due to unexpected exception: %s",
        //                     t.getMessage()));
        //     t.printStackTrace(writer);
        // } finally {
        String testClassName;
        mTestRunner->GetTestClassName(&testClassName);
        String byteArrayOutputStreamStr;
        byteArrayOutputStream->ToString(&byteArrayOutputStreamStr);
        String value("");
        value.AppendFormat("\nTest results for %s=%s", testClassName.string(), byteArrayOutputStreamStr.string());
        mResults->PutString(IInstrumentation::REPORT_KEY_STREAMRESULT, value);

        if (mCoverage) {
            GenerateCoverageReport();
        }
        writer->Close();

        Finish(IActivity::RESULT_OK, mResults);
        // }
    }
    return NOERROR;
}
Example #25
0
/**
 * Run mCount cycles and see if we hit any crashers.
 * <p>
 * TODO: Meta state on keys
 *
 * @return Returns the last cycle which executed. If the value == mCount, no
 *         errors detected.
 */
Int32 Monkey::RunMonkeyCycles()
{
    Int32 eventCounter = 0;
    Int32 cycleCounter = 0;

    Boolean shouldReportAnrTraces = FALSE;
    Boolean shouldReportDumpsysMemInfo = FALSE;
    Boolean shouldAbort = FALSE;
    Boolean systemCrashed = FALSE;
    AutoPtr<ISystem> systemObj;
    Elastos::Core::CSystem::AcquireSingleton((ISystem**)&systemObj);

    // TO DO : The count should apply to each of the script file.
    while (!systemCrashed && cycleCounter < mCount) {
        {
            if ( -1 == system("cd /data && ./getsysinfo.sh")) {
                PFL_EX("please check whether the shell script file is correct or not")
            }
            AutoLock lock(mLockLock);
            if (mRequestProcRank) {
                ReportProcRank();
                mRequestProcRank = FALSE;
            }
            if (mRequestAnrTraces) {
                mRequestAnrTraces = FALSE;
                shouldReportAnrTraces = TRUE;
            }
            if (mRequestAnrBugreport){
                GetBugreport(String("anr_") + mReportProcessName + "_");
                mRequestAnrBugreport = FALSE;
            }
            if (mRequestAppCrashBugreport){
                GetBugreport(String("app_crash") + mReportProcessName + "_");
                mRequestAppCrashBugreport = FALSE;
            }
            if (mRequestPeriodicBugreport){
                GetBugreport(String("Bugreport_"));
                mRequestPeriodicBugreport = FALSE;
            }
            if (mRequestDumpsysMemInfo) {
                mRequestDumpsysMemInfo = FALSE;
                shouldReportDumpsysMemInfo = TRUE;
            }
            if (mMonitorNativeCrashes) {
                // first time through, when eventCounter == 0, just set up
                // the watcher (ignore the error)
                if (CheckNativeCrashes() && (eventCounter > 0)) {
                    PFL_EX("** New native crash detected.");
                    if (mRequestBugreport) {
                        GetBugreport(String("native_crash_"));
                    }
                    mAbort = mAbort || !mIgnoreNativeCrashes || mKillProcessAfterError;
                }
            }
            if (mAbort) {
                shouldAbort = TRUE;
            }
        }

        // Report ANR, dumpsys after releasing lock on this.
        // This ensures the availability of the lock to Activity controller's appNotResponding
        if (shouldReportAnrTraces) {
           shouldReportAnrTraces = FALSE;
           ReportAnrTraces();
        }

        if (shouldReportDumpsysMemInfo) {
           shouldReportDumpsysMemInfo = FALSE;
           ReportDumpsysMemInfo();
        }

        if (shouldAbort) {
           shouldAbort = FALSE;
           PFL_EX("** Monkey aborted due to error.");
           PFL_EX("Events injected: %d", eventCounter);
           return eventCounter;
        }

        // In this debugging mode, we never send any events. This is
        // primarily here so you can manually test the package or category
        // limits, while manually exercising the system.
        if (mSendNoEvents) {
            eventCounter++;
            cycleCounter++;
            continue;
        }

        if ((mVerbose > 0) && (eventCounter % 100) == 0 && eventCounter != 0) {
            String calendarTime;
            Int64 now;
            systemObj->GetCurrentTimeMillis(&now);
            MonkeyUtils::ToCalendarTime(now, &calendarTime);


            Int64 systemUpTime = SystemClock::GetElapsedRealtime();
            PFL_EX("    //[calendar_time:%s system_uptime:%lld]", calendarTime.string(),
                               systemUpTime);
            PFL_EX("    // Sending event #%d", eventCounter);
        }

        AutoPtr<IMonkeyEvent> ev;
        mEventSource->GetNextEvent((IMonkeyEvent**)&ev);
        if (ev != NULL) {
            Int32 injectCode;
            ev->InjectEvent(mWm, mAm, mVerbose, &injectCode);
            if (injectCode == IMonkeyEvent::INJECT_FAIL) {
                if (IMonkeyKeyEvent::Probe(ev) != NULL) {
                    mDroppedKeyEvents++;
                }
                else if (IMonkeyMotionEvent::Probe(ev) != NULL) {
                    mDroppedPointerEvents++;
                }
                else if (IMonkeyFlipEvent::Probe(ev) != NULL) {
                    mDroppedFlipEvents++;
                }
                else if (IMonkeyRotationEvent::Probe(ev) != NULL) {
                    mDroppedRotationEvents++;
                }
            }
            else if (injectCode == IMonkeyEvent::INJECT_ERROR_REMOTE_EXCEPTION) {
                systemCrashed = TRUE;
                PFL_EX("** Error: RemoteException while injecting event.");
            }
            else if (injectCode == IMonkeyEvent::INJECT_ERROR_SECURITY_EXCEPTION) {
                systemCrashed = !mIgnoreSecurityExceptions;
                if (systemCrashed) {
                    PFL_EX("** Error: SecurityException while injecting event.");
                }
            }

            // Don't count throttling as an event.
            if (IMonkeyThrottleEvent::Probe(ev) == NULL) {
                eventCounter++;
                if (mCountEvents) {
                    cycleCounter++;
                }
            }
        }
        else {
            if (!mCountEvents) {
                cycleCounter++;
                WriteScriptLog(cycleCounter);
                //Capture the bugreport after n iteration
                if (mGetPeriodicBugreport) {
                    if ((cycleCounter % mBugreportFrequency) == 0) {
                        mRequestPeriodicBugreport = TRUE;
                    }
                }
            } else {
                // Event Source has signaled that we have no more events to process
                break;
            }
        }
    }
    PFL_EX("Events injected: %d", eventCounter);
    return eventCounter;
}
Example #26
0
ECode NetworkRequest::ToString(
    /* [out] */ String* result)
{
    VALIDATE_NOT_NULL(result)

    String request("NetworkRequest [ id=");
    String s;
    IObject::Probe(mNetworkCapabilities)->ToString(&s);
    request.AppendFormat(" requestId:%d, legacyType=%d, %s ]", mRequestId, mLegacyType, s.string());
    *result = request;
    return NOERROR;
}
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;
}
ECode PreferenceActivity::LoadHeadersFromResource(
    /* [in] */ Int32 resid,
    /* [in] */ IObjectContainer* target)
{
    AutoPtr<IXmlResourceParser> parser;
    // try {
    AutoPtr<IResources> resource;
    GetResources((IResources**)&resource);
    resource->GetXml(resid, (IXmlResourceParser**)&parser);
    AutoPtr<IAttributeSet> attrs = Xml::AsAttributeSet(parser);

    Int32 type;
    while (parser->Next(&type),
            (type != IXmlPullParser::END_DOCUMENT && type != IXmlPullParser::START_TAG)) {
        // Parse next until start tag is found
    }

    String nodeName;
    parser->GetName(&nodeName);
    if (!nodeName.Equals("preference-headers")) {
        String description;
        parser->GetPositionDescription(&description);
        Logger::E("PreferenceActivity", "XML document must start with <preference-headers> tag; found %s at %s"
                , nodeName.string(), description.string());
        if (parser != NULL) parser->Close();
        return E_RUNTIME_EXCEPTION;
    }

    AutoPtr<IBundle> curBundle;

    Int32 outerDepth;
    parser->GetDepth(&outerDepth);
    Int32 depth;
    while ((parser->Next(&type), (type != IXmlPullParser::END_DOCUMENT
           && type != IXmlPullParser::END_TAG)) || (parser->GetDepth(&depth), depth > outerDepth)) {
        if (type == IXmlPullParser::END_TAG || type == IXmlPullParser::TEXT) {
            continue;
        }

        parser->GetName(&nodeName);
        if (nodeName.Equals("header")) {
            AutoPtr<IPreferenceActivityHeader> header;
            CPreferenceActivityHeader::New((IPreferenceActivityHeader**)&header);

            Int32 size = ARRAY_SIZE(R::styleable::PreferenceHeader);
            AutoPtr<ArrayOf<Int32> > layout = ArrayOf<Int32>::Alloc(size);
            layout->Copy(R::styleable::PreferenceHeader, size);
            AutoPtr<ITypedArray> sa;
            resource->ObtainAttributes(attrs, layout, (ITypedArray**)&sa);
            Int32 id;
            sa->GetResourceId(R::styleable::PreferenceHeader_id, HEADER_ID_UNDEFINED, &id);
            header->SetId(id);

            AutoPtr<ITypedValue> tv;
            sa->PeekValue(R::styleable::PreferenceHeader_title, (ITypedValue**)&tv);
            Int32 type;
            if (tv != NULL && (tv->GetType(&type), type == ITypedValue::TYPE_STRING)) {
                Int32 resourceId;
                tv->GetResourceId(&resourceId);
                if (resourceId != 0) {
                    header->SetTitleRes(resourceId);
                }
                else {
                    AutoPtr<ICharSequence> string;
                    tv->GetString((ICharSequence**)&string);
                    header->SetTitle(string);
                }
            }

            tv = NULL;
            sa->PeekValue(R::styleable::PreferenceHeader_summary, (ITypedValue**)&tv);
            if (tv != NULL && (tv->GetType(&type), type == ITypedValue::TYPE_STRING)) {
                Int32 resourceId;
                tv->GetResourceId(&resourceId);
                if (resourceId != 0) {
                    header->SetSummaryRes(resourceId);
                }
                else {
                    AutoPtr<ICharSequence> string;
                    tv->GetString((ICharSequence**)&string);
                    header->SetSummary(string);
                }
            }

            tv = NULL;
            sa->PeekValue(R::styleable::PreferenceHeader_breadCrumbTitle, (ITypedValue**)&tv);
            if (tv != NULL && (tv->GetType(&type), type == ITypedValue::TYPE_STRING)) {
                Int32 resourceId;
                tv->GetResourceId(&resourceId);
                if (resourceId != 0) {
                    header->SetBreadCrumbTitleRes(resourceId);
                }
                else {
                    AutoPtr<ICharSequence> string;
                    tv->GetString((ICharSequence**)&string);
                    header->SetBreadCrumbTitle(string);
                }
            }

            tv = NULL;
            sa->PeekValue(R::styleable::PreferenceHeader_breadCrumbShortTitle, (ITypedValue**)&tv);
            if (tv != NULL && (tv->GetType(&type), type == ITypedValue::TYPE_STRING)) {
                Int32 resourceId;
                tv->GetResourceId(&resourceId);
                if (resourceId != 0) {
                    header->SetBreadCrumbShortTitleRes(resourceId);
                }
                else {
                    AutoPtr<ICharSequence> string;
                    tv->GetString((ICharSequence**)&string);
                    header->SetBreadCrumbShortTitle(string);
                }
            }

            Int32 resourceId;
            sa->GetResourceId(R::styleable::PreferenceHeader_icon, 0, &resourceId);
            header->SetIconRes(resourceId);
            String fragment;
            sa->GetString(R::styleable::PreferenceHeader_fragment, &fragment);
            header->SetFragment(fragment);
            sa->Recycle();

            if (curBundle == NULL) {
                CBundle::New((IBundle**)&curBundle);
            }

            Int32 innerDepth;
            parser->GetDepth(&innerDepth);
            while ((parser->Next(&type), type != IXmlPullParser::END_DOCUMENT
                   && type != IXmlPullParser::END_TAG) || (parser->GetDepth(&depth), depth > innerDepth)) {
                if (type == IXmlPullParser::END_TAG || type == IXmlPullParser::TEXT) {
                    continue;
                }

                String innerNodeName;
                parser->GetName(&innerNodeName);
                if (innerNodeName.Equals("extra")) {
                    resource->ParseBundleExtra(String("extra"), attrs, curBundle);
                    XmlUtils::SkipCurrentTag(parser);

                }
                else if (innerNodeName.Equals("intent")) {
                    AutoPtr<IIntentHelper> helper;
                    CIntentHelper::AcquireSingleton((IIntentHelper**)&helper);
                    AutoPtr<IIntent> intent;
                    helper->ParseIntent(resource, parser, attrs, (IIntent**)&intent);
                    header->SetIntent(intent);
                }
                else {
                    XmlUtils::SkipCurrentTag(parser);
                }
            }

            if (curBundle->GetSize(&size), size > 0) {
                header->SetFragmentArguments(curBundle);
                curBundle = NULL;
            }

            target->Add(header);
        }
        else {
            XmlUtils::SkipCurrentTag(parser);
        }
    }

    return NOERROR;
    // } catch (XmlPullParserException e) {
    //     throw new RuntimeException("Error parsing headers", e);
    // } catch (IOException e) {
    //     throw new RuntimeException("Error parsing headers", e);
    // } finally {
    //     if (parser != null) parser.close();
    // }
}
Example #29
0
Handle32 CRemoteDisplay::NativeListen(
    /* [in] */ const String& iface)
{
    android::sp<android::IServiceManager> sm = android::defaultServiceManager();
    android::sp<android::IMediaPlayerService> service = android::interface_cast<android::IMediaPlayerService>(
            sm->getService(android::String16("media.player")));
    if (service == NULL) {
        Logger::E("RemoteDisplay", "Could not obtain IMediaPlayerService from service manager");
        return 0;
    }

    android::sp<NativeRemoteDisplayClient> client = new NativeRemoteDisplayClient(this);
    android::sp<android::IRemoteDisplay> display = service->listenForRemoteDisplay(client, android::String8(iface.string()));
    if (display == NULL) {
         Logger::E("RemoteDisplay", "Media player service rejected request to listen for remote display '%s'.", iface.string());
         return 0;
    }

    AutoPtr<NativeRemoteDisplay> wrapper = new NativeRemoteDisplay(display.get(), client);
    return (Handle32)wrapper.Get();
}
ECode ProfileManagerService::LoadXml(
    /* [in] */ IXmlPullParser* xpp,
    /* [in] */ IContext* context)
{
    Int32 event;
    xpp->Next(&event);
    String active;
    String _name;
    while (event != IXmlPullParser::END_TAG || !String("profiles").Equals((xpp->GetName(&_name), _name))) {
        if (event == IXmlPullParser::START_TAG) {
            String name;
            xpp->GetName(&name);
            if (name.Equals("active")) {
                xpp->NextText(&active);
                Logger::D(TAG, "Found active: %s", active.string());
            }
            else if (name.Equals("profile")) {
                AutoPtr<IProfileHelper> phl;
                CProfileHelper::AcquireSingleton((IProfileHelper**)&phl);
                AutoPtr<IProfile> prof;
                phl->FromXml(xpp, context, (IProfile**)&prof);
                AddProfileInternal(prof.Get());
                // Failsafe if no active found
                if (active.IsNull()) {
                    AutoPtr<IUUID> uuid;
                    prof->GetUuid((IUUID**)&uuid);
                    uuid->ToString(&active);
                }
            }
            else if (name.Equals("notificationGroup")) {
                AutoPtr<INotificationGroupHelper> ngh;
                CNotificationGroupHelper::AcquireSingleton((INotificationGroupHelper**)&ngh);
                AutoPtr<INotificationGroup> ng;
                ngh->FromXml(xpp, context, (INotificationGroup**)&ng);
                AddNotificationGroupInternal(ng);
            }
        }
        else if (event == IXmlPullParser::END_DOCUMENT) {
            Slogger::E("ProfileManagerService", "Premature end of file while reading %p", PROFILE_FILE.Get());
            // throw new IOException("Premature end of file while reading " + PROFILE_FILE);
            return E_IO_EXCEPTION;
        }
        xpp->Next(&event);
    }
    // Don't do initialisation on startup. The AudioManager doesn't exist yet
    // and besides, the volume settings will have survived the reboot.
    // try {
        // Try / catch block to detect if XML file needs to be upgraded.
        ECode ec = NOERROR;
        AutoPtr<IUUIDHelper> uudh;
        CUUIDHelper::AcquireSingleton((IUUIDHelper**)&uudh);
        AutoPtr<IUUID> uuid;
        uudh->FromString(active, (IUUID**)&uuid);
        Boolean flag = FALSE;
        ec = SetActiveProfile(uuid.Get(), FALSE, &flag);
    // } catch (IllegalArgumentException e) {
        if (ec == (ECode)E_ILLEGAL_ARGUMENT_EXCEPTION) {
            Boolean flag = FALSE;
            mProfileNames->ContainsKey(StringUtils::ParseCharSequence(active), &flag);
            if (flag) {
                AutoPtr<IInterface> obj;
                mProfileNames->Get(StringUtils::ParseCharSequence(active), (IInterface**)&obj);
                IUUID* uid = IUUID::Probe(obj);
                SetActiveProfile(uid, FALSE, &flag);
            }
            else {
                // Final fail-safe: We must have SOME profile active.
                // If we couldn't select one by now, we'll pick the first in the set.
                AutoPtr<ICollection> values;
                mProfiles->GetValues((ICollection**)&values);
                AutoPtr<IIterator> it;
                values->GetIterator((IIterator**)&it);
                AutoPtr<IInterface> obj;
                it->GetNext((IInterface**)&obj);
                IProfile* profile = IProfile::Probe(obj);
                SetActiveProfile(profile, FALSE);
            }
            // This is a hint that we probably just upgraded the XML file. Save changes.
            mDirty = TRUE;
        }
    // }
    return NOERROR;
}