Java Code Examples for org.chromium.base.Log

The following are top voted examples for showing how to use org.chromium.base.Log. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: chromium-for-android-56-debug-video   File: NewTabPageAdapter.java   View source code 6 votes vote down vote up
/**
 * Dismisses the item at the provided adapter position. Can also cause the dismissal of other
 * items or even entire sections.
 */
// TODO(crbug.com/635567): Fix this properly.
@SuppressLint("SwitchIntDef")
public void dismissItem(int position) {
    int itemViewType = getItemViewType(position);

    // TODO(dgn): Polymorphism is supposed to allow to avoid that kind of stuff.
    switch (itemViewType) {
        case ItemViewType.STATUS:
        case ItemViewType.ACTION:
            dismissSection(getSuggestionsSection(position));
            return;

        case ItemViewType.SNIPPET:
            dismissSuggestion(position);
            return;

        case ItemViewType.PROMO:
            dismissPromo();
            return;

        default:
            Log.wtf(TAG, "Unsupported dismissal of item of type %d", itemViewType);
            return;
    }
}
 
Example 2
Project: chromium-net-for-android   File: CronetActivity.java   View source code 6 votes vote down vote up
@Override
public void onSucceeded(UrlRequest request, UrlResponseInfo info) {
    Log.i(TAG, "****** Request Completed, status code is %d, total received bytes is %d",
            info.getHttpStatusCode(), info.getReceivedBytesCount());

    final String receivedData = mBytesReceived.toString();
    final String url = info.getUrl();
    final String text = "Completed " + url + " (" + info.getHttpStatusCode() + ")";
    CronetActivity.this.runOnUiThread(new Runnable() {
        public void run() {
            mResultText.setText(text);
            mReceiveDataText.setText(receivedData);
            promptForURL(url);
        }
    });
}
 
Example 3
Project: chromium-for-android-56-debug-video   File: WebappActivity.java   View source code 6 votes vote down vote up
@Override
protected void onNewIntent(Intent intent) {
    if (intent == null) return;
    super.onNewIntent(intent);

    WebappInfo newWebappInfo = createWebappInfo(intent);
    if (newWebappInfo == null) {
        Log.e(TAG, "Failed to parse new Intent: " + intent);
        finish();
    } else if (!TextUtils.equals(mWebappInfo.id(), newWebappInfo.id())) {
        mWebappInfo = newWebappInfo;
        resetSavedInstanceState();
        if (mIsInitialized) initializeUI(null);
        // TODO(dominickn): send the web app into fullscreen if mDisplayMode is
        // WebDisplayMode.Fullscreen. See crbug.com/581522
    }
}
 
Example 4
Project: chromium-for-android-56-debug-video   File: SigninHelper.java   View source code 6 votes vote down vote up
/**
 * Deal with account rename. The current approach is to sign out and then sign back in.
 * In the (near) future, we should just be clearing all the cached email address here
 * and have the UI re-fetch the emailing address based on the ID.
 */
private void handleAccountRename(final String oldName, final String newName) {
    Log.i(TAG, "handleAccountRename from: " + oldName + " to " + newName);

    // TODO(acleung): I think most of the operations need to run on the main
    // thread. May be we should have a progress Dialog?

    // TODO(acleung): Deal with passphrase or just prompt user to re-enter it?
    // Perform a sign-out with a callback to sign-in again.
    mSigninManager.signOut(new Runnable() {
        @Override
        public void run() {
            // Clear the shared perf only after signOut is successful.
            // If Chrome dies, we can try it again on next run.
            // Otherwise, if re-sign-in fails, we'll just leave chrome
            // signed-out.
            clearNewSignedInAccountName(mContext);
            performResignin(newName);
        }
    });
}
 
Example 5
Project: chromium-net-for-android   File: LibraryLoader.java   View source code 6 votes vote down vote up
private void initializeAlreadyLocked() throws ProcessInitException {
    if (mInitialized) {
        return;
    }

    ensureCommandLineSwitchedAlreadyLocked();

    if (!nativeLibraryLoaded()) {
        Log.e(TAG, "error calling nativeLibraryLoaded");
        throw new ProcessInitException(LoaderErrors.LOADER_ERROR_FAILED_TO_REGISTER_JNI);
    }

    // From now on, keep tracing in sync with native.
    TraceEvent.registerNativeEnabledObserver();

    // From this point on, native code is ready to use and checkIsReady()
    // shouldn't complain from now on (and in fact, it's used by the
    // following calls).
    // Note that this flag can be accessed asynchronously, so any initialization
    // must be performed before.
    mInitialized = true;
}
 
Example 6
Project: chromium-net-for-android   File: Linker.java   View source code 6 votes vote down vote up
/**
 * Get singleton instance. Returns either a LegacyLinker or a ModernLinker.
 *
 * Returns a ModernLinker if running on Android M or later, otherwise returns
 * a LegacyLinker.
 *
 * ModernLinker requires OS features from Android M and later: a system linker
 * that handles packed relocations and load from APK, and android_dlopen_ext()
 * for shared RELRO support. It cannot run on Android releases earlier than M.
 *
 * LegacyLinker runs on all Android releases but it is slower and more complex
 * than ModernLinker, so ModernLinker is preferred for Android M and later.
 *
 * @return the Linker implementation instance.
 */
public static final Linker getInstance() {
    synchronized (sSingletonLock) {
        if (sSingleton == null) {
            // With incremental install, it's important to fall back to the "normal"
            // library loading path in order for the libraries to be found.
            String appClass =
                    ContextUtils.getApplicationContext().getApplicationInfo().className;
            boolean isIncrementalInstall =
                    appClass != null && appClass.contains("incrementalinstall");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isIncrementalInstall) {
                sSingleton = ModernLinker.create();
            } else {
                sSingleton = LegacyLinker.create();
            }
            Log.i(TAG, "Using linker: " + sSingleton.getClass().getName());
        }
        return sSingleton;
    }
}
 
Example 7
Project: chromium-net-for-android   File: Linker.java   View source code 6 votes vote down vote up
/**
 * Set Linker implementation type.
 * For testing. Sets either a LegacyLinker or a ModernLinker. Must be called
 * before getInstance().
 *
 * @param type LINKER_IMPLEMENTATION_LEGACY or LINKER_IMPLEMENTATION_MODERN
 */
public static final void setImplementationForTesting(int type) {
    // Sanity check. This method may only be called during tests.
    assertLinkerTestsAreEnabled();
    assertForTesting(type == LINKER_IMPLEMENTATION_LEGACY
                     || type == LINKER_IMPLEMENTATION_MODERN);

    synchronized (sSingletonLock) {
        assertForTesting(sSingleton == null);

        if (type == LINKER_IMPLEMENTATION_MODERN) {
            sSingleton = ModernLinker.create();
        } else if (type == LINKER_IMPLEMENTATION_LEGACY) {
            sSingleton = LegacyLinker.create();
        }
        Log.i(TAG, "Forced linker: " + sSingleton.getClass().getName());
    }
}
 
Example 8
Project: chromium-net-for-android   File: Linker.java   View source code 6 votes vote down vote up
/**
 * Get Linker implementation type.
 * For testing.
 *
 * @return LINKER_IMPLEMENTATION_LEGACY or LINKER_IMPLEMENTATION_MODERN
 */
public final int getImplementationForTesting() {
    // Sanity check. This method may only be called during tests.
    assertLinkerTestsAreEnabled();

    synchronized (sSingletonLock) {
        assertForTesting(sSingleton == this);

        if (sSingleton instanceof ModernLinker) {
            return LINKER_IMPLEMENTATION_MODERN;
        } else if (sSingleton instanceof LegacyLinker) {
            return LINKER_IMPLEMENTATION_LEGACY;
        } else {
            Log.wtf(TAG, "Invalid linker: " + sSingleton.getClass().getName());
            assertForTesting(false);
        }
        return 0;
    }
}
 
Example 9
Project: chromium-net-for-android   File: Linker.java   View source code 6 votes vote down vote up
/**
 * Set up the Linker for a test.
 * Convenience function that calls setImplementationForTesting() to force an
 * implementation, and then setTestRunnerClassNameForTesting() to set the test
 * class name.
 *
 * On first call, instantiates a Linker of the requested type and sets its test
 * runner class name. On subsequent calls, checks that the singleton produced by
 * the first call matches the requested type and test runner class name.
 */
public static final void setupForTesting(int type, String testRunnerClassName) {
    if (DEBUG) {
        Log.i(TAG, "setupForTesting(" + type + ", " + testRunnerClassName + ") called");
    }
    // Sanity check. This method may only be called during tests.
    assertLinkerTestsAreEnabled();

    synchronized (sSingletonLock) {
        // If this is the first call, configure the Linker to the given type and test class.
        if (sSingleton == null) {
            setImplementationForTesting(type);
            sSingleton.setTestRunnerClassNameForTesting(testRunnerClassName);
            return;
        }

        // If not the first call, check that the Linker configuration matches this request.
        assertForTesting(sSingleton.getImplementationForTesting() == type);
        String ourTestRunnerClassName = sSingleton.getTestRunnerClassNameForTesting();
        if (testRunnerClassName == null) {
            assertForTesting(ourTestRunnerClassName == null);
        } else {
            assertForTesting(ourTestRunnerClassName.equals(testRunnerClassName));
        }
    }
}
 
Example 10
Project: chromium-for-android-56-debug-video   File: UpdateMenuItemHelper.java   View source code 6 votes vote down vote up
/**
 * Handles a click on the update menu item.
 * @param activity The current {@link ChromeActivity}.
 */
public void onMenuItemClicked(ChromeActivity activity) {
    if (mUpdateUrl == null) return;

    // If the update menu item is showing because it was forced on through about://flags
    // then mLatestVersion may be null.
    if (mLatestVersion != null) {
        PrefServiceBridge.getInstance().setLatestVersionWhenClickedUpdateMenuItem(
                mLatestVersion);
    }

    // Fire an intent to open the URL.
    try {
        Intent launchIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mUpdateUrl));
        activity.startActivity(launchIntent);
        recordItemClickedHistogram(ITEM_CLICKED_INTENT_LAUNCHED);
        PrefServiceBridge.getInstance().setClickedUpdateMenuItem(true);
    } catch (ActivityNotFoundException e) {
        Log.e(TAG, "Failed to launch Activity for: %s", mUpdateUrl);
        recordItemClickedHistogram(ITEM_CLICKED_INTENT_FAILED);
    }
}
 
Example 11
Project: chromium-net-for-android   File: Linker.java   View source code 6 votes vote down vote up
/**
 * Obtain a random base load address at which to place loaded libraries.
 *
 * @return new base load address
 */
protected long getRandomBaseLoadAddress() {
    // nativeGetRandomBaseLoadAddress() returns an address at which it has previously
    // successfully mapped an area larger than the largest library we expect to load,
    // on the basis that we will be able, with high probability, to map our library
    // into it.
    //
    // One issue with this is that we do not yet know the size of the library that
    // we will load is. If it is smaller than the size we used to obtain a random
    // address the library mapping may still succeed. The other issue is that
    // although highly unlikely, there is no guarantee that something else does not
    // map into the area we are going to use between here and when we try to map into it.
    //
    // The above notes mean that all of this is probablistic. It is however okay to do
    // because if, worst case and unlikely, we get unlucky in our choice of address,
    // the back-out and retry without the shared RELRO in the ChildProcessService will
    // keep things running.
    final long address = nativeGetRandomBaseLoadAddress();
    if (DEBUG) {
        Log.i(TAG, String.format(Locale.US, "Random native base load address: 0x%x", address));
    }
    return address;
}
 
Example 12
Project: chromium-net-for-android   File: LegacyLinker.java   View source code 6 votes vote down vote up
/**
 * Call this method just before loading any native shared libraries in this process.
 */
@Override
public void prepareLibraryLoad() {
    if (DEBUG) {
        Log.i(TAG, "prepareLibraryLoad() called");
    }
    synchronized (mLock) {
        ensureInitializedLocked();
        mPrepareLibraryLoadCalled = true;

        if (mInBrowserProcess) {
            // Force generation of random base load address, as well
            // as creation of shared RELRO sections in this process.
            setupBaseLoadAddressLocked();
        }
    }
}
 
Example 13
Project: chromium-for-android-56-debug-video   File: PwsClientImpl.java   View source code 6 votes vote down vote up
private static Collection<PwsResult> parseResolveScanResponse(JSONObject result) {
    // Get the metadata array.
    Collection<PwsResult> pwsResults = new ArrayList<>();
    JSONArray metadata = result.optJSONArray("results");
    if (metadata == null) {
        // There are no valid results.
        return pwsResults;
    }

    // Loop through the metadata for each url.
    for (int i = 0; i < metadata.length(); i++) {
        try {
            pwsResults.add(PwsResult.jsonDeserialize(metadata.getJSONObject(i)));
        } catch (JSONException e) {
            Log.e(TAG, "PWS returned invalid data", e);
            continue;
        }
    }
    return pwsResults;
}
 
Example 14
Project: chromium-net-for-android   File: ModernLinker.java   View source code 6 votes vote down vote up
/**
 * Call this method just after loading all native shared libraries in this process.
 * If not in the browser, closes the LibInfo entries used for RELRO sharing.
 */
@Override
public void finishLibraryLoad() {
    if (DEBUG) {
        Log.i(TAG, "finishLibraryLoad() called");
    }

    synchronized (mLock) {
        assert mPrepareLibraryLoadCalled;

        // Close shared RELRO file descriptors if not in the browser.
        if (!mInBrowserProcess && mSharedRelros != null) {
            closeLibInfoMap(mSharedRelros);
            mSharedRelros = null;
        }

        // If testing, run tests now that all libraries are loaded and initialized.
        if (NativeLibraries.sEnableLinkerTests) {
            runTestRunnerClassForTesting(0, mInBrowserProcess);
        }
    }
}
 
Example 15
Project: chromium-for-android-56-debug-video   File: SigninManager.java   View source code 6 votes vote down vote up
/**
 * Signs out of Chrome.
 * <p/>
 * This method clears the signed-in username, stops sync and sends out a
 * sign-out notification on the native side.
 *
 * @param callback Will be invoked after signout completes, if not null.
 * @param wipeDataHooks Hooks to call during data wiping in case the account is managed.
 */
public void signOut(Runnable callback, WipeDataHooks wipeDataHooks) {
    mSignOutInProgress = true;
    mSignOutCallback = callback;

    boolean wipeData = getManagementDomain() != null;
    Log.d(TAG, "Signing out, wipe data? " + wipeData);

    // Native signout must happen before resetting the account so data is deleted correctly.
    // http://crbug.com/589028
    nativeSignOut(mNativeSigninManagerAndroid);
    ChromeSigninController.get(mContext).setSignedInAccountName(null);
    AndroidSyncSettings.updateAccount(mContext, null);

    if (wipeData) {
        wipeProfileData(wipeDataHooks);
    } else {
        onSignOutDone();
    }

    AccountTrackerService.get(mContext).invalidateAccountSeedStatus(true);
}
 
Example 16
Project: chromium-for-android-56-debug-video   File: VrShellDelegate.java   View source code 6 votes vote down vote up
private boolean isVrCoreCompatible() {
    if (mVrCoreVersionChecker != null) {
        return mVrCoreVersionChecker.isVrCoreCompatible();
    }

    if (mVrCoreVersionCheckerClass == null) {
        return false;
    }

    try {
        Constructor<?> mVrCoreVersionCheckerConstructor =
                mVrCoreVersionCheckerClass.getConstructor();
        mVrCoreVersionChecker =
                (VrCoreVersionChecker) mVrCoreVersionCheckerConstructor.newInstance();
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException e) {
        Log.d(TAG, "Unable to instantiate VrCoreVersionChecker", e);
        return false;
    }
    return mVrCoreVersionChecker.isVrCoreCompatible();
}
 
Example 17
Project: chromium-for-android-56-debug-video   File: LogcatExtractionCallable.java   View source code 6 votes vote down vote up
@VisibleForTesting
protected List<String> getLogcat() throws IOException, InterruptedException {
    // Grab the last lines of the logcat output, with a generous buffer to compensate for any
    // microdumps that might be in the logcat output, since microdumps are stripped in the
    // extraction code. Note that the repeated check of the process exit value is to account for
    // the fact that the process might not finish immediately.  And, it's not appropriate to
    // call p.waitFor(), because this call will block *forever* if the process's output buffer
    // fills up.
    Process p = Runtime.getRuntime().exec("logcat -d");
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    LinkedList<String> rawLogcat = new LinkedList<>();
    Integer exitValue = null;
    try {
        while (exitValue == null) {
            String logLn;
            while ((logLn = reader.readLine()) != null) {
                rawLogcat.add(logLn);
                if (rawLogcat.size() > LOGCAT_SIZE * 4) {
                    rawLogcat.removeFirst();
                }
            }

            try {
                exitValue = p.exitValue();
            } catch (IllegalThreadStateException itse) {
                Thread.sleep(HALF_SECOND);
            }
        }
    } finally {
        reader.close();
    }

    if (exitValue != 0) {
        String msg = "Logcat failed: " + exitValue;
        Log.w(TAG, msg);
        throw new IOException(msg);
    }

    return trimLogcat(rawLogcat, LOGCAT_SIZE);
}
 
Example 18
Project: chromium-for-android-56-debug-video   File: UrlManager.java   View source code 6 votes vote down vote up
/**
 * Remove a URL from the store of URLs.
 * This method additionally updates the Physical Web notification.
 * @param urlInfo The URL to remove.
 */
public void removeUrl(UrlInfo urlInfo) {
    Log.d(TAG, "URL lost: %s", urlInfo);
    recordUpdate();

    if (!mNearbyUrls.contains(urlInfo.getUrl())) {
        return;
    }

    mNearbyUrls.remove(urlInfo.getUrl());
    putCachedNearbyUrls();

    // If the URL was previously displayable (both nearby and resolved) and is now no longer
    // nearby, notify listeners that the URL is lost.
    if (mPwsResultMap.containsKey(urlInfo.getUrl())) {
        safeNotifyNativeListenersOnLost(urlInfo.getUrl());
    }

    // If there are no URLs nearby to display, clear the notification.
    if (getUrls(PhysicalWeb.isOnboarding()).isEmpty()) {
        clearNotification();
    }
}
 
Example 19
Project: chromium-for-android-56-debug-video   File: CustomTabsConnection.java   View source code 6 votes vote down vote up
/** Warmup activities that should only happen once. */
@SuppressFBWarnings("DM_EXIT")
private static void initializeBrowser(final Application app) {
    ThreadUtils.assertOnUiThread();
    try {
        ChromeBrowserInitializer.getInstance(app).handleSynchronousStartup();
    } catch (ProcessInitException e) {
        Log.e(TAG, "ProcessInitException while starting the browser process.");
        // Cannot do anything without the native library, and cannot show a
        // dialog to the user.
        System.exit(-1);
    }
    final Context context = app.getApplicationContext();
    final ChromeApplication chrome = (ChromeApplication) context;
    ChildProcessCreationParams.set(chrome.getChildProcessCreationParams());
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            ChildProcessLauncher.warmUp(context);
            return null;
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    ChromeBrowserInitializer.initNetworkChangeNotifier(context);
    WarmupManager.getInstance().initializeViewHierarchy(
            context, R.layout.custom_tabs_control_container, R.layout.custom_tabs_toolbar);
}
 
Example 20
Project: chromium-for-android-56-debug-video   File: ExternalAuthUtils.java   View source code 6 votes vote down vote up
/**
 * Same as {@link #canUseGooglePlayServices(Context, UserRecoverableErrorHandler)}.
 * @param context The current context.
 * @param errorHandler How to handle user-recoverable errors; must be non-null.
 * @return the result code specifying Google Play Services availability.
 */
public int canUseGooglePlayServicesResultCode(
        final Context context, final UserRecoverableErrorHandler errorHandler) {
    final int resultCode = checkGooglePlayServicesAvailable(context);
    recordConnectionResult(resultCode);
    if (resultCode != ConnectionResult.SUCCESS) {
        // resultCode is some kind of error.
        Log.v(TAG, "Unable to use Google Play Services: %s", describeError(resultCode));

        if (isUserRecoverableError(resultCode)) {
            Runnable errorHandlerTask = new Runnable() {
                @Override
                public void run() {
                    errorHandler.handleError(context, resultCode);
                }
            };
            ThreadUtils.runOnUiThread(errorHandlerTask);
        }
    }
    return resultCode;
}
 
Example 21
Project: chromium-for-android-56-debug-video   File: MediaCaptureNotificationService.java   View source code 6 votes vote down vote up
/**
 * Send an intent to MediaCaptureNotificationService to either create, update or destroy the
 * notification identified by tabId.
 * @param tabId Unique notification id.
 * @param mediaType The media type that is being captured.
 * @param fullUrl Url of the current webrtc call.
 */
public static void updateMediaNotificationForTab(
        Context context, int tabId, int mediaType, String fullUrl) {
    if (!shouldStartService(context, mediaType, tabId)) return;
    Intent intent = new Intent(context, MediaCaptureNotificationService.class);
    intent.setAction(ACTION_MEDIA_CAPTURE_UPDATE);
    intent.putExtra(NOTIFICATION_ID_EXTRA, tabId);
    String baseUrl = fullUrl;
    try {
        URL url = new URL(fullUrl);
        baseUrl = url.getProtocol() + "://" + url.getHost();
    } catch (MalformedURLException e) {
        Log.w(TAG, "Error parsing the webrtc url, %s ", fullUrl);
    }
    intent.putExtra(NOTIFICATION_MEDIA_URL_EXTRA, baseUrl);
    intent.putExtra(NOTIFICATION_MEDIA_TYPE_EXTRA, mediaType);
    context.startService(intent);
}
 
Example 22
Project: chromium-for-android-56-debug-video   File: PwsResult.java   View source code 6 votes vote down vote up
/**
 * Construct a PwsResult.
 */
PwsResult(String requestUrl, String siteUrl, String iconUrl, String title, String description,
            String groupId) {
    this.requestUrl = requestUrl;
    this.siteUrl = siteUrl;
    this.iconUrl = iconUrl;
    this.title = title;
    this.description = description;

    String groupIdToSet = groupId;
    if (groupId == null) {
        try {
            groupIdToSet = new URL(siteUrl).getHost() + title;
        } catch (MalformedURLException e) {
            Log.e(TAG, "PwsResult created with a malformed URL", e);
            groupIdToSet = siteUrl + title;
        }
    }
    this.groupId = groupIdToSet;
}
 
Example 23
Project: chromium-for-android-56-debug-video   File: ChromeWebApkHost.java   View source code 6 votes vote down vote up
/**
 * Once native is loaded we can consult the command-line (set via about:flags) and also finch
 * state to see if we should enable WebAPKs.
 */
public static void cacheEnabledStateForNextLaunch() {
    ChromePreferenceManager preferenceManager =
            ChromePreferenceManager.getInstance(ContextUtils.getApplicationContext());

    boolean wasCommandLineEnabled = preferenceManager.getCachedWebApkCommandLineEnabled();
    boolean isCommandLineEnabled = isCommandLineFlagSet();
    if (isCommandLineEnabled != wasCommandLineEnabled) {
        // {@link launchWebApkRequirementsDialogIfNeeded()} is skipped the first time Chrome is
        // launched so do caching here instead.
        preferenceManager.setCachedWebApkCommandLineEnabled(isCommandLineEnabled);
    }

    boolean wasEnabled = isEnabledInPrefs();
    boolean isEnabled = computeEnabled();
    if (isEnabled != wasEnabled) {
        Log.d(TAG, "WebApk setting changed (%s => %s)", wasEnabled, isEnabled);
        preferenceManager.setCachedWebApkRuntimeEnabled(isEnabled);
    }
}
 
Example 24
Project: chromium-for-android-56-debug-video   File: DefaultMediaRouteController.java   View source code 6 votes vote down vote up
/**
 * Send the given intent to the current route. The result will be returned in the given
 * ResultBundleHandler. This function will also check to see if the current route can handle the
 * intent before sending it.
 *
 * @param intent the intent to send to the current route.
 * @param bundleHandler contains the result of sending the intent
 */
private void sendIntentToRoute(final Intent intent, final ResultBundleHandler bundleHandler) {
    if (getCurrentRoute() == null) {
        logIntent("sendIntentToRoute ", intent);
        Log.d(TAG, "The current route is null.");
        if (bundleHandler != null) bundleHandler.onError(null, null);
        return;
    }

    if (!getCurrentRoute().supportsControlRequest(intent)) {
        logIntent("sendIntentToRoute ", intent);
        Log.d(TAG, "The intent is not supported by the route: %s", getCurrentRoute());
        if (bundleHandler != null) bundleHandler.onError(null, null);
        return;
    }

    sendControlIntent(intent, bundleHandler);
}
 
Example 25
Project: chromium-for-android-56-debug-video   File: PrecacheController.java   View source code 6 votes vote down vote up
@Override
public void onReceive(final Context context, Intent intent) {
    runOnInstanceThread(new Runnable() {
        @Override
        public void run() {
            Log.v(TAG, "conditions changed: precaching(%s), powered(%s), unmetered(%s)",
                    isPrecaching(), mDeviceState.isPowerConnected(context),
                    mDeviceState.isUnmeteredNetworkAvailable(context));
            if (isPrecaching()
                    && ((ChromeVersionInfo.isStableBuild()
                                && !mDeviceState.isPowerConnected(context))
                               || !mDeviceState.isUnmeteredNetworkAvailable(context))) {
                recordFailureReasons(context);
                cancelPrecaching(!mDeviceState.isUnmeteredNetworkAvailable(context)
                                ? PrecacheUMA.Event.PRECACHE_CANCEL_NO_UNMETERED_NETWORK
                                : PrecacheUMA.Event.PRECACHE_CANCEL_NO_POWER);
            }
        }
    });
}
 
Example 26
Project: chromium-for-android-56-debug-video   File: UrlManager.java   View source code 6 votes vote down vote up
/**
 * Adds a URL that has been resolved by the PWS.
 * @param pwsResult The meta data associated with the resolved URL.
 */
private void addResolvedUrl(PwsResult pwsResult) {
    Log.d(TAG, "PWS resolved: %s", pwsResult.requestUrl);
    if (mPwsResultMap.containsKey(pwsResult.requestUrl)) {
        return;
    }

    mPwsResultMap.put(pwsResult.requestUrl, pwsResult);
    putCachedPwsResultMap();

    if (!mNearbyUrls.contains(pwsResult.requestUrl)
            || !mUrlInfoMap.containsKey(pwsResult.requestUrl)) {
        return;
    }
    registerNewDisplayableUrl(mUrlInfoMap.get(pwsResult.requestUrl));
}
 
Example 27
Project: chromium-for-android-56-debug-video   File: SnippetsLauncher.java   View source code 5 votes vote down vote up
@CalledByNative
private boolean schedule(long periodWifiSeconds, long periodFallbackSeconds) {
    if (!mGCMEnabled) return false;
    Log.i(TAG, "Scheduling: " + periodWifiSeconds + " " + periodFallbackSeconds);

    boolean isScheduled = periodWifiSeconds != 0 || periodFallbackSeconds != 0;
    ContextUtils.getAppSharedPreferences()
            .edit()
            .putBoolean(PREF_IS_SCHEDULED, isScheduled)
            .apply();

    // Google Play Services may not be up to date, if the application was not installed through
    // the Play Store. In this case, scheduling the task will fail silently.
    try {
        mScheduler.cancelTask(OBSOLETE_TASK_TAG_WIFI_CHARGING, ChromeBackgroundService.class);
        scheduleOrCancelFetchTask(
                TASK_TAG_WIFI, periodWifiSeconds, Task.NETWORK_STATE_UNMETERED);
        scheduleOrCancelFetchTask(
                TASK_TAG_FALLBACK, periodFallbackSeconds, Task.NETWORK_STATE_CONNECTED);
        mScheduler.cancelTask(OBSOLETE_TASK_TAG_RESCHEDULE, ChromeBackgroundService.class);
    } catch (IllegalArgumentException e) {
        // Disable GCM for the remainder of this session.
        mGCMEnabled = false;

        ContextUtils.getAppSharedPreferences().edit().remove(PREF_IS_SCHEDULED).apply();
        // Return false so that the failure will be logged.
        return false;
    }
    return true;
}
 
Example 28
Project: chromium-for-android-56-debug-video   File: DocumentModeAssassin.java   View source code 5 votes vote down vote up
/** Deletes all remnants of the document mode directory and preferences. */
final void deleteDocumentModeData() {
    ThreadUtils.assertOnUiThread();
    if (!setStage(STAGE_CHANGE_SETTINGS_DONE, STAGE_DELETION_STARTED)) return;

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            Log.d(TAG, "Starting to delete document mode data.");

            // Delete the old tab state directory.
            FileUtils.recursivelyDeleteFile(getDocumentDataDirectory());

            // Clean up the {@link DocumentTabModel} shared preferences.
            SharedPreferences prefs = getContext().getSharedPreferences(
                    DocumentTabModelImpl.PREF_PACKAGE, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.clear();
            editor.apply();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.d(TAG, "Finished deleting document mode data.");
            setStage(STAGE_DELETION_STARTED, STAGE_DONE);
        }
    }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
 
Example 29
Project: chromium-for-android-56-debug-video   File: MinidumpPreparationService.java   View source code 5 votes vote down vote up
private void handleMinidumpPreparationRequest(Intent intent) {
    try {
        if (!createMinidumpPreparationCallable(getApplicationContext(), intent).call()) {
            Log.w(TAG, "Fail to prepare minidump with logcat!");
        }
    } catch (Exception e) {
        Log.w(TAG, e.toString());
    }
}
 
Example 30
Project: chromium-net-for-android   File: LibraryLoader.java   View source code 5 votes vote down vote up
/** Prefetches the native libraries in a background thread.
 *
 * Launches an AsyncTask that, through a short-lived forked process, reads a
 * part of each page of the native library.  This is done to warm up the
 * page cache, turning hard page faults into soft ones.
 *
 * This is done this way, as testing shows that fadvise(FADV_WILLNEED) is
 * detrimental to the startup time.
 */
public void asyncPrefetchLibrariesToMemory() {
    final boolean coldStart = mPrefetchLibraryHasBeenCalled.compareAndSet(false, true);
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            TraceEvent.begin("LibraryLoader.asyncPrefetchLibrariesToMemory");
            int percentage = nativePercentageOfResidentNativeLibraryCode();
            boolean success = false;
            // Arbitrary percentage threshold. If most of the native library is already
            // resident (likely with monochrome), don't bother creating a prefetch process.
            boolean prefetch = coldStart && percentage < 90;
            if (prefetch) {
                success = nativeForkAndPrefetchNativeLibrary();
                if (!success) {
                    Log.w(TAG, "Forking a process to prefetch the native library failed.");
                }
            }
            // As this runs in a background thread, it can be called before histograms are
            // initialized. In this instance, histograms are dropped.
            RecordHistogram.initialize();
            if (prefetch) {
                RecordHistogram.recordBooleanHistogram("LibraryLoader.PrefetchStatus", success);
            }
            if (percentage != -1) {
                String histogram = "LibraryLoader.PercentageOfResidentCodeBeforePrefetch"
                        + (coldStart ? ".ColdStartup" : ".WarmStartup");
                RecordHistogram.recordPercentageHistogram(histogram, percentage);
            }
            TraceEvent.end("LibraryLoader.asyncPrefetchLibrariesToMemory");
            return null;
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example 31
Project: chromium-for-android-56-debug-video   File: OmahaClient.java   View source code 5 votes vote down vote up
/**
 * Sets up a timer to fire after each interval.
 * Override to prevent a real alarm from being set.
 */
@VisibleForTesting
protected void setAlarm(AlarmManager am, PendingIntent operation, int alarmType,
        long triggerAtTime) {
    try {
        am.setRepeating(AlarmManager.RTC, triggerAtTime, MS_BETWEEN_REQUESTS, operation);
    } catch (SecurityException e) {
        Log.e(TAG, "Failed to set repeating alarm.");
    }
}
 
Example 32
Project: chromium-net-for-android   File: Linker.java   View source code 5 votes vote down vote up
/**
 * Set the TestRunner by its class name. It will be instantiated at
 * runtime after all libraries are loaded.
 *
 * @param testRunnerClassName null or a String for the class name of the
 * TestRunner to use.
 */
public final void setTestRunnerClassNameForTesting(String testRunnerClassName) {
    if (DEBUG) {
        Log.i(TAG, "setTestRunnerClassNameForTesting(" + testRunnerClassName + ") called");
    }
    // Sanity check. This method may only be called during tests.
    assertLinkerTestsAreEnabled();

    synchronized (mLock) {
        assertForTesting(mTestRunnerClassName == null);
        mTestRunnerClassName = testRunnerClassName;
    }
}
 
Example 33
Project: chromium-net-for-android   File: Linker.java   View source code 5 votes vote down vote up
/**
 * Load the Linker JNI library. Throws UnsatisfiedLinkError on error.
 * In a component build, the suffix ".cr" is added to each library name, so
 * if the initial load fails we retry with a suffix.
 */
protected static void loadLinkerJniLibrary() {
    String libName = "lib" + LINKER_JNI_LIBRARY + ".so";
    if (DEBUG) {
        Log.i(TAG, "Loading " + libName);
    }
    try {
        System.loadLibrary(LINKER_JNI_LIBRARY);
    } catch (UnsatisfiedLinkError e) {
        Log.w(TAG, "Couldn't load " + libName + ", trying " + libName + ".cr");
        System.loadLibrary(LINKER_JNI_LIBRARY + ".cr");
    }
}
 
Example 34
Project: chromium-for-android-56-debug-video   File: VrShellDelegate.java   View source code 5 votes vote down vote up
@CalledByNative
private void presentRequested() {
    // TODO(mthiesse): There's a GVR bug where they're not calling us back with the intent we
    // ask them to when we call DaydreamApi#launchInVr. As a temporary hack, remember locally
    // that we want to enter webVR.
    mRequestedWebVR = true;
    switch (enterVRIfNecessary()) {
        case ENTER_VR_NOT_NECESSARY:
            mVrShell.setWebVrModeEnabled(true);
            nativeSetPresentResult(mNativeVrShellDelegate, true);
            mRequestedWebVR = false;
            break;
        case ENTER_VR_CANCELLED:
            nativeSetPresentResult(mNativeVrShellDelegate, false);
            mRequestedWebVR = false;
            break;
        case ENTER_VR_REQUESTED:
            break;
        case ENTER_VR_SUCCEEDED:
            mVrShell.setWebVrModeEnabled(true);
            nativeSetPresentResult(mNativeVrShellDelegate, true);
            mRequestedWebVR = false;
            break;
        default:
            Log.e(TAG, "Unexpected enum.");
    }
}
 
Example 35
Project: chromium-net-for-android   File: Linker.java   View source code 5 votes vote down vote up
public void close() {
    if (mRelroFd >= 0) {
        try {
            ParcelFileDescriptor.adoptFd(mRelroFd).close();
        } catch (java.io.IOException e) {
            if (DEBUG) {
                Log.e(TAG, "Failed to close fd: " + mRelroFd);
            }
        }
        mRelroFd = -1;
    }
}
 
Example 36
Project: chromium-net-for-android   File: LegacyLinker.java   View source code 5 votes vote down vote up
/**
 * Call this method before loading any libraries to indicate that this
 * process shall neither create or reuse shared RELRO sections.
 */
@Override
public void disableSharedRelros() {
    if (DEBUG) {
        Log.i(TAG, "disableSharedRelros() called");
    }
    synchronized (mLock) {
        ensureInitializedLocked();
        mInBrowserProcess = false;
        mWaitForSharedRelros = false;
        mBrowserUsesSharedRelro = false;
    }
}
 
Example 37
Project: chromium-for-android-56-debug-video   File: DelayedInvalidationsController.java   View source code 5 votes vote down vote up
private static boolean isManualRequest(Bundle extras) {
    if (extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false)) {
        Log.d(TAG, "Manual sync requested.");
        return true;
    }
    return false;
}
 
Example 38
Project: chromium-for-android-56-debug-video   File: PrecacheController.java   View source code 5 votes vote down vote up
/**
 * Sets whether or not precaching is enabled. If precaching is enabled, a
 * periodic precaching task will be scheduled to run. If disabled, any
 * running precache session will be stopped, and all tasks canceled.
 */
public static void setIsPrecachingEnabled(Context context, boolean enabled) {
    boolean cancelRequired = !enabled && PrecacheController.hasInstance();
    Context appContext = context.getApplicationContext();

    SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences();
    if (sharedPreferences.getBoolean(PREF_IS_PRECACHING_ENABLED, !enabled) == enabled) {
        return;
    }

    Log.v(TAG, "setting precache enabled to %s", enabled);
    sharedPreferences.edit().putBoolean(PREF_IS_PRECACHING_ENABLED, enabled).apply();

    if (enabled) {
        if (!schedulePeriodicPrecacheTask(appContext)) {
            // Clear the preference, for the task to be scheduled next time.
            sharedPreferences.edit().putBoolean(PREF_IS_PRECACHING_ENABLED, false).apply();
            PrecacheUMA.record(PrecacheUMA.Event.PERIODIC_TASK_SCHEDULE_STARTUP_FAIL);
        } else {
            PrecacheUMA.record(PrecacheUMA.Event.PERIODIC_TASK_SCHEDULE_STARTUP);
        }
    } else {
        // If precaching, stop.
        cancelPeriodicPrecacheTask(appContext);
        cancelPrecacheCompletionTask(appContext);
    }
    if (cancelRequired) {
        sInstance.cancelPrecaching(PrecacheUMA.Event.PRECACHE_CANCEL_DISABLED_PREF);
    }
}
 
Example 39
Project: chromium-for-android-56-debug-video   File: ContextReporter.java   View source code 5 votes vote down vote up
/**
 * Creates a ContextReporter for an Activity.
 * @param activity Chrome Activity which context will be reported.
 * @param controller used to communicate with GSA
 */
public ContextReporter(ChromeActivity activity, GSAContextReportDelegate controller) {
    mActivity = activity;
    mDelegate = controller;
    mContextInUse = new AtomicBoolean(false);
    Log.d(TAG, "Created a new ContextReporter");
}
 
Example 40
Project: chromium-net-for-android   File: AndroidKeyStore.java   View source code 5 votes vote down vote up
/**
 * Returns the 'order' parameter of a given ECDSA private key as a
 * a byte buffer.
 * @param privateKey A PrivateKey instance. Must implement ECKey.
 * @return A byte buffer corresponding to the 'order' parameter.
 * This is a big-endian representation of a BigInteger.
 */
@CalledByNative
private static byte[] getECKeyOrder(PrivateKey privateKey) {
    if (privateKey instanceof ECKey) {
        ECParameterSpec params = ((ECKey) privateKey).getParams();
        return params.getOrder().toByteArray();
    }
    Log.w(TAG, "Not an ECKey instance!");
    return null;
}