1 /*
2  * Copyright (C) 2019 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.integrity.parser;
18 
19 import android.annotation.Nullable;
20 import android.util.Xml;
21 
22 import com.android.modules.utils.TypedXmlPullParser;
23 import com.android.server.integrity.model.RuleMetadata;
24 
25 import org.xmlpull.v1.XmlPullParser;
26 import org.xmlpull.v1.XmlPullParserException;
27 
28 import java.io.IOException;
29 import java.io.InputStream;
30 
31 /** Helper class for parsing rule metadata. */
32 public class RuleMetadataParser {
33 
34     public static final String RULE_PROVIDER_TAG = "P";
35     public static final String VERSION_TAG = "V";
36 
37     /** Parse the rule metadata from an input stream. */
38     @Nullable
parse(InputStream inputStream)39     public static RuleMetadata parse(InputStream inputStream)
40             throws XmlPullParserException, IOException {
41 
42         String ruleProvider = "";
43         String version = "";
44 
45         TypedXmlPullParser xmlPullParser = Xml.resolvePullParser(inputStream);
46 
47         int eventType;
48         while ((eventType = xmlPullParser.next()) != XmlPullParser.END_DOCUMENT) {
49             if (eventType == XmlPullParser.START_TAG) {
50                 String tag = xmlPullParser.getName();
51                 switch (tag) {
52                     case RULE_PROVIDER_TAG:
53                         ruleProvider = xmlPullParser.nextText();
54                         break;
55                     case VERSION_TAG:
56                         version = xmlPullParser.nextText();
57                         break;
58                     default:
59                         throw new IllegalStateException("Unknown tag in metadata: " + tag);
60                 }
61             }
62         }
63 
64         return new RuleMetadata(ruleProvider, version);
65     }
66 }
67