Selaa lähdekoodia

Revert "Organized and formatted whole project"

This reverts commit 5cd5ede8fff9ecd95c9bcce72f9119275d3c5f56.
Tankernn 10 vuotta sitten
vanhempi
commit
5cbec855d1
31 muutettua tiedostoa jossa 402 lisäystä ja 513 poistoa
  1. 16 16
      src/main/java/client/ChatClient.java
  2. 76 99
      src/main/java/client/ChatWindow.java
  3. 11 15
      src/main/java/client/Console.java
  4. 15 22
      src/main/java/command/Ban.java
  5. 5 9
      src/main/java/command/Command.java
  6. 6 7
      src/main/java/command/CreateChannel.java
  7. 2 2
      src/main/java/command/Exit.java
  8. 8 18
      src/main/java/command/Help.java
  9. 6 9
      src/main/java/command/JoinChannel.java
  10. 4 6
      src/main/java/command/Kick.java
  11. 10 15
      src/main/java/command/LeaveChannel.java
  12. 10 15
      src/main/java/command/List.java
  13. 6 10
      src/main/java/command/PrivateMessage.java
  14. 14 21
      src/main/java/common/Message.java
  15. 10 13
      src/main/java/server/BanNote.java
  16. 3 3
      src/main/java/server/Channel.java
  17. 44 51
      src/main/java/server/Client.java
  18. 23 26
      src/main/java/server/ClientCollection.java
  19. 58 0
      src/main/java/server/CommandHandler.java
  20. 0 57
      src/main/java/server/CommandRegistry.java
  21. 7 8
      src/main/java/server/LocalClient.java
  22. 6 6
      src/main/java/server/Logger.java
  23. 6 7
      src/main/java/server/Pong.java
  24. 17 7
      src/main/java/server/Server.java
  25. 0 13
      src/main/java/server/util/Numbers.java
  26. 0 18
      src/main/java/server/util/StringArrays.java
  27. 18 18
      src/test/java/client/ClientTestCase.java
  28. 1 2
      src/test/java/client/ClientTestSuite.java
  29. 4 4
      src/test/java/common/CompleteTestSuite.java
  30. 9 9
      src/test/java/server/ServerTestCase.java
  31. 7 7
      src/test/java/server/ServerTestSuite.java

+ 16 - 16
src/main/java/client/ChatClient.java

@@ -16,8 +16,8 @@ import javax.swing.JTextField;
 public class ChatClient {
 public class ChatClient {
 	static Properties prop = new Properties();
 	static Properties prop = new Properties();
 	static File confFile = new File("client.properties");
 	static File confFile = new File("client.properties");
-
-	public static void main(String[] arg) {
+	
+	public static void main (String[] arg) {
 		try {
 		try {
 			prop.load(new FileInputStream(confFile));
 			prop.load(new FileInputStream(confFile));
 		} catch (FileNotFoundException e) {
 		} catch (FileNotFoundException e) {
@@ -27,24 +27,25 @@ public class ChatClient {
 		} catch (IOException e) {
 		} catch (IOException e) {
 			e.printStackTrace();
 			e.printStackTrace();
 		}
 		}
-
+		
 		JTextField hostBox = new JTextField(prop.getProperty("host"));
 		JTextField hostBox = new JTextField(prop.getProperty("host"));
 		JTextField portBox = new JTextField(prop.getProperty("port"));
 		JTextField portBox = new JTextField(prop.getProperty("port"));
 		JTextField userBox = new JTextField(prop.getProperty("username"));
 		JTextField userBox = new JTextField(prop.getProperty("username"));
-		final JComponent[] inputs = new JComponent[] { new JLabel("Host:"),
-				hostBox, new JLabel("Port:"), portBox, new JLabel("Username:"),
-				userBox };
-
+		final JComponent[] inputs = new JComponent[] {
+				new JLabel("Host:"), hostBox,
+				new JLabel("Port:"), portBox,
+				new JLabel("Username:"), userBox
+		};
+		
 		String host, username, portString;
 		String host, username, portString;
-
-		JOptionPane.showMessageDialog(null, inputs, "Chat settings",
-				JOptionPane.PLAIN_MESSAGE);
-
+		
+		JOptionPane.showMessageDialog(null, inputs, "Chat settings", JOptionPane.PLAIN_MESSAGE);
+		
 		host = hostBox.getText();
 		host = hostBox.getText();
 		prop.setProperty("host", host);
 		prop.setProperty("host", host);
 		username = userBox.getText();
 		username = userBox.getText();
 		prop.setProperty("username", username);
 		prop.setProperty("username", username);
-
+		
 		portString = portBox.getText();
 		portString = portBox.getText();
 		Scanner sc = new Scanner(portString);
 		Scanner sc = new Scanner(portString);
 		int port = sc.nextInt();
 		int port = sc.nextInt();
@@ -52,16 +53,15 @@ public class ChatClient {
 		prop.setProperty("port", portString);
 		prop.setProperty("port", portString);
 
 
 		writeConfFile();
 		writeConfFile();
-
+		
 		new ChatWindow(host, port, username);
 		new ChatWindow(host, port, username);
 	}
 	}
-
+	
 	static void writeConfFile() {
 	static void writeConfFile() {
 		try {
 		try {
 			if (!confFile.exists())
 			if (!confFile.exists())
 				confFile.createNewFile();
 				confFile.createNewFile();
-			prop.store(new FileOutputStream(confFile),
-					"Configuration for chat client");
+			prop.store(new FileOutputStream(confFile), "Configuration for chat client");
 		} catch (IOException e) {
 		} catch (IOException e) {
 			e.printStackTrace();
 			e.printStackTrace();
 		}
 		}

+ 76 - 99
src/main/java/client/ChatWindow.java

@@ -19,66 +19,55 @@ import java.net.Socket;
 import java.net.SocketTimeoutException;
 import java.net.SocketTimeoutException;
 import java.util.ArrayList;
 import java.util.ArrayList;
 
 
-import javax.swing.DefaultListModel;
-import javax.swing.JButton;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JList;
-import javax.swing.JPanel;
-import javax.swing.JScrollPane;
-import javax.swing.JTextField;
-import javax.swing.ListSelectionModel;
-import javax.swing.SwingConstants;
-import javax.swing.WindowConstants;
+import javax.swing.*;
 import javax.swing.border.EmptyBorder;
 import javax.swing.border.EmptyBorder;
 
 
 import common.Message;
 import common.Message;
 import common.Message.MessageType;
 import common.Message.MessageType;
 
 
 @SuppressWarnings("serial")
 @SuppressWarnings("serial")
-public class ChatWindow extends JFrame implements ActionListener, Runnable,
-		KeyListener {
+public class ChatWindow extends JFrame implements ActionListener, Runnable, KeyListener{
 	Thread getMessages;
 	Thread getMessages;
 	static File confFile = new File("client.properties");
 	static File confFile = new File("client.properties");
-
+	
 	String adress, username;
 	String adress, username;
 	ArrayList<String> lastMess = new ArrayList<String>();
 	ArrayList<String> lastMess = new ArrayList<String>();
 	int port, messIndex = 0;
 	int port, messIndex = 0;
-
+	
 	Socket so = new Socket();
 	Socket so = new Socket();
 	ObjectInputStream objIn;
 	ObjectInputStream objIn;
 	PrintWriter out;
 	PrintWriter out;
-
+	
 	GridBagLayout g = new GridBagLayout();
 	GridBagLayout g = new GridBagLayout();
 	GridBagConstraints con = new GridBagConstraints();
 	GridBagConstraints con = new GridBagConstraints();
-
+	
 	JPanel right = new JPanel();
 	JPanel right = new JPanel();
 	JLabel lblUsersOnline = new JLabel("Users online:");
 	JLabel lblUsersOnline = new JLabel("Users online:");
 	DefaultListModel<String> model = new DefaultListModel<String>();
 	DefaultListModel<String> model = new DefaultListModel<String>();
 	JList<String> userList = new JList<String>(model);
 	JList<String> userList = new JList<String>(model);
 	JButton reconnect = new JButton("Reconnect");
 	JButton reconnect = new JButton("Reconnect");
-
+	
 	Console chat = new Console();
 	Console chat = new Console();
 	JScrollPane scroll = new JScrollPane(chat);
 	JScrollPane scroll = new JScrollPane(chat);
 	JTextField write = new JTextField();
 	JTextField write = new JTextField();
-
+	
 	public ChatWindow(String adress, int port, String username) {
 	public ChatWindow(String adress, int port, String username) {
 		this.adress = adress;
 		this.adress = adress;
 		this.port = port;
 		this.port = port;
 		this.username = username;
 		this.username = username;
-
-		// List config
+		
+		//List config
 		userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
 		userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
 		userList.setLayoutOrientation(JList.VERTICAL);
 		userList.setLayoutOrientation(JList.VERTICAL);
-		// Label config
-		lblUsersOnline.setHorizontalAlignment(SwingConstants.CENTER);
+		//Label config
+		lblUsersOnline.setHorizontalAlignment(JLabel.CENTER);
 		lblUsersOnline.setBorder(new EmptyBorder(5, 5, 5, 5));
 		lblUsersOnline.setBorder(new EmptyBorder(5, 5, 5, 5));
-		// Layout config
+		//Layout config
 		right.setLayout(g);
 		right.setLayout(g);
 		con.fill = GridBagConstraints.HORIZONTAL;
 		con.fill = GridBagConstraints.HORIZONTAL;
 		con.weightx = 1;
 		con.weightx = 1;
 		con.gridx = 0;
 		con.gridx = 0;
-
+		
 		right.add(lblUsersOnline, con);
 		right.add(lblUsersOnline, con);
 
 
 		con.weighty = 1;
 		con.weighty = 1;
@@ -88,81 +77,75 @@ public class ChatWindow extends JFrame implements ActionListener, Runnable,
 		con.weighty = 0;
 		con.weighty = 0;
 		con.fill = GridBagConstraints.HORIZONTAL;
 		con.fill = GridBagConstraints.HORIZONTAL;
 		right.add(reconnect, con);
 		right.add(reconnect, con);
-
+		
 		setLayout(new BorderLayout());
 		setLayout(new BorderLayout());
-		add(chat, BorderLayout.NORTH);
-		add(write, BorderLayout.SOUTH);
-		add(right, BorderLayout.EAST);
-
-		// Scrollbar config
+		add(chat, BorderLayout.NORTH); add(write, BorderLayout.SOUTH); add(right, BorderLayout.EAST);
+		
+		//Scrollbar config
 		add(scroll);
 		add(scroll);
 		scroll.setMinimumSize(new Dimension(100, 100));
 		scroll.setMinimumSize(new Dimension(100, 100));
 		scroll.setViewportView(chat);
 		scroll.setViewportView(chat);
 		scroll.setSize(500, 130);
 		scroll.setSize(500, 130);
-
-		// Listener config
+		
+		//Listener config
 		reconnect.addActionListener(this);
 		reconnect.addActionListener(this);
 		write.addKeyListener(this);
 		write.addKeyListener(this);
-
-		// Window config
+		
+		//Window config
 		this.setLocation(new Point(100, 100));
 		this.setLocation(new Point(100, 100));
 		setSize(600, 600);
 		setSize(600, 600);
 		setVisible(true);
 		setVisible(true);
 		setTitle("Chat on " + adress + " | Username: " + username);
 		setTitle("Chat on " + adress + " | Username: " + username);
 		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
-
+		
 		connect(adress, port, username);
 		connect(adress, port, username);
 	}
 	}
-
+	
 	public void send(String text) {
 	public void send(String text) {
 		if (so.isConnected() && !so.isClosed())
 		if (so.isConnected() && !so.isClosed())
 			out.println(text);
 			out.println(text);
 		else {
 		else {
-			chat.log(new Message("Not connected to server!",
-					MessageType.WARNING, false));
+			chat.log(new Message("Not connected to server!", MessageType.WARNING, false));
 			write.setEnabled(false);
 			write.setEnabled(false);
 		}
 		}
 	}
 	}
-
+	
 	void connect(String address, int port, String username) {
 	void connect(String address, int port, String username) {
-		chat.log(new Message("Connecting to " + address + " on port " + port
-				+ ".", MessageType.INFO, false));
+		chat.log(new Message("Connecting to " + address + " on port " + port + ".", MessageType.INFO, false));
 		if (getMessages != null)
 		if (getMessages != null)
 			getMessages.interrupt();
 			getMessages.interrupt();
-
+		
 		try {
 		try {
 			so.close();
 			so.close();
 			objIn.close();
 			objIn.close();
 			out.close();
 			out.close();
 		} catch (NullPointerException ex) {
 		} catch (NullPointerException ex) {
-			// Nothing
+			//Nothing
 		} catch (IOException ex) {
 		} catch (IOException ex) {
 			chat.log(new Message(ex.toString(), MessageType.ERROR, false));
 			chat.log(new Message(ex.toString(), MessageType.ERROR, false));
 		}
 		}
-
+		
 		try {
 		try {
 			so = new Socket();
 			so = new Socket();
 			so.connect(new InetSocketAddress(address, port), 1000);
 			so.connect(new InetSocketAddress(address, port), 1000);
-			objIn = new ObjectInputStream(so.getInputStream());
-			out = new PrintWriter(so.getOutputStream(), true);
+			objIn =		new ObjectInputStream(so.getInputStream());
+			out =		new PrintWriter(so.getOutputStream(), true);
 		} catch (SocketTimeoutException ex) {
 		} catch (SocketTimeoutException ex) {
-			chat.log(new Message(
-					"Could not connect to server. (Connection timed out!)",
-					MessageType.ERROR, false));
+			chat.log(new Message("Could not connect to server. (Connection timed out!)", MessageType.ERROR, false));
 			return;
 			return;
 		} catch (IOException e) {
 		} catch (IOException e) {
 			chat.log(new Message(e.toString(), MessageType.ERROR, false));
 			chat.log(new Message(e.toString(), MessageType.ERROR, false));
 			return;
 			return;
 		}
 		}
-
-		send(username); // First packet sent to server sets username
-
+		
+		send(username); //First packet sent to server sets username
+		
 		getMessages = new Thread(this);
 		getMessages = new Thread(this);
 		getMessages.start();
 		getMessages.start();
-
+		
 		write.setEnabled(true);
 		write.setEnabled(true);
 	}
 	}
-
+	
 	@Override
 	@Override
 	public void actionPerformed(ActionEvent e) {
 	public void actionPerformed(ActionEvent e) {
 		if (e.getSource() == reconnect)
 		if (e.getSource() == reconnect)
@@ -174,35 +157,31 @@ public class ChatWindow extends JFrame implements ActionListener, Runnable,
 		try {
 		try {
 			getMessages();
 			getMessages();
 		} catch (EOFException eof) {
 		} catch (EOFException eof) {
-			chat.log(new Message(eof.toString() + " Disconnected from host.",
-					MessageType.ERROR, false));
+			chat.log(new Message(eof.toString() + " Disconnected from host.", MessageType.ERROR, false));
 		} catch (ClassNotFoundException cnf) {
 		} catch (ClassNotFoundException cnf) {
-			chat.log(new Message(
-					"The message recieved from the server could not be understood. Are you using the right version?",
-					MessageType.ERROR, false));
+			chat.log(new Message("The message recieved from the server could not be understood. Are you using the right version?", MessageType.ERROR, false));
 		} catch (IOException e) {
 		} catch (IOException e) {
 			chat.log(new Message(e.toString(), MessageType.ERROR, false));
 			chat.log(new Message(e.toString(), MessageType.ERROR, false));
 		}
 		}
 	}
 	}
-
+	
 	public void getMessages() throws IOException, ClassNotFoundException {
 	public void getMessages() throws IOException, ClassNotFoundException {
-		while (!getMessages.isInterrupted()) {
+		while(!getMessages.isInterrupted()) {
 			Object fromServer = objIn.readObject();
 			Object fromServer = objIn.readObject();
 			if (fromServer instanceof Message) {
 			if (fromServer instanceof Message) {
-				Message mess = ((Message) fromServer);
+				Message mess = ((Message)fromServer);
 				chat.log(mess);
 				chat.log(mess);
-
+				
 				if (mess.usersOnline == null)
 				if (mess.usersOnline == null)
 					continue;
 					continue;
-
+				
 				model = new DefaultListModel<String>();
 				model = new DefaultListModel<String>();
-				for (String user : mess.usersOnline)
+				for (String user: mess.usersOnline)
 					model.addElement(user);
 					model.addElement(user);
-
+				
 				userList.setModel(model);
 				userList.setModel(model);
 			} else if (fromServer instanceof String) {
 			} else if (fromServer instanceof String) {
-				chat.log(new Message((String) fromServer, MessageType.NORMAL,
-						false));
+				chat.log(new Message((String)fromServer, MessageType.NORMAL, false));
 			} else
 			} else
 				throw new ClassNotFoundException();
 				throw new ClassNotFoundException();
 		}
 		}
@@ -211,39 +190,37 @@ public class ChatWindow extends JFrame implements ActionListener, Runnable,
 	@Override
 	@Override
 	public void keyPressed(KeyEvent eKey) {
 	public void keyPressed(KeyEvent eKey) {
 		int keyCode = eKey.getKeyCode();
 		int keyCode = eKey.getKeyCode();
-		switch (keyCode) {
-		case KeyEvent.VK_UP:
-			if (messIndex > 0)
-				messIndex--;
-			if (!lastMess.isEmpty())
-				write.setText(lastMess.get(messIndex));
-			break;
-		case KeyEvent.VK_DOWN:
-			if (messIndex <= lastMess.size())
-				messIndex++;
-			if (messIndex >= lastMess.size()) {
-				messIndex = lastMess.size();
-				write.setText("");
-			} else
-				write.setText(lastMess.get(messIndex));
-			break;
-		case KeyEvent.VK_ENTER:
-			String text = write.getText().trim();
-			if (!text.equals("")) {
-				send(text);
-				lastMess.add(text);
-				messIndex = lastMess.size();
-				write.setText("");
-			}
-			break;
-		}
+		 switch( keyCode ) {
+	        case KeyEvent.VK_UP:
+	        	if (messIndex > 0)
+	        		messIndex--;
+	        	if (!lastMess.isEmpty())
+	        		write.setText(lastMess.get(messIndex));
+	            break;
+	        case KeyEvent.VK_DOWN:
+	        	if (messIndex <= lastMess.size())
+	        		messIndex++;
+	        	if (messIndex >= lastMess.size()) {
+	        		messIndex = lastMess.size();
+	        		write.setText("");
+	        	} else
+	        		write.setText(lastMess.get(messIndex));
+	            break;
+	        case KeyEvent.VK_ENTER:
+	        	String text = write.getText().trim();
+	    		if (!text.equals("")) {
+	    			send(text);
+	    			lastMess.add(text);
+	    			messIndex = lastMess.size();
+	    			write.setText("");
+	    		}
+	        	break;
+	     }
 	}
 	}
 
 
 	@Override
 	@Override
-	public void keyReleased(KeyEvent arg0) {
-	}
+	public void keyReleased(KeyEvent arg0) {}
 
 
 	@Override
 	@Override
-	public void keyTyped(KeyEvent arg0) {
-	}
+	public void keyTyped(KeyEvent arg0) {}
 }
 }

+ 11 - 15
src/main/java/client/Console.java

@@ -1,41 +1,37 @@
 package client;
 package client;
 
 
-import javax.swing.JTextPane;
-import javax.swing.SwingUtilities;
-import javax.swing.text.SimpleAttributeSet;
-import javax.swing.text.StyledDocument;
+import javax.swing.*;
+import javax.swing.text.*;
 
 
 import common.Message;
 import common.Message;
 
 
 @SuppressWarnings("serial")
 @SuppressWarnings("serial")
 public class Console extends JTextPane {
 public class Console extends JTextPane {
-
+	
 	public Console() {
 	public Console() {
 		setEditable(false);
 		setEditable(false);
 	}
 	}
-
+	
 	void log(Message mess) {
 	void log(Message mess) {
-		SwingUtilities.invokeLater(new AppendThread(mess.toString(),
-				mess.style, this.getStyledDocument()));
+		SwingUtilities.invokeLater(new AppendThread(mess.toString(), mess.style, this.getStyledDocument()));
 	}
 	}
-
+	
 	private static class AppendThread extends Thread {
 	private static class AppendThread extends Thread {
 		String text;
 		String text;
 		SimpleAttributeSet style;
 		SimpleAttributeSet style;
 		StyledDocument doc;
 		StyledDocument doc;
-
-		public AppendThread(String text, SimpleAttributeSet style,
-				StyledDocument doc) {
+		
+		public AppendThread(String text, SimpleAttributeSet style, StyledDocument doc) {
 			this.text = text;
 			this.text = text;
 			this.style = style;
 			this.style = style;
 			this.doc = doc;
 			this.doc = doc;
 		}
 		}
-
+		
 		@Override
 		@Override
 		public synchronized void run() {
 		public synchronized void run() {
 			try {
 			try {
-				doc.insertString(doc.getLength(), text + "\n", style);
-			} catch (Exception e) {
+			    doc.insertString(doc.getLength(), text + "\n", style);
+			} catch(Exception e) {
 				System.out.println(e);
 				System.out.println(e);
 			}
 			}
 		}
 		}

+ 15 - 22
src/main/java/command/Ban.java

@@ -2,14 +2,12 @@ package command;
 
 
 import java.util.InputMismatchException;
 import java.util.InputMismatchException;
 
 
-import server.BanNote;
-import server.Client;
-import server.Server;
-import server.util.Numbers;
-import server.util.StringArrays;
-
 import common.Message;
 import common.Message;
 import common.Message.MessageType;
 import common.Message.MessageType;
+import server.Client;
+import server.CommandHandler;
+import server.Server;
+import server.BanNote;
 
 
 public class Ban extends Command {
 public class Ban extends Command {
 
 
@@ -18,37 +16,32 @@ public class Ban extends Command {
 		String IP = null;
 		String IP = null;
 		int duration = -1;
 		int duration = -1;
 		Client victim;
 		Client victim;
-
+		
 		try {
 		try {
 			victim = Server.getUserByName(args[0]);
 			victim = Server.getUserByName(args[0]);
-		} catch (NullPointerException e) {
+		}	catch (NullPointerException e) {
 			caller.send(new Message("No such user!", MessageType.WARNING, false));
 			caller.send(new Message("No such user!", MessageType.WARNING, false));
 			return;
 			return;
 		}
 		}
-
+		
 		IP = victim.sock.getInetAddress().toString();
 		IP = victim.sock.getInetAddress().toString();
-
+		
 		BanNote bn = new BanNote(IP);
 		BanNote bn = new BanNote(IP);
-
+		
 		if (args.length == 1)
 		if (args.length == 1)
 			bn = new BanNote(IP);
 			bn = new BanNote(IP);
 		else
 		else
 			try {
 			try {
-				duration = Numbers.CInt(args[1]);
-
+				duration = Server.CInt(args[1]);
+				
 				if (args.length >= 3)
 				if (args.length >= 3)
-					bn = new BanNote(
-							IP,
-							duration,
-							StringArrays.arrayToString(StringArrays
-									.removeFirst(StringArrays.removeFirst(args))));
+					bn = new BanNote(IP, duration, CommandHandler.stringArrayToString(CommandHandler.removeFirst(CommandHandler.removeFirst(args))));
 				else
 				else
 					bn = new BanNote(IP, duration);
 					bn = new BanNote(IP, duration);
 			} catch (InputMismatchException ime) {
 			} catch (InputMismatchException ime) {
-				bn = new BanNote(IP, StringArrays.arrayToString(StringArrays
-						.removeFirst(args)));
+				bn = new BanNote(IP, CommandHandler.stringArrayToString(CommandHandler.removeFirst(args)));
 			}
 			}
-
+		
 		Server.banNotes.add(bn);
 		Server.banNotes.add(bn);
 		victim.disconnect(false);
 		victim.disconnect(false);
 	}
 	}
@@ -64,7 +57,7 @@ public class Ban extends Command {
 	}
 	}
 
 
 	@Override
 	@Override
-	public String getDescription() {
+	public String writeDescription() {
 		return "Bans a user. (/ban <username> [seconds] [reason])";
 		return "Bans a user. (/ban <username> [seconds] [reason])";
 	}
 	}
 
 

+ 5 - 9
src/main/java/command/Command.java

@@ -3,13 +3,9 @@ package command;
 import server.Client;
 import server.Client;
 
 
 public abstract class Command {
 public abstract class Command {
-	public abstract void execute(String[] args, Client caller) throws Exception;
-
-	public abstract String getName();
-
-	public abstract String getPermission();
-
-	public abstract String getDescription();
-
-	public abstract int getMinArgNumber();
+	public abstract void execute (String[] args, Client caller) throws Exception;
+	public abstract String getName ();
+	public abstract String getPermission ();
+	public abstract String writeDescription ();
+	public abstract int getMinArgNumber ();
 }
 }

+ 6 - 7
src/main/java/command/CreateChannel.java

@@ -1,18 +1,17 @@
 package command;
 package command;
 
 
+import common.Message;
+
 import server.Client;
 import server.Client;
 import server.Server;
 import server.Server;
 
 
-import common.Message;
-
-public class CreateChannel extends Command {
+public class CreateChannel extends Command{
 
 
 	@Override
 	@Override
 	public void execute(String[] args, Client caller) throws Exception {
 	public void execute(String[] args, Client caller) throws Exception {
 		Server.channels.add(new server.Channel(args[0]));
 		Server.channels.add(new server.Channel(args[0]));
-
-		Server.wideBroadcast(new Message("Channel " + args[0]
-				+ " is now available. Use '/join " + args[0] + "' to join."));
+		
+		Server.wideBroadcast(new Message("Channel " + args[0] + " is now available. Use '/join " + args[0] + "' to join."));
 	}
 	}
 
 
 	@Override
 	@Override
@@ -26,7 +25,7 @@ public class CreateChannel extends Command {
 	}
 	}
 
 
 	@Override
 	@Override
-	public String getDescription() {
+	public String writeDescription() {
 		return "Creates a channel with specified settings. (/createchannel <name>)";
 		return "Creates a channel with specified settings. (/createchannel <name>)";
 	}
 	}
 
 

+ 2 - 2
src/main/java/command/Exit.java

@@ -3,7 +3,7 @@ package command;
 import server.Client;
 import server.Client;
 import server.Server;
 import server.Server;
 
 
-public class Exit extends Command {
+public class Exit extends Command{
 
 
 	@Override
 	@Override
 	public void execute(String[] args, Client caller) {
 	public void execute(String[] args, Client caller) {
@@ -21,7 +21,7 @@ public class Exit extends Command {
 	}
 	}
 
 
 	@Override
 	@Override
-	public String getDescription() {
+	public String writeDescription() {
 		return "Exits the server.";
 		return "Exits the server.";
 	}
 	}
 
 

+ 8 - 18
src/main/java/command/Help.java

@@ -1,30 +1,20 @@
 package command;
 package command;
 
 
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import server.Client;
-import server.Server;
-
 import common.Message;
 import common.Message;
 import common.Message.MessageType;
 import common.Message.MessageType;
+import server.Client;
+import server.CommandHandler;
 
 
 public class Help extends Command {
 public class Help extends Command {
 
 
 	@Override
 	@Override
 	public void execute(String[] args, Client caller) {
 	public void execute(String[] args, Client caller) {
 		String help = "Help for all commands:" + "\n";
 		String help = "Help for all commands:" + "\n";
-		Iterator<Entry<String, Command>> it = Server.commReg.entrySet()
-				.iterator();
-
-		while (it.hasNext()) {
-			Map.Entry<String, Command> pair = it
-					.next();
-
-			help += pair.getKey() + ": " + "\t"
-					+ pair.getValue().getDescription();
-			if (it.hasNext())
+		for (int i = 0; i < CommandHandler.commands.length; i++) {
+			help += CommandHandler.commands[i].getName() + ": ";
+			help += "\t";
+			help += CommandHandler.commands[i].writeDescription();
+			if (i + 1 < CommandHandler.commands.length)
 				help += "\n";
 				help += "\n";
 		}
 		}
 		caller.send(new Message(help, MessageType.COMMAND, false));
 		caller.send(new Message(help, MessageType.COMMAND, false));
@@ -41,7 +31,7 @@ public class Help extends Command {
 	}
 	}
 
 
 	@Override
 	@Override
-	public String getDescription() {
+	public String writeDescription() {
 		return "Writes the descriptions for all commands.";
 		return "Writes the descriptions for all commands.";
 	}
 	}
 
 

+ 6 - 9
src/main/java/command/JoinChannel.java

@@ -1,10 +1,9 @@
 package command;
 package command;
 
 
-import server.Client;
-import server.Server;
-
 import common.Message;
 import common.Message;
 import common.Message.MessageType;
 import common.Message.MessageType;
+import server.Client;
+import server.Server;
 
 
 public class JoinChannel extends Command {
 public class JoinChannel extends Command {
 
 
@@ -14,15 +13,13 @@ public class JoinChannel extends Command {
 			caller.send("Client-only command.");
 			caller.send("Client-only command.");
 			return;
 			return;
 		}
 		}
-
+		
 		try {
 		try {
 			Server.getChannelByName(args[0]).add(caller);
 			Server.getChannelByName(args[0]).add(caller);
 			caller.primaryChannel = Server.getChannelByName(args[0]);
 			caller.primaryChannel = Server.getChannelByName(args[0]);
-			caller.send(new Message("You are now speaking in channel "
-					+ args[0] + ".", MessageType.COMMAND, false));
+			caller.send(new Message("You are now speaking in channel " + args[0] + ".", MessageType.COMMAND, false));
 		} catch (NullPointerException ex) {
 		} catch (NullPointerException ex) {
-			caller.send(new Message("No such channel!", MessageType.ERROR,
-					false));
+			caller.send(new Message("No such channel!", MessageType.ERROR, false));
 		}
 		}
 	}
 	}
 
 
@@ -37,7 +34,7 @@ public class JoinChannel extends Command {
 	}
 	}
 
 
 	@Override
 	@Override
-	public String getDescription() {
+	public String writeDescription() {
 		return "Sets specified channel as primary (/join <channel>)";
 		return "Sets specified channel as primary (/join <channel>)";
 	}
 	}
 
 

+ 4 - 6
src/main/java/command/Kick.java

@@ -1,10 +1,9 @@
 package command;
 package command;
 
 
-import server.Client;
-import server.Server;
-
 import common.Message;
 import common.Message;
 import common.Message.MessageType;
 import common.Message.MessageType;
+import server.Client;
+import server.Server;
 
 
 public class Kick extends Command {
 public class Kick extends Command {
 
 
@@ -13,8 +12,7 @@ public class Kick extends Command {
 		try {
 		try {
 			Server.getUserByName(args[0]).disconnect(false);
 			Server.getUserByName(args[0]).disconnect(false);
 		} catch (NullPointerException ex) {
 		} catch (NullPointerException ex) {
-			caller.send(new Message("No user called " + args[0] + "!",
-					MessageType.ERROR, false));
+			caller.send(new Message("No user called " + args[0] + "!", MessageType.ERROR, false));
 		}
 		}
 	}
 	}
 
 
@@ -29,7 +27,7 @@ public class Kick extends Command {
 	}
 	}
 
 
 	@Override
 	@Override
-	public String getDescription() {
+	public String writeDescription() {
 		return "Kicks a user. (/kick <username>)";
 		return "Kicks a user. (/kick <username>)";
 	}
 	}
 
 

+ 10 - 15
src/main/java/command/LeaveChannel.java

@@ -1,32 +1,27 @@
 package command;
 package command;
 
 
-import server.Client;
-import server.Server;
-
 import common.Message;
 import common.Message;
 import common.Message.MessageType;
 import common.Message.MessageType;
+import server.Client;
+import server.Server;
 
 
-public class LeaveChannel extends Command {
+public class LeaveChannel extends Command{
 
 
 	@Override
 	@Override
 	public void execute(String[] args, Client caller) throws Exception {
 	public void execute(String[] args, Client caller) throws Exception {
-		if (caller.equals(Server.OPClient)) {
+		if (caller.equals(Server.OPClient)){
 			caller.send("Client-only command.");
 			caller.send("Client-only command.");
 			return;
 			return;
 		}
 		}
-
+		
 		try {
 		try {
 			Server.getChannelByName(args[0]).remove(caller);
 			Server.getChannelByName(args[0]).remove(caller);
 			if (caller.primaryChannel.equals(Server.getChannelByName(args[0])))
 			if (caller.primaryChannel.equals(Server.getChannelByName(args[0])))
 				caller.primaryChannel = Server.channels.get(0);
 				caller.primaryChannel = Server.channels.get(0);
-			caller.send(new Message("You left channel " + args[0] + ".",
-					MessageType.COMMAND, false));
-			caller.send(new Message("You are now speaking in channel "
-					+ caller.primaryChannel.name + ".", MessageType.COMMAND,
-					false));
-		} catch (NullPointerException ex) {
-			caller.send(new Message("No channel named " + args[0] + ".",
-					MessageType.ERROR, false));
+			caller.send(new Message("You left channel " + args[0] + ".", MessageType.COMMAND, false));
+			caller.send(new Message("You are now speaking in channel " + caller.primaryChannel.name + ".", MessageType.COMMAND, false));
+		} catch(NullPointerException ex) {
+			caller.send(new Message("No channel named " + args[0] + ".", MessageType.ERROR, false));
 			return;
 			return;
 		}
 		}
 	}
 	}
@@ -42,7 +37,7 @@ public class LeaveChannel extends Command {
 	}
 	}
 
 
 	@Override
 	@Override
-	public String getDescription() {
+	public String writeDescription() {
 		return "Removes caller from specified channel. (/leave <channel>)";
 		return "Removes caller from specified channel. (/leave <channel>)";
 	}
 	}
 
 

+ 10 - 15
src/main/java/command/List.java

@@ -1,36 +1,31 @@
 package command;
 package command;
 
 
-import server.Client;
-import server.Server;
-
 import common.Message;
 import common.Message;
 import common.Message.MessageType;
 import common.Message.MessageType;
+import server.Client;
+import server.Server;
 
 
 public class List extends Command {
 public class List extends Command {
-
+	
 	@Override
 	@Override
 	public void execute(String[] args, Client caller) {
 	public void execute(String[] args, Client caller) {
 		String arr, channelName = null;
 		String arr, channelName = null;
-
+		
 		if (args.length >= 1) {
 		if (args.length >= 1) {
 			channelName = args[0];
 			channelName = args[0];
 			try {
 			try {
 				arr = Server.getChannelByName(channelName).listClients();
 				arr = Server.getChannelByName(channelName).listClients();
 			} catch (NullPointerException ex) {
 			} catch (NullPointerException ex) {
-				caller.send(new Message(
-						"No channel named " + channelName + ".",
-						MessageType.ERROR, false));
+				caller.send(new Message("No channel named " + channelName + ".", MessageType.ERROR, false));
 				return;
 				return;
 			}
 			}
 		} else
 		} else
-			arr = Server.listClients();
-
+			arr =  Server.listClients();
+		
 		if (channelName == null)
 		if (channelName == null)
-			caller.send(new Message("Users online are:" + "\n" + arr,
-					MessageType.COMMAND, false));
+			caller.send(new Message("Users online are:" + "\n" + arr, MessageType.COMMAND, false));
 		else
 		else
-			caller.send(new Message("Users in channel " + channelName + " are:"
-					+ "\n" + arr, MessageType.COMMAND, false));
+			caller.send(new Message("Users in channel " + channelName + " are:" + "\n" + arr, MessageType.COMMAND, false));
 	}
 	}
 
 
 	@Override
 	@Override
@@ -44,7 +39,7 @@ public class List extends Command {
 	}
 	}
 
 
 	@Override
 	@Override
-	public String getDescription() {
+	public String writeDescription() {
 		return "Lists all users online. (/list [channel])";
 		return "Lists all users online. (/list [channel])";
 	}
 	}
 
 

+ 6 - 10
src/main/java/command/PrivateMessage.java

@@ -1,10 +1,9 @@
 package command;
 package command;
 
 
+import common.Message;
 import server.Client;
 import server.Client;
+import server.CommandHandler;
 import server.Server;
 import server.Server;
-import server.util.StringArrays;
-
-import common.Message;
 
 
 public class PrivateMessage extends Command {
 public class PrivateMessage extends Command {
 
 
@@ -19,13 +18,10 @@ public class PrivateMessage extends Command {
 			caller.send("No user called " + args[0] + ".");
 			caller.send("No user called " + args[0] + ".");
 			return;
 			return;
 		}
 		}
+		
+		Message mess = new Message("PM", caller.username, CommandHandler.stringArrayToString(CommandHandler.removeFirst(args)), Message.MessageType.PM);
 
 
-		Message mess = new Message("PM", caller.username,
-				StringArrays.arrayToString(StringArrays.removeFirst(args)),
-				Message.MessageType.PM);
-
-		reciever.send(mess);
-		caller.send(mess);
+		reciever.send(mess); caller.send(mess);
 
 
 	}
 	}
 
 
@@ -40,7 +36,7 @@ public class PrivateMessage extends Command {
 	}
 	}
 
 
 	@Override
 	@Override
-	public String getDescription() {
+	public String writeDescription() {
 		return "Sends a private message to a user";
 		return "Sends a private message to a user";
 	}
 	}
 
 

+ 14 - 21
src/main/java/common/Message.java

@@ -12,17 +12,17 @@ import server.Server;
 
 
 @SuppressWarnings("serial")
 @SuppressWarnings("serial")
 public class Message implements java.io.Serializable {
 public class Message implements java.io.Serializable {
-
+	
 	public enum MessageType {
 	public enum MessageType {
 		PM, NORMAL, WARNING, ERROR, COMMAND, INFO
 		PM, NORMAL, WARNING, ERROR, COMMAND, INFO
 	}
 	}
-
+	
 	public MessageType messType = MessageType.NORMAL;
 	public MessageType messType = MessageType.NORMAL;
 	public String content = "", channel = "", sender = "";
 	public String content = "", channel = "", sender = "";
 	public SimpleAttributeSet style = new SimpleAttributeSet();
 	public SimpleAttributeSet style = new SimpleAttributeSet();
 	public String[] usersOnline;
 	public String[] usersOnline;
 	public boolean preInfo = true;
 	public boolean preInfo = true;
-
+	
 	public Message(String channel, String send, String con, MessageType messType) {
 	public Message(String channel, String send, String con, MessageType messType) {
 		this.sender = send;
 		this.sender = send;
 		this.channel = channel;
 		this.channel = channel;
@@ -30,39 +30,32 @@ public class Message implements java.io.Serializable {
 		this.messType = messType;
 		this.messType = messType;
 		usersOnline = Server.getUsersOnline();
 		usersOnline = Server.getUsersOnline();
 	}
 	}
-
+	
 	public Message(String sender, String con) {
 	public Message(String sender, String con) {
 		this("", sender, con, MessageType.NORMAL);
 		this("", sender, con, MessageType.NORMAL);
 	}
 	}
-
+	
 	public Message(String con) {
 	public Message(String con) {
 		this("Info", "SERVER", con, MessageType.INFO);
 		this("Info", "SERVER", con, MessageType.INFO);
 	}
 	}
-
-	public Message(String con, MessageType messType, boolean preInfo) { // TODO
-																		// Needs
-																		// to
-																		// include
-																		// Server.getUsersOnline()
-																		// to
-																		// prevent
-																		// NullPointerException
+	
+	public Message(String con, MessageType messType, boolean preInfo) { //TODO Needs to include Server.getUsersOnline() to prevent NullPointerException
 		this.content = con;
 		this.content = con;
-		this.preInfo = preInfo;
+		this.preInfo = preInfo; 
 		this.messType = messType;
 		this.messType = messType;
 		if (preInfo)
 		if (preInfo)
 			usersOnline = Server.getUsersOnline();
 			usersOnline = Server.getUsersOnline();
 		else
 		else
 			usersOnline = null;
 			usersOnline = null;
 	}
 	}
-
+	
 	public boolean validate() {
 	public boolean validate() {
 		if (content.equals("") || content == null) {
 		if (content.equals("") || content == null) {
 			return false;
 			return false;
 		}
 		}
 		return true;
 		return true;
 	}
 	}
-
+	
 	@Override
 	@Override
 	public String toString() {
 	public String toString() {
 		switch (messType) {
 		switch (messType) {
@@ -85,14 +78,14 @@ public class Message implements java.io.Serializable {
 			break;
 			break;
 		default:
 		default:
 			break;
 			break;
-		}
-
+		}	
+		
 		DateFormat dateFormat = new SimpleDateFormat("[HH:mm:ss]");
 		DateFormat dateFormat = new SimpleDateFormat("[HH:mm:ss]");
 		Date time = new Date();
 		Date time = new Date();
 		String timestamp = dateFormat.format(time);
 		String timestamp = dateFormat.format(time);
-
+		
 		String preInfoStr = timestamp + "<" + channel + ">" + sender + ": ";
 		String preInfoStr = timestamp + "<" + channel + ">" + sender + ": ";
-
+		
 		if (preInfo)
 		if (preInfo)
 			return preInfoStr + content;
 			return preInfoStr + content;
 		else
 		else

+ 10 - 13
src/main/java/server/BanNote.java

@@ -7,40 +7,37 @@ import java.time.temporal.ChronoUnit;
 public class BanNote {
 public class BanNote {
 	String ip, reason;
 	String ip, reason;
 	LocalDateTime expiry;
 	LocalDateTime expiry;
-
+	
 	public BanNote(String ip, int duration, String reason) {
 	public BanNote(String ip, int duration, String reason) {
 		this.ip = ip;
 		this.ip = ip;
 		if (duration == -1)
 		if (duration == -1)
 			this.expiry = null;
 			this.expiry = null;
-
+		
 		else
 		else
-			this.expiry = LocalDateTime.now()
-					.plus(duration, ChronoUnit.SECONDS);
+			this.expiry = LocalDateTime.now().plus(duration, ChronoUnit.SECONDS);
 		this.reason = reason;
 		this.reason = reason;
 	}
 	}
-
+	
 	public BanNote(String ip, String reason) {
 	public BanNote(String ip, String reason) {
 		this(ip, -1, reason);
 		this(ip, -1, reason);
 	}
 	}
-
+	
 	public BanNote(String ip, int duration) {
 	public BanNote(String ip, int duration) {
 		this(ip, duration, "You are banned.");
 		this(ip, duration, "You are banned.");
 	}
 	}
-
+	
 	public BanNote(String ip) {
 	public BanNote(String ip) {
 		this(ip, -1);
 		this(ip, -1);
 	}
 	}
-
+	
 	@Override
 	@Override
 	public String toString() {
 	public String toString() {
 		String expStr;
 		String expStr;
 		if (expiry == null)
 		if (expiry == null)
 			expStr = "Forever";
 			expStr = "Forever";
 		else
 		else
-			expStr = expiry.format(DateTimeFormatter
-					.ofPattern("yyyy-MM-dd HH:mm:ss"));
-
-		return "You are banned from this server." + "\n" + "Reason: " + reason
-				+ "\n" + "Expiry: " + expStr;
+			expStr = expiry.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+		
+		return "You are banned from this server." + "\n" + "Reason: " + reason + "\n" + "Expiry: " + expStr;
 	}
 	}
 }
 }

+ 3 - 3
src/main/java/server/Channel.java

@@ -7,14 +7,14 @@ public class Channel extends ClientCollection {
 	 * 
 	 * 
 	 */
 	 */
 	private static final long serialVersionUID = 1L;
 	private static final long serialVersionUID = 1L;
-
+	
 	public String name;
 	public String name;
-
+	
 	public Channel(String name) {
 	public Channel(String name) {
 		super();
 		super();
 		this.name = name;
 		this.name = name;
 	}
 	}
-
+	
 	@Override
 	@Override
 	void broadcast(Message mess) {
 	void broadcast(Message mess) {
 		mess.channel = name;
 		mess.channel = name;

+ 44 - 51
src/main/java/server/Client.java

@@ -8,74 +8,70 @@ import java.io.InputStreamReader;
 import java.io.ObjectOutputStream;
 import java.io.ObjectOutputStream;
 import java.net.Socket;
 import java.net.Socket;
 import java.time.LocalDateTime;
 import java.time.LocalDateTime;
-
 import javax.swing.Timer;
 import javax.swing.Timer;
 
 
 import common.Message;
 import common.Message;
 
 
 public class Client implements Runnable, ActionListener {
 public class Client implements Runnable, ActionListener {
 	Thread readuser;
 	Thread readuser;
-
+	
 	BufferedReader in;
 	BufferedReader in;
 	ObjectOutputStream objOut;
 	ObjectOutputStream objOut;
-
+	
 	public String username;
 	public String username;
 	public Socket sock;
 	public Socket sock;
-
+	
 	String[] permissions;
 	String[] permissions;
-
+	
 	int messLastPeriod = 0;
 	int messLastPeriod = 0;
 	Timer timer = new Timer(3000, this);
 	Timer timer = new Timer(3000, this);
-
+	
 	public Channel primaryChannel = Server.channels.get(0);
 	public Channel primaryChannel = Server.channels.get(0);
-
+	
 	public Client(Socket s) {
 	public Client(Socket s) {
 		sock = s;
 		sock = s;
-
+		
 		try {
 		try {
-			in = new BufferedReader(
-					new InputStreamReader(sock.getInputStream()));
+			in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
 			objOut = new ObjectOutputStream(sock.getOutputStream());
 			objOut = new ObjectOutputStream(sock.getOutputStream());
 			username = in.readLine();
 			username = in.readLine();
 		} catch (IOException e) {
 		} catch (IOException e) {
 			e.printStackTrace();
 			e.printStackTrace();
 		}
 		}
-
+		
 		if (!validateUser()) {
 		if (!validateUser()) {
 			disconnect(false);
 			disconnect(false);
 			throw new IllegalArgumentException();
 			throw new IllegalArgumentException();
 		}
 		}
-
-		permissions = new String[] { "noob.*" };
-
+		
+		permissions = new String[] {"noob.*"};
+		
 		send(new Message("Welcome to the server! Enjoy your stay!"));
 		send(new Message("Welcome to the server! Enjoy your stay!"));
-
+		
 		readuser = new Thread(this, username);
 		readuser = new Thread(this, username);
 		readuser.start();
 		readuser.start();
-
+		
 		timer.start();
 		timer.start();
 	}
 	}
-
-	public Client() {
-	}
-
+	
+	public Client() {}
+	
 	private boolean validateUser() {
 	private boolean validateUser() {
-		// No spaces
-		if (username.contains(" ")) {
+		//No spaces
+		if (username.contains(" ")){
 			send("No spaces in usernames please!");
 			send("No spaces in usernames please!");
 			return false;
 			return false;
 		}
 		}
-
-		// Not same username as anyone else
+		
+		//Not same username as anyone else
 		if (Server.clients.getClientByName(username) != null) {
 		if (Server.clients.getClientByName(username) != null) {
 			send("Username already taken!");
 			send("Username already taken!");
 			return false;
 			return false;
 		}
 		}
-
-		// No connect if banned
+			
+		//No connect if banned
 		for (int i = 0; i < Server.banNotes.size(); i++)
 		for (int i = 0; i < Server.banNotes.size(); i++)
-			if (Server.banNotes.get(i).ip.equals(sock.getInetAddress()
-					.toString())) {
+			if (Server.banNotes.get(i).ip.equals(sock.getInetAddress().toString())) {
 				BanNote bn = Server.banNotes.get(i);
 				BanNote bn = Server.banNotes.get(i);
 				if (bn.expiry == null) {
 				if (bn.expiry == null) {
 					send(bn.toString());
 					send(bn.toString());
@@ -88,45 +84,43 @@ public class Client implements Runnable, ActionListener {
 					return false;
 					return false;
 				}
 				}
 			}
 			}
-
+		
 		return true;
 		return true;
 	}
 	}
-
+	
 	public void disconnect(boolean output) {
 	public void disconnect(boolean output) {
-		if (!isConnected()) // Already disconnected
+		if (!isConnected()) //Already disconnected
 			return;
 			return;
-
+		
 		if (timer.isRunning())
 		if (timer.isRunning())
 			timer.stop();
 			timer.stop();
-
+		
 		if (readuser != null)
 		if (readuser != null)
 			readuser.interrupt();
 			readuser.interrupt();
-
+		
 		try {
 		try {
 			sock.close();
 			sock.close();
 		} catch (IOException e) {
 		} catch (IOException e) {
 			e.printStackTrace();
 			e.printStackTrace();
 		}
 		}
-
+		
 		Server.cleanUp();
 		Server.cleanUp();
-
+		
 		if (output)
 		if (output)
 			Server.wideBroadcast(new Message(username + " has disconnected."));
 			Server.wideBroadcast(new Message(username + " has disconnected."));
 	}
 	}
-
+	
 	public void disconnect() {
 	public void disconnect() {
 		disconnect(true);
 		disconnect(true);
 	}
 	}
-
+	
 	public boolean isConnected() {
 	public boolean isConnected() {
 		return !sock.isClosed();
 		return !sock.isClosed();
 	}
 	}
-
+	
 	boolean hasPermission(String commandPermission) {
 	boolean hasPermission(String commandPermission) {
 		for (int i = 0; i < permissions.length; i++) {
 		for (int i = 0; i < permissions.length; i++) {
-			if (commandPermission.startsWith(permissions[i].replace(".*", "."))
-					|| commandPermission.equalsIgnoreCase(permissions[i])
-					|| permissions[i].equalsIgnoreCase("*"))
+			if (commandPermission.startsWith(permissions[i].replace(".*", ".")) || commandPermission.equalsIgnoreCase(permissions[i]) || permissions[i].equalsIgnoreCase("*"))
 				return true;
 				return true;
 		}
 		}
 		return false;
 		return false;
@@ -136,21 +130,20 @@ public class Client implements Runnable, ActionListener {
 	public void run() {
 	public void run() {
 		String lastMess;
 		String lastMess;
 		try {
 		try {
-			while (!readuser.isInterrupted()
-					&& ((lastMess = in.readLine()) != null)) {
-				if (lastMess.startsWith("/")) // Command handling
+			while (!readuser.isInterrupted() && ((lastMess = in.readLine()) != null)) {
+				if (lastMess.startsWith("/")) //Command handling
 				{
 				{
 					String[] commandarray = lastMess.substring(1).split(" ");
 					String[] commandarray = lastMess.substring(1).split(" ");
-					Server.commReg.executeCommand(commandarray, this);
-				} else // Normal message handling
+					CommandHandler.executeCommand(commandarray, this);
+				}
+				else //Normal message handling
 				{
 				{
 					messLastPeriod++;
 					messLastPeriod++;
 					if (messLastPeriod > 5) {
 					if (messLastPeriod > 5) {
 						send("No spamming!");
 						send("No spamming!");
 						disconnect(false);
 						disconnect(false);
 					} else
 					} else
-						primaryChannel.broadcast(new Message(this.username,
-								lastMess));
+						primaryChannel.broadcast(new Message(this.username, lastMess));
 				}
 				}
 			}
 			}
 			disconnect();
 			disconnect();
@@ -158,7 +151,7 @@ public class Client implements Runnable, ActionListener {
 			disconnect();
 			disconnect();
 		}
 		}
 	}
 	}
-
+	
 	public void send(Object message) {
 	public void send(Object message) {
 		try {
 		try {
 			objOut.writeObject(message);
 			objOut.writeObject(message);
@@ -167,7 +160,7 @@ public class Client implements Runnable, ActionListener {
 			e.printStackTrace();
 			e.printStackTrace();
 		}
 		}
 	}
 	}
-
+	
 	@Override
 	@Override
 	public String toString() {
 	public String toString() {
 		return username;
 		return username;

+ 23 - 26
src/main/java/server/ClientCollection.java

@@ -4,73 +4,70 @@ import java.util.ArrayList;
 
 
 import common.Message;
 import common.Message;
 
 
-public class ClientCollection extends ArrayList<Client> {
+public class ClientCollection extends ArrayList<Client>{
 	/**
 	/**
 	 * 
 	 * 
 	 */
 	 */
 	private static final long serialVersionUID = 1L;
 	private static final long serialVersionUID = 1L;
-
+	
 	int maxClients = Server.maxUsers;
 	int maxClients = Server.maxUsers;
-
+	
 	public ClientCollection() {
 	public ClientCollection() {
 		this(Server.maxUsers);
 		this(Server.maxUsers);
 	}
 	}
-
+	
 	public ClientCollection(int maxUsers) {
 	public ClientCollection(int maxUsers) {
 		super(maxUsers);
 		super(maxUsers);
 		maxClients = maxUsers;
 		maxClients = maxUsers;
 	}
 	}
-
+	
 	public Client getClientByName(String name) throws NullPointerException {
 	public Client getClientByName(String name) throws NullPointerException {
-		for (Client c : this) {
+		for (Client c: this) {
 			if (c.username.equals(name))
 			if (c.username.equals(name))
 				return c;
 				return c;
 		}
 		}
 		return null;
 		return null;
 	}
 	}
-
-	void broadcast(Message mess) { // Broadcast to all
-		if (mess.validate()) {
-			for (Client c : this)
+	
+	void broadcast(Message mess) { //Broadcast to all
+		 if (mess.validate()) {
+			for (Client c: this)
 				c.send(mess);
 				c.send(mess);
 			Server.OPClient.send(mess.toString());
 			Server.OPClient.send(mess.toString());
 		}
 		}
 	}
 	}
-
+	
 	@Override
 	@Override
-	public boolean add(Client user) throws ArrayIndexOutOfBoundsException { // Add
-																			// user
+	public boolean add(Client user) throws ArrayIndexOutOfBoundsException { //Add user
 		if (contains(user))
 		if (contains(user))
 			return true;
 			return true;
-
+		
 		if (size() >= maxClients)
 		if (size() >= maxClients)
 			throw new ArrayIndexOutOfBoundsException();
 			throw new ArrayIndexOutOfBoundsException();
 		else
 		else
 			super.add(user);
 			super.add(user);
 		return true;
 		return true;
 	}
 	}
-
-	public void remove(Client user) { // Remove without DC
+	
+	public void remove(Client user) { //Remove without DC
 		remove(user, false);
 		remove(user, false);
 	}
 	}
-
-	public void remove(Client user, boolean disconnect) { // Remove and
-															// disconnect if
-															// needed
+	
+	public void remove(Client user, boolean disconnect) { //Remove and disconnect if needed
 		if (disconnect)
 		if (disconnect)
 			user.disconnect();
 			user.disconnect();
 		super.remove(user);
 		super.remove(user);
 	}
 	}
-
-	public String listClients() { // String from array
+	
+	public String listClients() { //String from array
 		return toString().replace(", ", "\n").replace("[", "").replace("]", "");
 		return toString().replace(", ", "\n").replace("[", "").replace("]", "");
 	}
 	}
-
-	public String[] listClientsArray() { // Array instead of string
+	
+	public String[] listClientsArray() { //Array instead of string
 		return listClients().split("\n");
 		return listClients().split("\n");
 	}
 	}
-
-	public void cleanUp() { // Remove unused clients
+	
+	public void cleanUp() { //Remove unused clients
 		for (int i = 0; i < size(); i++)
 		for (int i = 0; i < size(); i++)
 			if (!get(i).isConnected())
 			if (!get(i).isConnected())
 				remove(i);
 				remove(i);

+ 58 - 0
src/main/java/server/CommandHandler.java

@@ -0,0 +1,58 @@
+package server;
+
+import command.*;
+
+public class CommandHandler {
+	
+	public static Command[] commands;
+	
+	public CommandHandler() {
+		commands = new Command[9];
+		commands[0] = new command.Kick();
+		commands[1] = new command.List();
+		commands[2] = new command.Exit();
+		commands[3] = new command.Help();
+		commands[4] = new command.PrivateMessage();
+		commands[5] = new command.JoinChannel();
+		commands[6] = new command.Ban();
+		commands[7] = new command.LeaveChannel();
+		commands[8] = new command.CreateChannel();
+	}
+	
+	public static void executeCommand(String[] command, Client caller) {
+		for (Command comm: commands) { //Go through all commands
+			if ((comm.getName()).equals(command[0])) { //Look for command with correct name
+				if (caller.hasPermission(comm.getPermission())) //Check if the client has permission
+					if (command.length -1 >= comm.getMinArgNumber()) { //Check the number of arguments
+						try {
+							comm.execute(removeFirst(command), caller); //Execute command
+						} catch (Exception e) {
+							caller.send("Error while executing command!");
+							e.printStackTrace();
+						} 
+						return;
+					} else {
+						caller.send("More arguments required!");
+						return;
+					}
+				else {
+					caller.send("Not enough permissions!");
+					return;
+				}
+			}
+		}
+		caller.send("No such command!");
+	}
+	
+	public static String[] removeFirst(String[] command) {
+		String[] newCommand = new String[command.length - 1];
+		for (int i = 0; i < command.length -1; i++) {
+			newCommand[i] = command[i + 1];
+		}
+		return newCommand;
+	}
+	
+	public static String stringArrayToString(String[] strArr) {
+		return strArr.toString().replace("[", "").replace("]", "").replace(", ", " ");
+	}
+}

+ 0 - 57
src/main/java/server/CommandRegistry.java

@@ -1,57 +0,0 @@
-package server;
-
-import java.util.HashMap;
-
-import server.util.StringArrays;
-
-import command.Command;
-
-public class CommandRegistry extends HashMap<String, Command> {
-
-	/**
-	 * 
-	 */
-	private static final long serialVersionUID = 1L;
-
-	public CommandRegistry() {
-		Command[] commands = new Command[9];
-		commands[0] = new command.Kick();
-		commands[1] = new command.List();
-		commands[2] = new command.Exit();
-		commands[3] = new command.Help();
-		commands[4] = new command.PrivateMessage();
-		commands[5] = new command.JoinChannel();
-		commands[6] = new command.Ban();
-		commands[7] = new command.LeaveChannel();
-		commands[8] = new command.CreateChannel();
-
-		for (Command comm : commands)
-			put(comm.getName(), comm);
-	}
-
-	public void executeCommand(String[] command, Client caller) {
-		Command comm;
-		if ((comm = get(command[0])) != null) // Get the command
-			if (caller.hasPermission(comm.getPermission())) { // Check if the client has permission
-				String[] args = StringArrays.removeFirst(command);
-				if (args.length >= comm.getMinArgNumber()) { // Check the number of arguments
-					try {
-						comm.execute(args, caller); // Execute command
-					} catch (Exception e) {
-						caller.send("Error while executing command!");
-						e.printStackTrace();
-					}
-					return;
-				} else {
-					caller.send("More arguments required!");
-					return;
-				}
-			} else {
-				caller.send("Not enough permissions!");
-				return;
-			}
-		else
-			caller.send("No such command! Type '/help' for a list of commands.");
-	}
-
-}

+ 7 - 8
src/main/java/server/LocalClient.java

@@ -4,23 +4,22 @@ import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.io.InputStreamReader;
 
 
 public class LocalClient extends Client {
 public class LocalClient extends Client {
-
-	public LocalClient() { // Constructor for local client, the server, with
-							// full permissions
+	
+	public LocalClient() { //Constructor for local client, the server, with full permissions
 		in = new BufferedReader(new InputStreamReader(System.in));
 		in = new BufferedReader(new InputStreamReader(System.in));
-
+		
 		username = "SERVER";
 		username = "SERVER";
-		permissions = new String[] { "*" };
-
+		permissions = new String[] {"*"};
+		
 		readuser = new Thread(this, username);
 		readuser = new Thread(this, username);
 		readuser.start();
 		readuser.start();
 	}
 	}
-
+	
 	@Override
 	@Override
 	public void disconnect() {
 	public void disconnect() {
 		readuser.interrupt();
 		readuser.interrupt();
 	}
 	}
-
+	
 	@Override
 	@Override
 	public void send(Object message) {
 	public void send(Object message) {
 		System.out.println(message);
 		System.out.println(message);

+ 6 - 6
src/main/java/server/util/Logger.java → src/main/java/server/Logger.java

@@ -1,4 +1,4 @@
-package server.util;
+package server;
 
 
 import java.io.File;
 import java.io.File;
 import java.io.IOException;
 import java.io.IOException;
@@ -8,26 +8,26 @@ import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.Date;
 
 
 public class Logger {
 public class Logger {
-
+	
 	PrintWriter out;
 	PrintWriter out;
 	File log;
 	File log;
-
+	
 	public Logger() throws IOException {
 	public Logger() throws IOException {
 		DateFormat dateFormat = new SimpleDateFormat("yyyy-dd-MM(HH-mm)");
 		DateFormat dateFormat = new SimpleDateFormat("yyyy-dd-MM(HH-mm)");
 		Date time = new Date();
 		Date time = new Date();
 		String timestamp = dateFormat.format(time);
 		String timestamp = dateFormat.format(time);
-
+		
 		log = new File("logs/log-" + timestamp + ".log");
 		log = new File("logs/log-" + timestamp + ".log");
 		log.getParentFile().mkdirs();
 		log.getParentFile().mkdirs();
 		log.createNewFile();
 		log.createNewFile();
 		out = new PrintWriter(log);
 		out = new PrintWriter(log);
 	}
 	}
-
+	
 	public void log(String txt) {
 	public void log(String txt) {
 		out.println(txt);
 		out.println(txt);
 		out.flush();
 		out.flush();
 	}
 	}
-
+	
 	public void close() {
 	public void close() {
 		out.close();
 		out.close();
 	}
 	}

+ 6 - 7
src/main/java/server/Pong.java

@@ -6,16 +6,15 @@ import java.awt.event.ActionListener;
 import javax.swing.Timer;
 import javax.swing.Timer;
 
 
 public class Pong implements ActionListener {
 public class Pong implements ActionListener {
-
+	
 	Timer tim = new Timer(100, this);
 	Timer tim = new Timer(100, this);
-
-	Client player1;
-	Client player2;
-
-	public Pong(Client p1, Client p2) {
+	
+	Client player1; Client player2;
+	
+	public Pong (Client p1, Client p2) {
 		player1 = p1;
 		player1 = p1;
 		player2 = p2;
 		player2 = p2;
-
+		
 		// TODO Initialize game here
 		// TODO Initialize game here
 	}
 	}
 
 

+ 17 - 7
src/main/java/server/Server.java

@@ -8,11 +8,12 @@ import java.io.IOException;
 import java.net.ServerSocket;
 import java.net.ServerSocket;
 import java.util.ArrayList;
 import java.util.ArrayList;
 import java.util.Properties;
 import java.util.Properties;
+import java.util.Scanner;
+import java.util.Set;
 
 
 import common.Message;
 import common.Message;
-import server.CommandRegistry;
+import server.CommandHandler;
 import server.Channel;
 import server.Channel;
-import server.util.*;
 
 
 public class Server {
 public class Server {
 	static Properties prop = new Properties();
 	static Properties prop = new Properties();
@@ -26,7 +27,6 @@ public class Server {
 	static ServerSocket so;
 	static ServerSocket so;
 	public static LocalClient OPClient;
 	public static LocalClient OPClient;
 	public static Logger log;
 	public static Logger log;
-	public static CommandRegistry commReg;
 	
 	
 	public static void main(String[] arg){
 	public static void main(String[] arg){
 		System.out.println("Starting ChatServer version " + version + "...");
 		System.out.println("Starting ChatServer version " + version + "...");
@@ -47,7 +47,7 @@ public class Server {
 		channels.add(new Channel("Main"));
 		channels.add(new Channel("Main"));
 		
 		
 		System.out.print("Starting commandhandler...");
 		System.out.print("Starting commandhandler...");
-		commReg = new CommandRegistry();
+		new CommandHandler();
 		System.out.println("Done");
 		System.out.println("Done");
 		
 		
 		System.out.print("Creating virtual local client...");
 		System.out.print("Creating virtual local client...");
@@ -140,9 +140,19 @@ public class Server {
 		} catch (IOException e) {
 		} catch (IOException e) {
 			e.printStackTrace();
 			e.printStackTrace();
 		}
 		}
+		
+		Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
+		for (Thread th: threadSet)
+			System.out.println(th.toString() + ", " + th.isAlive());
 	}
 	}
 	
 	
-	
+	public static int CInt(String str) {
+		int i;
+		Scanner sc = new Scanner(str);
+		i = sc.nextInt();
+		sc.close();
+		return i;
+	}
 	
 	
 	static void loadProperties() {
 	static void loadProperties() {
 		System.out.println("Loadning properties file.");
 		System.out.println("Loadning properties file.");
@@ -157,8 +167,8 @@ public class Server {
 		
 		
 		System.out.println("Reading numbers from properties object.");
 		System.out.println("Reading numbers from properties object.");
 		try {
 		try {
-			port = Numbers.CInt(prop.getProperty("port"));
-			maxUsers = Numbers.CInt(prop.getProperty("maxUsers"));
+			port = CInt(prop.getProperty("port"));
+			maxUsers = CInt(prop.getProperty("maxUsers"));
 		} catch (NullPointerException ex) {
 		} catch (NullPointerException ex) {
 			System.out.println("Could not get values from properties file.");
 			System.out.println("Could not get values from properties file.");
 			newPropertiesFile();
 			newPropertiesFile();

+ 0 - 13
src/main/java/server/util/Numbers.java

@@ -1,13 +0,0 @@
-package server.util;
-
-import java.util.Scanner;
-
-public class Numbers {
-	public static int CInt(String str) {
-		int i;
-		Scanner sc = new Scanner(str);
-		i = sc.nextInt();
-		sc.close();
-		return i;
-	}
-}

+ 0 - 18
src/main/java/server/util/StringArrays.java

@@ -1,18 +0,0 @@
-package server.util;
-
-import java.util.ArrayList;
-
-public class StringArrays {
-	public static String[] removeFirst(String[] oldArr) {
-		ArrayList<String> newArr = new ArrayList<String>();
-		for (int i = 1; i < oldArr.length; i++) {
-			newArr.add(oldArr[i]);
-		}
-		return (String[]) newArr.toArray();
-	}
-
-	public static String arrayToString(String[] arr) {
-		return arr.toString().replace("[", "").replace("]", "")
-				.replace(", ", " ");
-	}
-}

+ 18 - 18
src/test/java/client/ClientTestCase.java

@@ -1,6 +1,6 @@
 package client;
 package client;
 
 
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.*;
 
 
 import org.junit.AfterClass;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.BeforeClass;
@@ -11,33 +11,33 @@ import server.Server;
 public class ClientTestCase {
 public class ClientTestCase {
 	public static ChatWindow user1;
 	public static ChatWindow user1;
 	public static ChatWindow user2;
 	public static ChatWindow user2;
-
-	static Thread runServer = new Thread() {
-		@Override
-		public void run() {
-			Server.main(new String[] {});
-		}
-	};
-
-	@BeforeClass
-	public static void setUpClass() {
+	
+	static Thread runServer = new Thread(){
+    	@Override
+    	public void run() {
+    		Server.main(new String[]{});
+    	}
+    };
+	
+    @BeforeClass 
+    public static void setUpClass() {
 		runServer.start();
 		runServer.start();
-		user1 = new ChatWindow("localhost", 25566, "user1");
-		assertTrue(user1.so.isConnected());
-	}
-
+        user1 = new ChatWindow("localhost", 25566, "user1");
+        assertTrue(user1.so.isConnected());
+    }
+	
 	@Test
 	@Test
 	public void testSend() {
 	public void testSend() {
 		user1.send("Hello!");
 		user1.send("Hello!");
 	}
 	}
-
+	
 	@Test
 	@Test
 	public void testPM() {
 	public void testPM() {
 		user2 = new ChatWindow("localhost", 25566, "user2");
 		user2 = new ChatWindow("localhost", 25566, "user2");
-
+		
 		user1.send("/pm user2 Hi there user2!");
 		user1.send("/pm user2 Hi there user2!");
 	}
 	}
-
+	
 	@AfterClass
 	@AfterClass
 	public static void tearDownClass() {
 	public static void tearDownClass() {
 		Server.exit();
 		Server.exit();

+ 1 - 2
src/test/java/client/ClientTestSuite.java

@@ -6,5 +6,4 @@ import org.junit.runners.Suite.SuiteClasses;
 
 
 @RunWith(value = Suite.class)
 @RunWith(value = Suite.class)
 @SuiteClasses(value = { ClientTestCase.class })
 @SuiteClasses(value = { ClientTestCase.class })
-public class ClientTestSuite {
-}
+public class ClientTestSuite {}

+ 4 - 4
src/test/java/common/CompleteTestSuite.java

@@ -1,24 +1,24 @@
 package common;
 package common;
 
 
+
 import org.junit.AfterClass;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.BeforeClass;
 import org.junit.runner.RunWith;
 import org.junit.runner.RunWith;
 import org.junit.runners.Suite;
 import org.junit.runners.Suite;
 import org.junit.runners.Suite.SuiteClasses;
 import org.junit.runners.Suite.SuiteClasses;
-
 import server.ServerTestSuite;
 import server.ServerTestSuite;
 
 
 @RunWith(Suite.class)
 @RunWith(Suite.class)
 @SuiteClasses({ ServerTestSuite.class, client.ClientTestSuite.class })
 @SuiteClasses({ ServerTestSuite.class, client.ClientTestSuite.class })
 public class CompleteTestSuite {
 public class CompleteTestSuite {
-
+	
 	@BeforeClass
 	@BeforeClass
 	public static void setUpBeforeClass() throws Exception {
 	public static void setUpBeforeClass() throws Exception {
-
+		
 	}
 	}
 
 
 	@AfterClass
 	@AfterClass
 	public static void tearDownAfterClass() throws Exception {
 	public static void tearDownAfterClass() throws Exception {
-
+		
 	}
 	}
 }
 }

+ 9 - 9
src/test/java/server/ServerTestCase.java

@@ -1,23 +1,23 @@
 package server;
 package server;
 
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.*;
 
 
 import org.junit.AfterClass;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.junit.Test;
 
 
 public class ServerTestCase {
 public class ServerTestCase {
-
-	@BeforeClass
-	public static void setUpClass() {
-		ServerTestSuite.runServer.start();
-	}
-
+	
+	@BeforeClass 
+    public static void setUpClass() {
+    	ServerTestSuite.runServer.start();
+    }
+	
 	@Test
 	@Test
 	public void testCInt() {
 	public void testCInt() {
-		assertEquals(server.util.Numbers.CInt("832"), 832);
+		assertEquals(Server.CInt("832"), 832);
 	}
 	}
-
+	
 	@AfterClass
 	@AfterClass
 	public static void tearDownClass() {
 	public static void tearDownClass() {
 		Server.exit();
 		Server.exit();

+ 7 - 7
src/test/java/server/ServerTestSuite.java

@@ -7,11 +7,11 @@ import org.junit.runners.Suite.SuiteClasses;
 @RunWith(value = Suite.class)
 @RunWith(value = Suite.class)
 @SuiteClasses(value = { client.ClientTestSuite.class })
 @SuiteClasses(value = { client.ClientTestSuite.class })
 public class ServerTestSuite {
 public class ServerTestSuite {
-
-	public static Thread runServer = new Thread() {
-		@Override
-		public void run() {
-			Server.main(new String[] {});
-		}
-	};
+	
+	public static Thread runServer = new Thread(){
+    	@Override
+    	public void run() {
+    		Server.main(new String[]{});
+    	}
+    };
 }
 }