Search in sources :

Example 51 with VisibleForTesting

use of com.android.internal.annotations.VisibleForTesting in project android_frameworks_base by ResurrectionRemix.

the class CarrierAppUtils method disableCarrierAppsUntilPrivileged.

// Must be public b/c framework unit tests can't access package-private methods.
@VisibleForTesting
public static void disableCarrierAppsUntilPrivileged(String callingPackage, IPackageManager packageManager, @Nullable TelephonyManager telephonyManager, ContentResolver contentResolver, int userId, String[] systemCarrierAppsDisabledUntilUsed, ArrayMap<String, List<String>> systemCarrierAssociatedAppsDisabledUntilUsed) {
    List<ApplicationInfo> candidates = getDefaultCarrierAppCandidatesHelper(packageManager, userId, systemCarrierAppsDisabledUntilUsed);
    if (candidates == null || candidates.isEmpty()) {
        return;
    }
    Map<String, List<ApplicationInfo>> associatedApps = getDefaultCarrierAssociatedAppsHelper(packageManager, userId, systemCarrierAssociatedAppsDisabledUntilUsed);
    List<String> enabledCarrierPackages = new ArrayList<>();
    boolean hasRunOnce = Settings.Secure.getIntForUser(contentResolver, Settings.Secure.CARRIER_APPS_HANDLED, 0, userId) == 1;
    try {
        for (ApplicationInfo ai : candidates) {
            String packageName = ai.packageName;
            boolean hasPrivileges = telephonyManager != null && telephonyManager.checkCarrierPrivilegesForPackageAnyPhone(packageName) == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
            if (hasPrivileges) {
                // updated we shouldn't touch it.
                if (!ai.isUpdatedSystemApp() && (ai.enabledSetting == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT || ai.enabledSetting == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
                    Slog.i(TAG, "Update state(" + packageName + "): ENABLED for user " + userId);
                    packageManager.setApplicationEnabledSetting(packageName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP, userId, callingPackage);
                }
                // Also enable any associated apps for this carrier app.
                List<ApplicationInfo> associatedAppList = associatedApps.get(packageName);
                if (associatedAppList != null) {
                    for (ApplicationInfo associatedApp : associatedAppList) {
                        if (associatedApp.enabledSetting == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT || associatedApp.enabledSetting == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                            Slog.i(TAG, "Update associated state(" + associatedApp.packageName + "): ENABLED for user " + userId);
                            packageManager.setApplicationEnabledSetting(associatedApp.packageName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP, userId, callingPackage);
                        }
                    }
                }
                // Always re-grant default permissions to carrier apps w/ privileges.
                enabledCarrierPackages.add(ai.packageName);
            } else {
                // updated we shouldn't touch it.
                if (!ai.isUpdatedSystemApp() && ai.enabledSetting == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
                    Slog.i(TAG, "Update state(" + packageName + "): DISABLED_UNTIL_USED for user " + userId);
                    packageManager.setApplicationEnabledSetting(packageName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED, 0, userId, callingPackage);
                }
                // distinction between "default" and "enabled".
                if (!hasRunOnce) {
                    List<ApplicationInfo> associatedAppList = associatedApps.get(packageName);
                    if (associatedAppList != null) {
                        for (ApplicationInfo associatedApp : associatedAppList) {
                            if (associatedApp.enabledSetting == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
                                Slog.i(TAG, "Update associated state(" + associatedApp.packageName + "): DISABLED_UNTIL_USED for user " + userId);
                                packageManager.setApplicationEnabledSetting(associatedApp.packageName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED, 0, userId, callingPackage);
                            }
                        }
                    }
                }
            }
        }
        // Mark the execution so we do not disable apps again.
        if (!hasRunOnce) {
            Settings.Secure.putIntForUser(contentResolver, Settings.Secure.CARRIER_APPS_HANDLED, 1, userId);
        }
        if (!enabledCarrierPackages.isEmpty()) {
            // Since we enabled at least one app, ensure we grant default permissions to those
            // apps.
            String[] packageNames = new String[enabledCarrierPackages.size()];
            enabledCarrierPackages.toArray(packageNames);
            packageManager.grantDefaultPermissionsToEnabledCarrierApps(packageNames, userId);
        }
    } catch (RemoteException e) {
        Slog.w(TAG, "Could not reach PackageManager", e);
    }
}
Also used : ApplicationInfo(android.content.pm.ApplicationInfo) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) RemoteException(android.os.RemoteException) VisibleForTesting(com.android.internal.annotations.VisibleForTesting)

Example 52 with VisibleForTesting

use of com.android.internal.annotations.VisibleForTesting in project android_frameworks_base by crdroidandroid.

the class InputMethodUtils method parseInputMethodsAndSubtypesString.

/**
     * Parses the setting stored input methods and subtypes string value.
     *
     * @param inputMethodsAndSubtypesString The input method subtypes value stored in settings.
     * @return Map from input method ID to set of input method subtypes IDs.
     */
@VisibleForTesting
public static ArrayMap<String, ArraySet<String>> parseInputMethodsAndSubtypesString(@Nullable final String inputMethodsAndSubtypesString) {
    final ArrayMap<String, ArraySet<String>> imeMap = new ArrayMap<>();
    if (TextUtils.isEmpty(inputMethodsAndSubtypesString)) {
        return imeMap;
    }
    final SimpleStringSplitter typeSplitter = new SimpleStringSplitter(INPUT_METHOD_SEPARATOR);
    final SimpleStringSplitter subtypeSplitter = new SimpleStringSplitter(INPUT_METHOD_SUBTYPE_SEPARATOR);
    List<Pair<String, ArrayList<String>>> allImeSettings = InputMethodSettings.buildInputMethodsAndSubtypeList(inputMethodsAndSubtypesString, typeSplitter, subtypeSplitter);
    for (Pair<String, ArrayList<String>> ime : allImeSettings) {
        ArraySet<String> subtypes = new ArraySet<>();
        if (ime.second != null) {
            subtypes.addAll(ime.second);
        }
        imeMap.put(ime.first, subtypes);
    }
    return imeMap;
}
Also used : ArraySet(android.util.ArraySet) ArrayList(java.util.ArrayList) ArrayMap(android.util.ArrayMap) SimpleStringSplitter(android.text.TextUtils.SimpleStringSplitter) Pair(android.util.Pair) VisibleForTesting(com.android.internal.annotations.VisibleForTesting)

Example 53 with VisibleForTesting

use of com.android.internal.annotations.VisibleForTesting in project android_frameworks_base by crdroidandroid.

the class LocaleUtils method filterByLanguage.

/**
     * Filters the given items based on language preferences.
     *
     * <p>For each language found in {@code preferredLanguages}, this method tries to copy at most
     * one best-match item from {@code source} to {@code dest}.  For example, if
     * {@code "en-GB", "ja", "en-AU", "fr-CA", "en-IN"} is specified to {@code preferredLanguages},
     * this method tries to copy at most one English locale, at most one Japanese, and at most one
     * French locale from {@code source} to {@code dest}.  Here the best matching English locale
     * will be searched from {@code source} based on matching score. For the score design, see
     * {@link LocaleUtils#calculateMatchingScore(ULocale, LocaleList, byte[])}</p>
     *
     * @param sources Source items to be filtered.
     * @param extractor Type converter from the source items to {@link Locale} object.
     * @param preferredLanguages Ordered list of locales with which the input items will be
     * filtered.
     * @param dest Destination into which the filtered items will be added.
     * @param <T> Type of the data items.
     */
@VisibleForTesting
public static <T> void filterByLanguage(@NonNull List<T> sources, @NonNull LocaleExtractor<T> extractor, @NonNull LocaleList preferredLanguages, @NonNull ArrayList<T> dest) {
    final HashMap<String, ScoreEntry> scoreboard = new HashMap<>();
    final byte[] score = new byte[preferredLanguages.size()];
    final int sourceSize = sources.size();
    for (int i = 0; i < sourceSize; ++i) {
        final Locale locale = extractor.get(sources.get(i));
        if (locale == null || !calculateMatchingScore(ULocale.addLikelySubtags(ULocale.forLocale(locale)), preferredLanguages, score)) {
            continue;
        }
        final String lang = locale.getLanguage();
        final ScoreEntry bestScore = scoreboard.get(lang);
        if (bestScore == null) {
            scoreboard.put(lang, new ScoreEntry(score, i));
        } else {
            bestScore.updateIfBetter(score, i);
        }
    }
    final ScoreEntry[] result = scoreboard.values().toArray(new ScoreEntry[scoreboard.size()]);
    Arrays.sort(result);
    for (final ScoreEntry entry : result) {
        dest.add(sources.get(entry.mIndex));
    }
}
Also used : Locale(java.util.Locale) ULocale(android.icu.util.ULocale) HashMap(java.util.HashMap) VisibleForTesting(com.android.internal.annotations.VisibleForTesting)

Example 54 with VisibleForTesting

use of com.android.internal.annotations.VisibleForTesting in project android_frameworks_base by crdroidandroid.

the class ResourcesManager method getDisplayMetrics.

/**
     * Protected so that tests can override and returns something a fixed value.
     */
@VisibleForTesting
@NonNull
protected DisplayMetrics getDisplayMetrics(int displayId, DisplayAdjustments da) {
    DisplayMetrics dm = new DisplayMetrics();
    final Display display = getAdjustedDisplay(displayId, da);
    if (display != null) {
        display.getMetrics(dm);
    } else {
        dm.setToDefaults();
    }
    return dm;
}
Also used : DisplayMetrics(android.util.DisplayMetrics) Display(android.view.Display) VisibleForTesting(com.android.internal.annotations.VisibleForTesting) NonNull(android.annotation.NonNull)

Example 55 with VisibleForTesting

use of com.android.internal.annotations.VisibleForTesting in project android_frameworks_base by crdroidandroid.

the class NetworkMonitor method sendHttpProbe.

/**
     * Do a URL fetch on a known web server to see if we get the data we expect.
     * @return a CaptivePortalProbeResult inferred from the HTTP response.
     */
@VisibleForTesting
protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType) {
    HttpURLConnection urlConnection = null;
    int httpResponseCode = 599;
    String redirectUrl = null;
    final Stopwatch probeTimer = new Stopwatch().start();
    try {
        urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
        urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
        urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
        urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
        urlConnection.setUseCaches(false);
        final String userAgent = getCaptivePortalUserAgent(mContext);
        if (userAgent != null) {
            urlConnection.setRequestProperty("User-Agent", userAgent);
        }
        // Time how long it takes to get a response to our request
        long requestTimestamp = SystemClock.elapsedRealtime();
        httpResponseCode = urlConnection.getResponseCode();
        redirectUrl = urlConnection.getHeaderField("location");
        // Time how long it takes to get a response to our request
        long responseTimestamp = SystemClock.elapsedRealtime();
        validationLog(ValidationProbeEvent.getProbeName(probeType) + " " + url + " time=" + (responseTimestamp - requestTimestamp) + "ms" + " ret=" + httpResponseCode + " headers=" + urlConnection.getHeaderFields());
        // proxy server.
        if (httpResponseCode == 200) {
            if (probeType == ValidationProbeEvent.PROBE_PAC) {
                validationLog("PAC fetch 200 response interpreted as 204 response.");
                httpResponseCode = 204;
            } else if (urlConnection.getContentLengthLong() == 0) {
                // Consider 200 response with "Content-length=0" to not be a captive portal.
                // There's no point in considering this a captive portal as the user cannot
                // sign-in to an empty page. Probably the result of a broken transparent proxy.
                // See http://b/9972012.
                validationLog("200 response with Content-length=0 interpreted as 204 response.");
                httpResponseCode = 204;
            } else if (urlConnection.getContentLengthLong() == -1) {
                // response. Do not use available() as it is unreliable. See http://b/33498325.
                if (urlConnection.getInputStream().read() == -1) {
                    validationLog("Empty 200 response interpreted as 204 response.");
                    httpResponseCode = 204;
                }
            }
        }
    } catch (IOException e) {
        validationLog("Probably not a portal: exception " + e);
        if (httpResponseCode == 599) {
        // TODO: Ping gateway and DNS server and log results.
        }
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    logValidationProbe(probeTimer.stop(), probeType, httpResponseCode);
    return new CaptivePortalProbeResult(httpResponseCode, redirectUrl, url.toString());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Stopwatch(android.net.util.Stopwatch) IOException(java.io.IOException) VisibleForTesting(com.android.internal.annotations.VisibleForTesting)

Aggregations

VisibleForTesting (com.android.internal.annotations.VisibleForTesting)141 ArrayList (java.util.ArrayList)39 IOException (java.io.IOException)26 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)18 ComponentName (android.content.ComponentName)15 File (java.io.File)14 RemoteException (android.os.RemoteException)13 ArraySet (android.util.ArraySet)10 AtomicFile (android.util.AtomicFile)10 FileInputStream (java.io.FileInputStream)10 Locale (java.util.Locale)10 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)9 FileNotFoundException (java.io.FileNotFoundException)9 Notification (android.app.Notification)6 ErrnoException (android.system.ErrnoException)6 FastXmlSerializer (com.android.internal.util.FastXmlSerializer)6 FileOutputStream (java.io.FileOutputStream)6 XmlSerializer (org.xmlpull.v1.XmlSerializer)6 ITransientNotification (android.app.ITransientNotification)5 UserInfo (android.content.pm.UserInfo)5