1 /*
2  * Copyright (C) 2011 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.MemInfoItem;
19 import com.android.loganalysis.util.ArrayUtil;
20 
21 import java.util.List;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
24 
25 /**
26  * A {@link IParser} to handle the output from {@code /proc/meminfo}.
27  */
28 public class MemInfoParser implements IParser {
29 
30     /** Match a single MemoryInfo line, such as "MemFree:           65420 kB" */
31     private static final Pattern INFO_LINE = Pattern.compile("^([^:]+):\\s+(\\d+) kB");
32 
33     /**
34      * {@inheritDoc}
35      *
36      * @return The {@link MemInfoItem}.
37      */
38     @Override
parse(List<String> lines)39     public MemInfoItem parse(List<String> lines) {
40         final String text = ArrayUtil.join("\n", lines).trim();
41         if ("".equals(text)) {
42             return null;
43         }
44 
45         MemInfoItem item = new MemInfoItem();
46         item.setText(text);
47 
48         for (String line : lines) {
49             Matcher m = INFO_LINE.matcher(line);
50             if (m.matches()) {
51                 String key = m.group(1);
52                 try {
53                     Long value = Long.parseLong(m.group(2));
54                     item.put(key, value);
55                 } catch (NumberFormatException e) {
56                     // Ignore
57                 }
58             }
59         }
60 
61         return item;
62     }
63 }
64