Advertisement
Guest User

Untitled

a guest
Feb 17th, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 16.20 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.io.*;
  4. import java.net.InetAddress;
  5. import java.net.Socket;
  6. import java.net.UnknownHostException;
  7. import java.util.ArrayList;
  8. import java.util.Base64;
  9. import java.util.Random;
  10. import java.util.Scanner;
  11.  
  12. /**
  13.  * Created by lamec on 12/7/2016.
  14.  */
  15. public class Client {
  16.     private static Socket socket;
  17.     private static String machineName;
  18.     private static int portNumber;
  19.     public static BufferedReader inputStream;
  20.     public static PrintStream outputStream;
  21.     public static String hostname;
  22.     private static String username;
  23.     private static ArrayList<String> activeUsers;
  24.     private static ArrayList<String> allUsers;
  25.     private static boolean isOperator = false;
  26.  
  27.     public static void main(String[] args){
  28.         Integer integer = new Integer(args[0]);
  29.         try {
  30.             Scanner sc = new Scanner(System.in);
  31.             portNumber = integer;
  32.             hostname = InetAddress.getLocalHost().getHostName();
  33.             socket = new Socket(hostname, portNumber);
  34.             inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  35.             outputStream = new PrintStream(socket.getOutputStream());
  36.             String serverResponse;
  37.             String userInput;
  38.             updateActiveUsers();
  39.  
  40.             activeUsers.add(username = authenticationClient());
  41.  
  42.             FileOutputStream fileOutputStream = new FileOutputStream("active.txt");
  43.             ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
  44.             objectOutputStream.writeObject(activeUsers);
  45.             fileOutputStream.close();
  46.             objectOutputStream.close();
  47.             allUsers = (ArrayList<String>)readObjectFromServer();
  48.             while(true){
  49.                 MailList currentMailList = (MailList)readObjectFromServer();
  50.                 boolean newMailCheck = false;
  51.                 for(int i = 0; i < currentMailList.getMailList().size(); i++){
  52.                     if(currentMailList.getMailList().get(i).isRead() == false && currentMailList.getMailList().get(i).getTo().equals(username))
  53.                         newMailCheck = true;
  54.                 }
  55.                 if(isOperator){
  56.                     String[] aux = (String[])readObjectFromServer();
  57.                     if(aux.length > 1 && allUsers.contains(aux[1])){
  58.                         System.out.println(aux[1] + " wants to access server. Allow? (Y/N):");
  59.                         userInput = sc.nextLine();
  60.                         outputStream.println(userInput);
  61.                     }
  62.                 }
  63.                 if(newMailCheck)
  64.                     System.out.println("You have unread messages!");
  65.                 System.out.println("\nWelcome " + username + ".\n" +
  66.                         "Please select an action:\n" +
  67.                         "1)List all messages.\n" +
  68.                         "2)List all users.\n" +
  69.                         "3)Send message.\n" +
  70.                         "4)List read.\n" +
  71.                         "5)Delete Messages.\n" +
  72.                         "6)Change Password.\n" +
  73.                         "7)Log in as operator.\n" +
  74.                         "8)Exit."
  75.                 );
  76.                 if(isOperator){
  77.                     System.out.println("9)Change server databases.");
  78.                 }
  79.                 userInput = sc.nextLine();
  80.                 outputStream.println(userInput);
  81.                 if(userInput.equals("1")){
  82.                     MailList userMailList = (MailList)readObjectFromServer();
  83.                     for(int i = 0; i < userMailList.getMailList().size(); i++){
  84.                         if(!userMailList.getMailList().get(i).isRead()){
  85.                             System.out.println("\nFrom: " + userMailList.getMailList().get(i).getFrom() + " Subject: " + userMailList.getMailList().get(i).getSubject());
  86.                             System.out.println(userMailList.getMailList().get(i).getMessage());
  87.                             userMailList.getMailList().get(i).setRead(true);
  88.                         }
  89.                     }
  90.                     writeObjectToServer(userMailList);
  91.                 }
  92.                 else if(userInput.equals("2")){
  93.                     for(int i = 0; i < activeUsers.size(); i++){
  94.                         System.out.println(activeUsers.get(i).toString());
  95.                     }
  96.                 }
  97.                 else if(userInput.equals("3")){
  98.                     sendMessage();
  99.                 }
  100.                 else if(userInput.equals("4")){
  101.                     MailList userMailList = (MailList)readObjectFromServer();
  102.                     for(int i = 0; i < userMailList.getMailList().size(); i++){
  103.                         if(userMailList.getMailList().get(i).isRead()){
  104.                             System.out.println("\nFrom: " + userMailList.getMailList().get(i).getFrom() + " Subject: " + userMailList.getMailList().get(i).getSubject());
  105.                             System.out.println(userMailList.getMailList().get(i).getMessage());
  106.                         }
  107.                     }
  108.                     writeObjectToServer(userMailList);
  109.                 }
  110.                 else if(userInput.equals("5")){
  111.                     MailList userMailList = (MailList)readObjectFromServer();
  112.                     for(int i = 0; i < userMailList.getMailList().size(); i++){
  113.                         if(userMailList.getMailList().get(i).isRead()){
  114.                             System.out.println("\n" + (i + 1) + "From: " + userMailList.getMailList().get(i).getFrom() + " Subject: " + userMailList.getMailList().get(i).getSubject());
  115.                         }
  116.                     }
  117.                     System.out.println("Enter the number of the messages you want to delete (separate with , and no spaces):");
  118.                     userInput = sc.nextLine();
  119.                     String[] messagesToDelete = userInput.split(",");
  120.  
  121.                     for(int i = 0; i < messagesToDelete.length; i++){
  122.                         int l = Integer.valueOf(messagesToDelete[i]);
  123.                         userMailList.getMailList().remove(l - 1 - i);
  124.                     }
  125.                     writeObjectToServer(userMailList);
  126.                 }
  127.                 else if(userInput.equals("6")){
  128.                     boolean flag = true;
  129.                     while(flag){
  130.                         System.out.println("Insert your desired new password:");
  131.                         userInput = sc.nextLine();
  132.                         if(userInput.length() > 9){
  133.                             System.out.println("Password too long, try again.");
  134.                         }
  135.                         else {
  136.                             flag = false;
  137.                         }
  138.                     }
  139.                     outputStream.println(userInput);
  140.                 }
  141.                 else if(userInput.equals("7")){
  142.                     String operatorPermission = inputStream.readLine();
  143.                     if (operatorPermission.equals("true")){
  144.                         isOperator = true;
  145.                         System.out.println("Operator permission granted.");
  146.                     }
  147.                     else{
  148.                         System.out.println("There is already a server operator.");
  149.                     }
  150.                 }
  151.                 else if(userInput.equals("9") && isOperator){
  152.                     while(!userInput.equals("3")){
  153.                         String[][] credentials = (String[][])readObjectFromServer();
  154.                         ArrayList<ArrayList<String>> mutableCredentials = new ArrayList<ArrayList<String>>();
  155.                         mutableCredentials.add(0, new ArrayList<String>());
  156.                         mutableCredentials.add(1, new ArrayList<String>());
  157.                         for(int i = 0; i < credentials[0].length; i++){
  158.                             mutableCredentials.get(0).add(credentials[0][i]);
  159.                             mutableCredentials.get(1).add(credentials[1][i]);
  160.                             System.out.println((i + 1) + ")\n" +
  161.                                     "Username:" + mutableCredentials.get(0).get(i) + "\n" +
  162.                                     "Password:" + mutableCredentials.get(1).get(i));
  163.                         }
  164.                         System.out.println("Press 1 to add, 2 to remove user and 3 to go back:");
  165.                         userInput = sc.nextLine();
  166.                         if(userInput.equals("1")){
  167.                             System.out.println("Insert desired username:");
  168.                             String tempUser = sc.nextLine();
  169.                             System.out.println("Insert desired password:");
  170.                             String tempPassword = sc.nextLine();
  171.                             mutableCredentials.get(0).add(tempUser);
  172.                             mutableCredentials.get(1).add(tempPassword);
  173.                         }
  174.                         else if(userInput.equals("2")){
  175.                             System.out.println("Which user do you want to remove?");
  176.                             String aux = sc.nextLine();
  177.                             int o = Integer.valueOf(aux) - 1;
  178.                             mutableCredentials.get(0).remove(o);
  179.                             mutableCredentials.get(1).remove(o);
  180.                         }
  181.                         writeObjectToServer(mutableCredentials);
  182.                         if(userInput.equals("3")){
  183.                             outputStream.println("false");
  184.                         }
  185.                         else{
  186.                             outputStream.println("true");
  187.                         }
  188.                     }
  189.                 }
  190.                 else{
  191.                     sc.close();
  192.                     closeClient();
  193.                 }
  194.             }
  195.         } catch (UnknownHostException e) {
  196.             e.printStackTrace();
  197.         } catch (IOException e) {
  198.             e.printStackTrace();
  199.         } catch (ClassNotFoundException e) {
  200.             e.printStackTrace();
  201.         }
  202.     }
  203.  
  204.     private static void updateActiveUsers() throws IOException, ClassNotFoundException {
  205.         //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
  206.         BufferedReader bufferedReader = new BufferedReader(new FileReader("active.txt"));
  207.         if(bufferedReader.readLine() != null){ //Check if file is empty
  208.             bufferedReader.close();
  209.             FileInputStream fileInputStream = new FileInputStream("active.txt");
  210.             ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
  211.             activeUsers = (ArrayList<String>)objectInputStream.readObject();
  212.             fileInputStream.close();
  213.             objectInputStream.close();
  214.         }
  215.         else {
  216.             bufferedReader.close();
  217.             activeUsers = new ArrayList<String>();
  218.         }
  219.     }
  220.     private static void sendMessage(){
  221.         String userInput;
  222.         Scanner sc = new Scanner(System.in);
  223.         boolean validTo = true;
  224.         String[] to = new String[0];
  225.         while(validTo) {
  226.             validTo = false;
  227.             System.out.println("Please insert all clients you want to send your message to (separated by , with no spaces):");
  228.             userInput = sc.nextLine();
  229.             to = userInput.split(",");
  230.             for (String aTo : to) {
  231.                 boolean foundName = false;
  232.                 for (int j = 0; j < allUsers.size(); j++) {
  233.                     if (aTo.equals(allUsers.get(j))) {
  234.                         foundName = true;
  235.                     }
  236.                 }
  237.                 if (!foundName) {
  238.                     validTo = true;
  239.                 }
  240.             }
  241.             if(validTo) {
  242.                 System.out.println("You entered one or more invalid users.");
  243.             }
  244.         }
  245.         System.out.println("Subject (enter to finish):");
  246.         String subject = sc.nextLine();
  247.         System.out.println("Message (enter to finish):");
  248.         String message = sc.nextLine();
  249.         Mail mail = new Mail(to,username,subject,false,message);
  250.         writeObjectToServer(mail);
  251.     }
  252.     private static Object readObjectFromServer(){
  253.         String aux = null;
  254.         Object o = new Object();
  255.         try {
  256.             aux = inputStream.readLine();
  257.             byte [] data = Base64.getDecoder().decode(aux);
  258.             ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
  259.             o  = ois.readObject();
  260.             ois.close();
  261.         } catch (IOException e) {
  262.             e.printStackTrace();
  263.         } catch (ClassNotFoundException e) {
  264.             e.printStackTrace();
  265.         }
  266.         return o;
  267.     }
  268.     private static void writeObjectToServer(Object o){
  269.         try{
  270.             ByteArrayOutputStream baos = new ByteArrayOutputStream();
  271.             ObjectOutputStream oos = new ObjectOutputStream( baos );
  272.             oos.writeObject(o);
  273.             oos.close();
  274.             String string = Base64.getEncoder().encodeToString(baos.toByteArray());
  275.             outputStream.println(string);}
  276.         catch (IOException e) {
  277.             e.printStackTrace();
  278.         }
  279.     }
  280.     private static String authenticationClient(){
  281.         try{
  282.             Scanner sc = new Scanner(System.in);
  283.             System.out.println(inputStream.readLine());
  284.             boolean aux = true;
  285.             String username = null;
  286.             while(aux){
  287.                 aux = false;
  288.                 username = sc.nextLine();
  289.                 for (int i = 0; i < activeUsers.size(); i++) {
  290.                     if (username.equals(activeUsers.get(i))) {
  291.                         System.out.println("That user is already active, try again.");
  292.                         aux = true;
  293.                     }
  294.                 }
  295.  
  296.             }
  297.             outputStream.println(username);
  298.             if(inputStream.readLine().equals("false")){
  299.                 System.out.println("Unauthorized username, disconnecting...");
  300.                 closeClient();
  301.                 return null;
  302.             }
  303.             while(true){
  304.                 System.out.println(inputStream.readLine());
  305.                 String password = sc.nextLine();
  306.                 outputStream.println(password);
  307.                 String receiver = inputStream.readLine();
  308.                 if(receiver.equals("true")) break;
  309.                 else{
  310.                     System.out.println(receiver);
  311.                     String string = sc.nextLine();
  312.                     outputStream.println(string);
  313.                     if(!string.equals("Y")){
  314.                         closeClient();
  315.                         return null;
  316.                     }
  317.                 }
  318.             }
  319.             String operatorCheck = inputStream.readLine();
  320.             if(operatorCheck.equals("true")){
  321.                 System.out.println("Waiting for operator permission...");
  322.                 String operationPermission = inputStream.readLine();
  323.                 if(operationPermission.equals("false")){
  324.                     System.out.println("Permission denied. Closing client.");
  325.                     closeClient();
  326.                 }
  327.             }
  328.             return username;
  329.         } catch (IOException e) {
  330.             e.printStackTrace();
  331.         }
  332.         return null;
  333.     }
  334.     private static void closeClient(){
  335.         try {
  336.             FileInputStream fileInputStream = new FileInputStream("active.txt");
  337.             ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
  338.  
  339.             activeUsers = (ArrayList<String>)objectInputStream.readObject();
  340.             activeUsers.remove(username);
  341.  
  342.             FileOutputStream fileOutputStream = new FileOutputStream("active.txt");
  343.             ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
  344.  
  345.             objectOutputStream.writeObject(activeUsers);
  346.  
  347.             outputStream.close();
  348.             inputStream.close();
  349.             socket.close();
  350.  
  351.         } catch (IOException e) {
  352.             e.printStackTrace();
  353.         } catch (ClassNotFoundException e) {
  354.             e.printStackTrace();
  355.         }
  356.         System.exit(0);
  357.     }
  358. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement