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.PolicyKey;
22 import android.app.admin.PolicyValue;
23 import android.app.admin.StringSetPolicyValue;
24 import android.util.Log;
25 
26 import com.android.modules.utils.TypedXmlPullParser;
27 import com.android.modules.utils.TypedXmlSerializer;
28 
29 import java.io.IOException;
30 import java.util.Objects;
31 import java.util.Set;
32 
33 // TODO(scottjonathan): Replace with generic set implementation
34 final class StringSetPolicySerializer extends PolicySerializer<Set<String>> {
35     private static final String ATTR_VALUES = ":strings";
36     private static final String ATTR_VALUES_SEPARATOR = ";";
37 
38     @Override
saveToXml(PolicyKey policyKey, TypedXmlSerializer serializer, @NonNull Set<String> value)39     void saveToXml(PolicyKey policyKey, TypedXmlSerializer serializer,
40             @NonNull Set<String> value) throws IOException {
41         Objects.requireNonNull(value);
42         serializer.attribute(
43                 /* namespace= */ null, ATTR_VALUES, String.join(ATTR_VALUES_SEPARATOR, value));
44     }
45 
46     @Nullable
47     @Override
readFromXml(TypedXmlPullParser parser)48     PolicyValue<Set<String>> readFromXml(TypedXmlPullParser parser) {
49         String valuesStr = parser.getAttributeValue(/* namespace= */ null, ATTR_VALUES);
50         if (valuesStr == null) {
51             Log.e(DevicePolicyEngine.TAG, "Error parsing StringSet policy value.");
52             return null;
53         }
54         Set<String> values = Set.of(valuesStr.split(ATTR_VALUES_SEPARATOR));
55         return new StringSetPolicyValue(values);
56     }
57 }
58