Java Code Examples for com.android.internal.util.XmlUtils#nextElementWithin()

The following examples show how to use com.android.internal.util.XmlUtils#nextElementWithin() . 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: PersistentDataStore.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void loadRememberedWifiDisplaysFromXml(XmlPullParser parser)
        throws IOException, XmlPullParserException {
    final int outerDepth = parser.getDepth();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        if (parser.getName().equals(TAG_WIFI_DISPLAY)) {
            String deviceAddress = parser.getAttributeValue(null, ATTR_DEVICE_ADDRESS);
            String deviceName = parser.getAttributeValue(null, ATTR_DEVICE_NAME);
            String deviceAlias = parser.getAttributeValue(null, ATTR_DEVICE_ALIAS);
            if (deviceAddress == null || deviceName == null) {
                throw new XmlPullParserException(
                        "Missing deviceAddress or deviceName attribute on wifi-display.");
            }
            if (findRememberedWifiDisplay(deviceAddress) >= 0) {
                throw new XmlPullParserException(
                        "Found duplicate wifi display device address.");
            }

            mRememberedWifiDisplays.add(
                    new WifiDisplay(deviceAddress, deviceName, deviceAlias,
                            false, false, false));
        }
    }
}
 
Example 2
Source File: PersistentDataStore.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void loadFromXml(XmlPullParser parser)
        throws IOException, XmlPullParserException {
    XmlUtils.beginDocument(parser, TAG_DISPLAY_MANAGER_STATE);
    final int outerDepth = parser.getDepth();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        if (parser.getName().equals(TAG_REMEMBERED_WIFI_DISPLAYS)) {
            loadRememberedWifiDisplaysFromXml(parser);
        }
        if (parser.getName().equals(TAG_DISPLAY_STATES)) {
            loadDisplaysFromXml(parser);
        }
        if (parser.getName().equals(TAG_STABLE_DEVICE_VALUES)) {
            mStableDeviceValues.loadFromXml(parser);
        }
        if (parser.getName().equals(TAG_BRIGHTNESS_CONFIGURATIONS)) {
            mBrightnessConfigurations.loadFromXml(parser);
        }
    }
}
 
Example 3
Source File: OverlayManagerSettings.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public static void restore(@NonNull final ArrayList<SettingsItem> table,
        @NonNull final InputStream is) throws IOException, XmlPullParserException {

    try (InputStreamReader reader = new InputStreamReader(is)) {
        table.clear();
        final XmlPullParser parser = Xml.newPullParser();
        parser.setInput(reader);
        XmlUtils.beginDocument(parser, TAG_OVERLAYS);
        int version = XmlUtils.readIntAttribute(parser, ATTR_VERSION);
        if (version != CURRENT_VERSION) {
            upgrade(version);
        }
        int depth = parser.getDepth();

        while (XmlUtils.nextElementWithin(parser, depth)) {
            switch (parser.getName()) {
                case TAG_ITEM:
                    final SettingsItem item = restoreRow(parser, depth + 1);
                    table.add(item);
                    break;
            }
        }
    }
}
 
Example 4
Source File: SystemImpl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Reads all signatures at the current depth (within the current provider) from the XML parser.
 */
private static String[] readSignatures(XmlResourceParser parser) throws IOException,
        XmlPullParserException {
    List<String> signatures = new ArrayList<String>();
    int outerDepth = parser.getDepth();
    while(XmlUtils.nextElementWithin(parser, outerDepth)) {
        if (parser.getName().equals(TAG_SIGNATURE)) {
            // Parse the value within the signature tag
            String signature = parser.nextText();
            signatures.add(signature);
        } else {
            Log.e(TAG, "Found an element in a webview provider that is not a signature");
        }
    }
    return signatures.toArray(new String[signatures.size()]);
}
 
Example 5
Source File: PersistentDataStore.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void loadFromXml(XmlPullParser parser)
        throws IOException, XmlPullParserException {
    XmlUtils.beginDocument(parser, TAG_TV_INPUT_MANAGER_STATE);
    final int outerDepth = parser.getDepth();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        if (parser.getName().equals(TAG_BLOCKED_RATINGS)) {
            loadBlockedRatingsFromXml(parser);
        } else if (parser.getName().equals(TAG_PARENTAL_CONTROLS)) {
            String enabled = parser.getAttributeValue(null, ATTR_ENABLED);
            if (TextUtils.isEmpty(enabled)) {
                throw new XmlPullParserException(
                        "Missing " + ATTR_ENABLED + " attribute on " + TAG_PARENTAL_CONTROLS);
            }
            mParentalControlsEnabled = Boolean.parseBoolean(enabled);
        }
    }
}
 
Example 6
Source File: FilterList.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public FilterList readFromXml(XmlPullParser parser) throws IOException, XmlPullParserException {
    int outerDepth = parser.getDepth();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        readChild(parser);
    }
    return this;
}
 
Example 7
Source File: XmlConfigSource.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private NetworkSecurityConfig.Builder parseDebugOverridesResource()
        throws IOException, XmlPullParserException, ParserException {
    Resources resources = mContext.getResources();
    String packageName = resources.getResourcePackageName(mResourceId);
    String entryName = resources.getResourceEntryName(mResourceId);
    int resId = resources.getIdentifier(entryName + "_debug", "xml", packageName);
    // No debug-overrides resource was found, nothing to parse.
    if (resId == 0) {
        return null;
    }
    NetworkSecurityConfig.Builder debugConfigBuilder = null;
    // Parse debug-overrides out of the _debug resource.
    try (XmlResourceParser parser = resources.getXml(resId)) {
        XmlUtils.beginDocument(parser, "network-security-config");
        int outerDepth = parser.getDepth();
        boolean seenDebugOverrides = false;
        while (XmlUtils.nextElementWithin(parser, outerDepth)) {
            if ("debug-overrides".equals(parser.getName())) {
                if (seenDebugOverrides) {
                    throw new ParserException(parser, "Only one debug-overrides allowed");
                }
                if (mDebugBuild) {
                    debugConfigBuilder =
                            parseConfigEntry(parser, null, null, CONFIG_DEBUG).get(0).first;
                } else {
                    XmlUtils.skipCurrentTag(parser);
                }
                seenDebugOverrides = true;
            } else {
                XmlUtils.skipCurrentTag(parser);
            }
        }
    }

    return debugConfigBuilder;
}
 
Example 8
Source File: XmlConfigSource.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private Collection<CertificatesEntryRef> parseTrustAnchors(XmlResourceParser parser,
        boolean defaultOverridePins)
        throws IOException, XmlPullParserException, ParserException {
    int outerDepth = parser.getDepth();
    List<CertificatesEntryRef> anchors = new ArrayList<>();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        String tagName = parser.getName();
        if (tagName.equals("certificates")) {
            anchors.add(parseCertificatesEntry(parser, defaultOverridePins));
        } else {
            XmlUtils.skipCurrentTag(parser);
        }
    }
    return anchors;
}
 
Example 9
Source File: UserManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static Bundle readBundleEntry(XmlPullParser parser, ArrayList<String> values)
        throws IOException, XmlPullParserException {
    Bundle childBundle = new Bundle();
    final int outerDepth = parser.getDepth();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        readEntry(childBundle, values, parser);
    }
    return childBundle;
}
 
Example 10
Source File: XmlConfigSource.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private PinSet parsePinSet(XmlResourceParser parser)
        throws IOException, XmlPullParserException, ParserException {
    String expirationDate = parser.getAttributeValue(null, "expiration");
    long expirationTimestampMilis = Long.MAX_VALUE;
    if (expirationDate != null) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.setLenient(false);
            Date date = sdf.parse(expirationDate);
            if (date == null) {
                throw new ParserException(parser, "Invalid expiration date in pin-set");
            }
            expirationTimestampMilis = date.getTime();
        } catch (ParseException e) {
            throw new ParserException(parser, "Invalid expiration date in pin-set", e);
        }
    }

    int outerDepth = parser.getDepth();
    Set<Pin> pins = new ArraySet<>();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        String tagName = parser.getName();
        if (tagName.equals("pin")) {
            pins.add(parsePin(parser));
        } else {
            XmlUtils.skipCurrentTag(parser);
        }
    }
    return new PinSet(pins, expirationTimestampMilis);
}
 
Example 11
Source File: PersistentDataStore.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void loadBlockedRatingsFromXml(XmlPullParser parser)
        throws IOException, XmlPullParserException {
    final int outerDepth = parser.getDepth();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        if (parser.getName().equals(TAG_RATING)) {
            String ratingString = parser.getAttributeValue(null, ATTR_STRING);
            if (TextUtils.isEmpty(ratingString)) {
                throw new XmlPullParserException(
                        "Missing " + ATTR_STRING + " attribute on " + TAG_RATING);
            }
            mBlockedRatings.add(TvContentRating.unflattenFromString(ratingString));
        }
    }
}
 
Example 12
Source File: XmlConfigSource.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
private PinSet parsePinSet(XmlResourceParser parser)
        throws IOException, XmlPullParserException, ParserException {
    String expirationDate = parser.getAttributeValue(null, "expiration");
    long expirationTimestampMilis = Long.MAX_VALUE;
    if (expirationDate != null) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.setLenient(false);
            Date date = sdf.parse(expirationDate);
            if (date == null) {
                throw new ParserException(parser, "Invalid expiration date in pin-set");
            }
            expirationTimestampMilis = date.getTime();
        } catch (ParseException e) {
            throw new ParserException(parser, "Invalid expiration date in pin-set", e);
        }
    }

    int outerDepth = parser.getDepth();
    Set<Pin> pins = new HashSet<>();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        String tagName = parser.getName();
        if (tagName.equals("pin")) {
            pins.add(parsePin(parser));
        } else {
            XmlUtils.skipCurrentTag(parser);
        }
    }
    return new PinSet(pins, expirationTimestampMilis);
}
 
Example 13
Source File: PersistentDataStore.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public void loadFromXml(XmlPullParser parser) throws IOException, XmlPullParserException {
    final int outerDepth = parser.getDepth();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        switch (parser.getName()) {
            case TAG_STABLE_DISPLAY_WIDTH:
                mWidth = loadIntValue(parser);
                break;
            case TAG_STABLE_DISPLAY_HEIGHT:
                mHeight = loadIntValue(parser);
                break;
        }
    }
}
 
Example 14
Source File: PersistentDataStore.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public void loadFromXml(XmlPullParser parser)
        throws IOException, XmlPullParserException {
    final int outerDepth = parser.getDepth();

    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        if (parser.getName().equals(TAG_COLOR_MODE)) {
            String value = parser.nextText();
            mColorMode = Integer.parseInt(value);
        }
    }
}
 
Example 15
Source File: AccountManagerBackupHelper.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public void restoreAccountAccessPermissions(byte[] data, int userId) {
    try {
        ByteArrayInputStream dataStream = new ByteArrayInputStream(data);
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(dataStream, StandardCharsets.UTF_8.name());
        PackageManager packageManager = mAccountManagerService.mContext.getPackageManager();

        final int permissionsOuterDepth = parser.getDepth();
        while (XmlUtils.nextElementWithin(parser, permissionsOuterDepth)) {
            if (!TAG_PERMISSIONS.equals(parser.getName())) {
                continue;
            }
            final int permissionOuterDepth = parser.getDepth();
            while (XmlUtils.nextElementWithin(parser, permissionOuterDepth)) {
                if (!TAG_PERMISSION.equals(parser.getName())) {
                    continue;
                }
                String accountDigest = parser.getAttributeValue(null, ATTR_ACCOUNT_SHA_256);
                if (TextUtils.isEmpty(accountDigest)) {
                    XmlUtils.skipCurrentTag(parser);
                }
                String packageName = parser.getAttributeValue(null, ATTR_PACKAGE);
                if (TextUtils.isEmpty(packageName)) {
                    XmlUtils.skipCurrentTag(parser);
                }
                String digest =  parser.getAttributeValue(null, ATTR_DIGEST);
                if (TextUtils.isEmpty(digest)) {
                    XmlUtils.skipCurrentTag(parser);
                }

                PendingAppPermission pendingAppPermission = new PendingAppPermission(
                        accountDigest, packageName, digest, userId);

                if (!pendingAppPermission.apply(packageManager)) {
                    synchronized (mLock) {
                        // Start watching before add pending to avoid a missed signal
                        if (mRestorePackageMonitor == null) {
                            mRestorePackageMonitor = new RestorePackageMonitor();
                            mRestorePackageMonitor.register(mAccountManagerService.mContext,
                                    mAccountManagerService.mHandler.getLooper(), true);
                        }
                        if (mRestorePendingAppPermissions == null) {
                            mRestorePendingAppPermissions = new ArrayList<>();
                        }
                        mRestorePendingAppPermissions.add(pendingAppPermission);
                    }
                }
            }
        }

        // Make sure we eventually prune the in-memory pending restores
        mRestoreCancelCommand = new CancelRestoreCommand();
        mAccountManagerService.mHandler.postDelayed(mRestoreCancelCommand,
                PENDING_RESTORE_TIMEOUT_MILLIS);
    } catch (XmlPullParserException | IOException e) {
        Log.e(TAG, "Error restoring app permissions", e);
    }
}
 
Example 16
Source File: XmlConfigSource.java    From cwac-netsecurity with Apache License 2.0 4 votes vote down vote up
private NetworkSecurityConfig.Builder parseDebugOverridesResource()
        throws IOException, XmlPullParserException, ParserException {
    Resources resources = mContext.getResources();
    String packageName = resources.getResourcePackageName(mResourceId);
    String entryName = resources.getResourceEntryName(mResourceId);
    int resId = resources.getIdentifier(entryName + "_debug", "xml", packageName);
    // No debug-overrides resource was found, nothing to parse.
    if (resId == 0) {
        return null;
    }
    NetworkSecurityConfig.Builder debugConfigBuilder = null;
    // Parse debug-overrides out of the _debug resource.
    XmlResourceParser parser=null;

    try {
        parser = resources.getXml(resId);

        XmlUtils.beginDocument(parser, "network-security-config");
        int outerDepth = parser.getDepth();
        boolean seenDebugOverrides = false;
        while (XmlUtils.nextElementWithin(parser, outerDepth)) {
            if ("debug-overrides".equals(parser.getName())) {
                if (seenDebugOverrides) {
                    throw new ParserException(parser, "Only one debug-overrides allowed");
                }
                if (mDebugBuild) {
                    debugConfigBuilder =
                            parseConfigEntry(parser, null, null, CONFIG_DEBUG).get(0).first;
                } else {
                    XmlUtils.skipCurrentTag(parser);
                }
                seenDebugOverrides = true;
            } else {
                XmlUtils.skipCurrentTag(parser);
            }
        }
    }
    finally {
        if (parser!=null) parser.close();
    }

    return debugConfigBuilder;
}
 
Example 17
Source File: XmlConfigSource.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private List<Pair<NetworkSecurityConfig.Builder, Set<Domain>>> parseConfigEntry(
        XmlResourceParser parser, Set<String> seenDomains,
        NetworkSecurityConfig.Builder parentBuilder, int configType)
        throws IOException, XmlPullParserException, ParserException {
    List<Pair<NetworkSecurityConfig.Builder, Set<Domain>>> builders = new ArrayList<>();
    NetworkSecurityConfig.Builder builder = new NetworkSecurityConfig.Builder();
    builder.setParent(parentBuilder);
    Set<Domain> domains = new ArraySet<>();
    boolean seenPinSet = false;
    boolean seenTrustAnchors = false;
    boolean defaultOverridePins = configType == CONFIG_DEBUG;
    String configName = parser.getName();
    int outerDepth = parser.getDepth();
    // Add this builder now so that this builder occurs before any of its children. This
    // makes the final build pass easier.
    builders.add(new Pair<>(builder, domains));
    // Parse config attributes. Only set values that are present, config inheritence will
    // handle the rest.
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        String name = parser.getAttributeName(i);
        if ("hstsEnforced".equals(name)) {
            builder.setHstsEnforced(
                    parser.getAttributeBooleanValue(i,
                            NetworkSecurityConfig.DEFAULT_HSTS_ENFORCED));
        } else if ("cleartextTrafficPermitted".equals(name)) {
            builder.setCleartextTrafficPermitted(
                    parser.getAttributeBooleanValue(i,
                            NetworkSecurityConfig.DEFAULT_CLEARTEXT_TRAFFIC_PERMITTED));
        }
    }
    // Parse the config elements.
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        String tagName = parser.getName();
        if ("domain".equals(tagName)) {
            if (configType != CONFIG_DOMAIN) {
                throw new ParserException(parser,
                        "domain element not allowed in " + getConfigString(configType));
            }
            Domain domain = parseDomain(parser, seenDomains);
            domains.add(domain);
        } else if ("trust-anchors".equals(tagName)) {
            if (seenTrustAnchors) {
                throw new ParserException(parser,
                        "Multiple trust-anchor elements not allowed");
            }
            builder.addCertificatesEntryRefs(
                    parseTrustAnchors(parser, defaultOverridePins));
            seenTrustAnchors = true;
        } else if ("pin-set".equals(tagName)) {
            if (configType != CONFIG_DOMAIN) {
                throw new ParserException(parser,
                        "pin-set element not allowed in " + getConfigString(configType));
            }
            if (seenPinSet) {
                throw new ParserException(parser, "Multiple pin-set elements not allowed");
            }
            builder.setPinSet(parsePinSet(parser));
            seenPinSet = true;
        } else if ("domain-config".equals(tagName)) {
            if (configType != CONFIG_DOMAIN) {
                throw new ParserException(parser,
                        "Nested domain-config not allowed in " + getConfigString(configType));
            }
            builders.addAll(parseConfigEntry(parser, seenDomains, builder, configType));
        } else {
            XmlUtils.skipCurrentTag(parser);
        }
    }
    if (configType == CONFIG_DOMAIN && domains.isEmpty()) {
        throw new ParserException(parser, "No domain elements in domain-config");
    }
    return builders;
}
 
Example 18
Source File: XmlConfigSource.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void parseNetworkSecurityConfig(XmlResourceParser parser)
        throws IOException, XmlPullParserException, ParserException {
    Set<String> seenDomains = new ArraySet<>();
    List<Pair<NetworkSecurityConfig.Builder, Set<Domain>>> builders = new ArrayList<>();
    NetworkSecurityConfig.Builder baseConfigBuilder = null;
    NetworkSecurityConfig.Builder debugConfigBuilder = null;
    boolean seenDebugOverrides = false;
    boolean seenBaseConfig = false;

    XmlUtils.beginDocument(parser, "network-security-config");
    int outerDepth = parser.getDepth();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        if ("base-config".equals(parser.getName())) {
            if (seenBaseConfig) {
                throw new ParserException(parser, "Only one base-config allowed");
            }
            seenBaseConfig = true;
            baseConfigBuilder =
                    parseConfigEntry(parser, seenDomains, null, CONFIG_BASE).get(0).first;
        } else if ("domain-config".equals(parser.getName())) {
            builders.addAll(
                    parseConfigEntry(parser, seenDomains, baseConfigBuilder, CONFIG_DOMAIN));
        } else if ("debug-overrides".equals(parser.getName())) {
            if (seenDebugOverrides) {
                throw new ParserException(parser, "Only one debug-overrides allowed");
            }
            if (mDebugBuild) {
                debugConfigBuilder =
                        parseConfigEntry(parser, null, null, CONFIG_DEBUG).get(0).first;
            } else {
                XmlUtils.skipCurrentTag(parser);
            }
            seenDebugOverrides = true;
        } else {
            XmlUtils.skipCurrentTag(parser);
        }
    }
    // If debug is true and there was no debug-overrides in the file check for an extra
    // _debug resource.
    if (mDebugBuild && debugConfigBuilder == null) {
        debugConfigBuilder = parseDebugOverridesResource();
    }

    // Use the platform default as the parent of the base config for any values not provided
    // there. If there is no base config use the platform default.
    NetworkSecurityConfig.Builder platformDefaultBuilder =
            NetworkSecurityConfig.getDefaultBuilder(mApplicationInfo);
    addDebugAnchorsIfNeeded(debugConfigBuilder, platformDefaultBuilder);
    if (baseConfigBuilder != null) {
        baseConfigBuilder.setParent(platformDefaultBuilder);
        addDebugAnchorsIfNeeded(debugConfigBuilder, baseConfigBuilder);
    } else {
        baseConfigBuilder = platformDefaultBuilder;
    }
    // Build the per-domain config mapping.
    Set<Pair<Domain, NetworkSecurityConfig>> configs = new ArraySet<>();

    for (Pair<NetworkSecurityConfig.Builder, Set<Domain>> entry : builders) {
        NetworkSecurityConfig.Builder builder = entry.first;
        Set<Domain> domains = entry.second;
        // Set the parent of configs that do not have a parent to the base-config. This can
        // happen if the base-config comes after a domain-config in the file.
        // Note that this is safe with regards to children because of the order that
        // parseConfigEntry returns builders, the parent is always before the children. The
        // children builders will not have build called until _after_ their parents have their
        // parent set so everything is consistent.
        if (builder.getParent() == null) {
            builder.setParent(baseConfigBuilder);
        }
        addDebugAnchorsIfNeeded(debugConfigBuilder, builder);
        NetworkSecurityConfig config = builder.build();
        for (Domain domain : domains) {
            configs.add(new Pair<>(domain, config));
        }
    }
    mDefaultConfig = baseConfigBuilder.build();
    mDomainMap = configs;
}
 
Example 19
Source File: XmlConfigSource.java    From cwac-netsecurity with Apache License 2.0 4 votes vote down vote up
private void parseNetworkSecurityConfig(XmlResourceParser parser)
        throws IOException, XmlPullParserException, ParserException {
    Set<String> seenDomains = new HashSet<>();
    List<Pair<NetworkSecurityConfig.Builder, Set<Domain>>> builders = new ArrayList<>();
    NetworkSecurityConfig.Builder baseConfigBuilder = null;
    NetworkSecurityConfig.Builder debugConfigBuilder = null;
    boolean seenDebugOverrides = false;
    boolean seenBaseConfig = false;

    XmlUtils.beginDocument(parser, "network-security-config");
    int outerDepth = parser.getDepth();
    while (XmlUtils.nextElementWithin(parser, outerDepth)) {
        if ("base-config".equals(parser.getName())) {
            if (seenBaseConfig) {
                throw new ParserException(parser, "Only one base-config allowed");
            }
            seenBaseConfig = true;
            baseConfigBuilder =
                    parseConfigEntry(parser, seenDomains, null, CONFIG_BASE).get(0).first;
        } else if ("domain-config".equals(parser.getName())) {
            builders.addAll(
                    parseConfigEntry(parser, seenDomains, baseConfigBuilder, CONFIG_DOMAIN));
        } else if ("debug-overrides".equals(parser.getName())) {
            if (seenDebugOverrides) {
                throw new ParserException(parser, "Only one debug-overrides allowed");
            }
            if (mDebugBuild) {
                debugConfigBuilder =
                        parseConfigEntry(parser, null, null, CONFIG_DEBUG).get(0).first;
            } else {
                XmlUtils.skipCurrentTag(parser);
            }
            seenDebugOverrides = true;
        } else {
            XmlUtils.skipCurrentTag(parser);
        }
    }
    // If debug is true and there was no debug-overrides in the file check for an extra
    // _debug resource.
    if (mDebugBuild && debugConfigBuilder == null) {
        debugConfigBuilder = parseDebugOverridesResource();
    }

    // Use the platform default as the parent of the base config for any values not provided
    // there. If there is no base config use the platform default.
    NetworkSecurityConfig.Builder platformDefaultBuilder =
            NetworkSecurityConfig.getDefaultBuilder(mTargetSdkVersion);
    addDebugAnchorsIfNeeded(debugConfigBuilder, platformDefaultBuilder);
    if (baseConfigBuilder != null) {
        baseConfigBuilder.setParent(platformDefaultBuilder);
        addDebugAnchorsIfNeeded(debugConfigBuilder, baseConfigBuilder);
    } else {
        baseConfigBuilder = platformDefaultBuilder;
    }
    // Build the per-domain config mapping.
    Set<Pair<Domain, NetworkSecurityConfig>> configs = new HashSet<>();

    for (Pair<NetworkSecurityConfig.Builder, Set<Domain>> entry : builders) {
        NetworkSecurityConfig.Builder builder = entry.first;
        Set<Domain> domains = entry.second;
        // Set the parent of configs that do not have a parent to the base-config. This can
        // happen if the base-config comes after a domain-config in the file.
        // Note that this is safe with regards to children because of the order that
        // parseConfigEntry returns builders, the parent is always before the children. The
        // children builders will not have build called until _after_ their parents have their
        // parent set so everything is consistent.
        if (builder.getParent() == null) {
            builder.setParent(baseConfigBuilder);
        }
        addDebugAnchorsIfNeeded(debugConfigBuilder, builder);
        NetworkSecurityConfig config = builder.build();
        for (Domain domain : domains) {
            configs.add(new Pair<>(domain, config));
        }
    }
    mDefaultConfig = baseConfigBuilder.build();
    mDomainMap = configs;
}
 
Example 20
Source File: RestrictionsManager.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private RestrictionEntry loadRestriction(Context appContext, TypedArray a, XmlResourceParser xml)
        throws IOException, XmlPullParserException {
    String key = a.getString(R.styleable.RestrictionEntry_key);
    int restrictionType = a.getInt(
            R.styleable.RestrictionEntry_restrictionType, -1);
    String title = a.getString(R.styleable.RestrictionEntry_title);
    String description = a.getString(R.styleable.RestrictionEntry_description);
    int entries = a.getResourceId(R.styleable.RestrictionEntry_entries, 0);
    int entryValues = a.getResourceId(R.styleable.RestrictionEntry_entryValues, 0);

    if (restrictionType == -1) {
        Log.w(TAG, "restrictionType cannot be omitted");
        return null;
    }

    if (key == null) {
        Log.w(TAG, "key cannot be omitted");
        return null;
    }

    RestrictionEntry restriction = new RestrictionEntry(restrictionType, key);
    restriction.setTitle(title);
    restriction.setDescription(description);
    if (entries != 0) {
        restriction.setChoiceEntries(appContext, entries);
    }
    if (entryValues != 0) {
        restriction.setChoiceValues(appContext, entryValues);
    }
    // Extract the default value based on the type
    switch (restrictionType) {
        case RestrictionEntry.TYPE_NULL: // hidden
        case RestrictionEntry.TYPE_STRING:
        case RestrictionEntry.TYPE_CHOICE:
            restriction.setSelectedString(
                    a.getString(R.styleable.RestrictionEntry_defaultValue));
            break;
        case RestrictionEntry.TYPE_INTEGER:
            restriction.setIntValue(
                    a.getInt(R.styleable.RestrictionEntry_defaultValue, 0));
            break;
        case RestrictionEntry.TYPE_MULTI_SELECT:
            int resId = a.getResourceId(R.styleable.RestrictionEntry_defaultValue, 0);
            if (resId != 0) {
                restriction.setAllSelectedStrings(
                        appContext.getResources().getStringArray(resId));
            }
            break;
        case RestrictionEntry.TYPE_BOOLEAN:
            restriction.setSelectedState(
                    a.getBoolean(R.styleable.RestrictionEntry_defaultValue, false));
            break;
        case RestrictionEntry.TYPE_BUNDLE:
        case RestrictionEntry.TYPE_BUNDLE_ARRAY:
            final int outerDepth = xml.getDepth();
            List<RestrictionEntry> restrictionEntries = new ArrayList<>();
            while (XmlUtils.nextElementWithin(xml, outerDepth)) {
                RestrictionEntry childEntry = loadRestrictionElement(appContext, xml);
                if (childEntry == null) {
                    Log.w(TAG, "Child entry cannot be loaded for bundle restriction " + key);
                } else {
                    restrictionEntries.add(childEntry);
                    if (restrictionType == RestrictionEntry.TYPE_BUNDLE_ARRAY
                            && childEntry.getType() != RestrictionEntry.TYPE_BUNDLE) {
                        Log.w(TAG, "bundle_array " + key
                                + " can only contain entries of type bundle");
                    }
                }
            }
            restriction.setRestrictions(restrictionEntries.toArray(new RestrictionEntry[
                    restrictionEntries.size()]));
            break;
        default:
            Log.w(TAG, "Unknown restriction type " + restrictionType);
    }
    return restriction;
}