public static void closeQuietly(Closeable closeable) {
  if (closeable != null) {
    try {
      closeable.close();
    } catch (IOException ignore) {
    }
  }
} public static List<String> readLines(File file) {
  return readLines(file, ACCEPT_ALL_LINES_FILTER);
} public static long ticksToTimeUnit(long clockTicks, long ticksPerSecond, TimeUnit unit) {
  switch (unit) {
    case DAYS:
    case HOURS:
    case MINUTES:
      return unit.convert(clockTicks / ticksPerSecond, SECONDS);
    case SECONDS:
      return clockTicks / ticksPerSecond;
    case MILLISECONDS:
    case MICROSECONDS:
    case NANOSECONDS:
      return unit.convert(1, SECONDS) * clockTicks / ticksPerSecond;
    default:
      throw new UnsupportedOperationException(String.valueOf(unit));
  }
} public class CpuDetails {

  private final String vendorId;
  private final String modelName;
  private final int cpuFrequency;
  private final int cacheSize;

  public CpuDetails(String vendorId, String modelName, int cpuFrequency, int cacheSize) {
    this.vendorId = vendorId;
    this.modelName = modelName;
    this.cpuFrequency = cpuFrequency;
    this.cacheSize = cacheSize;
  }

  public String getVendorId() {
    return vendorId;
  }

  public String getModelName() {
    return modelName;
  }

  /**
   * @return frequency in MHz
   */
  public int getCpuFrequency() {
    return cpuFrequency;
  }

  /**
   * @return cache size in kilobytes
   */
  public int getCacheSize() {
    return cacheSize;
  }

  @Override
  public String toString() {
    return "CpuDetails[" +
           "vendorId='" + vendorId + '\'' +
           ", modelName='" + modelName + '\'' +
           ", cpuFrequency(MHz)=" + cpuFrequency +
           ", cacheSize(KB)=" + cacheSize +
           ']';
  }
} public interface CpuService {

  int getCpuCount();

  List<CpuDetails> getAllCpuDetails();

  List<CpuUsage> getAllCpuUsage();
} public class CpuUsage {

  private final long user;
  private final long nice;
  private final long system;
  private final long idle;
  private final long ioWait;
  private final long irq;
  private final long softIrq;
  private final long steal;
  private final long guest;
  private final long guestNice;

  public CpuUsage(long user, long nice, long system, long idle, long ioWait, long irq, long softIrq, long steal,
                  long guest, long guestNice) {
    this.user = user;
    this.nice = nice;
    this.system = system;
    this.idle = idle;
    this.ioWait = ioWait;
    this.irq = irq;
    this.softIrq = softIrq;
    this.steal = steal;
    this.guest = guest;
    this.guestNice = guestNice;
  }

  public long getUser() {
    return user;
  }

  public long getNice() {
    return nice;
  }

  public long getSystem() {
    return system;
  }

  public long getIdle() {
    return idle;
  }

  public long getIoWait() {
    return ioWait;
  }

  public long getIrq() {
    return irq;
  }

  public long getSoftIrq() {
    return softIrq;
  }

  public long getSteal() {
    return steal;
  }

  public long getGuest() {
    return guest;
  }

  public long getGuestNice() {
    return guestNice;
  }

  public long getTotal() {
    return user + nice + system + idle + ioWait + irq + softIrq + steal + guest + guestNice;
  }

  @Override
  public String toString() {
    return "CpuUsage(milliseconds)[" +
           "user=" + user +
           ", nice=" + nice +
           ", system=" + system +
           ", idle=" + idle +
           ", ioWait=" + ioWait +
           ", irq=" + irq +
           ", softIrq=" + softIrq +
           ", steal=" + steal +
           ", guest=" + guest +
           ", guestNice=" + guestNice +
           ']';
  }

} public class CpuUsageRatio {

  private final float user;
  private final float nice;
  private final float system;
  private final float idle;
  private final float ioWait;
  private final float irq;
  private final float softIrq;
  private final float steal;
  private final float guest;
  private final float guestNice;
  private final long sampleTime;

  public CpuUsageRatio(CpuUsage start, CpuUsage end) {
    sampleTime = end.getTotal() - start.getTotal();
    if (sampleTime <= 0) {
      user = nice = system = idle = ioWait = irq = softIrq = steal = guest = guestNice = 0f;
    } else {
      user = getRatio(start.getUser(), end.getUser(), sampleTime);
      nice = getRatio(start.getNice(), end.getNice(), sampleTime);
      system = getRatio(start.getSystem(), end.getSystem(), sampleTime);
      idle = getRatio(start.getIdle(), end.getIdle(), sampleTime);
      ioWait = getRatio(start.getIoWait(), end.getIoWait(), sampleTime);
      irq = getRatio(start.getIrq(), end.getIrq(), sampleTime);
      softIrq = getRatio(start.getSoftIrq(), end.getSoftIrq(), sampleTime);
      steal = getRatio(start.getSteal(), end.getSteal(), sampleTime);
      guest = getRatio(start.getGuest(), end.getGuest(), sampleTime);
      guestNice = getRatio(start.getGuestNice(), end.getGuestNice(), sampleTime);
    }
  }

  private float getRatio(long start, long end, long totalDifference) {
    long difference = end - start;
    if (difference > totalDifference) {
      return 0f;
    }
    return (float) (difference / (double) totalDifference);
  }

  public float getUser() {
    return user;
  }

  public float getNice() {
    return nice;
  }

  public float getSystem() {
    return system;
  }

  public float getIdle() {
    return idle;
  }

  public float getIoWait() {
    return ioWait;
  }

  public float getIrq() {
    return irq;
  }

  public float getSoftIrq() {
    return softIrq;
  }

  public float getSteal() {
    return steal;
  }

  public float getGuest() {
    return guest;
  }

  public float getGuestNice() {
    return guestNice;
  }

  /**
   * @return milliseconds between measures
   */
  public long getSampleTime() {
    return sampleTime;
  }

  @Override
  public String toString() {
    NumberFormat formatter = NumberFormat.getPercentInstance();
    formatter.setMinimumFractionDigits(3);
    formatter.setMaximumFractionDigits(3);
    return "CpuUsageRatio[" +
           "user=" + formatter.format(user) +
           ", nice=" + formatter.format(nice) +
           ", system=" + formatter.format(system) +
           ", idle=" + formatter.format(idle) +
           ", ioWait=" + formatter.format(ioWait) +
           ", irq=" + formatter.format(irq) +
           ", softIrq=" + formatter.format(softIrq) +
           ", steal=" + formatter.format(steal) +
           ", guest=" + formatter.format(guest) +
           ", guestNice=" + formatter.format(guestNice) +
           ", sampleTime(milliseconds)=" + sampleTime +
           ']';
  }
} public class IOUtil {

  private static final AcceptAllLinesFilter ACCEPT_ALL_LINES_FILTER = new AcceptAllLinesFilter();

  public static final String EMPTY_STRING = "";

  public interface LineFilter {

    boolean accept(String line);
  }

  private IOUtil() {
    // Utility
  }

  public static String readFirstLine(File file) {
    if (file == null || !file.canRead()) {
      return EMPTY_STRING;
    }
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    try {
      fileReader = new FileReader(file);
      bufferedReader = new BufferedReader(fileReader);
      return bufferedReader.readLine();
    } catch (Exception e) {
      return EMPTY_STRING;
    } finally {
      closeQuietly(bufferedReader);
      closeQuietly(fileReader);
    }
  }

  public static List<String> readLines(File file) {
    return readLines(file, ACCEPT_ALL_LINES_FILTER);
  }

  public static List<String> readLines(File file, LineFilter lineFilter) {
    if (file == null || !file.canRead()) {
      return new ArrayList<String>();
    }
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    try {
      List<String> result = new ArrayList<String>();
      fileReader = new FileReader(file);
      bufferedReader = new BufferedReader(fileReader);
      for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
        if (lineFilter.accept(line)) {
          result.add(line);
        }
      }
      return result;
    } catch (Exception e) {
      return new ArrayList<String>();
    } finally {
      closeQuietly(bufferedReader);
      closeQuietly(fileReader);
    }
  }

  public static void closeQuietly(Closeable closeable) {
    if (closeable != null) {
      try {
        closeable.close();
      } catch (IOException ignore) {
      }
    }
  }

  private static class AcceptAllLinesFilter implements LineFilter {

    @Override
    public boolean accept(String line) {
      return true;
    }
  }
} public interface Log {

  boolean isTraceEnabled();

  void trace(String message);

  void trace(String message, Throwable t);

  boolean isDebugEnabled();

  void debug(String message);

  void debug(String message, Throwable t);

  boolean isInfoEnabled();

  void info(String message);

  void info(String message, Throwable t);

  boolean isWarnEnabled();

  void warn(String message);

  void warn(String message, Throwable t);

  void error(String message);

  void error(String message, Throwable t);
} public class LogFactory {

  private LogFactory() {
    // Factory
  }

  public static Log getLog(Class clazz) {
    return new ConsoleLog(clazz);
  }
}
import static java.lang.Long.parseLong;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.rhq.simone.util.IOUtil.closeQuietly;
import static org.rhq.simone.util.IOUtil.readLines;
import static org.rhq.simone.util.TickUtil.ticksToTimeUnit;
import jnr.constants.platform.Sysconf;
import jnr.posix.POSIX;
import jnr.posix.POSIXFactory;
import org.rhq.simone.cpu.CpuDetails;
import org.rhq.simone.cpu.CpuService;
import org.rhq.simone.cpu.CpuUsage;
import org.rhq.simone.cpu.CpuUsageRatio;
import org.rhq.simone.util.IOUtil;
import org.rhq.simone.util.log.Log;
import org.rhq.simone.util.log.LogFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/*
 * Copyright 2014 Red Hat, Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.rhq.simone.cpu.linux;




/**
 * @author Thomas Segismont
 */
public class LinuxCpuService implements CpuService {

  private static final Log LOG = LogFactory.getLog(LinuxCpuService.class);

  private static final CpuUsageLineFilter CPU_USAGE_LINE_FILTER = new CpuUsageLineFilter();

  private final int cpuCount;
  private final long ticksPerSecond;

  public LinuxCpuService(POSIX posix) {
    cpuCount = (int) posix.sysconf(Sysconf._SC_NPROCESSORS_CONF);
    ticksPerSecond = posix.sysconf(Sysconf._SC_CLK_TCK);
  }

  @Override
  public int getCpuCount() {
    return cpuCount;
  }

  @Override
  public List<CpuDetails> getAllCpuDetails() {
    List<CpuDetails> result = new ArrayList<CpuDetails>();
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    CpuDetailsParser cpuDetailsParser = null;
    try {
      fileReader = new FileReader("/proc/cpuinfo");
      bufferedReader = new BufferedReader(fileReader);
      cpuDetailsParser = new CpuDetailsParser(bufferedReader);
      for (CpuDetails cpuDetails : cpuDetailsParser) {
        result.add(cpuDetails);
      }
    } catch (FileNotFoundException e) {
      return result;
    } finally {
      closeQuietly(cpuDetailsParser);
      closeQuietly(bufferedReader);
      closeQuietly(fileReader);
    }
    return result;
  }

  @Override
  public List<CpuUsage> getAllCpuUsage() {
    List<String> cpuLines = readLines(new File("/proc/stat"), CPU_USAGE_LINE_FILTER);