ECode SQLiteProgram::BindString( /* [in] */ Int32 index, /* [in] */ const String& value) { if (value.IsNullOrEmpty()) { // throw new IllegalArgumentException("the bind value at index " + index + " is null"); Slogger::E(String("SQLiteProgram"), "the bind value at index %d is null", index); return E_ILLEGAL_ARGUMENT_EXCEPTION; } AutoPtr<ICharSequence> valueSequence; CString::New(value, (ICharSequence**)&valueSequence); return Bind(index, valueSequence); }
AutoPtr<LoadUrlParams> LoadUrlParams::CreateLoadDataParamsWithBaseUrl( /* [in] */ const String& data, /* [in] */ const String& mimeType, /* [in] */ Boolean isBase64Encoded, /* [in] */ const String& baseUrl, /* [in] */ const String& historyUrl, /* [in] */ const String& charset) { AutoPtr<LoadUrlParams> params = CreateLoadDataParams(data, mimeType, isBase64Encoded, charset); // For WebView compatibility, when the base URL has the 'data:' // scheme, we treat it as a regular data URL load and skip setting // // baseUrl and historyUrl. // TODO(joth): we should just append baseURL and historyURL here, and move the // WebView specific transform up to a wrapper factory function in android_webview/. if (baseUrl.IsNullOrEmpty() || !baseUrl.ToLowerCase(/*TODO ILocale::US*/).StartWith("data:")) { params->SetBaseUrlForDataUrl(!baseUrl.IsNullOrEmpty() ? baseUrl : String("about:blank")); params->SetVirtualUrlForDataUrl(!historyUrl.IsNullOrEmpty() ? historyUrl : String("about:blank")); } return params; }
ECode Build::EnsureFingerprintProperty() { String value = GetStringProperty(String("ro.build.fingerprint")); if (value.IsNullOrEmpty()) { // try { AutoPtr<ISystemProperties> sysProp; CSystemProperties::AcquireSingleton((ISystemProperties**)&sysProp); sysProp->Set(String("ro.build.fingerprint"), FINGERPRINT); // } catch (IllegalArgumentException e) { // Slog.e(TAG, "Failed to set fingerprint property", e); // } } return NOERROR; }
/** * Get cookie(s) for a given url so that it can be set to "cookie:" in http * request header. * @param url The url needs cookie * @return The cookies in the format of NAME=VALUE [; NAME=VALUE] */ String AwCookieManager::GetCookie( /* [in] */ const String& url) { String cookie = NativeGetCookie(url); // Return null if the string is empty to match legacy behavior //return cookie == NULL || cookie.Trim().IsEmpty() ? NULL : cookie; if (cookie.IsNullOrEmpty()) { return String(NULL); } if (cookie.Trim().IsEmpty()) { return String(NULL); } return cookie; }
Boolean URLUtil::IsValidUrl( /* [in] */ const String& url) { if (url.IsNullOrEmpty()) { return FALSE; } return (IsAssetUrl(url) || IsResourceUrl(url) || IsFileUrl(url) || IsAboutUrl(url) || IsHttpUrl(url) || IsHttpsUrl(url) || IsJavaScriptUrl(url) || IsContentUrl(url)); }
ECode CertPathValidator::GetInstance( /* [in] */ const String& algorithm, /* [in] */ const String& provider, /* [out] */ ICertPathValidator **validator) { if (provider.IsNullOrEmpty()) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } AutoPtr<IProvider> impProvider; AutoPtr<ISecurity> security; CSecurity::AcquireSingleton((ISecurity**)&security); FAIL_RETURN(security->GetProvider(provider, (IProvider**)&impProvider)) if (impProvider == NULL) { return E_NO_SUCH_PROVIDER_EXCEPTION; } return GetInstance(algorithm, impProvider, validator); }
ECode CJDBCConnection::constructor( /* [in] */ const String& url, /* [in] */ const String& enc, /* [in] */ const String& pwd, /* [in] */ const String& drep, /* [in] */ const String& vfs) { ECode ec = NOERROR; if (url.StartWith("sqlite:/")) { mDbfile = url.Substring(0, 8); } else if (url.StartWith("jdbc:sqlite:/")) { mDbfile = url.Substring(0, 13); } else { return E_SQL_EXCEPTION; } this->mUrl = url; this->mEnc = enc; this->mVfs = vfs; ec = Open(mReadonly, (IDatabase**)&mDb); if (FAILED(ec)) { return E_SQL_EXCEPTION; } if (!pwd.IsNullOrEmpty()) { ec = mDb->Key(pwd); if (FAILED(ec)) { return E_SQL_EXCEPTION; } } IBusyHandler* hd = IBusyHandler::Probe(this); ec = mDb->BusyHandler(hd); //ec = mDb->BusyHandler(this); if (FAILED(ec)) { if (mDb != NULL) { mDb->Close(); } } if (!drep.IsNull() && (drep.StartWith("j") || drep.StartWith("J"))) { mUseJulian = TRUE; } return NOERROR; }
ECode 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 CSystem::SetProperty( /* [in] */ const String& prop, /* [in] */ const String& value, /* [out] */ String* oldValue) { VALIDATE_NOT_NULL(value); *oldValue = String(NULL); if (prop.IsNullOrEmpty()) { ALOGD("Failed to SetProperty! parameter prop is null or empty!"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } AutoPtr<IProperties> properties; GetProperties((IProperties**)&properties); properties->SetProperty(prop, value, oldValue); return NOERROR; }
static AutoPtr<ArrayOf<String> > GetStringPropertyList( /* [in] */ const String& property, /* [in] */ const String& separator) { AutoPtr<ISystemProperties> sysProp; CSystemProperties::AcquireSingleton((ISystemProperties**)&sysProp); String value; sysProp->Get(property, &value); AutoPtr<ArrayOf<String> > array; if (value.IsNullOrEmpty()) { array = ArrayOf<String>::Alloc(0); } else { StringUtils::Split(value, separator, (ArrayOf<String>**)&array); } return array; }
ECode File::constructor( /* [in] */ const String& dirPath, /* [in] */ const String& name) { if (name.IsNull()) { // throw new NullPointerException("name == null"); return E_NULL_POINTER_EXCEPTION; } if (dirPath.IsNullOrEmpty()) { mPath = FixSlashes(name); } else if (name.IsEmpty()) { mPath = FixSlashes(dirPath); } else { mPath = FixSlashes(Join(dirPath, name)); } return NOERROR; }
ECode SQLiteSession::ExecuteForCursorWindow( /* [in] */ const String& sql, /* [in] */ ArrayOf<IInterface*>* bindArgs, /* [in] */ ICursorWindow* window, /* [in] */ Int32 startPos, /* [in] */ Int32 requiredPos, /* [in] */ Boolean countAllRows, /* [in] */ Int32 connectionFlags, /* [in] */ ICancellationSignal* cancellationSignal, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result); *result = 0; if (sql.IsNullOrEmpty()) { //throw new IllegalArgumentException("sql must not be null."); Slogger::E("SQLiteSession", "sql must not be null."); return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (window == NULL) { //throw new IllegalArgumentException("window must not be null."); Slogger::E("SQLiteSession", "window must not be null."); return E_ILLEGAL_ARGUMENT_EXCEPTION; } Boolean isSuccess; FAIL_RETURN(ExecuteSpecial(sql, bindArgs, connectionFlags, cancellationSignal, &isSuccess)) if (isSuccess) { window->Clear(); *result = 0; return NOERROR; } FAIL_RETURN(AcquireConnection(sql, connectionFlags, cancellationSignal)) // might throw //try { ECode ec = mConnection->ExecuteForCursorWindow(sql, bindArgs, window, startPos, requiredPos, countAllRows, cancellationSignal, result); // might throw //} finally { FAIL_RETURN(ReleaseConnection()) // might throw //} return ec; }
ECode InetAddress::ParseNumericAddress( /* [in] */ const String& numericAddress, /* [out] */ IInetAddress** result) { VALIDATE_NOT_NULL(result); if (numericAddress.IsNullOrEmpty()) { *result = CInet6Address::LOOPBACK; REFCOUNT_ADD(*result); return NOERROR; } AutoPtr<IInetAddress> resultTemp = ParseNumericAddressNoThrow(numericAddress); resultTemp = DisallowDeprecatedFormats(numericAddress, resultTemp); if (resultTemp == NULL) { return E_ILLEGAL_ARGUMENT_EXCEPTION; } *result = resultTemp; REFCOUNT_ADD(*result); return NOERROR; }
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); }
/** * Load a list of package names from a file. * * @param fileName The file name, with package names separated by new line. * @param list The destination list. * @return Returns FALSE if any error occurs. */ Boolean Monkey::LoadPackageListFromFile( /* [in] */ const String& fileName, /* [in] */ HashSet<String>* list) { AutoPtr<IBufferedReader> reader; AutoPtr<IFileReader> fileReader; CFileReader::New(fileName, (IFileReader**)&fileReader); CBufferedReader::New(fileReader, (IBufferedReader**)&reader); String s; while(reader->ReadLine(&s), !s.IsNull()) { s = s.Trim(); if(!s.IsNullOrEmpty() && !s.StartWith("#")) { list->Insert(s); } } if(!reader.Get()) { //reader->Close(); } return TRUE; }
/** * Some devices split the fingerprint components between multiple * partitions, so we might derive the fingerprint at runtime. */ static String DeriveFingerprint() { String finger = GetStringProperty(String("ro.build.fingerprint")); if (finger.IsNullOrEmpty()) { StringBuilder sb; sb += GetStringProperty(String("ro.product.brand")); sb.AppendChar('/'); sb += GetStringProperty(String("ro.product.name")); sb.AppendChar('/'); sb += GetStringProperty(String("ro.product.device")); sb.AppendChar(':'); sb += GetStringProperty(String("ro.build.version.release")); sb.AppendChar('/'); sb += GetStringProperty(String("ro.build.id")); sb.AppendChar('/'); sb += GetStringProperty(String("ro.build.version.incremental")); sb.AppendChar(':'); sb += GetStringProperty(String("ro.build.type")); sb.AppendChar('/'); sb += GetStringProperty(String("ro.build.tags")); finger = sb.ToString(); } return finger; }
ECode InetAddress::GetAllByNameImpl( /* [in] */ const String& host, /* [in] */ Int32 netId, /* [out, callee] */ ArrayOf<IInetAddress*>** addresses) { VALIDATE_NOT_NULL(addresses) *addresses = NULL; if (host.IsNullOrEmpty()) { return LoopbackAddresses(addresses); } //Is it a numeric address? AutoPtr<IInetAddress> result = ParseNumericAddressNoThrow(host); if (result != NULL) { result = DisallowDeprecatedFormats(host, result); if (result == NULL) { return E_UNKNOWN_HOST_EXCEPTION; } AutoPtr< ArrayOf<IInetAddress*> > addrs = ArrayOf<IInetAddress*>::Alloc(1); addrs->Set(0, result); *addresses = addrs; REFCOUNT_ADD(*addresses); return NOERROR; } AutoPtr< ArrayOf<IInetAddress*> > addrs; FAIL_RETURN(LookupHostByName(host, netId, (ArrayOf<IInetAddress*>**)&addrs)); AutoPtr<ArrayOf<IInetAddress*> > res; if (addrs != NULL) { res = addrs->Clone(); } *addresses = res; REFCOUNT_ADD(*addresses); return NOERROR; }
Event::Event(EventType eType, bool bInitialState, const String &szName /* = Nothing */) { NTSTATUS status; if (szName.IsNullOrEmpty()) { this->m_name.Buffer = nullptr; status = NtCreateEvent(&this->Handle, EVENT_ALL_ACCESS, NULL, static_cast<EVENT_TYPE>(eType), static_cast<BOOLEAN>(bInitialState)); } else { GlobalizeString u_name(_R("\\BaseNamedObjects\\") + szName); RtlInitUnicodeString(&this->m_name, u_name.SuppressFinalize(u_name.toUnicode())); InitializeObjectAttributes(&this->m_obj, &this->m_name, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, nullptr); status = NtCreateEvent(&this->Handle, EVENT_ALL_ACCESS, &this->m_obj, static_cast<EVENT_TYPE>(eType), static_cast<BOOLEAN>(bInitialState)); } //if if (status != STATUS_SUCCESS) { Exception::SetLastException(status, true); } //if }
ECode CTextServicesManagerService::SetCurrentSpellCheckerLocked( /* [in] */ const String& sciId) { if (DBG) { Slogger::W(TAG, "setCurrentSpellChecker: %s", sciId.string()); } HashMap<String, AutoPtr<ISpellCheckerInfo> >::Iterator it = mSpellCheckerMap.Find(sciId); if (sciId.IsNullOrEmpty() || it == mSpellCheckerMap.End()) return NOERROR; const AutoPtr<ISpellCheckerInfo> currentSci; GetCurrentSpellChecker(String(NULL), (ISpellCheckerInfo**)¤tSci); String id; if (currentSci != NULL && (currentSci->GetId(&id), id.Equals(sciId))) { // Do nothing if the current spell checker is same as new spell checker. return NOERROR; } const Int64 ident = Binder::ClearCallingIdentity(); //try { mSettings->PutSelectedSpellChecker(sciId); SetCurrentSpellCheckerSubtypeLocked(0); //} finally { //} return Binder::RestoreCallingIdentity(ident); }
ECode CRecognitionManagerService::GetCurRecognizer( /* [in] */ Int32 userHandle, /* [out] */ IComponentName** componentName) { VALIDATE_NOT_NULL(componentName); *componentName = NULL; String curRecognizer; AutoPtr<IContentResolver> contentResolver; mContext->GetContentResolver((IContentResolver**)&contentResolver); AutoPtr<ISettingsSecure> settingsSecure; CSettingsSecure::AcquireSingleton((ISettingsSecure**)&settingsSecure); settingsSecure->GetStringForUser(contentResolver, ISettingsSecure::VOICE_RECOGNITION_SERVICE, userHandle, &curRecognizer); if (curRecognizer.IsNullOrEmpty()) { *componentName = NULL; return NOERROR; } if (DEBUG) { Slogger::I(TAG, "getCurRecognizer curRecognizer=%s user=%d", curRecognizer.string(), userHandle); } AutoPtr<IComponentNameHelper> helper; CComponentNameHelper::AcquireSingleton((IComponentNameHelper**)&helper); return helper->UnflattenFromString(curRecognizer, componentName); }
/** * Called when the <code>selectionString</code> has changed. */ void AccessibilityInjectorFallback::OnSelectionStringChange( /* [in] */ const String& selectionString) { // if (DEBUG) { // Log.d(LOG_TAG, "Selection string: " + selectionString); // } mIsLastSelectionStringNull = (selectionString.IsNull()); if (mScheduledEventStack.IsEmpty()) { return; } AutoPtr<IAccessibilityEvent> event = mScheduledEventStack.GetTop(); mScheduledEventStack.Pop(); if ((event != NULL) && !selectionString.IsNullOrEmpty()) { AutoPtr<IObjectContainer> container; event->GetText((IObjectContainer**)&container); AutoPtr<ICharSequence> csSelectionString; CStringWrapper::New(selectionString, (ICharSequence**)&csSelectionString); container->Add(csSelectionString); event->SetFromIndex(0); event->SetToIndex(selectionString.GetLength()); SendAccessibilityEvent(event); } }
ECode CTextServicesManagerService::GetSpellCheckerService( /* [in] */ const String& sciId, /* [in] */ const String& locale, /* [in] */ ITextServicesSessionListener* tsListener, /* [in] */ ISpellCheckerSessionListener* scListener, /* [in] */ IBundle* bundle) { if (!CalledFromValidUser()) { return NOERROR; } if (!mSystemReady) { return NOERROR; } if (sciId.IsNullOrEmpty() || tsListener == NULL || scListener == NULL) { Slogger::E(TAG, "getSpellCheckerService: Invalid input."); return NOERROR; } { AutoLock lock(mSpellCheckerMapLock); ManagedISpellCheckerInfoMapIt it = mSpellCheckerMap.Find(sciId); if (it == mSpellCheckerMap.End()) { return NOERROR; } AutoPtr<ISpellCheckerInfo> sci; sci = it->mSecond; Int32 uid = Binder::GetCallingUid(); ManagedSpellCheckerBindGroupMapIt it2 = mSpellCheckerBindGroups.Find(sciId); if (it2 != mSpellCheckerBindGroups.End()) { AutoPtr<SpellCheckerBindGroup> bindGroup = it2->mSecond; if (bindGroup != NULL) { AutoPtr<InternalDeathRecipient> recipient; bindGroup->AddListener(tsListener, locale, scListener, uid, bundle, (InternalDeathRecipient**)&recipient); if (recipient == NULL) { if (DBG) { Slogger::W(TAG, "Didn't create a death recipient."); return NOERROR; } } if ((bindGroup->mSpellChecker == NULL) && bindGroup->mConnected) { Slogger::E(TAG, "The state of the spell checker bind group is illegal."); bindGroup->RemoveAll(); } else if (bindGroup->mSpellChecker != NULL) { if (DBG) { Slogger::W(TAG, "Existing bind found. Return a spell checker session now. Listeners count = %d", bindGroup->mListeners.GetSize()); } //try { AutoPtr<IISpellCheckerSession> session; bindGroup->mSpellChecker->GetISpellCheckerSession( recipient->mScLocale, recipient->mScListener, bundle, (IISpellCheckerSession**)&session); if (session != NULL) { tsListener->OnServiceConnected(session); return NOERROR; } else { if (DBG) { Slogger::W(TAG, "Existing bind already expired. "); } bindGroup->RemoveAll(); } //} /*catch (RemoteException e) { Slog.e(TAG, "Exception in getting spell checker session: " + e); bindGroup.removeAll(); }*/ } } } Int64 ident = Binder::ClearCallingIdentity(); //try { StartSpellCheckerServiceInnerLocked( sci, locale, tsListener, scListener, uid, bundle); Binder::RestoreCallingIdentity(ident); /*} finally { Binder.restoreCallingIdentity(ident); }*/ } } return NOERROR; }
ECode CBrowserActivity::OnCreate( /* [in] */ IBundle* savedInstanceState) { Logger::D(TAG, "OnCreate()---"); Activity::OnCreate(savedInstanceState); SetContentView(R::layout::activity_browser); AutoPtr<IWeakReference> weakHost; GetWeakReference((IWeakReference**)&weakHost); mMyHandler = new MyHandler(weakHost); mMyListener = new MyListener(this); AutoPtr<IView> view = FindViewById(R::id::pic_back); mBackButton = IImageView::Probe(view); assert(mBackButton != NULL); view = FindViewById(R::id::pic_folder_name); AutoPtr<ITextView> albumName = ITextView::Probe(view); assert(albumName != NULL); view = FindViewById(R::id::pic_btn_wallpaper); mWallpaperLayout = ILinearLayout::Probe(view); assert(mWallpaperLayout != NULL); view = FindViewById(R::id::pic_btn_detail); mDetailLayout = ILinearLayout::Probe(view); assert(mDetailLayout != NULL); view = FindViewById(R::id::pic_btn_share); mShareLayout = ILinearLayout::Probe(view); assert(mShareLayout != NULL); view = FindViewById(R::id::pic_btn_popup); mPopButton = IButton::Probe(view); assert(mPopButton != NULL); view = FindViewById(R::id::pic_gridview); mGridView = IGridView::Probe(view); assert(mGridView != NULL); AutoPtr<IIntent> intent; GetIntent((IIntent**)&intent); if (intent != NULL) { String path; intent->GetStringExtra(DataSourceHelper::SOURCE_PATH, &path); if (!path.IsNullOrEmpty()) { String folderName; intent->GetStringExtra(DataSourceHelper::SOURCE_DESC, &folderName); AutoPtr<List<String> > imageItems = DataSourceHelper::GetItemList(path); if (imageItems != NULL) { AutoPtr<PictureEntry> entry; List<String>::Iterator it = imageItems->Begin(); for (Int32 i = 0; it != imageItems->End(); ++it, ++i) { entry = new PictureEntry(); entry->sourcePath = path; entry->sourcePath += DataSourceHelper::PATH_SPLITE; entry->sourcePath += *it; entry->desc = folderName; // Logger::D(TAG, " > %d, path:%s, folderName:%s", i, entry->sourcePath.string(), entry->desc.string()); mPictureEntryList.PushBack(entry); } AutoPtr<ICharSequence> cs; CStringWrapper::New(folderName, (ICharSequence**)&cs); albumName->SetText(cs); mSimpleAdapter = GetSimpleAdapter(); if (mSimpleAdapter == NULL) { Logger::W(TAG, "mSimpleAdapter is null!"); } mGridView->SetAdapter(IAdapter::Probe(mSimpleAdapter)); } else { Logger::W(TAG, "imageItems is null!"); } } } AutoPtr<IViewOnClickListener> clickListener = (IViewOnClickListener*)mMyListener.Get(); mBackButton->SetOnClickListener(clickListener); mWallpaperLayout->SetOnClickListener(clickListener); mDetailLayout->SetOnClickListener(clickListener); mShareLayout->SetOnClickListener(clickListener); mPopButton->SetOnClickListener(clickListener); return NOERROR; }
ECode CObjInfoList::AcquireDynamicStructInfo( /* [in] */ const String& name, /* [in] */ ArrayOf<String>* fieldNames, /* [in] */ ArrayOf<IDataTypeInfo*>* fieldTypeInfos, /* [out] */ IStructInfo** structInfo) { if (name.IsNullOrEmpty() || fieldNames == NULL || fieldTypeInfos == NULL || !structInfo || fieldNames->GetLength() != fieldTypeInfos->GetLength()) { return E_INVALID_ARGUMENT; } InfoLinkNode* node = mStructInfoHead; String structName; AutoPtr<CStructInfo> structInfoObj; Int32 count = 0, i = 0; LockHashTable(EntryType_Struct); for (; node; node = node->mNext) { structInfoObj = (CStructInfo *)node->mInfo; structInfoObj->GetName(&structName); if (name.Equals(structName)) { structInfoObj->GetFieldCount(&count); if (count != fieldNames->GetLength()) { UnlockHashTable(EntryType_Struct); return E_DATAINFO_EXIST; } AutoPtr< ArrayOf<String> > _fieldNames = structInfoObj->mFieldNames; AutoPtr< ArrayOf<IDataTypeInfo*> > _fieldTypeInfos = structInfoObj->mFieldTypeInfos; for (i = 0; i < count; i++) { if (!(*fieldNames)[i].Equals((*_fieldNames)[i])) { UnlockHashTable(EntryType_Struct); return E_DATAINFO_EXIST; } if ((*_fieldTypeInfos)[i] != (*fieldTypeInfos)[i]) { UnlockHashTable(EntryType_Struct); return E_DATAINFO_EXIST; } } *structInfo = structInfoObj; (*structInfo)->AddRef(); UnlockHashTable(EntryType_Struct); return NOERROR; } } structInfoObj = new CStructInfo(); if (structInfoObj == NULL) { UnlockHashTable(EntryType_Struct); return E_OUT_OF_MEMORY; } ECode ec = structInfoObj->InitDynamic(name, fieldNames, fieldTypeInfos); if (FAILED(ec)) { UnlockHashTable(EntryType_Struct); return ec; } ec = AddInfoNode(structInfoObj, &mStructInfoHead); if (FAILED(ec)) { UnlockHashTable(EntryType_Struct); return ec; } *structInfo = structInfoObj; (*structInfo)->AddRef(); UnlockHashTable(EntryType_Struct); return NOERROR; }
ECode CResources::UpdateConfiguration( /* [in] */ IConfiguration* config, /* [in] */ IDisplayMetrics* metrics) { { Mutex::Autolock lock(mTmpValueLock); Int32 configChanges = 0xfffffff; if (config != NULL) { mConfiguration->UpdateFrom(config, &configChanges); } if (mConfiguration->mLocale == NULL) { AutoPtr<ILocaleHelper> helper; FAIL_RETURN(CLocaleHelper::AcquireSingleton( (ILocaleHelper**)&helper)); FAIL_RETURN(helper->GetDefault( (ILocale**)&mConfiguration->mLocale)); } if (metrics != NULL) { mMetrics->SetTo(metrics); mMetrics->UpdateMetrics(mCompatibilityInfo.Get(), mConfiguration->mOrientation, mConfiguration->mScreenLayout); } mMetrics->mScaledDensity = mMetrics->mDensity * mConfiguration->mFontScale; StringBuffer locale; if (mConfiguration->mLocale != NULL) { String str; FAIL_RETURN(mConfiguration->mLocale->GetLanguage(&str)); locale = str; String country; FAIL_RETURN(mConfiguration->mLocale->GetCountry(&country)); if (!country.IsNullOrEmpty()) { locale += "-" + country; } } Int32 width, height; if (mMetrics->mWidthPixels >= mMetrics->mHeightPixels) { width = mMetrics->mWidthPixels; height = mMetrics->mHeightPixels; } else { //noinspection SuspiciousNameCombination width = mMetrics->mHeightPixels; //noinspection SuspiciousNameCombination height = mMetrics->mWidthPixels; } Int32 keyboardHidden = mConfiguration->mKeyboardHidden; if (keyboardHidden == Configuration_KEYBOARDHIDDEN_NO && mConfiguration->mHardKeyboardHidden == Configuration_HARDKEYBOARDHIDDEN_YES) { keyboardHidden = Configuration_KEYBOARDHIDDEN_SOFT; } mAssets->SetConfiguration(mConfiguration->mMcc, mConfiguration->mMnc, String((const char *)locale), mConfiguration->mOrientation, mConfiguration->mTouchscreen, (Int32)(mMetrics->mDensity * 160), mConfiguration->mKeyboard, keyboardHidden, mConfiguration->mNavigation, width, height, mConfiguration->mScreenLayout, mConfiguration->mUiMode, sSdkVersion); // int N = mDrawableCache.size(); if (DEBUG_CONFIG) { Logger::D(TAG, StringBuffer("Cleaning up drawables config changes: 0x") + configChanges); } // for (int i=0; i < N; i++) { // WeakReference<Drawable.ConstantState> ref = mDrawableCache.valueAt(i); // if (ref != null) { // Drawable.ConstantState cs = ref.get(); // if (cs != null) { // if (Configuration.needNewResources( // configChanges, cs.getChangingConfigurations())) { // if (DEBUG_CONFIG) { // Log.d(TAG, "FLUSHING #0x" // + Long.toHexString(mDrawableCache.keyAt(i)) // + " / " + cs + " with changes: 0x" // + Integer.toHexString(cs.getChangingConfigurations())); // } // mDrawableCache.setValueAt(i, null); // } else if (DEBUG_CONFIG) { // Log.d(TAG, "(Keeping #0x" // + Long.toHexString(mDrawableCache.keyAt(i)) // + " / " + cs + " with changes: 0x" // + Integer.toHexString(cs.getChangingConfigurations()) // + ")"); // } // } // } // } // mDrawableCache.clear(); // mColorStateListCache.clear(); FlushLayoutCache(); } { Mutex::Autolock lock(mSyncLock); if (mPluralRule != NULL) { assert(config); mPluralRule = PluralRules::RuleForLocale(((CConfiguration*)config)->mLocale); } } return NOERROR; }
void CheckVersionReturnance () { #if defined(WIN32) && !defined(NO_MULTITHREAD_VERSION_CHECK) if (VersionCheckReady) { if (!receiveBuffer.IsNullOrEmpty() && (receiveBuffer[0] != '<')) { CParser Parser (receiveBuffer.CString(), PSP_COMMENT_LINE); String prefix; Parser.ParseToken (PSF_ALLOW_NEWLINES, prefix); uint8 minor; uint16 major; uint32 build; Parser.ParseDataType<uint16> (PSF_ALLOW_NEWLINES, &major, 1); Parser.ParseDataType<uint8> (PSF_ALLOW_NEWLINES, &minor, 1); Parser.ParseDataType<uint32> (PSF_ALLOW_NEWLINES, &build, 1); #if defined(WIN32) && !defined(NO_MULTITHREAD_VERSION_CHECK) VersionReturnance = CompareVersion (prefix.CString(), major, minor, build); VersionPrefix = prefix; VersionMinor = minor; VersionMajor = major; VersionBuild = build; VersionCheckReady = true; #else if (CompareVersion (prefix.CString(), minor, major, build) == VERSION_NEWER) ServerPrintf ( "==================================\n" "*****************************\n" "There is an update available for CleanCode!\n" "Please go to http://code.google.com/p/cleancodequake2 and update accordingly.\n" "Your version: "CLEANCODE_VERSION_PRINT"\n" "Update version: "CLEANCODE_VERSION_PRINT"\n" "*****************************\n" "==================================\n", CLEANCODE_VERSION_PRINT_ARGS, prefix.CString(), major, minor, build); else ServerPrint ("Your version of CleanCode is up to date.\n"); #endif } if (VersionReturnance == VERSION_NEWER) ServerPrintf ( "==================================\n" "*****************************\n" "There is an update available for CleanCode!\n" "Please go to http://code.google.com/p/cleancodequake2 and update accordingly\nor run the auto updater." "Your version: "CLEANCODE_VERSION_PRINT"\n" "Update version: "CLEANCODE_VERSION_PRINT"\n" "*****************************\n" "==================================\n", CLEANCODE_VERSION_PRINT_ARGS, VersionPrefix.CString(), VersionMajor, VersionMinor, VersionBuild); else ServerPrint ("Your version of CleanCode is up to date.\n"); VersionReturnance = VERSION_SAME; VersionCheckReady = false; CloseHandle (hThread); hThread = NULL; iID = 0; } #endif }
void Execute() { if (CurrentVote.Voting) { Player->PrintToClient(PRINT_HIGH, "Vote already in progress."); return; } if (ArgCount() != 3) { Player->PrintToClient (PRINT_HIGH, "Use \"players\" to check the player IDs for kick-by-ID. Syntax:\n vote ban/kick n:id\n vote ban/kick p:playerName\n\n Example: vote ban/kick n:8\n Example: vote ban/kick p:Paril\n"); return; } String str = ArgGets(2); if (str.Count() < 3 || str[1] != ':' || (str[0] != 'p' && str[0] != 'n')) { Player->PrintToClient (PRINT_HIGH, "Syntax error. Type \"vote ban\" or \"vote kick\" to see syntax.\n"); return; } int playerToKick = -1; if (str[0] == 'p') { String playerName = str.Substring(2).ToLower(); if (playerName.IsNullOrEmpty()) { Player->PrintToClient (PRINT_HIGH, "Syntax error. Type \"vote ban\" or \"vote kick\" to see syntax.\n"); return; } for (int i = 1; i <= Game.MaxClients; ++i) { if (entity_cast<CPlayerEntity>(Game.Entities[i].Entity)->Client.Persistent.Name.Clone().ToLower() == playerName) { if (playerToKick != -1) { Player->PrintToClient (PRINT_HIGH, "Multiple players exist by that name. Type \"vote ban\" or \"vote kick\" to see how to ban by player number instead.\n"); return; } playerToKick = i; } } if (playerToKick == -1) { Player->PrintToClient (PRINT_HIGH, "Player does not exist.\n"); return; } } else { String playerNum = str.Substring(2); for (size_t i = 0; i < playerNum.Count(); ++i) { if (playerNum[i] < '0' || playerNum[i] > '9') { Player->PrintToClient (PRINT_HIGH, "Invalid player number.\n"); return; } } playerToKick = atoi(str.Substring(2).CString()); if (playerToKick <= 0 || playerToKick > Game.MaxClients) { Player->PrintToClient (PRINT_HIGH, "Invalid player number.\n"); return; } } CVoteKickBanData *voteData = QNew(TAG_GENERIC) CVoteKickBanData(ban, playerToKick); CurrentVote.StartVote(voteType, voteData, Player->Client.Persistent.Name); }
ECode IconPackHelper::ColorFilterUtils::ParseIconFilter( /* [in] */ IXmlPullParser* parser, /* [in] */ IColorFilterUtilsBuilder* builder, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = FALSE; String tag; parser->GetName(&tag); if (!TAG_FILTER.Equals(tag)) return NOERROR; Int32 attrCount; parser->GetAttributeCount(&attrCount); String attrName; String attr; Int32 intValue; while (attrCount-- > 0) { parser->GetAttributeName(attrCount, &attrName); if (attrName.Equals("name")) { parser->GetAttributeValue(attrCount, &attr); } } String content; FAIL_RETURN(parser->NextText(&content)); if (!attr.IsNull() && !content.IsNullOrEmpty()) { content = content.Trim(); if (FILTER_HUE.EqualsIgnoreCase(attr)) { intValue = ClampValue(GetInt32(content, 0), MIN_HUE, MAX_HUE); builder->Hue(intValue); } else if (FILTER_SATURATION.EqualsIgnoreCase(attr)) { intValue = ClampValue(GetInt32(content, 100), MIN_SATURATION, MAX_SATURATION); builder->Saturate(intValue); } else if (FILTER_INVERT.EqualsIgnoreCase(attr)) { if (String("true").EqualsIgnoreCase(content)) { builder->InvertColors(); } } else if (FILTER_BRIGHTNESS.EqualsIgnoreCase(attr)) { intValue = ClampValue(GetInt32(content, 100), MIN_BRIGHTNESS, MAX_BRIGHTNESS); builder->Brightness(intValue); } else if (FILTER_CONTRAST.EqualsIgnoreCase(attr)) { intValue = ClampValue(GetInt32(content, 0), MIN_CONTRAST, MAX_CONTRAST); builder->Contrast(intValue); } else if (FILTER_ALPHA.EqualsIgnoreCase(attr)) { intValue = ClampValue(GetInt32(content, 100), MIN_ALPHA, MAX_ALPHA); builder->Alpha(intValue); } else if (FILTER_TINT.EqualsIgnoreCase(attr)) { // try { ECode ec = Color::ParseColor(content, &intValue); if (SUCCEEDED(ec)) builder->Tint(intValue); // } catch (IllegalArgumentException e) { // Log.w(TAG, "Cannot apply tint, invalid argument: " + content); // } } } *result = TRUE; return NOERROR; }
/** * 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; }
ECode CTextServicesManagerService::GetCurrentSpellCheckerSubtype( /* [in] */ const String& locale, /* [in] */ Boolean allowImplicitlySelectedSubtype, /* [out] */ ISpellCheckerSubtype** subtype) { VALIDATE_NOT_NULL(subtype); *subtype = NULL; // TODO: Make this work even for non-current users? if (!CalledFromValidUser()) { return NOERROR; } { AutoLock lock(mSpellCheckerMapLock); String subtypeHashCodeStr; mSettings->GetSelectedSpellCheckerSubtype(&subtypeHashCodeStr); if (DBG) { Slogger::W(TAG, "getCurrentSpellCheckerSubtype: %s", subtypeHashCodeStr.string()); } AutoPtr<ISpellCheckerInfo> sci; GetCurrentSpellChecker(String(NULL), (ISpellCheckerInfo**)&sci); Int32 subtypeCount; if (sci == NULL || (sci->GetSubtypeCount(&subtypeCount), subtypeCount == 0)) { if (DBG) { Slogger::W(TAG, "Subtype not found."); } return NOERROR; } Int32 hashCode; if (!subtypeHashCodeStr.IsNullOrEmpty()) { hashCode = StringUtils::ParseInt32(subtypeHashCodeStr); } else { hashCode = 0; } if (hashCode == 0 && !allowImplicitlySelectedSubtype) { return NOERROR; } String candidateLocale(NULL); if (hashCode == 0) { // Spell checker language settings == "auto" AutoPtr<IInputMethodManager> imm; mContext->GetSystemService(IContext::INPUT_METHOD_SERVICE, (IInterface**)&imm); if (imm != NULL) { AutoPtr<IInputMethodSubtype> currentInputMethodSubtype; imm->GetCurrentInputMethodSubtype((IInputMethodSubtype**)¤tInputMethodSubtype); if (currentInputMethodSubtype != NULL) { String localeString; currentInputMethodSubtype->GetLocale(&localeString); if (!localeString.IsNullOrEmpty()) { // 1. Use keyboard locale if available in the spell checker candidateLocale = localeString; } } } if (candidateLocale == NULL) { // 2. Use System locale if available in the spell checker AutoPtr<IResources> res; mContext->GetResources((IResources**)&res); AutoPtr<IConfiguration> configuration; res->GetConfiguration((IConfiguration**)&configuration); AutoPtr<ILocale> iLocale; configuration->GetLocale((ILocale**)&iLocale); iLocale->ToString(&candidateLocale); } } AutoPtr<ISpellCheckerSubtype> candidate; for (Int32 i = 0; i < subtypeCount; ++i) { AutoPtr<ISpellCheckerSubtype> scs; Int32 hashCode2; sci->GetSubtypeAt(i, (ISpellCheckerSubtype**)&scs); assert(scs != NULL); scs->GetHashCode(&hashCode2); if (hashCode == 0) { String scsLocale; scs->GetLocale(&scsLocale); if (candidateLocale.Equals(scsLocale)) { *subtype = scs; REFCOUNT_ADD(*subtype); return NOERROR; } else if (candidate == NULL) { if (candidateLocale.GetLength() >= 2 && scsLocale.GetLength() >= 2 && candidateLocale.StartWith(scsLocale)) { // Fall back to the applicable language candidate = scs; } } } else if (hashCode2 == hashCode) { if (DBG) { Slogger::W(TAG, "Return subtype:%d , input= %s", hashCode2, locale.string()); // + ", " + scs.getLocale()); } // 3. Use the user specified spell check language *subtype = scs; REFCOUNT_ADD(*subtype); return NOERROR; } } // 4. Fall back to the applicable language and return it if not null // 5. Simply just return it even if it's null which means we could find no suitable // spell check languages *subtype = candidate; REFCOUNT_ADD(*subtype); return NOERROR; } }