PageRenderTime 74ms CodeModel.GetById 2ms app.highlight 66ms RepoModel.GetById 1ms app.codeStats 0ms

/src/serverClient/Request.java

https://bitbucket.org/mohamedmohamed1/mailserver
Java | 709 lines | 661 code | 31 blank | 17 comment | 24 complexity | 8e1ab683ff8789f026b2f3242bf3a118 MD5 | raw file
  1package serverClient;
  2
  3import java.io.BufferedInputStream;
  4import java.io.DataInputStream;
  5import java.io.DataOutputStream;
  6import java.io.File;
  7import java.io.FileInputStream;
  8import java.net.Socket;
  9import java.util.StringTokenizer;
 10
 11import org.json.simple.JSONObject;
 12import org.json.simple.parser.JSONParser;
 13import org.json.simple.parser.ParseException;
 14
 15import ServerFileSystem.Email;
 16import ServerFileSystem.ServerFolder;
 17import ServerFileSystem.User;
 18import dataStructure.DoubleLinkedList;
 19
 20
 21/**
 22 * @author Muhammad Salah
 23 *
 24 */
 25public class Request{
 26    JSONObject req = null;
 27    JSONObject response = null;
 28    JSONParser parser = new JSONParser();
 29    DataInputStream dis = null;
 30    DataOutputStream dos = null;
 31    DoubleLinkedList users = null;
 32    Socket skt = null;
 33    String name = null;
 34    public void setName(String name) {
 35        this.name = name;
 36    }
 37    public void setskt(Socket s) {
 38        skt = s;
 39    }
 40    public void setUsers(DoubleLinkedList u) {
 41        users = u;
 42    }
 43    public Request(DataInputStream di, DataOutputStream d) {
 44        dis = di;
 45        dos = d;
 46    }
 47    /******************************* client side Functions *********************************/
 48    public String reqRegister(String name, String pass) {
 49        req = new JSONObject();
 50        req.put("name", name);
 51        req.put("password", pass);
 52        req.put("reqNum", "1");
 53        return req.toString();
 54    }
 55    public String loginClient(String name, String pass) {
 56        req = new JSONObject();
 57        req.put("name", name);
 58        req.put("password", pass);
 59        req.put("reqNum", "2");
 60        return req.toString();
 61    }
 62    public String reqClose() {
 63        req = new JSONObject();
 64        req.put("reqNum", "0");
 65        return req.toString();
 66    }
 67    public boolean loginResponse(String s) throws ParseException {
 68    	req = (JSONObject) parser.parse(s);
 69    	return (boolean)req.get("res");
 70
 71    }
 72
 73    public String getFoldersReq (String name ) {
 74        req = new JSONObject();
 75        req.put("name", name);
 76
 77        req.put("reqNum", "3");
 78        return req.toString();
 79    }
 80
 81    public String createFolderReq(String userName, String folderName) {
 82        req = new JSONObject();
 83        req.put("name", userName);
 84        req.put("folderName", folderName);
 85        req.put("reqNum", "4");
 86        return req.toString();
 87    }
 88    public String deleteFolderReq(String userName, String folderName) {
 89        req = new JSONObject();
 90        req.put("reqNum", "6");
 91        req.put("userName", userName);
 92        req.put("folderName", folderName);
 93        return req.toString();
 94    }
 95    public boolean deleteFolderRes(String res) throws ParseException {
 96        req = (JSONObject) parser.parse(res);
 97        return (boolean)req.get("res");
 98    }
 99    public String getEmailsInFolderRequest (String name , String foldername) {
100        req = new JSONObject();
101        req.put("name", name);
102        req.put("folderName", foldername);
103        req.put("reqNum", "5");
104        return req.toString();
105    }
106    public JSONObject EmailsResponse(String s) throws ParseException {
107        JSONParser p = new JSONParser();
108        return (JSONObject) p.parse(s);
109    }
110
111    public JSONObject foldersResponse(String s) throws ParseException {
112        JSONParser p = new JSONParser();
113        return (JSONObject) p.parse(s);
114    }
115    public String starUnstarEmailReq(String star,String userName, String folderName, String emailnum) {
116    	req = new JSONObject();
117    	 req.put("name", userName);
118    	 req.put("starred", star);
119         req.put("folderName", folderName);
120         req.put("emailnum",emailnum);
121         req.put("reqNum", "8");
122         return req.toString();
123    }
124    public String renameFolderReq(String userName, String folderName, String newFolder) {
125        req = new JSONObject();
126        req.put("name", userName);
127        req.put("folderName", folderName);
128        req.put("newFolder", newFolder);
129        req.put("reqNum", "7");
130        return req.toString();
131    }
132    public String newFolderReq(String userName, String folderName) {
133        req = new JSONObject();
134        req.put("name", userName);
135        req.put("folderName", folderName);
136        req.put("reqNum", "7");
137        return req.toString();
138    }
139    public String setPriorityReq(String priority,String userName, String folderName, String emailnum) {
140    	req = new JSONObject();
141   	 	req.put("name", userName);
142    	req.put("folderName", folderName);
143        req.put("emailnum",emailnum);
144        req.put("priority", priority);
145        req.put("reqNum", "10");
146        return req.toString();
147	}
148    public boolean newFolderRes(String res) throws ParseException {
149        req = (JSONObject) parser.parse(res);
150        return (boolean)req.get("res");
151    }
152    public boolean renameFolderRes(String res) throws ParseException {
153        req = (JSONObject) parser.parse(res);
154        return (boolean)req.get("res");
155    }
156    public boolean starUnstarEmailRes(String res) throws ParseException {
157        req = (JSONObject) parser.parse(res);
158        return (boolean)req.get("res");
159    }
160    public boolean setPriorityRes(String res) throws ParseException {
161        req = (JSONObject) parser.parse(res);
162        return (boolean)req.get("res");
163    }
164    public String sendEmailReq(String to, String sub, String body, String userName, String attachNum) {
165        req = new JSONObject();
166        req.put("reqNum", "11");
167        req.put("to", to);
168        req.put("sub", sub);
169        req.put("body", body);
170        req.put("name", userName);
171        req.put("attach", attachNum);
172        return req.toString();
173    }
174    public String laodEmailreq(String username , String foldername , String emailnum) {
175    	req = new JSONObject();
176        req.put("reqNum", "12");
177        req.put("name", username);
178        req.put("folderName", foldername);
179        req.put("emailNum",emailnum );
180        return req.toString();
181    }
182    public String SendAttachReq(File f) throws Exception {
183        byte [] mybytearray  = new byte [(int)f.length()];
184        FileInputStream fis = new FileInputStream(f);
185        BufferedInputStream bis = new BufferedInputStream(fis);
186        bis.read(mybytearray,0,mybytearray.length);
187        String s = new String(mybytearray);
188        return s;
189    }
190    public String markAllAsReadReq(String username , String foldername) {
191        req = new JSONObject();
192        req.put("reqNum", "13");
193        req.put("name", username);
194        req.put("folderName", foldername);
195        return req.toString();
196    }
197    public String DeleteEmailReq(String username , String foldername, String emailNum) {
198        req = new JSONObject();
199        req.put("reqNum", "14");
200        req.put("name", username);
201        req.put("folderName", foldername);
202        req.put("emailNum", emailNum);
203        return req.toString();
204    }
205    public String moveEmailReq(String username , String foldername,String folderTo, String emailNum) {
206        req = new JSONObject();
207        req.put("reqNum", "15");
208        req.put("name", username);
209        req.put("folderName", foldername);
210        req.put("emailNum", emailNum);
211        req.put("folderTo",folderTo);
212        return req.toString();
213    }
214    public String getContactsReq(String userName) {
215        req = new JSONObject();
216        req.put("reqNum", "16");
217        req.put("name", userName);
218        return req.toString();
219    }
220    public JSONObject getContactsRes(String res) {
221        JSONObject contacts = new JSONObject();
222        try {
223            contacts = (JSONObject) parser.parse(res);
224        } catch (Exception e) {
225            e.printStackTrace();
226        }
227        return contacts;
228    }
229    public String newContactReq(String userName, String contact) {
230        req = new JSONObject();
231        req.put("reqNum", "17");
232        req.put("name", userName);
233        req.put("contact", contact);
234        return req.toString();
235    }
236    public String reportSpamReq(String userName, String folderName, String emailNum) {
237        req = new JSONObject();
238        req.put("reqNum", "18");
239        req.put("name", userName);
240        req.put("folderName", folderName);
241        req.put("emailNum", emailNum);
242        return req.toString();
243    }
244    public String removeContactReq(String userName, String contact) {
245        req = new JSONObject();
246        req.put("reqNum", "19");
247        req.put("name", userName);
248        req.put("contact", contact);
249        return req.toString();
250    }
251
252    /******************************* Server side Functions *********************************/
253    public void recieveReq(String r) throws ParseException {
254        if(r == "exit") {
255            return;
256        }
257        req = (JSONObject) parser.parse(r);
258    }
259    /**
260     * this  function checks  the request number and the user name
261     * and password of user and  set response to true if the user name and
262     * password matches
263     * @param s
264     * @return
265     * @throws Exception
266     */
267    public String response() throws Exception {
268    	int reqnum = Integer.valueOf((String) req.get("reqNum"));
269    	switch (reqnum) {
270		case 1:
271			return register();
272		case 2:
273			return login();
274		case 3:
275		    String x = loaduserdata();
276			return x;
277		case 4:
278		    return createNewFolder();
279		case 5:
280		    return loadFoldersIndex();
281		case 6:
282		    return deleteFolder();
283		case 7:
284		    return renameFolder();
285		case 8:
286			return starunstarEmail();
287		case 9:
288		    return newFolder();
289		case 10:
290			return setPriority();
291		case 11:
292		    return recieveEmail();
293		case 12:
294			return returnEmail();
295		case 13:
296		    return markAllEmailsRead();
297		case 14:
298		    return DeleteEmail();
299		case 15:
300		    return moveEmail();
301		case 16:
302		    return getContacts();
303		case 17:
304		    return newContact();
305		case 18:
306		    return reportSpam();
307		case 19:
308			return removeContact();
309		default:
310			break;
311		}
312    	return null;
313    }
314
315	private  String loaduserdata() throws Exception {
316		ServerFolder server = new ServerFolder();
317		server.startServer("server");
318		server.emptyTrash((String)req.get("name"));
319		return (server.loadUserIndex((String)req.get("name"))).toString();
320	}
321
322
323    private String register() throws Exception {
324    	ServerFolder server = new ServerFolder();
325		server.startServer("server");
326		User u = new User();
327		u.setName((String)req.get("name"));
328		u.setPassword((String)req.get("password"));
329
330		response = new JSONObject();
331		response.put("res", server.addUser(u));
332		return response.toString();
333    }
334    private String login() throws Exception {
335    		ServerFolder server = new ServerFolder();
336    		server.startServer("server");
337    		User u = new User();
338    		u.setName((String)req.get("name"));
339    		u.setPassword((String)req.get("password"));
340    		server.emptyTrash((String)req.get("name"));
341    		response = new JSONObject();
342    		response.put("res", server.login(u));
343    		return response.toString();
344
345
346	}
347    private String createNewFolder() {
348        boolean b = false;
349        try {
350            ServerFolder server = new ServerFolder();
351            server.startServer("server");
352            String userName = (String) req.get("name");
353            String folderName = (String) req.get("folderName");
354            server.emptyTrash((String)req.get("name"));
355            b = server.createFilter(userName, folderName);
356        } catch(Exception e) {
357            b = false;
358        }
359        response = new JSONObject();
360        response.put("res", b);
361        return response.toString();
362    }
363    public String[] getRegReq() {
364        String[] s = {(String) req.get("name") , (String) req.get("password")};
365        return s;
366    }
367    private String loadFoldersIndex() throws Exception {
368        ServerFolder server = new ServerFolder();
369        server.startServer("server");
370        server.emptyTrash((String)req.get("name"));
371        return (server.loadfolderindex((String)req.get("name"),(String)req.get("folderName"))).toString();
372    }
373    private String deleteFolder() throws Exception {
374        boolean b = false;
375        try {
376            String fname = (String) req.get("folderName");
377            String userName = (String) req.get("userName");
378            ServerFolder server = new ServerFolder();
379            server.startServer("server");
380            server.emptyTrash((String)req.get("name"));
381            b = server.deleteFolder(userName, fname);
382        } catch(Exception e) {
383            b = false;
384        }
385        response = new JSONObject();
386        response.put("res", b);
387        return response.toString();
388    }
389    private String renameFolder() {
390        boolean b = false;
391        try {
392            String fname = (String) req.get("folderName");
393            String userName = (String) req.get("name");
394            String newFolder = (String) req.get("newFolder");
395            ServerFolder server = new ServerFolder();
396            server.startServer("server");
397            server.emptyTrash((String)req.get("name"));
398            b = server.renameFolder(userName, fname, newFolder);
399        } catch(Exception e) {
400            b = false;
401        }
402        response = new JSONObject();
403        response.put("res", b);
404
405        return response.toString();
406    }
407    private String starunstarEmail() {
408    	boolean  b = false;
409    	try {
410    		 String fname = (String) req.get("folderName");
411             String userName = (String) req.get("name");
412             String eNum = (String) req.get("emailnum");
413             String star = (String) req.get("starred");
414             ServerFolder server = new ServerFolder();
415             server.startServer("server");
416
417             server.emptyTrash((String)req.get("name"));
418             if(star.equals("false")) {
419            	 b = server.starEmail(userName, fname, eNum);
420
421             } else {
422            	 b = server.removeStarEmail(userName, fname, eNum);
423             }
424
425		} catch (Exception e) {
426			b = false;
427		}
428    	response = new JSONObject();
429    	response.put("res", b);
430        return response.toString();
431
432    }
433    private String newFolder() {
434        boolean b = false;
435        try {
436            String folderName = (String) req.get("folderName");
437            String userName = (String) req.get("name");
438            ServerFolder server = new ServerFolder();
439            server.startServer("server");
440            server.emptyTrash((String)req.get("name"));
441            server.createFilter(userName, folderName);
442            b = true;
443        } catch (Exception e) {
444            b = false;
445        }
446        response = new JSONObject();
447        response.put("res", b);
448        return response.toString();
449    }
450    private String setPriority() {
451    	boolean b = false;
452    	try {
453    		String fname = (String) req.get("folderName");
454            String userName = (String) req.get("name");
455            String eNum = (String) req.get("emailnum");
456            String priority =  (String) req.get("priority");
457            ServerFolder server = new ServerFolder();
458            server.startServer("server");
459            server.emptyTrash((String)req.get("name"));
460            b = server.setPriority(userName, fname, eNum, priority);
461            if(!b) {
462            	throw new Exception();
463            }
464		} catch (Exception e) {
465
466		}
467    	response = new JSONObject();
468        response.put("res", b);
469        return response.toString();
470	}
471    private String recieveEmail() {
472        try {
473            String to = (String) req.get("to");
474            String userName = (String) req.get("name");
475            String sub = (String) req.get("sub");
476            String body =  (String) req.get("body");
477            int attach = Integer.valueOf((String) req.get("attach"));
478            Email e = new Email();
479            e.newEmail(sub, userName, to, body, "3");
480            dos.writeUTF("okay");
481            for(int i = 0; i < attach; i++) {
482                String fileName = dis.readUTF();
483
484                String size = dis.readUTF();
485                int filesize = Integer.valueOf(size);
486                byte[] file = new byte[filesize];
487
488                if(filesize>0) {
489                	dis.readFully(file, 0, filesize);
490                    e.addAttachment(file, fileName);
491                } else {
492                	throw new Exception();
493                }
494
495            }
496            ServerFolder server = new ServerFolder();
497            server.startServer("server");
498            server.emptyTrash((String)req.get("name"));
499            boolean bool = server.recieveFile(e);
500            response = new JSONObject();
501            response.put("res", bool);
502            return response.toString();
503        } catch (Exception e) {
504            boolean bool = false;
505            response = new JSONObject();
506            response.put("res", bool);
507            return response.toString();
508        }
509    }
510    private String returnEmail() {
511    	try {
512    		String fname = (String) req.get("folderName");
513            String userName = (String) req.get("name");
514            String eNum = (String) req.get("emailNum");
515            ServerFolder server = new ServerFolder();
516            server.startServer("server");
517            server.emptyTrash((String)req.get("name"));
518            Email e = server.loadEmail(userName, fname, eNum);
519            byte[] mybytes = e.toByteArray();
520            dos.writeUTF(String.valueOf(mybytes.length));
521            dos.write(mybytes);
522            response = new JSONObject();
523            response.put("res",true);
524            return response.toString();
525		} catch (Exception e) {
526			boolean bool = false;
527            response = new JSONObject();
528            response.put("res", bool);
529            return response.toString();
530		}
531
532
533    }
534    private String markAllEmailsRead() {
535        try {
536            String fname = (String) req.get("folderName");
537            String userName = (String) req.get("name");
538            ServerFolder server = new ServerFolder();
539            server.startServer("server");
540            server.emptyTrash((String)req.get("name"));
541            server.markAllEmailsRead(userName, fname);
542            response = new JSONObject();
543            response.put("res",true);
544            return response.toString();
545        } catch (Exception e) {
546            boolean bool = false;
547            response = new JSONObject();
548            response.put("res", bool);
549            return response.toString();
550        }
551    }
552    private String DeleteEmail() {
553        try {
554            String fname = (String) req.get("folderName");
555            String userName = (String) req.get("name");
556            String emailNum = (String) req.get("emailNum");
557            ServerFolder server = new ServerFolder();
558            server.startServer("server");
559            server.emptyTrash((String)req.get("name"));
560            boolean bool = server.deleteEmail(userName, fname, emailNum);
561            if(!bool) {
562                throw new Exception();
563            } else {
564                response = new JSONObject();
565                response.put("res", bool);
566                return response.toString();
567            }
568        } catch (Exception e) {
569            e.printStackTrace();
570            response = new JSONObject();
571            response.put("res", false);
572            return response.toString();
573        }
574
575    }
576    private String moveEmail() {
577        try {
578            String fname = (String) req.get("folderName");
579            String userName = (String) req.get("name");
580            String emailNum = (String) req.get("emailNum");
581            String folderTo = (String) req.get("folderTo");
582            ServerFolder server = new ServerFolder();
583            server.startServer("server");
584            server.emptyTrash((String)req.get("name"));
585            boolean bool = server.moveEmail(userName, fname, folderTo, emailNum);
586            if(!bool) {
587                throw new Exception();
588            } else {
589                response = new JSONObject();
590                response.put("res", bool);
591                return response.toString();
592            }
593        } catch (Exception e) {
594            e.printStackTrace();
595            response = new JSONObject();
596            response.put("res", false);
597            return response.toString();
598        }
599
600    }
601    private String getContacts() {
602        try {
603            String userName = (String) req.get("name");;
604            ServerFolder server = new ServerFolder();
605            server.startServer("server");
606            server.emptyTrash((String)req.get("name"));
607            String res = server.getContacts(userName);
608            return res;
609        } catch (Exception e) {
610            e.printStackTrace();
611            return null;
612        }
613    }
614    private String newContact() {
615        try {
616            String userName = (String) req.get("name");
617            String contactName = (String) req.get("contact");
618            ServerFolder server = new ServerFolder();
619            server.startServer("server");
620            server.emptyTrash((String)req.get("name"));
621            boolean bool = server.addContact(userName, contactName);
622            if(!bool) {
623                throw new Exception();
624            } else {
625                response = new JSONObject();
626                response.put("res", bool);
627                return response.toString();
628            }
629        } catch (Exception e) {
630            e.printStackTrace();
631            response = new JSONObject();
632            response.put("res", false);
633            return response.toString();
634        }
635    }
636    private String reportSpam() {
637        try {
638            String userName = (String) req.get("name");
639            String folderName = (String) req.get("folderName");
640            String emailNum = (String) req.get("emailNum");
641            ServerFolder server = new ServerFolder();
642            server.startServer("server");
643            server.emptyTrash((String)req.get("name"));
644            boolean bool = server.reportSpam(userName, folderName, emailNum);
645            if(!bool) {
646                throw new Exception();
647            } else {
648                response = new JSONObject();
649                response.put("res", bool);
650                return response.toString();
651            }
652        } catch (Exception e) {
653            e.printStackTrace();
654            response = new JSONObject();
655            response.put("res", false);
656            return response.toString();
657        }
658    }
659    private String removeContact() {
660    	try {
661            String userName = (String) req.get("name");
662            String contactName = (String) req.get("contact");
663            ServerFolder server = new ServerFolder();
664            server.startServer("server");
665            server.emptyTrash((String)req.get("name"));
666            boolean bool = server.removeContact(userName, contactName);
667            if(!bool) {
668                throw new Exception();
669            } else {
670                response = new JSONObject();
671                response.put("res", bool);
672                return response.toString();
673            }
674        } catch (Exception e) {
675            e.printStackTrace();
676            response = new JSONObject();
677            response.put("res", false);
678            return response.toString();
679        }
680	}
681    private String startChat() {
682        while (true) {
683            try {
684                String received = dis.readUTF();
685                System.out.println(received);
686                if(received.equals("logout")){
687                    break;
688                }
689                // break the string into message and recipient part
690                StringTokenizer st = new StringTokenizer(received, "#");
691                String MsgToSend = st.nextToken();
692                String recipient = st.nextToken();
693                // search for the recipient in the connected devices list.
694                // ar is the vector storing client of active users
695                for (int i = 0; i < users.size(); i++) {
696                    ClientHandler1 mc = (ClientHandler1) users.get(i);
697                    if (mc.name.equals(recipient) && mc.isLoggedin==true) {
698                        mc.dos.writeUTF(this.name+" : "+MsgToSend);
699                        break;
700                    }
701                }
702            } catch (Exception e) {
703
704                e.printStackTrace();
705            }
706        }
707        return "Done";
708    }
709}