/*
 * GNU.FREE 2002
 *
 * Copyright (c) 1999, 2000, 2001, 2002
 * The Free Software Foundation (www.fsf.org)
 *
 * GNU.FREE Co-ordinator: Jason Kitcat <jeep@free-project.org>
 *
 * GNU site: http://www.gnu.org/software/free/
 * 
 * FREE e-democracy site: http://www.free-project.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program (COPYING); if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

package FreeTest;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

import Free.awt.*;

public class TestFrame1 extends Frame implements ActionListener
{

	public Vector stressVector;
	
	ScrollPane jScrollPane1 = new ScrollPane();
	TextArea jTextPane1 = new TextArea(10, 10);
	ScrollPane jScrollPane2 = new ScrollPane();
	TextArea jTextPane2 = new TextArea(10, 10);
	Label jLabel1 = new Label();
	Label jLabel2 = new Label();
	TextField jTextField1 = new TextField();
	Label jLabel3 = new Label();

	// menu vars
	MenuBar mb;
	Menu m1, m2, m3;
	MenuItem item1_1, item1_2, item1_3, item2_1, item2_2, item2_3, item2_4, item3_1, item3_2, item3_3, item3_4, item3_5, item3_6;
	
	public TestFrame1()
	{
		// build menu
		mb = new MenuBar();
		setMenuBar(mb);

		// it's a tear-off menu
		m1 = new Menu("Actions", true);
		mb.add(m1);
		item1_2 = new MenuItem("Verify ER Logs");
		m1.add(item1_2);
		item1_3 = new MenuItem("Verify RT Logs");
		m1.add(item1_3);
		item1_1 = new MenuItem("Exit");
		m1.add(item1_1);
		m2 = new Menu("RTServer Tests", true);
		mb.add(m2);
		item2_1 = new MenuItem("Boundary Tests");
		m2.add(item2_1);
		item2_2 = new MenuItem("Stamp Tests");
		m2.add(item2_2);
		item2_3 = new MenuItem("MAC Tests");
		m2.add(item2_3);
		item2_4 = new MenuItem("Stress Tests");
		m2.add(item2_4);
		m3 = new Menu("ERServer Tests", true);
		mb.add(m3);
		item3_1 = new MenuItem("Boundary Tests");
		m3.add(item3_1);
		item3_2 = new MenuItem("Auth Tests");
		m3.add(item3_2);
		item3_3 = new MenuItem("MAC Tests");
		m3.add(item3_3);
		item3_4 = new MenuItem("Stress Tests");
		m3.add(item3_4);
		item3_5 = new MenuItem("AuthKey Tests");
		m3.add(item3_5);
		item3_6 = new MenuItem("Build user data");
		m3.add(item3_6);
	}

	public Insets getInsets(){
	
		return new Insets( 20, 10, 10, 10);
	}
	
	public void initComponents() throws Exception
	{
		jScrollPane1.add(jTextPane1);
		jTextPane1.setVisible(true);
		jScrollPane2.add(jTextPane2);
		jLabel1.setFont( new Font("Dialog", Font.BOLD, 12));
		jLabel2.setFont( new Font("Dialog", Font.BOLD, 12));
		jLabel1.setText("Test Results");
		jLabel2.setText("Status");
		jTextField1.setLocation(new java.awt.Point(390, 240));
		jLabel3.setText("No. of connections");

		setLocation(new java.awt.Point(0, 0));
		setTitle("GNU.FREE: Test Suite");
		
		FreePanel scrollPanel = new FreePanel("GNU.FREE: Test Suite");
		scrollPanel.setInsets(3, 3, 3, 3);
		
		scrollPanel.addComponent( 1, 0, 1, 1, 0, 0, GridBagConstraints.NONE, 
			1.0f, 0.0f, jLabel2);
		scrollPanel.addComponent( 1, 2, 1, 1, 0, 0, GridBagConstraints.NONE, 
			1.0f, 0.0f, jLabel1);
		scrollPanel.addComponent( 2, 0, 19, 1, 0, 0, GridBagConstraints.BOTH, 
			0.4f, 1.0f, jTextPane1);
		scrollPanel.addComponent( 2, 2, 19, 1, 0, 0, GridBagConstraints.BOTH, 
			0.4f, 1.0f, jTextPane2);
			
		scrollPanel.addComponent( 3, 1, 1, 1, 0, 0, GridBagConstraints.BOTH, 
			0.2f, 0.0f, jLabel3);
		scrollPanel.addComponent( 4, 1, 1, 1, 0, 0, GridBagConstraints.HORIZONTAL, 
			0.2f, 0.0f, jTextField1);
		
		FreePanel fp = new FreePanel();
		
		fp.addComponent( 1, 1, 1, 1, 0, 0, GridBagConstraints.BOTH, 
			1.0f, 1.0f, scrollPanel);

		add(fp, BorderLayout.CENTER);
		setSize( 700, 500);
		
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent e) {
				thisWindowClosing(e);
			}
		});

		m1.addActionListener(this);
		m2.addActionListener(this);
		m3.addActionListener(this);
		
		item1_1.setActionCommand("item1_1");
		item1_2.setActionCommand("item1_2");
		item1_3.setActionCommand("item1_3");
		item2_1.setActionCommand("item2_1");
		item2_2.setActionCommand("item2_2");
		item2_3.setActionCommand("item2_3");
		item2_4.setActionCommand("item2_4");
		item3_1.setActionCommand("item3_1");
		item3_2.setActionCommand("item3_2");
		item3_3.setActionCommand("item3_3");
		item3_4.setActionCommand("item3_4");
		item3_5.setActionCommand("item3_5");
		item3_6.setActionCommand("item3_6");
	}
 
	// Show an informational message (black, plain text)
	protected void showInfo(String msg) {
		showMsg(msg);
	}
  
	// Show an warning message (red, bold text)
	protected void showError(String msg) {
		showMsg(msg);
	}
	
	// Show a text message using the specified AttributeSet
	protected void showMsg(String msg) {
		msg += "\n";
		jTextPane1.setText(jTextPane1.getText() + msg);
	}


	// Show an informational message (black, plain text)
	public void showInfo2(String msg) {
		showMsg2(msg);
	}
  
	// Show an warning message (red, bold text)
	public void showError2(String msg) {
		showMsg2(msg);
	}
	
	// Show a text message using the specified AttributeSet
	protected void showMsg2(String msg) {
		msg += "\n";
		jTextPane2.setText(jTextPane2.getText() + msg);
	}

	// Close the window when the close box is clicked
	void thisWindowClosing(java.awt.event.WindowEvent e)
	{
		setVisible(false);
		dispose();
		System.exit(0);
	}
	
	protected void checkLogs(String filename) {
		
		Vector logVector = new Vector(10000);
		Vector secVector = new Vector(10000);
		String inData = "";
		String previousString = "STARTING VALUE";
		boolean logOK = true;
		showInfo2("Reading data from " + filename + ".log and " + filename + ".sec.log");
	
		try {
			/* Read in log file */
			BufferedReader in = new BufferedReader(new FileReader(filename+".log"));
			inData = in.readLine();

			while (inData!=null) {
				// parse
				String data, status;
				int i=0;
				int t=0;
				data = inData;

				while (data.charAt(i)!=']') {
					i++;
				}
				
				t = i+5; // skip a safe amount (we know cat data there)
			
				while (data.charAt(t)!='-') {
					t++;
				}
				
				status = data.substring(t+2); // got true logging data

				logVector.addElement(status);
				inData = in.readLine();
			}
			in.close();
				
			inData = "";
				
			/* Read in log digest file */
			in = new BufferedReader(new FileReader(filename+".sec.log"));
			inData = in.readLine();

			while (inData!=null) {
				// no need to parse
				secVector.addElement(inData);
				inData = in.readLine();
			}
			in.close();
				
			String tempDigest;
				
			// work through the vectors checking if they match
			for (int q=0; (q < logVector.size())&(logOK == true); q++) {
				tempDigest = AuthSys.makeDigest(logVector.elementAt(q).toString() + previousString);
				//showInfo(logVector.elementAt(q).toString() + previousString);
				//showInfo(tempDigest + " - " + secVector.elementAt(q).toString());
				if (tempDigest.equalsIgnoreCase(secVector.elementAt(q).toString())) {
					// another line matches
					previousString = logVector.elementAt(q).toString();
				} else {
					// no match so report
					showError2("Log altered. Begins line: " + q);
					logOK = false;
				}
			}
			
			if (logOK) {
				showInfo2("Log checks out ok.");
			} else {
				showError2("The log has probably been altered.");
			}
				
		} catch (Exception ex) {
			showError2("Check Logs: " + ex.getMessage());
		}

	} //EOF checkLogs

	
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand()=="item1_1") {
			setVisible(false);
			dispose();
			System.exit(0);
		} else if (e.getActionCommand()=="item1_2") {
			// ER verify
			checkLogs("erserver");
		} else if (e.getActionCommand()=="item1_3") {
			// RT verify
			checkLogs("rtserver");
		} else if (e.getActionCommand()=="item2_1") {
			FTest.comms.isStress = false;
			Boundary.doVoteTests();
		} else if (e.getActionCommand()=="item2_2") {
			FTest.comms.isStress = false;
			Boundary.doStampTests();
		} else if (e.getActionCommand()=="item2_3") {
			FTest.comms.isStress = false;
			Boundary.doMACTests();
		} else if (e.getActionCommand()=="item2_4") {
		
			/* In this method we spin off multiple Stress classes which
			 * in turn start their own TCPClient thread to send a vote packet.
			 * Using this system we can simulate many simultaneous votes.
			 */

			int clients;
			Integer t;
			String superTemp = "";

			t = new Integer(jTextField1.getText());
			clients = t.intValue();
			stressVector = new Vector(clients);
			FTest.comms.stressClients = clients;

			Stress[] stressClients = new Stress[clients];  // array to hold threads
		
			try {
		
				showInfo2("Starting stress test...");
				showInfo2("Simulating " + clients + " clients.");

				FTest.comms.isStress = true;
				FTest.comms.stressCount = 0;
				
				// check check date stack is empty
				if (!FTest.comms.checkStack.isEmpty()) {
					FTest.comms.checkStack = new Vector();
				}

				// pre-create packet info to ease processing load
				FTest.comms.setType('V');
				FTest.comms.setCheck(new Date());
				FTest.comms.setsession_key(RSAEncrypt.makeSessionKey());
				
				// import user data
				String inData = "";

				showInfo2("Importing users from erserver.users");
	
				BufferedReader in = new BufferedReader(new FileReader("erserver.users"));
		
				inData = in.readLine();

				while (inData!=null) {
					// parse
					String data, name, code, pword, status;
					int i=0;
					int j=0;
					int k=0;
					data = inData;

					// parse to get seperate data fields
					while (data.charAt(i)!=',') {
						i++;
					}
					name = data.substring(0,i); // got name

					j = i+2;
					
					while (data.charAt(j)!=',') {
						j++;
					}
			
					code = data.substring((i+1),j); //got pin code
				
					k = j+2;
					
					while (data.charAt(k)!=',') {
						k++;
					}
				
					pword = data.substring((j+1),k); //got password
					status = data.substring(k+1);
					
					// build packet
					String tempKey = AuthKey.build(name,AuthSys.makeDigest(code),AuthSys.makeDigest(pword),2);
					String tempDate = new Date().toString();
					FTest.comms.checkStack.addElement(new String(tempKey+"-"+tempDate));
					data = tempDate + "-TEST-" + tempKey;
					showInfo2("Data: " + data);
					data = RSAEncrypt.pubEncrypt(FTest.comms.rt_public_key,FTest.comms.getsession_key()) + "-" + RSAEncrypt.blowEncrypt(FTest.comms.getsession_key(),"V|" + data + "|" + AuthSys.makeDigest("V|" + data));
					stressVector.addElement(data);
					inData = in.readLine();
				}
	 
				showInfo2("Import complete.");

				// initialise clients
				for (int i = 0; i < clients; i++) {
					stressClients[i] = new Stress(i);
				}
	
				FTest.comms.stressBefore = new Date();

				// go!
				for (int i = 0; i < clients; i++) {
					stressClients[i].start();
				}

			} catch (Exception exc) {
				FTest.frame.showError("Stress Test Error: " + exc.getMessage());
			}
		} else if (e.getActionCommand()=="item3_1") {
			FTest.comms.isStress = false;
			Boundary.doERTests();
		} else if (e.getActionCommand()=="item3_2") {
			FTest.comms.isStress = false;
			Boundary.doAuthTests();
		} else if (e.getActionCommand()=="item3_3") {
			FTest.comms.isStress = false;
			Boundary.doERMACTests();
		} else if (e.getActionCommand()=="item3_4") {
		
			/* In this method we spin off multiple Stress classes which
			 * in turn start their own TCPClient thread to send a vote packet.
			 * Using this system we can simulate auth requests.
			 */

			int clients;
			Integer t;

			t = new Integer(jTextField1.getText());
			clients = t.intValue();
			stressVector = new Vector(clients);
			FTest.comms.stressClients = clients;

			Stress[] stressClients = new Stress[clients];  // array to hold threads
		
			try {
		
				showInfo2("Starting stress test...");
				showInfo2("Simulating " + clients + " clients.");

				FTest.comms.isStress = true;
				FTest.comms.stressCount = 0;

				// pre-create packet info to ease processing load
				FTest.comms.setType('E');
				FTest.comms.setsession_key(RSAEncrypt.makeSessionKey());
				
				// import user data
				String inData = "";

				showInfo2("Importing users from erserver.users");
	
				BufferedReader in = new BufferedReader(new FileReader("erserver.users"));
		
				inData = in.readLine();

				while (inData!=null) {
					// parse
					String data, name, code, pword, status;
					int i=0;
					int j=0;
					int k=0;
					data = inData;

					// parse to get seperate data fields
					while (data.charAt(i)!=',') {
						i++;
					}
					name = data.substring(0,i); // got name

					j = i+2;
					
					while (data.charAt(j)!=',') {
						j++;
					}
			
					code = data.substring((i+1),j); //got pin code
				
					k = j+2;
					
					while (data.charAt(k)!=',') {
						k++;
					}
				
					pword = data.substring((j+1),k); //got password
					status = data.substring(k+1);
					
					// build packet
					data = name + "-" + AuthSys.makeDigest(code) + "-" + AuthSys.makeDigest(pword);
					data = RSAEncrypt.pubEncrypt(FTest.comms.er_public_key,FTest.comms.getsession_key()) + "-" + RSAEncrypt.blowEncrypt(FTest.comms.getsession_key(),"E|" + data + "|" + AuthSys.makeDigest("E|" + data));
					stressVector.addElement(data);
					inData = in.readLine();
				}
	 
				showInfo2("Import complete.");

				// initialise clients
				for (int i = 0; i < clients; i++) {
					stressClients[i] = new Stress(i);
				}
	
				FTest.comms.stressBefore = new Date();

				// go!
				for (int i = 0; i < clients; i++) {
					stressClients[i].start();
				}

			} catch (Exception exc) {
				FTest.frame.showError("Stress Test Error: " + exc.getMessage());
			}
		} else if (e.getActionCommand()=="item3_5") {
			FTest.comms.isStress = false;
			Boundary.doERKeyTests();
		} else if (e.getActionCommand()=="item3_6") {
			try {
				FTest.frame.showInfo("Building erserver.users...");
		
				File keyFile = new File("erserver.users");
				FileWriter out = new FileWriter(keyFile);
				String temp;
				Integer t;
				int count;
				t = new Integer(jTextField1.getText());
				count = t.intValue();

				for (int i = 0; i < count; i++) {
					// build output
					temp = "test"+i+",1234,"+i+"tset,F,I";
					out.write(temp + "\r\n");
				}
			
				out.close();
				FTest.frame.showInfo("Done! Wrote erserver.users for export.");
			} catch (Exception exc) {
				FTest.frame.showError("File build error: " + exc.getMessage());
			}
		} else {
			FTest.frame.showInfo("Command not recognised!");
		}
	}
	
} //eof testframe1
