1 /*
2  * Copyright (C) 2023 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.app.admin.LockTaskPolicy;
21 import android.app.admin.PolicyKey;
22 import android.util.Log;
23 
24 import com.android.modules.utils.TypedXmlPullParser;
25 import com.android.modules.utils.TypedXmlSerializer;
26 
27 import org.xmlpull.v1.XmlPullParserException;
28 
29 import java.io.IOException;
30 import java.util.Objects;
31 import java.util.Set;
32 
33 final class LockTaskPolicySerializer extends PolicySerializer<LockTaskPolicy> {
34 
35     private static final String TAG = "LockTaskPolicySerializer";
36 
37     private static final String ATTR_PACKAGES = "packages";
38     private static final String ATTR_PACKAGES_SEPARATOR = ";";
39     private static final String ATTR_FLAGS = "flags";
40 
41     @Override
saveToXml(PolicyKey policyKey, TypedXmlSerializer serializer, @NonNull LockTaskPolicy value)42     void saveToXml(PolicyKey policyKey, TypedXmlSerializer serializer,
43             @NonNull LockTaskPolicy value) throws IOException {
44         Objects.requireNonNull(value);
45         serializer.attribute(
46                 /* namespace= */ null,
47                 ATTR_PACKAGES,
48                 String.join(ATTR_PACKAGES_SEPARATOR, value.getPackages()));
49         serializer.attributeInt(
50                 /* namespace= */ null,
51                 ATTR_FLAGS,
52                 value.getFlags());
53     }
54 
55     @Override
readFromXml(TypedXmlPullParser parser)56     LockTaskPolicy readFromXml(TypedXmlPullParser parser) {
57         String packagesStr = parser.getAttributeValue(
58                 /* namespace= */ null,
59                 ATTR_PACKAGES);
60         if (packagesStr == null) {
61             Log.e(TAG, "Error parsing LockTask policy value.");
62             return null;
63         }
64         Set<String> packages = Set.of(packagesStr.split(ATTR_PACKAGES_SEPARATOR));
65         try {
66             int flags = parser.getAttributeInt(
67                     /* namespace= */ null,
68                     ATTR_FLAGS);
69             return new LockTaskPolicy(packages, flags);
70         } catch (XmlPullParserException e) {
71             Log.e(TAG, "Error parsing LockTask policy value", e);
72             return null;
73         }
74     }
75 }
76