
/*Copyright 2011 Veeresh Rudrappa & Dilum Bandara

		   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.
 */

/*** Contact Info *****
 * 
 * Veeresh Rudrappa  
 * Colorado State University
 * email: veeresh.rudrappa@colostate.edu
 * 
 * Dilum Bandara
 * Colorado State University
 * email: dilumb@engr.colostate.edu
 * 
 */

package com.project.extract;


import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.GregorianCalendar;
import java.util.Timer;
import java.util.TimerTask;
import java.lang.reflect.*;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


import com.project.schedule.Scheduler;

/*  Order In which Data has been written to File       
  
  	
  	MacAddr
    IPaddr
	Interface
	Model
	NumCores
	ProcSpeed
	Vendor
	cacheSize
	RamSize
    MemAvail
    MemUsedPerc
    MemFreePerc
    SwapAvail
    SwapUsed
	Uptime
	FileSystem
	MaxSpace
	FreeSpace
	OsName
	OSDescription	
	OSArch
	
	OsVersion
	UnixTime
	OneMinAvg
	FiveMinAvg
	FifteenMinAvg
	MTU
	RX TX Bytes
	CPU flags
	Num Process Extracted
	Process Name Proc Cpu Util 	Proc Mem Util
		
  */

public class SystemInfo {
	
	
	static String TopS;
	static String OneMinAvg;
	static String FiveMinAvg;
	static String FifMinAvg;
	static String MTU;

	
	public static String MacFileName;
	public static String InfoFile;
	
	private final static long ONCE_EVERY_HOUR = 1000*60*60;
	
	public static String uploadLocation;


	
	 private static int MINUTES = 7;

/**** Main function *********/
	 
	 
	public static void main(String[] args)throws Exception
	{
	

		String Country="";
		String Location="";
		String ComputerType="";
		String OwnerType="";
		
		

		int Choice;
		System.out.println("Application Started");
		
		Random diceRoller = new Random();
		MINUTES = diceRoller.nextInt(60);
		
		String userHome=System.getProperty("user.home");

		System.setProperty( "java.library.path", userHome+"/ResourceTracker/SigarLib");

		Field fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
		fieldSysPath.setAccessible( true );
		fieldSysPath.set( null, null );
		
		
		NetworkInfo net= new NetworkInfo();
		net.outputTcpStats();
		net.output();
		String[] token= net.MacAddr.split(":");
		
		MacFileName = token[0]+token[1]+token[2]+token[3]+token[4]+token[5];

	
		InfoFile = SystemInfo.MacFileName + "_Info.txt";
		
		File config = new File(userHome+"/ResourceTracker/"+"ConfigFile.txt");
		
		if(!config.exists()) 
		{ 
		
			FileWriter Cs = new FileWriter(userHome+"/ResourceTracker/"+"ConfigFile.txt",true);
			PrintWriter cw = new PrintWriter(Cs);
			
			try{
				System.out.println("Enter The Address of the Server Where You Want To Upload Your Data.");
				
				BufferedReader UserInput = new BufferedReader(new InputStreamReader(System.in));
				String address = UserInput.readLine();
				cw.println(address);
				
				cw.close();
			
			}
			catch(Exception e)
			{
				
			}
			
		    BufferedReader fileInput =  new BufferedReader(new FileReader(userHome+"/ResourceTracker/"+"ConfigFile.txt"));
		      try {
		    	  uploadLocation  = fileInput.readLine(); 
		    	  fileInput.close();
		      }
		      catch(Exception e)
		      {
		    	  
		      }
			
		}
		File f = new File(userHome+"/ResourceTracker/"+InfoFile);
		if(!f.exists()) 
		{ 
						
					
		FileWriter Is = new FileWriter(userHome+"/ResourceTracker/"+InfoFile,true);
		PrintWriter Fd = new PrintWriter(Is);	
		
		try{
			
		BufferedReader UserIn = new BufferedReader(new InputStreamReader(System.in));
		
		
		
		System.out.println("Kindly answer few questions which would help us in our Research");
		
		System.out.println("A.Enter the Country Name where this Computer is Located");
		Country=UserIn.readLine();

		
		System.out.println("B.Enter the City Name where this Computer is Located");
		Location=UserIn.readLine();

		
		System.out.println("C.This Machine is :");
		System.out.println("Enter 1  for Laptop");
		System.out.println("Enter 2  for Desktop");
		
		Choice = Integer.parseInt(UserIn.readLine());
		
		if(Choice==1){
			ComputerType="Laptop";
		}
		else if(Choice==2){
			ComputerType="Personal Desktop";
		}
		else{
			
			ComputerType="UnKnown";
		}

		
		System.out.println("C.This Computer is :");
		System.out.println("Enter 1  for Personal Computer");
		System.out.println("Enter 2  for College Campus Computer");
		System.out.println("Enter 3  for Office(WorkPlace) Computer");
		
		
		Choice = Integer.parseInt(UserIn.readLine());
		
		if(Choice==1){
			OwnerType="Personal Computer";
		}
		else if(Choice==2){
			OwnerType="College Campus Computer";
		}
		else if(Choice==3){
			OwnerType="College Office Computer";
		}
		else{
			
			OwnerType="UnKnown";
		}
		
		Fd.println("Country :"+Country);
		Fd.println("City :"+Location);
		Fd.println("ComputerType : "+ComputerType);
		Fd.println("Ownertype :"+OwnerType);
		
		Fd.close();
		Is.close();
		
		
	
		SystemInfo.upload();

		
		System.out.println("Thank you, The Application is Scheduled and will run in the Background");
		

		}catch(Exception e){
			
			System.out.println("Kindly Restart the Application "+e);

		}
		finally{
			System.exit(0);
		}
		
		
		}
		
/* Till Here **/		
		
		
		/********** Scheduling a Task ***********/
		
		
		TimerTask UploadFile  = new Scheduler();
		Timer timer = new Timer();
		
		/******* Copy The Period *******/
		
		timer.scheduleAtFixedRate(UploadFile , UploadTomorrow(), ONCE_EVERY_HOUR);
	
		PrintWriter pw= null;
	
		while(true)
		{
			
			try{
		
		  Calendar today = new GregorianCalendar();
		  int todayDate = today.get(Calendar.DATE);
		   
		  
		  String WriteFileName = SystemInfo.MacFileName + "_" +  todayDate + ".txt";
		
		
		  FileWriter fs = new FileWriter(userHome+"/ResourceTracker/"+WriteFileName,true);
		  pw = new PrintWriter(fs);

		  /********* Network Information ********/
		  
		  NetworkInfo netinfo= new NetworkInfo();
		  netinfo.outputTcpStats();
		  netinfo.output(); 
		
		  pw.println((netinfo.MacAddr));
		  pw.println((netinfo.IPaddr));
		  pw.println((netinfo.Interface));



		
		  /******** CPU Information *********/
		
		
		  CpuInfo cpuinfo =new CpuInfo();
		  cpuinfo.output();
		
		  pw.println((cpuinfo.Model));
		  pw.println((cpuinfo.NumCores));
		  pw.println((cpuinfo.ProcSpeed));
		  pw.println((cpuinfo.Vendor));
		  pw.println((cpuinfo.cacheSize));
		
		
		/******** Memory Information **********/
		
		  Memory meminfo = new Memory();
		  meminfo.output();
		      
		  pw.println((meminfo.RamSize));
		  pw.println((meminfo.MemAvail));
		  pw.println((meminfo.MemUsedPerc));
		  pw.println((meminfo.MemFreePerc));
		  pw.println((meminfo.SwapAvail));
		  pw.println((meminfo.SwapUsed));
                
				
		  Uptime uptime=new Uptime();
		  uptime.output();
		
		  pw.println((uptime.Uptime));
		
		
		
		  GeneralInfo geninfo=new GeneralInfo();

		  /****** Hard Disk Memory Information ******/
		  
		  geninfo.RuntimeProperties();
				
		  for(int i=0;i<GeneralInfo.NumFs;i++){
			pw.println(geninfo.Memory[i].FsystemRoot);
			pw.println(geninfo.Memory[i].MaxSpace);
			pw.println(geninfo.Memory[i].FreeSpace);
		  }
		
		  /*** OS Information ******/
	
		  geninfo.getOsInfo();	

		  pw.println(geninfo.OsName);
		  pw.println(geninfo.OsDesc);
		  pw.println(geninfo.OsArch);
		  pw.println(geninfo.OsVersion);

		
		  //UnixTime
		  
		  long unixTime = System.currentTimeMillis() / 1000L;

		  pw.println(unixTime);
			
		  String[] tokens = uptime.Uptime.split("average: ");
		  tokens = tokens[1].split(", ");
		
		  OneMinAvg= new String(tokens[0]);
		  FiveMinAvg= new String(tokens[1]);
		  FifMinAvg= new String(tokens[2]);

		  pw.println(OneMinAvg);
		  pw.println(FiveMinAvg);
		  pw.println(FifMinAvg);

		  
		  /******* Extract process Total RX and TX bytes From ifconfig *****/
		  
		  
		  Process ProcIfconfig = Runtime.getRuntime().exec("/sbin/ifconfig");
		  ProcIfconfig.waitFor();
		  
		  BufferedReader in = new BufferedReader(new InputStreamReader(ProcIfconfig.getInputStream()));
		  String RxTX = null;

		  while((RxTX= in.readLine())!=null)
		  {
		
				if((RxTX.contains("MTU"))){
					
				int index= RxTX.lastIndexOf("MTU");
				
					MTU=RxTX.substring(index+4, index+8);
					pw.println(MTU);
					
					
				}
				if((RxTX.contains("RX bytes"))){
			
				
				pw.println(RxTX);			
				break;
			
				}
			
		  }
		
		  /******* Extract process Cpu Flags From /proc/cpuinfo *****/
		  
		  
		Process Proc = Runtime.getRuntime().exec("cat /proc/cpuinfo");
		Proc.waitFor();
		
		BufferedReader Pinput = new BufferedReader(new InputStreamReader(Proc.getInputStream()));
		String Flags = null;

		while((Flags= Pinput.readLine())!=null)
		{
				if((Flags.contains("flags"))){
			
			String[] tok= Flags.split(": ");
				pw.println(tok[1]);
			
				break;
				
			
			}
		}
		
		
		pw.println("10");

		/******* Extract process Cpu Usage From Top Command *****/
		
		Process P = Runtime.getRuntime().exec("top -b -n 1");
		P.waitFor();
		
		BufferedReader StdInput = new BufferedReader(new InputStreamReader(P.getInputStream()));

		int i=0;
		
		try{
			
		while((TopS= StdInput.readLine())!=null)
		{
		
			if(i==2)
				pw.println(TopS);

			if(i>6 && i<17)
			{

				TopS=TopS.replaceAll("  ", " ");
				TopS=TopS.replaceAll("  ", " ");
				TopS=TopS.replaceAll("  ", " ");
				
				String[] tokens1= TopS.split(" ");
				
				int j=8;
				if(tokens1[0].isEmpty())
					j=j+1;
				
				String ProcCpuUtil = new String(tokens1[j]);
				
				j++;
			
				Float ProcMemUtil = Float.parseFloat(tokens1[j]);
				
				j = j+2;

				String ProcName = new String(tokens1[j]);

				pw.print(ProcName+"\t");
				pw.print(ProcCpuUtil+"\t");
				pw.println(ProcMemUtil);
				
			}
			i++;
			
		}
		}
		catch(Exception e){
			
			
			System.out.println("Exception "+e);
			
		}
		
		pw.println("\n\n");
		pw.close();	

	}
	catch(Exception e){

		System.err.println("Error: " + e.getMessage());
		pw.close();	
	}

			Thread.sleep(60000);
	}

		
	}

	/****** Schedule timer *******/
	
	
	/********* Even THis *************/
	
	private static Date UploadTomorrow(){
	    Calendar tomorrow = new GregorianCalendar();
	    //tomorrow.add(Calendar.DATE, 1);
	    Calendar result = new GregorianCalendar(
	      tomorrow.get(Calendar.YEAR),
	      tomorrow.get(Calendar.MONTH),
	      tomorrow.get(Calendar.DATE),
	      tomorrow.get(Calendar.HOUR_OF_DAY),
	      MINUTES
	    );
	    
	    
	    
	    return result.getTime();
	  }


	  public static void upload() throws Exception {
		
		
		  try{

		  
		  
		  String userHome=System.getProperty("user.home");
		  
		  String FileName = SystemInfo.InfoFile;
		  

		  
		HttpClient httpclient = new DefaultHttpClient();
	    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
	    
	    


	    HttpPost httppost = new HttpPost(uploadLocation);
	    
	    

	    
	    File file = new File(userHome+"/ResourceTracker/"+FileName);

	    
	    MultipartEntity mpEntity = new MultipartEntity();
	    ContentBody cbFile = new FileBody(file);
	    mpEntity.addPart("userfile", cbFile);

	    
	    
	    httppost.setEntity(mpEntity);
	    
	    
	    
	    System.out.println("executing request " + httppost.getRequestLine());
	    HttpResponse response = httpclient.execute(httppost);
	    HttpEntity resEntity = response.getEntity(); 
	    

	    System.out.println(response.getStatusLine());
	    
	    
	    
	    if (resEntity != null) {
	      System.out.println(EntityUtils.toString(resEntity));
	    }
	    if (resEntity != null) {
	      resEntity.consumeContent();
	    }

	    httpclient.getConnectionManager().shutdown();
	  
	
	  }catch(Exception e){
		  
		  System.out.println("Exception in upload function: "+e);
		  
	  }
	
	
}
	  
}
