Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.*;
- import java.net.InetAddress;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.util.ArrayList;
- import java.util.Base64;
- import java.util.Random;
- import java.util.Scanner;
- /**
- * Created by lamec on 12/7/2016.
- */
- public class Client {
- private static Socket socket;
- private static String machineName;
- private static int portNumber;
- public static BufferedReader inputStream;
- public static PrintStream outputStream;
- public static String hostname;
- private static String username;
- private static ArrayList<String> activeUsers;
- private static ArrayList<String> allUsers;
- private static boolean isOperator = false;
- public static void main(String[] args){
- Integer integer = new Integer(args[0]);
- try {
- Scanner sc = new Scanner(System.in);
- portNumber = integer;
- hostname = InetAddress.getLocalHost().getHostName();
- socket = new Socket(hostname, portNumber);
- inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- outputStream = new PrintStream(socket.getOutputStream());
- String serverResponse;
- String userInput;
- updateActiveUsers();
- activeUsers.add(username = authenticationClient());
- FileOutputStream fileOutputStream = new FileOutputStream("active.txt");
- ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
- objectOutputStream.writeObject(activeUsers);
- fileOutputStream.close();
- objectOutputStream.close();
- allUsers = (ArrayList<String>)readObjectFromServer();
- while(true){
- MailList currentMailList = (MailList)readObjectFromServer();
- boolean newMailCheck = false;
- for(int i = 0; i < currentMailList.getMailList().size(); i++){
- if(currentMailList.getMailList().get(i).isRead() == false && currentMailList.getMailList().get(i).getTo().equals(username))
- newMailCheck = true;
- }
- if(isOperator){
- String[] aux = (String[])readObjectFromServer();
- if(aux.length > 1 && allUsers.contains(aux[1])){
- System.out.println(aux[1] + " wants to access server. Allow? (Y/N):");
- userInput = sc.nextLine();
- outputStream.println(userInput);
- }
- }
- if(newMailCheck)
- System.out.println("You have unread messages!");
- System.out.println("\nWelcome " + username + ".\n" +
- "Please select an action:\n" +
- "1)List all messages.\n" +
- "2)List all users.\n" +
- "3)Send message.\n" +
- "4)List read.\n" +
- "5)Delete Messages.\n" +
- "6)Change Password.\n" +
- "7)Log in as operator.\n" +
- "8)Exit."
- );
- if(isOperator){
- System.out.println("9)Change server databases.");
- }
- userInput = sc.nextLine();
- outputStream.println(userInput);
- if(userInput.equals("1")){
- MailList userMailList = (MailList)readObjectFromServer();
- for(int i = 0; i < userMailList.getMailList().size(); i++){
- if(!userMailList.getMailList().get(i).isRead()){
- System.out.println("\nFrom: " + userMailList.getMailList().get(i).getFrom() + " Subject: " + userMailList.getMailList().get(i).getSubject());
- System.out.println(userMailList.getMailList().get(i).getMessage());
- userMailList.getMailList().get(i).setRead(true);
- }
- }
- writeObjectToServer(userMailList);
- }
- else if(userInput.equals("2")){
- for(int i = 0; i < activeUsers.size(); i++){
- System.out.println(activeUsers.get(i).toString());
- }
- }
- else if(userInput.equals("3")){
- sendMessage();
- }
- else if(userInput.equals("4")){
- MailList userMailList = (MailList)readObjectFromServer();
- for(int i = 0; i < userMailList.getMailList().size(); i++){
- if(userMailList.getMailList().get(i).isRead()){
- System.out.println("\nFrom: " + userMailList.getMailList().get(i).getFrom() + " Subject: " + userMailList.getMailList().get(i).getSubject());
- System.out.println(userMailList.getMailList().get(i).getMessage());
- }
- }
- writeObjectToServer(userMailList);
- }
- else if(userInput.equals("5")){
- MailList userMailList = (MailList)readObjectFromServer();
- for(int i = 0; i < userMailList.getMailList().size(); i++){
- if(userMailList.getMailList().get(i).isRead()){
- System.out.println("\n" + (i + 1) + "From: " + userMailList.getMailList().get(i).getFrom() + " Subject: " + userMailList.getMailList().get(i).getSubject());
- }
- }
- System.out.println("Enter the number of the messages you want to delete (separate with , and no spaces):");
- userInput = sc.nextLine();
- String[] messagesToDelete = userInput.split(",");
- for(int i = 0; i < messagesToDelete.length; i++){
- int l = Integer.valueOf(messagesToDelete[i]);
- userMailList.getMailList().remove(l - 1 - i);
- }
- writeObjectToServer(userMailList);
- }
- else if(userInput.equals("6")){
- boolean flag = true;
- while(flag){
- System.out.println("Insert your desired new password:");
- userInput = sc.nextLine();
- if(userInput.length() > 9){
- System.out.println("Password too long, try again.");
- }
- else {
- flag = false;
- }
- }
- outputStream.println(userInput);
- }
- else if(userInput.equals("7")){
- String operatorPermission = inputStream.readLine();
- if (operatorPermission.equals("true")){
- isOperator = true;
- System.out.println("Operator permission granted.");
- }
- else{
- System.out.println("There is already a server operator.");
- }
- }
- else if(userInput.equals("9") && isOperator){
- while(!userInput.equals("3")){
- String[][] credentials = (String[][])readObjectFromServer();
- ArrayList<ArrayList<String>> mutableCredentials = new ArrayList<ArrayList<String>>();
- mutableCredentials.add(0, new ArrayList<String>());
- mutableCredentials.add(1, new ArrayList<String>());
- for(int i = 0; i < credentials[0].length; i++){
- mutableCredentials.get(0).add(credentials[0][i]);
- mutableCredentials.get(1).add(credentials[1][i]);
- System.out.println((i + 1) + ")\n" +
- "Username:" + mutableCredentials.get(0).get(i) + "\n" +
- "Password:" + mutableCredentials.get(1).get(i));
- }
- System.out.println("Press 1 to add, 2 to remove user and 3 to go back:");
- userInput = sc.nextLine();
- if(userInput.equals("1")){
- System.out.println("Insert desired username:");
- String tempUser = sc.nextLine();
- System.out.println("Insert desired password:");
- String tempPassword = sc.nextLine();
- mutableCredentials.get(0).add(tempUser);
- mutableCredentials.get(1).add(tempPassword);
- }
- else if(userInput.equals("2")){
- System.out.println("Which user do you want to remove?");
- String aux = sc.nextLine();
- int o = Integer.valueOf(aux) - 1;
- mutableCredentials.get(0).remove(o);
- mutableCredentials.get(1).remove(o);
- }
- writeObjectToServer(mutableCredentials);
- if(userInput.equals("3")){
- outputStream.println("false");
- }
- else{
- outputStream.println("true");
- }
- }
- }
- else{
- sc.close();
- closeClient();
- }
- }
- } catch (UnknownHostException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- private static void updateActiveUsers() throws IOException, ClassNotFoundException {
- //Idealmente o cliente não precisaria de acesso ao ficheiro com os utilizadores ativos, mas como ele tem acesso a essa informação de qualquer maneira colocamos aqui para simplificar o código já complicado de autenticação
- BufferedReader bufferedReader = new BufferedReader(new FileReader("active.txt"));
- if(bufferedReader.readLine() != null){ //Check if file is empty
- bufferedReader.close();
- FileInputStream fileInputStream = new FileInputStream("active.txt");
- ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
- activeUsers = (ArrayList<String>)objectInputStream.readObject();
- fileInputStream.close();
- objectInputStream.close();
- }
- else {
- bufferedReader.close();
- activeUsers = new ArrayList<String>();
- }
- }
- private static void sendMessage(){
- String userInput;
- Scanner sc = new Scanner(System.in);
- boolean validTo = true;
- String[] to = new String[0];
- while(validTo) {
- validTo = false;
- System.out.println("Please insert all clients you want to send your message to (separated by , with no spaces):");
- userInput = sc.nextLine();
- to = userInput.split(",");
- for (String aTo : to) {
- boolean foundName = false;
- for (int j = 0; j < allUsers.size(); j++) {
- if (aTo.equals(allUsers.get(j))) {
- foundName = true;
- }
- }
- if (!foundName) {
- validTo = true;
- }
- }
- if(validTo) {
- System.out.println("You entered one or more invalid users.");
- }
- }
- System.out.println("Subject (enter to finish):");
- String subject = sc.nextLine();
- System.out.println("Message (enter to finish):");
- String message = sc.nextLine();
- Mail mail = new Mail(to,username,subject,false,message);
- writeObjectToServer(mail);
- }
- private static Object readObjectFromServer(){
- String aux = null;
- Object o = new Object();
- try {
- aux = inputStream.readLine();
- byte [] data = Base64.getDecoder().decode(aux);
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
- o = ois.readObject();
- ois.close();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- return o;
- }
- private static void writeObjectToServer(Object o){
- try{
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream( baos );
- oos.writeObject(o);
- oos.close();
- String string = Base64.getEncoder().encodeToString(baos.toByteArray());
- outputStream.println(string);}
- catch (IOException e) {
- e.printStackTrace();
- }
- }
- private static String authenticationClient(){
- try{
- Scanner sc = new Scanner(System.in);
- System.out.println(inputStream.readLine());
- boolean aux = true;
- String username = null;
- while(aux){
- aux = false;
- username = sc.nextLine();
- for (int i = 0; i < activeUsers.size(); i++) {
- if (username.equals(activeUsers.get(i))) {
- System.out.println("That user is already active, try again.");
- aux = true;
- }
- }
- }
- outputStream.println(username);
- if(inputStream.readLine().equals("false")){
- System.out.println("Unauthorized username, disconnecting...");
- closeClient();
- return null;
- }
- while(true){
- System.out.println(inputStream.readLine());
- String password = sc.nextLine();
- outputStream.println(password);
- String receiver = inputStream.readLine();
- if(receiver.equals("true")) break;
- else{
- System.out.println(receiver);
- String string = sc.nextLine();
- outputStream.println(string);
- if(!string.equals("Y")){
- closeClient();
- return null;
- }
- }
- }
- String operatorCheck = inputStream.readLine();
- if(operatorCheck.equals("true")){
- System.out.println("Waiting for operator permission...");
- String operationPermission = inputStream.readLine();
- if(operationPermission.equals("false")){
- System.out.println("Permission denied. Closing client.");
- closeClient();
- }
- }
- return username;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- private static void closeClient(){
- try {
- FileInputStream fileInputStream = new FileInputStream("active.txt");
- ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
- activeUsers = (ArrayList<String>)objectInputStream.readObject();
- activeUsers.remove(username);
- FileOutputStream fileOutputStream = new FileOutputStream("active.txt");
- ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
- objectOutputStream.writeObject(activeUsers);
- outputStream.close();
- inputStream.close();
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- System.exit(0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement