Collector.java 2.8 KB
package se.lil.om;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

class Collector {
	ArrayList<LongDelta> list = new ArrayList<LongDelta>();
	String name = "";
	Boolean debugLog = false;
	
	public Collector(String name) {
		this.name = name;
	}
	
	public void update(ResultSet rset) throws Throwable {
		String timeStamp = null;
		BufferedWriter writer = null;
		
		if(debugLog) {
			timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
			writer = new BufferedWriter(new FileWriter("Collector_" + name + "_" + timeStamp + ".txt"));
		}
		while(rset.next()) {
			// Add try catch for issue #5
			Timestamp ts = rset.getTimestamp(1);
			String name = rset.getString(2);
			BigDecimal value;
			try {
				value = rset.getBigDecimal(3);
			}
			catch (java.sql.SQLException e) {
				value = BigDecimal.ZERO;
			}
			updateValue(ts, name, value);
			if(writer != null) {
				writer.write(ts + ":" + name + ":" + value);
				writer.newLine();
			}
		}
		if(writer != null) {
			writer.close();
		}
		rset.close();
	}
	
	public void updateValue(Timestamp timestamp, String name, BigDecimal value) {
		LongDelta myDelta = null;
		for(int x = 0; x<list.size() && myDelta == null; x++) {
			if(list.get(x).matches(name)) {
				myDelta = list.get(x);
			}
		}
		if(myDelta != null) {
			myDelta.update(value, timestamp);
		} else {
			myDelta = new LongDelta(name);
			myDelta.update(value, timestamp);
			list.add(myDelta);
		}
	}
	
	public long getCurrentValue(String name) throws Throwable {
		LongDelta myDelta = null;
		for(int x = 0; x<list.size() && myDelta == null; x++) {
			if(list.get(x).matches(name)) {
				myDelta = list.get(x);
			}
		}
		if(myDelta != null)
			return myDelta.getCurrentValue();
		else
			return 0;
	}
	
//	public long getDelta(String name) throws Throwable {
//		LongDelta myDelta = null;
//		for(int x = 0; x<list.size() && myDelta == null; x++) {
//			if(list.get(x).matches(name)) {
//				myDelta = list.get(x);
//			}
//		}
//		if(myDelta != null)
//			return myDelta.getDelta();
//		else
//			return 0;
//	}
	
	public double getPerSecValue(String name) throws Throwable {
		LongDelta myDelta = null;
		for(int x = 0; x<list.size() && myDelta == null; x++) {
			if(list.get(x).matches(name)) {
				myDelta = list.get(x);
			}
		}
		if(myDelta != null)
			return myDelta.getPerSecondValue();
		else
			return 0;
	}
	
	public double getSeconds(String name) throws Throwable {
		LongDelta myDelta = null;
		for(int x = 0; x<list.size() && myDelta == null; x++) {
			if(list.get(x).matches(name)) {
				myDelta = list.get(x);
			}
		}
		if(myDelta != null)
			return myDelta.getSeconds();
		else
			return 0;
	}
}