1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.devicepolicy;
18 
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.app.admin.PolicyValue;
22 import android.app.admin.PackageSetPolicyValue;
23 import android.util.Log;
24 
25 import com.android.modules.utils.TypedXmlPullParser;
26 import com.android.modules.utils.TypedXmlSerializer;
27 
28 import java.io.IOException;
29 import java.util.Objects;
30 import java.util.Set;
31 
32 // TODO(scottjonathan): Replace with generic set implementation
33 final class PackageSetPolicySerializer extends PolicySerializer<Set<String>> {
34     private static final String ATTR_VALUES = "strings";
35     private static final String ATTR_VALUES_SEPARATOR = ";";
36     @Override
saveToXml(TypedXmlSerializer serializer, @NonNull Set<String> value)37     void saveToXml(TypedXmlSerializer serializer, @NonNull Set<String> value) throws IOException {
38         Objects.requireNonNull(value);
39         serializer.attribute(
40                 /* namespace= */ null, ATTR_VALUES, String.join(ATTR_VALUES_SEPARATOR, value));
41     }
42 
43     @Nullable
44     @Override
readFromXml(TypedXmlPullParser parser)45     PolicyValue<Set<String>> readFromXml(TypedXmlPullParser parser) {
46         String valuesStr = parser.getAttributeValue(/* namespace= */ null, ATTR_VALUES);
47         if (valuesStr == null) {
48             Log.e(DevicePolicyEngine.TAG, "Error parsing PackageSet policy value.");
49             return null;
50         }
51         Set<String> values = Set.of(valuesStr.split(ATTR_VALUES_SEPARATOR));
52         return new PackageSetPolicyValue(values);
53     }
54 }
55