package com.ns;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.Counters;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobStatus;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.Counters.Counter;

public class CounterUtility {

	long count;

	public long getCounter(String jobName, String groupName,
			String counterName) throws IOException {
		try {
			Configuration conf = new Configuration();
			JobClient job = new JobClient(
					new InetSocketAddress("100.100.100.222", 9001), conf);
			if (job == null) {
				System.out.println("Job is null");
			}
			JobStatus[] jobStatus = job.getAllJobs();

			for (int i = 0; i < jobStatus.length; i++) {

				if (true) {
					//if (jobStatus[i].getRunState() == jobStatus[i].RUNNING) {

						RunningJob runningjob = job.getJob(jobStatus[i]
								.getJobID());
						Counters counters = runningjob.getCounters();
						// System.out.println(" the job name is "+jobName);
						if (runningjob.getJobName().equalsIgnoreCase(jobName)) {
							Counter counter = counters.findCounter(groupName,
									counterName);

							count = counter.getCounter();
							System.out.println(" the count id " + count);

						}
					}
				}
			//}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return count;
	}

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		CounterUtility con = new CounterUtility();
		System.out.println("the counter is "+con.getCounter("Doc Extraction", "com.integreon.util.Utility", "Extraction"));

	}

}
