1 /*
2  * Copyright (C) 2015 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 package com.android.loganalysis.parser;
17 
18 import com.android.loganalysis.item.BatteryUsageItem;
19 
20 import java.util.List;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23 
24 /**
25  * A {@link IParser} to parse battery usage statistics
26  */
27 public class BatteryUsageParser implements IParser {
28 
29     /**
30      * Matches: Capacity: 3220, Computed drain: 11.0, actual drain: 0
31      */
32     private static final Pattern Capacity = Pattern.compile(
33             "^\\s*Capacity: (\\d+), Computed drain: \\d+.*");
34 
35     private static final Pattern Usage = Pattern.compile("^\\s*(.*): (\\d+(\\.\\d*)?)");
36     private BatteryUsageItem mItem = new BatteryUsageItem();
37 
38     /**
39      * {@inheritDoc}
40      *
41      * @return The {@link BatteryUsageItem}.
42      */
43     @Override
parse(List<String> lines)44     public BatteryUsageItem parse(List<String> lines) {
45         for (String line : lines) {
46             Matcher m = Capacity.matcher(line);
47             if(m.matches()) {
48                 mItem.setBatteryCapacity(Integer.parseInt(m.group(1)));
49             } else {
50                 m = Usage.matcher(line);
51                 if (m.matches()) {
52                     mItem.addBatteryUsage(m.group(1), Double.parseDouble(m.group(2)));
53                 }
54             }
55         }
56         return mItem;
57     }
58 
59     /**
60      * Get the {@link BatteryUsageItem}.
61      * <p>
62      * Exposed for unit testing.
63      * </p>
64      */
getItem()65     BatteryUsageItem getItem() {
66         return mItem;
67     }
68 }
69