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