Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class ClientShell {
- public static final String COMMAND_SEPARATOR = "%%";
- static User loggedInUser = null;
- public static void main(String[] args) throws ClassNotFoundException {
- try {
- String message = "";
- String response = null;
- Scanner keyboard = new Scanner(System.in);
- // 1) Build data socket for client to use
- Socket serverLink = new Socket("localhost", 5555);
- // 2) Set up streams
- // PrintWriter used for sending messages
- PrintWriter output = new PrintWriter(serverLink.getOutputStream());
- // Scanner / BufferedReader used for receiving messages
- Scanner input = new Scanner(serverLink.getInputStream());
- ObjectOutputStream objectOutput = new ObjectOutputStream(serverLink.getOutputStream());
- ObjectInputStream objectInput = new ObjectInputStream(serverLink.getInputStream());
- // 3) While we want still want to exchange messages
- while(!message.equalsIgnoreCase("exit"))
- {
- while(loggedInUser==null){
- notLoggedInOptions(keyboard,message,response,output,input,objectInput);
- }
- loggedInOptions(keyboard,message,response,output,input,objectInput,objectOutput);
- }
- // 8) Close the link to the server (the data socket)
- serverLink.close();
- } catch (IOException ex) {
- Logger.getLogger(ClientShell.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- public static void notLoggedInOptions(Scanner keyboard,String message,String response,
- PrintWriter output,Scanner input,ObjectInputStream objectInput) throws IOException, ClassNotFoundException{
- System.out.println("Type login for login or register for register");
- message = keyboard.nextLine();
- if(message.equalsIgnoreCase("register")){
- message="";
- boolean validUserName = false;
- while(validUserName == false){
- System.out.println("Type the username you want as your prefix for your email");
- System.out.println("It must be between 5 and 10 characters");
- System.out.println("eg type mgraham if you want mgraham@danielhaughton@haughton.com");
- message = keyboard.nextLine();
- if(message.length()>4 && message.length()<11 == true){
- validUserName = true;
- }else{
- System.out.println("It must be between 5 and 10 characters try again" );
- }
- }
- String username = message;
- message="";
- boolean validPassword = false;
- while(validPassword == false){
- System.out.println("Type the password you want");
- System.out.println("It must be atleast 8 characterrs");
- message = keyboard.nextLine();
- if(message.length()> 7){
- validPassword = true;
- }else{
- System.out.println("It must be atleast 8 characterrs,try again");
- }
- }
- String password = message;
- output.println("register"+ COMMAND_SEPARATOR + username + COMMAND_SEPARATOR + password);
- output.flush();
- response = input.nextLine();
- System.out.println(response);
- }else if(message.equalsIgnoreCase("login")){
- System.out.println("Type your full email eg goku@danielhaughton.com");
- String email = keyboard.nextLine();
- System.out.println("Type your password(note:Case sensitive)");
- String password = keyboard.nextLine();
- output.println("login"+ COMMAND_SEPARATOR + email + COMMAND_SEPARATOR + password);
- output.flush();
- Object responseObject = objectInput.readObject();
- if(responseObject == null){
- System.out.println("the server couldnt find a user with those details");
- } else {
- loggedInUser = (User)responseObject;
- System.out.println("Welcome" + loggedInUser.getEmail());
- }
- }
- else{
- System.out.println("Unsupported command!try again");
- }
- }
- public static void loggedInOptions(Scanner keyboard,String message,String response,
- PrintWriter output,Scanner input,ObjectInputStream objectInput,
- ObjectOutputStream objectOutput) throws IOException, ClassNotFoundException{
- System.out.println("Type compose to send an email");
- System.out.println("Type mysent to see all of your sent emails");
- System.out.println("Type unreademails to see all of your emails");
- System.out.println("Type allemails to view all of your emails");
- System.out.println("Type read-x to read the email with the ID x");
- message = keyboard.nextLine();
- if(message.equals("compose")){
- compose(keyboard,message,response,output,input,objectInput,objectOutput);
- }else if(message.equals("mysent")){
- mysent(keyboard,message,response,output,input,objectInput,objectOutput);
- }
- }
- public static void compose(Scanner keyboard,String message,String response,
- PrintWriter output,Scanner input,ObjectInputStream objectInput,
- ObjectOutputStream objectOutput) throws IOException{
- System.out.println("What is the subject of your email");
- String subject = keyboard.nextLine();
- System.out.println("What is the text of your email");
- String text = keyboard.nextLine();
- ArrayList<String> to = new ArrayList<>();
- System.out.println("How many people do you want to send the email to?(write 2 not two)");
- int number = Integer.parseInt(keyboard.nextLine());
- for(int i=0;i<number;i++){
- System.out.println("Enter one of the addresses you want to send to");
- to.add(keyboard.nextLine());
- Email email = new Email(0,loggedInUser.getEmail(),to,subject,text);
- //0 is an id placeholder
- //will be replaced by server
- output.println("send");
- output.flush();
- objectOutput.writeObject(email);
- objectOutput.flush();
- input.reset();
- response = input.nextLine().trim();
- System.out.println(response);
- }
- }
- public static void mysent(Scanner keyboard,String message,String response,
- PrintWriter output,Scanner input,ObjectInputStream objectInput,
- ObjectOutputStream objectOutput) throws IOException, ClassNotFoundException{
- output.println("mysent");
- output.flush();
- List<Email> results = (List<Email>) objectInput.readObject();
- System.out.println("done");
- }
- }
- class Server implements Runnable
- {
- Socket connectionSocket;
- static UserRepo userRepo = new UserRepo();
- static EmailRepo emailRepo = new EmailRepo();
- public static final String COMMAND_SEPARATOR = "%%";
- private User loggedInUser;
- private ObjectOutputStream outputObject;
- private ObjectInputStream inputObject;
- public Server(Socket s){
- try{
- System.out.println("Client Got Connected " );
- connectionSocket=s;
- loggedInUser= null;
- }catch(Exception e){e.printStackTrace();}
- }
- public void run(){
- try{
- String recievedMessage="";
- BufferedReader reader =
- new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
- BufferedWriter writer=
- new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
- outputObject = new ObjectOutputStream(connectionSocket.getOutputStream());
- inputObject = new ObjectInputStream(connectionSocket.getInputStream());
- while(!recievedMessage.equalsIgnoreCase("exit")){
- recievedMessage = reader.readLine().trim();
- String [] components = recievedMessage.split(COMMAND_SEPARATOR);
- if(components[0].equals("register")){
- User user= userRepo.addUser(components[1], components[2]);
- if(user==null){
- System.out.println("User is already in system");
- writer.write("Server Response: User wasnt added,"
- + "mayby there is already an account for that email? rn " );
- writer.flush();
- }else{
- writer.write("Server response:User was added,try logging in rn");
- System.out.println("user added");
- writer.flush();
- }
- }
- else if(components[0].equals("login")){
- User user= userRepo.login(components[1], components[2]);
- loggedInUser = user;
- outputObject.writeObject(user);
- outputObject.flush();
- outputObject.reset();
- }
- else if(components[0].equals("send")){
- Email email = (Email) inputObject.readObject();
- emailRepo.addEmail(email);
- writer.write("Server response:Email was sent rn");
- writer.flush();
- }
- else if(components[0].equals("mysent")){
- List<Email> results = Collections.synchronizedList(emailRepo.findEmailsSentBy(loggedInUser.getEmail()));
- outputObject.writeObject(results);
- outputObject.flush();
- outputObject.reset();
- }
- recievedMessage="";
- }
- connectionSocket.close();
- }catch(Exception e){e.printStackTrace();}
- }
- public static void main(String argv[]) throws Exception
- {
- System.out.println("Threaded Server is Running " );
- ServerSocket mysocket = new ServerSocket(5555);
- while(true)
- {
- Socket sock = mysocket.accept();
- Server server=new Server(sock);
- Thread serverThread=new Thread(server);
- serverThread.start();
- }
- }
- }
- public class EmailRepo {
- private List<Email> emails;
- private static int counter = 0; //used for ids for emails
- public EmailRepo() {
- emails =Collections.synchronizedList(new ArrayList<Email>());
- }
- public synchronized boolean addEmail(Email email){
- counter ++;
- email.setId(counter);
- emails.add(email);
- return true;
- }
- public synchronized List<Email> findEmailsSentBy(String by){
- List<Email> results = Collections.synchronizedList(new ArrayList<Email>());
- for(int i=0;i<emails.size();i++){
- if(emails.get(i).getFrom().equalsIgnoreCase(by)){
- results.add(emails.get(i));
- }
- }
- return results;
- }
- public class Email implements Serializable {
- private int id;
- private String from;
- private ArrayList<String> to;
- private String subject;
- private String text;
- private Date date;
- //unreadby contains the email address of those who recieved the email and read it,
- private ArrayList<String> unreadBy;
- //markedasspambye contains email addresses of those who recieved the email and marked it as spam
- private ArrayList<String> markedAsSpamBy;
- private ArrayList<String> deletedBy;
- public Email() {
- }
- public Email(int id, String from, ArrayList<String> to, String subject, String text, Date date, ArrayList<String> unreadBy, ArrayList<String> markedAsSpamBy, ArrayList<String> deletedBy) {
- this.id = id;
- this.from = from;
- this.to = to;
- this.subject = subject;
- this.text = text;
- this.date = date;
- this.unreadBy = unreadBy;
- this.markedAsSpamBy = markedAsSpamBy;
- this.deletedBy = deletedBy;
- }
- public Email(int id,String from,ArrayList<String> to,String subject,String text){
- this.id = id;
- this.from = from;
- this.to = to;
- this.subject = subject;
- this.text = text;
- date = new Date();
- unreadBy = new ArrayList<>();
- //add all receiptants to unreadby as when an email is sent nobody has read it
- for(int i=0;i<to.size();i++){
- unreadBy.add(to.get(i));
- }
- markedAsSpamBy = new ArrayList<>();
- deletedBy = new ArrayList<>();
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public Date getDate() {
- return date;
- }
- public void setDate(Date date) {
- this.date = date;
- }
- public ArrayList<String> getDeletedBy() {
- return deletedBy;
- }
- public void setDeletedBy(ArrayList<String> deletedBy) {
- this.deletedBy = deletedBy;
- }
- public String getSubject() {
- return subject;
- }
- public void setSubject(String subject) {
- this.subject = subject;
- }
- public String getFrom() {
- return from;
- }
- public void setFrom(String from) {
- this.from = from;
- }
- public ArrayList<String> getTo() {
- return to;
- }
- public void setTo(ArrayList<String> to) {
- this.to = to;
- }
- public String getText() {
- return text;
- }
- public void setText(String text) {
- this.text = text;
- }
- public ArrayList<String> getUnreadBy() {
- return unreadBy;
- }
- public void setUnreadBy(ArrayList<String> unreadBy) {
- this.unreadBy = unreadBy;
- }
- public ArrayList<String> getMarkedAsSpamBy() {
- return markedAsSpamBy;
- }
- public void setMarkedAsSpamBy(ArrayList<String> markedAsSpamBy) {
- this.markedAsSpamBy = markedAsSpamBy;
- }
- }
Add Comment
Please, Sign In to add comment