1 /* 2 * Copyright (C) 2013 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.TopItem; 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 of the top command output. 27 * <p> 28 * The parser only record the last top entry if multiple entries are printed by the top command. It 29 * only parses the total cpu usage. 30 * </p> 31 */ 32 public class TopParser implements IParser { 33 34 /** 35 * Match a valid cpu ticks line, such as: 36 * "User 5 + Nice 0 + Sys 14 + Idle 207 + IOW 0 + IRQ 0 + SIRQ 0 = 226" 37 */ 38 private static final Pattern TICKS_PAT = Pattern.compile( 39 "User (\\d+) \\+ Nice (\\d+) \\+ Sys (\\d+) \\+ Idle (\\d+) \\+ IOW (\\d+) \\+ " + 40 "IRQ (\\d+) \\+ SIRQ (\\d+) = (\\d+)"); 41 42 /** 43 * {@inheritDoc} 44 */ 45 @Override parse(List<String> lines)46 public TopItem parse(List<String> lines) { 47 final String text = ArrayUtil.join("\n", lines).trim(); 48 if ("".equals(text)) { 49 return null; 50 } 51 52 TopItem item = new TopItem(); 53 item.setText(text); 54 55 for (String line : lines) { 56 Matcher m = TICKS_PAT.matcher(line); 57 if (m.matches()) { 58 item.setUser(Integer.parseInt(m.group(1))); 59 item.setNice(Integer.parseInt(m.group(2))); 60 item.setSystem(Integer.parseInt(m.group(3))); 61 item.setIdle(Integer.parseInt(m.group(4))); 62 item.setIow(Integer.parseInt(m.group(5))); 63 item.setIrq(Integer.parseInt(m.group(6))); 64 item.setSirq(Integer.parseInt(m.group(7))); 65 item.setTotal(Integer.parseInt(m.group(8))); 66 } 67 } 68 return item; 69 } 70 } 71