Java Code Examples for org.chromium.base.annotations.CalledByNative

The following examples show how to use org.chromium.base.annotations.CalledByNative. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@SuppressWarnings("unused")
@CalledByNative
private String[] onHostResolve(String hostname) {
    String[] ips = null;
    if (mHostResolver != null) {
        try {
            List<InetAddress> ipList = mHostResolver.resolve(hostname);
            if (ipList != null && ipList.size() > 0) {
                ips = new String[ipList.size()];
                for (int i = 0; i < ipList.size(); ++i) {
                    InetAddress ipAddr = ipList.get(i);
                    ips[i] = ipAddr.getHostAddress();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (ips == null) {
        ips = new String[0];
    }
    return ips;
}
 
Example 2
@SuppressWarnings("unused")
@CalledByNative
private void onRttObservation(final int rttMs, final long whenMs, final int source) {
    synchronized (mNetworkQualityLock) {
        for (final VersionSafeCallbacks.NetworkQualityRttListenerWrapper listener :
                mRttListenerList) {
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    listener.onRttObservation(rttMs, whenMs, source);
                }
            };
            postObservationTaskToExecutor(listener.getExecutor(), task);
        }
    }
}
 
Example 3
/**
 * Registers the single thread-safe native activity status listener.
 * This handles the case where the caller is not on the main thread.
 * Note that this is used by a leaky singleton object from the native
 * side, hence lifecycle management is greatly simplified.
 */
@CalledByNative
private static void registerThreadSafeNativeApplicationStateListener() {
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (sNativeApplicationStateListener != null) return;

            sNativeApplicationStateListener = new ApplicationStateListener() {
                @Override
                public void onApplicationStateChange(int newState) {
                    nativeOnApplicationStateChange(newState);
                }
            };
            registerApplicationStateListener(sNativeApplicationStateListener);
        }
    });
}
 
Example 4
/**
 * Check whether a content URI exists.
 *
 * @param uriString the content URI to query.
 * @return true if the URI exists, or false otherwise.
 */
@CalledByNative
public static boolean contentUriExists(String uriString) {
    AssetFileDescriptor asf = null;
    try {
        asf = getAssetFileDescriptor(uriString);
        return asf != null;
    } finally {
        // Do not use StreamUtil.closeQuietly here, as AssetFileDescriptor
        // does not implement Closeable until KitKat.
        if (asf != null) {
            try {
                asf.close();
            } catch (IOException e) {
                // Closing quietly.
            }
        }
    }
}
 
Example 5
/**
 * Called from native library to ensure that library is initialized.
 * May be called on any thread, but initialization is performed on
 * this.sInitThread.
 *
 * Expects that ContextUtils.initApplicationContext() was called already
 * either by some testing framework or an embedder constructing a Java
 * CronetEngine via CronetEngine.Builder.build().
 *
 * TODO(mef): In the long term this should be changed to some API with
 * lower overhead like CronetEngine.Builder.loadNativeCronet().
 */
@CalledByNative
private static void ensureInitializedFromNative() {
    // Called by native, so native library is already loaded.
    // It is possible that loaded native library is not regular
    // "libcronet.xyz.so" but test library that statically links
    // native code like "libcronet_unittests.so".
    synchronized (sLoadLock) {
        sLibraryLoaded = true;
        sWaitForLibLoad.open();
    }

    // The application context must already be initialized
    // using ContextUtils.initApplicationContext().
    Context applicationContext = ContextUtils.getApplicationContext();
    assert applicationContext != null;
    ensureInitialized(applicationContext, null);
}
 
Example 6
@SuppressWarnings("unused")
@CalledByNative
private void onThroughputObservation(
        final int throughputKbps, final long whenMs, final int source) {
    synchronized (mNetworkQualityLock) {
        for (final VersionSafeCallbacks.NetworkQualityThroughputListenerWrapper listener :
                mThroughputListenerList) {
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    listener.onThroughputObservation(throughputKbps, whenMs, source);
                }
            };
            postObservationTaskToExecutor(listener.getExecutor(), task);
        }
    }
}
 
Example 7
/**
 * Returns true if the system's captive portal probe was blocked for the current default data
 * network. The method will return false if the captive portal probe was not blocked, the login
 * process to the captive portal has been successfully completed, or if the captive portal
 * status can't be determined. Requires ACCESS_NETWORK_STATE permission. Only available on
 * Android Marshmallow and later versions. Returns false on earlier versions.
 */
@TargetApi(Build.VERSION_CODES.M)
@CalledByNative
private static boolean getIsCaptivePortal() {
    // NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL is only available on Marshmallow and
    // later versions.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;
    ConnectivityManager connectivityManager =
            (ConnectivityManager) ContextUtils.getApplicationContext().getSystemService(
                    Context.CONNECTIVITY_SERVICE);
    if (connectivityManager == null) return false;

    Network network = ApiHelperForM.getActiveNetwork(connectivityManager);
    if (network == null) return false;

    NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
    return capabilities != null
            && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL);
}
 
Example 8
Source Project: cronet   Source File: NetStringUtil.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Convert text in a given character set to a Unicode string.  Any invalid
 * characters are replaced with U+FFFD.  Returns null if the character set
 * is not recognized.
 * @param text ByteBuffer containing the character array to convert.
 * @param charsetName Character set it's in encoded in.
 * @return: Unicode string on success, null on failure.
 */
@CalledByNative
private static String convertToUnicodeWithSubstitutions(
        ByteBuffer text,
        String charsetName) {
    try {
        Charset charset = Charset.forName(charsetName);

        // TODO(mmenke):  Investigate if Charset.decode() can be used
        // instead.  The question is whether it uses the proper replace
        // character.  JDK CharsetDecoder docs say U+FFFD is the default,
        // but Charset.decode() docs say it uses the "charset's default
        // replacement byte array".
        CharsetDecoder decoder = charset.newDecoder();
        decoder.onMalformedInput(CodingErrorAction.REPLACE);
        decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
        decoder.replaceWith("\uFFFD");
        return decoder.decode(text).toString();
    } catch (Exception e) {
        return null;
    }
}
 
Example 9
/**
 * Called by the native code on the network thread to report metrics. Happens before
 * onSucceeded, onError and onCanceled.
 */
@SuppressWarnings("unused")
@CalledByNative
private void onMetricsCollected(long requestStartMs, long dnsStartMs, long dnsEndMs,
        long connectStartMs, long connectEndMs, long sslStartMs, long sslEndMs,
        long sendingStartMs, long sendingEndMs, long pushStartMs, long pushEndMs,
        long responseStartMs, long requestEndMs, boolean socketReused, long sentByteCount,
        long receivedByteCount) {
    synchronized (mUrlRequestAdapterLock) {
        if (mMetrics != null) {
            throw new IllegalStateException("Metrics collection should only happen once.");
        }
        mMetrics = new CronetMetrics(requestStartMs, dnsStartMs, dnsEndMs, connectStartMs,
                connectEndMs, sslStartMs, sslEndMs, sendingStartMs, sendingEndMs, pushStartMs,
                pushEndMs, responseStartMs, requestEndMs, socketReused, sentByteCount,
                receivedByteCount);
    }
    // Metrics are reported to RequestFinishedListener when the final UrlRequest.Callback has
    // been invoked.
}
 
Example 10
/**
 * Called by native code to make the UploadDataProvider rewind upload data.
 */
@SuppressWarnings("unused")
@CalledByNative
void rewind() {
    Runnable task = new Runnable() {
        @Override
        public void run() {
            synchronized (mLock) {
                if (mUploadDataStreamAdapter == 0) {
                    return;
                }
                checkState(UserCallback.NOT_IN_CALLBACK);
                mInWhichUserCallback = UserCallback.REWIND;
            }
            try {
                checkCallingThread();
                mDataProvider.rewind(CronetUploadDataStream.this);
            } catch (Exception exception) {
                onError(exception);
            }
        }
    };
    postTaskToExecutor(task);
}
 
Example 11
@SuppressWarnings("unused")
@CalledByNative
private void onResponseTrailersReceived(String[] trailers) {
    final UrlResponseInfo.HeaderBlock trailersBlock =
            new UrlResponseInfoImpl.HeaderBlockImpl(headersListFromStrings(trailers));
    postTaskToExecutor(new Runnable() {
        @Override
        public void run() {
            synchronized (mNativeStreamLock) {
                if (isDoneLocked()) {
                    return;
                }
            }
            try {
                mCallback.onResponseTrailersReceived(
                        CronetBidirectionalStream.this, mResponseInfo, trailersBlock);
            } catch (Exception e) {
                onCallbackException(e);
            }
        }
    });
}
 
Example 12
/**
 * Called when request is completed successfully, no callbacks will be
 * called afterwards.
 *
 * @param receivedByteCount number of bytes received.
 */
@SuppressWarnings("unused")
@CalledByNative
private void onSucceeded(long receivedByteCount) {
    mResponseInfo.setReceivedByteCount(receivedByteCount);
    Runnable task = new Runnable() {
        @Override
        public void run() {
            synchronized (mUrlRequestAdapterLock) {
                if (isDoneLocked()) {
                    return;
                }
                // Destroy adapter first, so request context could be shut
                // down from the listener.
                destroyRequestAdapterLocked(RequestFinishedInfo.SUCCEEDED);
            }
            try {
                mCallback.onSucceeded(CronetUrlRequest.this, mResponseInfo);
                maybeReportMetrics();
            } catch (Exception e) {
                Log.e(CronetUrlRequestContext.LOG_TAG, "Exception in onSucceeded method", e);
            }
        }
    };
    postTaskToExecutor(task);
}
 
Example 13
/**
 * Called when request is canceled, no callbacks will be called afterwards.
 */
@SuppressWarnings("unused")
@CalledByNative
private void onCanceled() {
    Runnable task = new Runnable() {
        @Override
        public void run() {
            try {
                mCallback.onCanceled(CronetUrlRequest.this, mResponseInfo);
                maybeReportMetrics();
            } catch (Exception e) {
                Log.e(CronetUrlRequestContext.LOG_TAG, "Exception in onCanceled method", e);
            }
        }
    };
    postTaskToExecutor(task);
}
 
Example 14
Source Project: cronet   Source File: JNIUtils.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @return whether or not the current process supports selective JNI registration.
 */
@CalledByNative
public static boolean isSelectiveJniRegistrationEnabled() {
    if (sSelectiveJniRegistrationEnabled == null) {
        sSelectiveJniRegistrationEnabled = false;
    }
    return sSelectiveJniRegistrationEnabled;
}
 
Example 15
Source Project: cronet   Source File: BuildInfo.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@CalledByNative
private static String[] getAll() {
    BuildInfo buildInfo = getInstance();
    String hostPackageName = ContextUtils.getApplicationContext().getPackageName();
    return new String[] {
            Build.BRAND, Build.DEVICE, Build.ID, Build.MANUFACTURER, Build.MODEL,
            String.valueOf(Build.VERSION.SDK_INT), Build.TYPE, Build.BOARD, hostPackageName,
            String.valueOf(buildInfo.hostVersionCode), buildInfo.hostPackageLabel,
            buildInfo.packageName, String.valueOf(buildInfo.versionCode), buildInfo.versionName,
            buildInfo.androidBuildFingerprint, buildInfo.gmsVersionCode,
            buildInfo.installerPackageName, buildInfo.abiString, BuildConfig.FIREBASE_APP_ID,
            buildInfo.customThemes, buildInfo.resourcesVersion, buildInfo.extractedFileSuffix,
    };
}
 
Example 16
Source Project: cronet   Source File: PathUtils.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @return Download directories including the default storage directory on SD card, and a
 * private directory on external SD card.
 */
@SuppressWarnings("unused")
@CalledByNative
public static String[] getAllPrivateDownloadsDirectories() {
    File[] files;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        StrictModeContext unused = null;
        try {
            unused = StrictModeContext.allowDiskWrites();
            files = ContextUtils.getApplicationContext().getExternalFilesDirs(
                    Environment.DIRECTORY_DOWNLOADS);
        } finally {
            if (unused != null) {
                try {
                    unused.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    } else {
        files = new File[] {Environment.getExternalStorageDirectory()};
    }

    ArrayList<String> absolutePaths = new ArrayList<String>();
    for (int i = 0; i < files.length; ++i) {
        if (files[i] == null || TextUtils.isEmpty(files[i].getAbsolutePath())) continue;
        absolutePaths.add(files[i].getAbsolutePath());
    }

    return absolutePaths.toArray(new String[absolutePaths.size()]);
}
 
Example 17
Source Project: cronet   Source File: PathUtils.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @return the path to native libraries.
 */
@SuppressWarnings("unused")
@CalledByNative
private static String getNativeLibraryDirectory() {
    ApplicationInfo ai = ContextUtils.getApplicationContext().getApplicationInfo();
    if ((ai.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0
            || (ai.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
        return ai.nativeLibraryDir;
    }

    return "/system/lib/";
}
 
Example 18
/**
 * @return The state of the application (see {@link ApplicationState}).
 */
@ApplicationState
@CalledByNative
public static int getStateForApplication() {
    synchronized (sCurrentApplicationStateLock) {
        return sCurrentApplicationState;
    }
}
 
Example 19
Source Project: cronet   Source File: ApkAssets.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@CalledByNative
public static long[] open(String fileName) {
    AssetFileDescriptor afd = null;
    try {
        AssetManager manager = ContextUtils.getApplicationContext().getAssets();
        afd = manager.openNonAssetFd(fileName);
        return new long[] {afd.getParcelFileDescriptor().detachFd(), afd.getStartOffset(),
                afd.getLength()};
    } catch (IOException e) {
        // As a general rule there's no point logging here because the caller should handle
        // receiving an fd of -1 sensibly, and the log message is either mirrored later, or
        // unwanted (in the case where a missing file is expected), or wanted but will be
        // ignored, as most non-fatal logs are.
        // It makes sense to log here when the file exists, but is unable to be opened as an fd
        // because (for example) it is unexpectedly compressed in an apk. In that case, the log
        // message might save someone some time working out what has gone wrong.
        // For that reason, we only suppress the message when the exception message doesn't look
        // informative (Android framework passes the filename as the message on actual file not
        // found, and the empty string also wouldn't give any useful information for debugging).
        if (!e.getMessage().equals("") && !e.getMessage().equals(fileName)) {
            Log.e(LOGTAG, "Error while loading asset " + fileName + ": " + e);
        }
        return new long[] {-1, -1, -1};
    } finally {
        try {
            if (afd != null) {
                afd.close();
            }
        } catch (IOException e2) {
            Log.e(LOGTAG, "Unable to close AssetFileDescriptor", e2);
        }
    }
}
 
Example 20
Source Project: cronet   Source File: TimezoneUtils.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @return the Olson timezone ID of the current system time zone.
 */
@CalledByNative
private static String getDefaultTimeZoneId() {
    // On Android N or earlier, getting the default timezone requires the disk
    // access when a device set up is skipped.
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    String timezoneID = TimeZone.getDefault().getID();
    StrictMode.setThreadPolicy(oldPolicy);
    return timezoneID;
}
 
Example 21
Source Project: cronet   Source File: LocaleUtils.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @return The default country code set during install.
 */
@CalledByNative
private static String getDefaultCountryCode() {
    CommandLine commandLine = CommandLine.getInstance();
    return commandLine.hasSwitch(BaseSwitches.DEFAULT_COUNTRY_CODE_AT_INSTALL)
            ? commandLine.getSwitchValue(BaseSwitches.DEFAULT_COUNTRY_CODE_AT_INSTALL)
            : Locale.getDefault().getCountry();
}
 
Example 22
/**
 * Opens the content URI for reading, and returns the file descriptor to
 * the caller. The caller is responsible for closing the file descriptor.
 *
 * @param uriString the content URI to open
 * @return file descriptor upon success, or -1 otherwise.
 */
@CalledByNative
public static int openContentUriForRead(String uriString) {
    AssetFileDescriptor afd = getAssetFileDescriptor(uriString);
    if (afd != null) {
        return afd.getParcelFileDescriptor().detachFd();
    }
    return -1;
}
 
Example 23
/**
 * Retrieve the MIME type for the content URI.
 *
 * @param uriString the content URI to look up.
 * @return MIME type or null if the input params are empty or invalid.
 */
@CalledByNative
public static String getMimeType(String uriString) {
    ContentResolver resolver = ContextUtils.getApplicationContext().getContentResolver();
    Uri uri = Uri.parse(uriString);
    if (isVirtualDocument(uri)) {
        String[] streamTypes = resolver.getStreamTypes(uri, "*/*");
        return (streamTypes != null && streamTypes.length > 0) ? streamTypes[0] : null;
    }
    return resolver.getType(uri);
}
 
Example 24
/**
* Called by the native code to report metrics just before the native adapter is destroyed.
*/
@SuppressWarnings("unused")
@CalledByNative
private void onMetricsCollected(long requestStartMs, long dnsStartMs, long dnsEndMs,
        long connectStartMs, long connectEndMs, long sslStartMs, long sslEndMs,
        long sendingStartMs, long sendingEndMs, long pushStartMs, long pushEndMs,
        long responseStartMs, long requestEndMs, boolean socketReused, long sentByteCount,
        long receivedByteCount) {
    synchronized (mNativeStreamLock) {
        if (mMetrics != null) {
            throw new IllegalStateException("Metrics collection should only happen once.");
        }
        mMetrics = new CronetMetrics(requestStartMs, dnsStartMs, dnsEndMs, connectStartMs,
                connectEndMs, sslStartMs, sslEndMs, sendingStartMs, sendingEndMs, pushStartMs,
                pushEndMs, responseStartMs, requestEndMs, socketReused, sentByteCount,
                receivedByteCount);
        assert mReadState == mWriteState;
        assert (mReadState == State.SUCCESS) || (mReadState == State.ERROR)
                || (mReadState == State.CANCELED);
        int finishedReason;
        if (mReadState == State.SUCCESS) {
            finishedReason = RequestFinishedInfo.SUCCEEDED;
        } else if (mReadState == State.CANCELED) {
            finishedReason = RequestFinishedInfo.CANCELED;
        } else {
            finishedReason = RequestFinishedInfo.FAILED;
        }
        final RequestFinishedInfo requestFinishedInfo = new RequestFinishedInfoImpl(mInitialUrl,
                mRequestAnnotations, mMetrics, finishedReason, mResponseInfo, mException);
        mRequestContext.reportFinished(requestFinishedInfo);
    }
}
 
Example 25
Source Project: cronet   Source File: TraceEvent.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Notification from native that tracing is enabled/disabled.
 */
@CalledByNative
public static void setEnabled(boolean enabled) {
    if (enabled) EarlyTraceEvent.disable();
    // Only disable logging if Chromium enabled it originally, so as to not disrupt logging done
    // by other applications
    if (sEnabled != enabled) {
        sEnabled = enabled;
        // Android M+ systrace logs this on its own. Only log it if not writing to Android
        // systrace.
        if (sATraceEnabled) return;
        ThreadUtils.getUiThreadLooper().setMessageLogging(
                enabled ? LooperMonitorHolder.sInstance : null);
    }
}
 
Example 26
@CalledByNative
private void startAndInitialize(final long nativeThread, final long nativeEvent) {
    maybeStart();
    new Handler(mThread.getLooper()).post(new Runnable() {
        @Override
        public void run() {
            nativeInitializeThread(nativeThread, nativeEvent);
        }
    });
}
 
Example 27
@CalledByNative
private void quitThreadSafely(final long nativeThread) {
    // Allow pending java tasks to run, but don't run any delayed or newly queued up tasks.
    new Handler(mThread.getLooper()).post(new Runnable() {
        @Override
        public void run() {
            mThread.quit();
            nativeOnLooperStopped(nativeThread);
        }
    });
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        // When we can, signal that new tasks queued up won't be run.
        mThread.getLooper().quitSafely();
    }
}
 
Example 28
@CalledByNative
private void listenForUncaughtExceptionsForTesting() {
    mThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            mUnhandledException = e;
        }
    });
}
 
Example 29
@CalledByNative
public byte[][] getCertificateChainEncoded() {
    byte[][] verifiedChainArray = new byte[mCertificateChain.size()][];
    try {
        for (int i = 0; i < mCertificateChain.size(); i++) {
            verifiedChainArray[i] = mCertificateChain.get(i).getEncoded();
        }
    } catch (CertificateEncodingException e) {
        return new byte[0][];
    }
    return verifiedChainArray;
}
 
Example 30
Source Project: cronet   Source File: PostTask.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@CalledByNative
private static void onNativeTaskSchedulerReady() {
    synchronized (sLock) {
        for (TaskRunner taskRunner : sPreNativeTaskRunners) {
            taskRunner.initNativeTaskRunner();
        }
        sPreNativeTaskRunners = null;
    }
}