Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package project.controller;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Date;
- import java.util.List;
- import java.util.PropertyResourceBundle;
- import java.util.ResourceBundle;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.MultipartConfig;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import javax.servlet.http.Part;
- import org.json.JSONArray;
- //import org.apache.tomcat.util.http.fileupload.UploadContext;
- import org.json.JSONObject;
- import com.google.gson.Gson;
- import com.google.gson.GsonBuilder;
- import com.google.gson.JsonArray;
- import com.google.gson.JsonElement;
- import com.google.gson.JsonObject;
- import beans.BlogBean;
- import beans.ConnectionsBean;
- import beans.FileBean;
- import beans.StudentBean;
- import daoimpl.BlogDaoImpl;
- import daoimpl.ConnectionDaoImpl;
- import daoimpl.FacultyDaoImpl;
- import daoimpl.FileDaoImpl;
- import daoimpl.LikeDaoImpl;
- import daoimpl.PostDaoImpl;
- import daoimpl.StudentDaoImpl;
- import dto.Blog;
- import dto.Event;
- import dto.Faculty;
- import dto.Like;
- import dto.News;
- import dto.Post;
- import dto.StudentPost;
- import service.EventReader;
- import service.NewsReader;
- import dto.Student;
- @WebServlet("/Controller")
- @MultipartConfig
- public class Controller extends HttpServlet {
- private static final long serialVersionUID = 1L;
- private StudentDaoImpl sdi = new StudentDaoImpl();
- private FacultyDaoImpl fdi = new FacultyDaoImpl();
- private PostDaoImpl pdi = new PostDaoImpl();
- private LikeDaoImpl ldi = new LikeDaoImpl();
- private FileDaoImpl fileDaoImpl = new FileDaoImpl();
- private BlogDaoImpl bdi = new BlogDaoImpl();
- private ConnectionDaoImpl cdi = new ConnectionDaoImpl();
- private EventReader er = new EventReader();
- private NewsReader nr = new NewsReader();
- int i = 0;
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("UTF-8");
- resp.setContentType("text/html; charset=UTF-8");
- resp.setCharacterEncoding("UTF-8");
- String address = "/login.jsp";
- String action = req.getParameter("action");
- HttpSession session = req.getSession();
- StudentBean sb2 = (StudentBean) session.getAttribute("studentBean");
- if(sb2!=null) {
- if (action == null || "".equals(action) || "login".equals(action)) {
- address = "/WEB-INF/pages/main.jsp";
- FileBean fileBean = new FileBean();
- req.setAttribute("fileBean", fileBean);
- BlogBean blogBean = new BlogBean();
- req.setAttribute("blogBean", blogBean);
- }
- else if("connNtf".equals(action)) {
- resp.getOutputStream().println(cdi.getNumOfNewReq(sb2.getStudent().getId()));
- return;
- }
- else if("get_posts".equals(action)) {
- List<Post> posts = getAllPosts(sb2.getStudent());
- List<JsonElement> jsonElements = new ArrayList<JsonElement>();
- Gson gson = new Gson();
- for(Post post : posts) {
- JsonElement je = gson.toJsonTree(post);
- if(post instanceof StudentPost) {
- StudentPost sp = (StudentPost) post;
- Student s = sdi.getStudentyById(sp.getStudentId());
- String url = s.getImage();
- if(url == null || "".equals(url))
- url = "https://image.flaticon.com/icons/svg/17/17004.svg";
- else {
- url = "/UniShare" + url;
- }
- je.getAsJsonObject().addProperty("user_img", url);
- je.getAsJsonObject().addProperty("student_name", s.getName() + " " + s.getSurname());
- }
- jsonElements.add(je);
- }
- String json = gson.toJson(jsonElements);
- resp.getOutputStream().println(json);
- return;
- }
- else if ("logout".equals(action)) {
- address = "/login.jsp";
- //StudentBean sb = (StudentBean) session.getAttribute("studentBean");
- sb2.logout();
- session.invalidate();
- } else if ("toUpdate".equals(action)) {
- address = "/WEB-INF/pages/updateProfile.jsp";
- } else if (action.equals("update")) {
- String name = req.getParameter("name");
- String surname = req.getParameter("surname");
- String password = req.getParameter("password");
- String username = req.getParameter("username");
- String mail = req.getParameter("mail");
- Faculty faculty = fdi.getFacultyByName(req.getParameter("faculty"));
- String fileName = req.getParameter("file_name");
- System.out.println(fileName.equals(""));
- String res = areRegistrationParamValid(name, surname, username, password, mail);
- if("".equals(res) && faculty!=null) {
- System.out.println("Udje li ovde");
- sb2.getStudent().setName(name);
- sb2.getStudent().setSurname(surname);
- sb2.getStudent().setPassword(password);
- sb2.getStudent().setUsername(username);
- sb2.getStudent().setMail(mail);
- sb2.getStudent().setDescription(req.getParameter("description"));
- sb2.getStudent().setStudyProgram(req.getParameter("studyProgram"));
- sb2.getStudent().setFaculty(faculty);
- sb2.getStudent().setFacultyYear(Integer.parseInt(req.getParameter("facultyYear")));
- Part filePart = req.getPart("file");
- try {
- // file saving
- InputStream fileContent = filePart.getInputStream();
- byte[] buffer = new byte[fileContent.available()];
- fileContent.read(buffer);
- String webRootPath = getWebRootPath();
- System.out.println("fileName: " + fileName);
- String uploadPath = "";
- if(fileName == null || "".equals(fileName) || " ".equals(fileName)) {
- uploadPath = webRootPath + "assets\\img\\userImg\\user-picture.png";
- sb2.getStudent().setImage("/assets/img/userImg/user-picture.png");
- }
- else {
- uploadPath = webRootPath + "assets\\img\\userImg\\" + username + "_" + fileName;
- sb2.getStudent().setImage("/assets/img/userImg/" + username + "_" + fileName);
- File targetFile = new File(uploadPath);
- OutputStream outStream = new FileOutputStream(targetFile);
- outStream.write(buffer);
- outStream.close();
- }
- } catch (IOException ioe) {
- // TODO: handle exception
- ioe.printStackTrace();
- }
- //sb2.update();
- address = "/WEB-INF/pages/updateProfile.jsp";
- if(!sb2.update()) {
- req.setAttribute("updateNotification", "Error updating your profile");
- }
- }
- else {
- if("".equals(res))
- res = "Please choose faculty";
- req.setAttribute("updateNotification", res);
- address = "/WEB-INF/pages/updateProfile.jsp";
- }
- } else if (action.equals("like")) {
- BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
- String json = "";
- if(br != null){
- json = br.readLine();
- }
- br.close();
- JSONObject obj = new JSONObject(json);
- int postId = obj.getInt("postId");
- int rate = obj.getInt("rate");
- int studentId = ((StudentBean)session.getAttribute("studentBean")).getStudent().getId();
- Like like = new Like();
- like.setPostId(postId);
- like.setStudentId(studentId);
- like.setType(rate);
- StudentPost post = pdi.getById(postId);
- if(ldi.isLiked(like)) {
- // ako takav lajk postoji skini ga
- ldi.removeLike(like);
- String result = "";
- if(rate == 0) {
- post.setNumberOfLikes(post.getNumberOfLikes() - 1);
- result = "like-removed";
- }
- else {
- post.setNumberOfDislikes(post.getNumberOfDislikes() - 1);
- result = "dislike-removed";
- }
- pdi.updatePostRate(post);
- resp.getWriter().write(result);
- return;
- }
- // da li postoji suprotan lajk
- like.setType(Math.abs(like.getType() - 1));
- if(ldi.isLiked(like)) {
- //ako da skini ga
- ldi.removeLike(like);
- like.setType(Math.abs(like.getType() - 1));
- ldi.insertLike(like);
- String result = "";
- if(like.getType() == 0) {
- post.setNumberOfLikes(post.getNumberOfLikes() + 1);
- post.setNumberOfDislikes(post.getNumberOfDislikes() - 1);
- result = "dislike-removed-like-added";
- }
- else {
- post.setNumberOfLikes(post.getNumberOfLikes() - 1);
- post.setNumberOfDislikes(post.getNumberOfDislikes() + 1);
- result = "like-removed-dislike-added";
- }
- pdi.updatePostRate(post);
- resp.getWriter().write(result);
- return;
- }
- // ako ne postoji suprotan onda samo lajkaj
- like = new Like();
- like.setPostId(postId);
- like.setStudentId(studentId);
- like.setType(rate);
- ldi.insertLike(like);
- String result = "";
- if(rate == 0) {
- result = "liked";
- post.setNumberOfLikes(post.getNumberOfLikes() + 1);
- }
- else {
- result = "disliked";
- post.setNumberOfDislikes(post.getNumberOfDislikes() + 1);
- }
- pdi.updatePostRate(post);
- resp.getWriter().write(result);
- return;
- } else if (action.equals("post")) {
- int studentId = Integer.parseInt(req.getParameter("studentId"));
- long dateCreated = Long.parseLong(req.getParameter("dateCreated"));
- String description = req.getParameter("description");
- String linkPost = req.getParameter("linkPostText");
- if("".equals(description) && "".equals(linkPost)) {
- resp.setStatus(403);
- resp.setContentType("text/plain");
- resp.getWriter().write("Invalid post data");
- return;
- }
- StudentPost post = new StudentPost();
- post.setDescription(description);
- post.setNumberOfLikes(0);
- post.setNumberOfDislikes(0);
- post.setStudentId(studentId);
- post.setDatePosted(new Date(dateCreated));
- String typeOfPost = "0";
- if(linkPost.equals(""))
- typeOfPost = "0";
- else if(linkPost.contains("youtube.com")) {
- typeOfPost = "2";
- linkPost = linkPost.replace("watch?v=", "embed/");
- }
- else {
- typeOfPost = "1";
- }
- post.setTypeOfPost(typeOfPost);
- post.setLinkPost(linkPost);
- PostDaoImpl pdi = new PostDaoImpl();
- pdi.insertPost(post);
- Student s = sdi.getStudentyById(studentId);
- String url = s.getImage();
- if(url == null || "".equals(url))
- url = "https://image.flaticon.com/icons/svg/17/17004.svg";
- else {
- url = "/UniShare" + url;
- }
- Gson gson = new Gson();
- JsonElement je = gson.toJsonTree(post);
- je.getAsJsonObject().addProperty("user_img", url);
- je.getAsJsonObject().addProperty("student_name", s.getName() + " " + s.getSurname());
- String json = gson.toJson(je);
- resp.getOutputStream().println(json);
- return;
- } else if (action.equals("addFile")) {
- StudentBean studentBean = (StudentBean) session.getAttribute("studentBean");
- int studentId = studentBean.getStudent().getId();
- String description = req.getParameter("fileDescription");
- String fileName = req.getParameter("file_name");
- Part filePart = req.getPart("file");
- InputStream fileContent = filePart.getInputStream();
- if("".equals(description) || description == null) {
- req.setAttribute("addFileNtf", "Please add description");
- }
- else {
- if("".equals(fileName)) {
- req.setAttribute("addFileNtf", "Please choose file");
- }
- else {
- try {
- byte[] buffer = new byte[fileContent.available()];
- fileContent.read(buffer);
- String root = getWebRootPath();
- String uploadPath = root + "assets\\files\\" + fileName;
- File targetFile = new File(uploadPath);
- OutputStream outStream = new FileOutputStream(targetFile);
- outStream.write(buffer);
- outStream.close();
- } catch (IOException e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- dto.File file = new dto.File();
- if("".equals(description)) {
- file.setDescription("No file description");
- }
- else
- file.setDescription(description);
- file.setPath("/assets/files/" + fileName);
- file.setStudentId(studentId);
- if(!fileDaoImpl.insertFile(file)) {
- req.setAttribute("addFileNtf", "Err saving Your file on server");
- }
- else {
- req.setAttribute("addFileNtf", "Succesful");
- }
- }
- }
- address = "/WEB-INF/pages/main.jsp";
- FileBean fileBean = new FileBean();
- req.setAttribute("fileBean", fileBean);
- BlogBean blogBean = new BlogBean();
- req.setAttribute("blogBean", blogBean);
- } else if (action.equals("addBlog")) {
- StudentBean studentBean = (StudentBean) session.getAttribute("studentBean");
- int studentId = studentBean.getStudent().getId();
- String title = req.getParameter("title");
- String blogDescription = req.getParameter("blogDescription");
- if("".equals(title) || "".equals(blogDescription)) {
- req.setAttribute("addBlogNtf", "Please add title and description of your blog.");
- }
- else {
- req.setAttribute("addBlogNtf", "Succesful");
- Blog blog = new Blog();
- blog.setDateCreated(new Date(System.currentTimeMillis()));
- blog.setContent(blogDescription);
- blog.setStudentId(studentId);
- blog.setTitle(title);
- bdi.insertBlog(blog);
- }
- address = "/WEB-INF/pages/main.jsp";
- FileBean fileBean = new FileBean();
- req.setAttribute("fileBean", fileBean);
- BlogBean blogBean = new BlogBean();
- req.setAttribute("blogBean", blogBean);
- return;
- } else if (action.equals("addComment")) {
- int studentId = sb2.getStudent().getId();
- String blogComment = req.getParameter("blogComment");
- if(studentId == 0 || blogComment == null || "".equals(blogComment)) {
- JsonObject json = new JsonObject();
- json.addProperty("Error", "Error");
- json.addProperty("msg", "Please add text");
- resp.getOutputStream().println(json.toString());
- return;
- }
- bdi.addComment(req.getParameter("blogId"), blogComment, studentId);
- System.out.println(req.getParameter("blogId"));
- System.out.println(blogComment);
- System.out.println(studentId);
- String url = sb2.getStudent().getImage();
- if(url == null || "".equals(url))
- url = "https://image.flaticon.com/icons/svg/17/17004.svg";
- else {
- url = "/UniShare" + url;
- }
- JsonObject json = new JsonObject();
- json.addProperty("username", sb2.getStudent().getUsername());
- json.addProperty("imageUrl", url);
- json.addProperty("blogId", req.getParameter("blogId"));
- json.addProperty("comment", blogComment);
- resp.getOutputStream().println(json.toString());
- return ;
- } else if(action.equals("connections")) {
- ConnectionsBean cb = new ConnectionsBean();
- cb.setStudent(((StudentBean) session.getAttribute("studentBean")).getStudent());
- req.setAttribute("connectionBean", cb);
- address = "/WEB-INF/pages/connection.jsp";
- } else if(action.equals("get_students")) {
- List<Student> ret = sdi.getAllStudentsByFacultyId(Integer.parseInt(req.getParameter("facultyId")));
- ret.remove(sb2.getStudent());
- List<Student> connectedStudents = sdi.getAllStudentsConnected(sb2.getStudent());
- List<Integer> studentRequests = cdi.getRequestsSent(sb2.getStudent().getId());
- JSONArray jsonArray = new JSONArray();
- for(Student student : ret) {
- String url = student.getImage();
- if(url == null || "".equals(url))
- url = "https://image.flaticon.com/icons/svg/17/17004.svg";
- else {
- url = "/UniShare" + url;
- }
- //String username = student.getUsername();
- int type= -1;
- if(studentRequests.contains(student.getId()))
- type = 0;
- else if(connectedStudents.contains(student))
- type = 1;
- else
- type = 2;
- JSONObject json = new JSONObject();
- json.put("id", student.getId());
- json.put("username", student.getName() + " " + student.getSurname());
- json.put("type", type);
- json.put("url", url);
- jsonArray.put(json);
- }
- resp.getOutputStream().println(jsonArray.toString());
- return;
- }
- else if(action.equals("sendConnectionRequest")) {
- address = "/WEB-INF/pages/connection.jsp";
- BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
- String json = "";
- if(br != null){
- json = br.readLine();
- //System.out.println(json);
- }
- JSONObject obj = new JSONObject(json);
- int senderId = obj.getInt("senderId");
- int recieverId = obj.getInt("recieverId");
- if(cdi.insertConnection(senderId, recieverId, 1))
- resp.setStatus(200);
- else {
- System.out.println("ERR");
- }
- return;
- } else if(action.equals("acceptConnectionRequest")) {
- address = "/WEB-INF/pages/connection.jsp";
- BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
- String json = "";
- if(br != null){
- json = br.readLine();
- //System.out.println(json);
- }
- JSONObject obj = new JSONObject(json);
- int senderId = obj.getInt("senderId");
- int accepterId = Integer.parseInt(obj.getString("accepterId"));
- int accept = obj.getInt("accept");
- if(accept==1) {
- cdi.acceptConnection(senderId, accepterId);
- }
- else {
- cdi.deleteConnection(senderId, accepterId);
- }
- resp.setStatus(200);
- return;
- } else if(action.equals("deleteConnection")) {
- address = "/WEB-INF/pages/connection.jsp";
- BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
- String json = "";
- if(br != null){
- json = br.readLine();
- //System.out.println(json);
- }
- JSONObject obj = new JSONObject(json);
- int senderId = obj.getInt("senderId");
- int accepterId = obj.getInt("accepterId");
- cdi.deleteConnection(senderId, accepterId);
- cdi.deleteConnection(accepterId, senderId);
- resp.setStatus(200);
- return;
- } else if(action.equals("viewProfile")) {
- address = "/WEB-INF/pages/profile.jsp";
- int userId = Integer.parseInt(req.getParameter("userId"));
- session.setAttribute("userId", userId);
- }
- }
- else {
- if ("login".equals(action)) {
- String username = req.getParameter("username");
- String password = req.getParameter("password");
- if(areLoginParamValid(username, password)) {
- StudentBean studentBean = new StudentBean();
- if(studentBean.login(username, password)) {
- //setStudentBean(studentBean);
- session.setAttribute("studentBean", studentBean);
- address = "/WEB-INF/pages/main.jsp";
- FileBean fileBean = new FileBean();
- req.setAttribute("fileBean", fileBean);
- BlogBean blogBean = new BlogBean();
- req.setAttribute("blogBean", blogBean);
- }
- else {
- Student s = studentBean.getStudent();
- if( s != null ) {
- if(studentBean.getStudent().isDisabled())
- req.setAttribute("loginNotification", "Account blocked");
- }else
- req.setAttribute("loginNotification", "Invalid username or password");
- }
- }
- }
- else if ("registration".equals(action)) {
- String name = req.getParameter("name");
- String surname = req.getParameter("surname");
- String password = req.getParameter("password");
- String username = req.getParameter("username");
- String mail = req.getParameter("mail");
- String res = areRegistrationParamValid(name, surname, username, password, mail);
- if("".equals(res)) {
- StudentBean studentBean = new StudentBean();
- Student student = new Student();
- student.setName(name);
- student.setSurname(surname);
- student.setPassword(password);
- student.setUsername(username);
- student.setMail(mail);
- student.setImage("/assets/img/userImg/user-picture.png");
- studentBean.setStudent(student);
- String insertionResult = studentBean.add(student);
- studentBean.login(username, password);
- if("success".equals(insertionResult)) {
- session.setAttribute("studentBean", studentBean);
- address = "/WEB-INF/pages/updateProfile.jsp";
- }
- else {
- req.setAttribute("registrationNotification", insertionResult);
- address = "/login.jsp";
- }
- }
- else {
- req.setAttribute("registrationNotification", res);
- }
- }
- }
- RequestDispatcher dispatcher = req.getRequestDispatcher(address);
- dispatcher.forward(req, resp);
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- private boolean areLoginParamValid(String username, String password) {
- if("".equals(username) || "".equals(password))
- return false;
- return true;
- }
- private String areRegistrationParamValid(String name, String surname, String username, String password, String mail) {
- if("".equals(name) || name.length() < 2)
- return "Invalid name";
- if("".equals(surname) || surname.length() < 2)
- return "Invalid surname";
- if("".equals(username))
- if( username.length() < 4)
- return "Invalid username";
- else if(sdi.doesUsernameExist(username)) {
- return "Username already exist";
- }
- if("".equals(password) || password.length() < 4)
- return "Invalid password";
- if("".equals(mail) || mail.length() < 5)
- return "Invalid mail";
- return "";
- }
- private String getWebRootPath() {
- ResourceBundle bundle =
- PropertyResourceBundle.getBundle("daoimpl.ConnectionPool");
- String result = bundle.getString("webRootFolder");
- return result;
- }
- private ArrayList<Post> getAllPosts(Student student) {
- ArrayList<StudentPost> posts = (ArrayList<StudentPost>) pdi.getAllByStudentId(student.getId());
- List<Student> studentsConnected = sdi.getAllStudentsConnected(student);
- List<News> news = nr.getAll();
- news.forEach(n -> n.setType("news"));
- List<Event> events = er.getAll();
- events.forEach(e -> e.setType("event"));
- for(Student s : studentsConnected) {
- posts.addAll(pdi.getAllByStudentId(s.getId()));
- }
- posts.forEach(s -> s.setType("studentPost"));
- List<Post> allPosts = new ArrayList<>();
- allPosts.addAll(news);
- allPosts.addAll(events);
- allPosts.addAll(posts);
- if(allPosts.size() > 5) {
- Collections.sort(allPosts, (p1, p2) -> (p2.getNumberOfLikes() - p2.getNumberOfDislikes()) - (p1.getNumberOfLikes() - p1.getNumberOfDislikes()));
- return (ArrayList<Post>) allPosts;
- }
- else
- return (ArrayList<Post>) allPosts;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement