org.chromium.base.annotations.CalledByNative Java Examples

The following examples show how to use org.chromium.base.annotations.CalledByNative. 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
Source File: CronetUrlRequest.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #2
Source File: CronetUrlRequest.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #3
Source File: ContentUriUtils.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #4
Source File: NetStringUtil.java    From cronet with 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 #5
Source File: CronetLibraryLoader.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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
Source File: CronetUrlRequestContext.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #7
Source File: CronetUploadDataStream.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #8
Source File: ApplicationStatus.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #9
Source File: CronetUrlRequestContext.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #10
Source File: CronetBidirectionalStream.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #11
Source File: CronetUrlRequest.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #12
Source File: CronetUrlRequestContext.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #13
Source File: AndroidNetworkLibrary.java    From cronet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #14
Source File: NetStringUtil.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Attempts to convert text in a given character set to a Unicode string.
 * Returns null on failure.
 * @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 convertToUnicode(
        ByteBuffer text,
        String charsetName) {
    try {
        Charset charset = Charset.forName(charsetName);
        CharsetDecoder decoder = charset.newDecoder();
        // On invalid characters, this will throw an exception.
        return decoder.decode(text).toString();
    } catch (Exception e) {
        return null;
    }
}
 
Example #15
Source File: JNIUtils.java    From cronet with 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 #16
Source File: AndroidNetworkLibrary.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the MCC+MNC (mobile country code + mobile network code) as
 * the numeric name of the current registered operator.
 */
@CalledByNative
private static String getNetworkOperator() {
    TelephonyManager telephonyManager =
            (TelephonyManager) ContextUtils.getApplicationContext().getSystemService(
                    Context.TELEPHONY_SERVICE);
    if (telephonyManager == null) return "";
    return telephonyManager.getNetworkOperator();
}
 
Example #17
Source File: JavaHandlerThread.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #18
Source File: NetStringUtil.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Convert a string to uppercase.
 * @param str String to convert.
 * @return: String converted to uppercase using default locale,
 * null on failure.
 */
@CalledByNative
private static String toUpperCase(String str) {
    try {
        return str.toUpperCase(Locale.getDefault());
    } catch (Exception e) {
        return null;
    }
}
 
Example #19
Source File: JavaHandlerThread.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@CalledByNative
private void listenForUncaughtExceptionsForTesting() {
    mThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            mUnhandledException = e;
        }
    });
}
 
Example #20
Source File: AndroidNetworkLibrary.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the MCC+MNC (mobile country code + mobile network code) as
 * the numeric name of the current SIM operator.
 */
@CalledByNative
private static String getSimOperator() {
    TelephonyManager telephonyManager =
            (TelephonyManager) ContextUtils.getApplicationContext().getSystemService(
                    Context.TELEPHONY_SERVICE);
    if (telephonyManager == null) return "";
    return telephonyManager.getSimOperator();
}
 
Example #21
Source File: HttpNegotiateAuthenticator.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @param nativeResultObject The C++ object used to return the result. For correct C++ memory
 *            management we must call nativeSetResult precisely once with this object.
 * @param principal The principal (must be host based).
 * @param authToken The incoming auth token.
 * @param canDelegate True if we can delegate.
 */
@VisibleForTesting
@CalledByNative
void getNextAuthToken(final long nativeResultObject, final String principal, String authToken,
        boolean canDelegate) {
    assert principal != null;

    Context applicationContext = ContextUtils.getApplicationContext();
    RequestData requestData = new RequestData();
    requestData.authTokenType = HttpNegotiateConstants.SPNEGO_TOKEN_TYPE_BASE + principal;
    requestData.accountManager = AccountManager.get(applicationContext);
    requestData.nativeResultObject = nativeResultObject;
    String features[] = {HttpNegotiateConstants.SPNEGO_FEATURE};

    requestData.options = new Bundle();
    if (authToken != null) {
        requestData.options.putString(
                HttpNegotiateConstants.KEY_INCOMING_AUTH_TOKEN, authToken);
    }
    if (mSpnegoContext != null) {
        requestData.options.putBundle(
                HttpNegotiateConstants.KEY_SPNEGO_CONTEXT, mSpnegoContext);
    }
    requestData.options.putBoolean(HttpNegotiateConstants.KEY_CAN_DELEGATE, canDelegate);

    Activity activity = ApplicationStatus.getLastTrackedFocusedActivity();
    if (activity == null) {
        requestTokenWithoutActivity(applicationContext, requestData, features);
    } else {
        requestTokenWithActivity(applicationContext, activity, requestData, features);
    }
}
 
Example #22
Source File: AndroidCertVerifyResult.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #23
Source File: NetStringUtil.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Attempts to convert text in a given character set to a Unicode string,
 * and normalize it.  Returns null on failure.
 * @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 convertToUnicodeAndNormalize(
        ByteBuffer text,
        String charsetName) {
    String unicodeString = convertToUnicode(text, charsetName);
    if (unicodeString == null) return null;
    return Normalizer.normalize(unicodeString, Normalizer.Form.NFC);
}
 
Example #24
Source File: CronetBidirectionalStream.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("unused")
@CalledByNative
private void onWritevCompleted(final ByteBuffer[] byteBuffers, int[] initialPositions,
        int[] initialLimits, boolean endOfStream) {
    assert byteBuffers.length == initialPositions.length;
    assert byteBuffers.length == initialLimits.length;
    synchronized (mNativeStreamLock) {
        if (isDoneLocked()) return;
        mWriteState = State.WAITING_FOR_FLUSH;
        // Flush if there is anything in the flush queue mFlushData.
        if (!mFlushData.isEmpty()) {
            sendFlushDataLocked();
        }
    }
    for (int i = 0; i < byteBuffers.length; i++) {
        ByteBuffer buffer = byteBuffers[i];
        if (buffer.position() != initialPositions[i] || buffer.limit() != initialLimits[i]) {
            failWithException(new CronetExceptionImpl(
                    "ByteBuffer modified externally during write", null));
            return;
        }
        // Current implementation always writes the complete buffer.
        buffer.position(buffer.limit());
        postTaskToExecutor(new OnWriteCompletedRunnable(buffer,
                // Only set endOfStream flag if this buffer is the last in byteBuffers.
                endOfStream && i == byteBuffers.length - 1));
    }
}
 
Example #25
Source File: CronetUrlRequestContext.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("unused")
@CalledByNative
private void onRTTOrThroughputEstimatesComputed(
        final int httpRttMs, final int transportRttMs, final int downstreamThroughputKbps) {
    synchronized (mNetworkQualityLock) {
        mHttpRttMs = httpRttMs;
        mTransportRttMs = transportRttMs;
        mDownstreamThroughputKbps = downstreamThroughputKbps;
    }
}
 
Example #26
Source File: IDNStringUtil.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Attempts to convert a Unicode string to an ASCII string using IDN rules.
 * As of May 2014, the underlying Java function IDNA2003.
 * @param src String to convert.
 * @return: String containing only ASCII characters on success, null on
 *                 failure.
 */
@CalledByNative
private static String idnToASCII(String src) {
    try {
        return IDN.toASCII(src, IDN.USE_STD3_ASCII_RULES);
    } catch (Exception e) {
        return null;
    }
}
 
Example #27
Source File: PostTask.java    From cronet with 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;
    }
}
 
Example #28
Source File: EarlyTraceEvent.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Sets the background startup tracing enabled in app preferences for next startup.
 */
@CalledByNative
static void setBackgroundStartupTracingFlag(boolean enabled) {
    ContextUtils.getAppSharedPreferences()
            .edit()
            .putBoolean(BACKGROUND_STARTUP_TRACING_ENABLED_KEY, enabled)
            .apply();
}
 
Example #29
Source File: CronetUrlRequestContext.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("unused")
@CalledByNative
private void onEffectiveConnectionTypeChanged(int effectiveConnectionType) {
    synchronized (mNetworkQualityLock) {
        // Convert the enum returned by the network quality estimator to an enum of type
        // EffectiveConnectionType.
        mEffectiveConnectionType = effectiveConnectionType;
    }
}
 
Example #30
Source File: PowerMonitor.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@CalledByNative
private static boolean isBatteryPower() {
    // Creation of the PowerMonitor can be deferred based on the browser startup path.  If the
    // battery power is requested prior to the browser triggering the creation, force it to be
    // created now.
    if (sInstance == null) create();

    return sInstance.mIsBatteryPower;
}