package com.lichtfragmente.servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.Vector;
import com.lichtfragmente.helpers.*;
import com.lichtfragmente.beans.MessageBean;
import com.lichtfragmente.beans.UserBean;
/**
* Servlet to carry out actions related to the provate message system.
* As the webapp contains a private message system, this servlet in concerned
* with carrying out all associated actions such as fetching inboxes, sent
* boxes, dispatching views for new messages, deleting messages and getting
* sepcific messages.
**/
public class MessageServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//check login
if (GlobalHelpers.isLoggedIn(request)) {
if (request.getParameter("action")!=null) {
String action=request.getParameter("action");
if (action.compareTo("inbox")==0) {
//inbox view
this.getInbox(request,response);
} else if (action.compareTo("sent")==0) {
//sent message view
this.getSent(request,response);
} else if (action.compareTo("new")==0) {
//new message view
this.getNew(request,response);
} else if (action.compareTo("get")==0) {
//message view
this.getMessage(request,response);
} else {
throw new ServletException("Command not recognized!");
}
}
} else {
response.sendRedirect("/lichtfragmente");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//check login
if (GlobalHelpers.isLoggedIn(request)) {
if (request.getParameter("action")!=null) {
String action=request.getParameter("action");
if (action.compareTo("new")==0) {
//user wants to write new message
synchronized(this) {
try {
PreparedStatement stmt=DBInterface.doQuery("INSERT INTO privatemessage(title,content,sender,recipient) VALUES(?,?,?,?)");
stmt.setString(1,request.getParameter("title"));
stmt.setString(2,request.getParameter("content"));
stmt.setInt(3,(Integer)request.getSession().getAttribute("userid"));
stmt.setInt(4,Integer.parseInt(request.getParameter("recipient")));
stmt.executeUpdate();
stmt.close();
DBInterface.close();
//redirect to inbox
response.sendRedirect("/lichtfragmente/message/inbox");
} catch(SQLException sql) {
throw new ServletException("Could not send message: "+sql.getMessage());
}
}
} else if (action.compareTo("delete")==0) {
//user wants to delete a message
synchronized(this) {
try {
//ID of message to delete
int msgid=Integer.parseInt(request.getParameter("id"));
PreparedStatement stmt=DBInterface.doQuery("DELETE FROM privatemessage where id=?");
stmt.setInt(1,msgid);
//as this request is served via AJAX, we only respond with
//'success' or 'error'
if (stmt.executeUpdate()!=0) {
response.getWriter().print("success");
} else {
response.getWriter().print("error");
}
stmt.close();
DBInterface.close();
} catch (SQLException sql) {
response.getWriter().print("error");
} catch (NumberFormatException nfe) {
response.getWriter().print("error");
}
}
}
}
} else {
response.sendRedirect("/lichtfragmente");
}
}
/**
* Get private message inbox.
* This method fetches a user's messsage inbox and dispatches the
* inbox view to the client.
*
* @param request The HTTP request
* @param response The HTTP response to write to
**/
private void getInbox(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
Vector<MessageBean> list=new Vector<MessageBean>();
synchronized(this) {
try {
//get userid for inbox
int userid=(Integer)request.getSession().getAttribute("userid");
//fetch messages for user
PreparedStatement stmt=DBInterface.doQuery("SELECT m.id,m.title,m.date,m.read,u.name,u.id " +
"FROM privatemessage m " +
"INNER JOIN users u ON m.sender=u.id " +
"WHERE m.recipient=? " +
"ORDER BY date DESC");
stmt.setInt(1,userid);
ResultSet result=stmt.executeQuery();
//wrap the results into a list of beans
while (result.next()) {
MessageBean temp=new MessageBean();
temp.setId(result.getInt(1));
temp.setTitle(result.getString(2));
temp.setDate(result.getTimestamp(3));
temp.setRead(result.getBoolean(4));
temp.getSenderBean().setName(result.getString(5));
temp.getSenderBean().setId(result.getInt(6));
list.add(temp);
}
result.close();
stmt.close();
DBInterface.close();
} catch (SQLException sql) {
throw new ServletException("Could not retrieve inbox: "+sql.getMessage());
}
}
//add the data and dispatch to the inbox view
request.setAttribute("messages",list);
RequestDispatcher dispatcher=request.getRequestDispatcher(GlobalHelpers.getIncludedUrl("message/inbox"));
dispatcher.forward(request,response);
}
/**
* Get list of private messages sent.
* This method fetches a user's sent messsages and dispatches the
* sent box view to the client.
*
* @param request The HTTP request
* @param response The HTTP response to write to
**/
private void getSent(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
Vector<MessageBean> list=new Vector<MessageBean>();
synchronized(this) {
try {
//get user id
int userid=(Integer)request.getSession().getAttribute("userid");
//fetch sent messages
PreparedStatement stmt=DBInterface.doQuery("SELECT m.id,m.title,m.date,u.name,u.id " +
"FROM privatemessage m " +
"INNER JOIN users u ON m.recipient=u.id " +
"WHERE m.sender=? " +
"ORDER BY date DESC");
stmt.setInt(1,userid);
ResultSet result=stmt.executeQuery();
//store messages in list of beans
while (result.next()) {
MessageBean temp=new MessageBean();
temp.setId(result.getInt(1));
temp.setTitle(result.getString(2));
temp.setDate(result.getTimestamp(3));
temp.getRecipientBean().setName(result.getString(4));
temp.getRecipientBean().setId(result.getInt(5));
list.add(temp);
}
result.close();
stmt.close();
DBInterface.close();
} catch (SQLException sql) {
throw new ServletException("Could not retrieve sent box: "+sql.getMessage());
}
}
//add list to request and dispatch sent view
request.setAttribute("messages",list);
RequestDispatcher dispatcher=request.getRequestDispatcher(GlobalHelpers.getIncludedUrl("message/sent"));
dispatcher.forward(request,response);
}
/**
* Dispatches view for sending new messages.
* This method fetches the list of possible recipients from the database
* and stores them into a list of beans and dispatches the reuqest to
* the view for new messages.
*
* @param request HTTP request
* @param response HTTP response to write to
**/
private void getNew(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
Vector<UserBean> list=new Vector<UserBean>();
synchronized(this) {
try {
//get user id
int userid=(Integer)request.getSession().getAttribute("userid");
//get list of recipients (excluding this user's user id)
PreparedStatement stmt=DBInterface.doQuery("SELECT id,name FROM users WHERE id<>? ORDER BY name");
stmt.setInt(1,userid);
ResultSet result=stmt.executeQuery();
//store result in a list of beans
while (result.next()) {
UserBean temp=new UserBean();
temp.setId(result.getInt(1));
temp.setName(result.getString(2));
list.add(temp);
}
result.close();
stmt.close();
DBInterface.close();
} catch (SQLException sql) {
throw new ServletException("Could not retrieve recipient list: "+sql.getMessage());
}
}
//store list in request and dipatch to new message view
request.setAttribute("recipients",list);
RequestDispatcher dispatcher=request.getRequestDispatcher(GlobalHelpers.getIncludedUrl("message/new"));
dispatcher.forward(request,response);
}
/**
* Retrieves a specific message from the database.
* This method reads a message ID from the supplied HTTP request
* and tries to fetch the corresponding message from the database
* and dipatches the request to the message view.
* Furthermore it checks if the 'markread' parameter exists, which
* determines if the message should be marked as read or not.
*
* @param request The HTTP request to read the ID from
* @param response The HTTP response to write to
**/
private void getMessage(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException {
//get message id
int msgid=Integer.parseInt(request.getParameter("id"));
synchronized(this) {
try {
PreparedStatement stmt;
//should the message be marked as read?
if (request.getParameter("markread")!=null) {
stmt=DBInterface.doQuery("UPDATE privatemessage SET read=true WHERE id=?");
stmt.setInt(1,msgid);
stmt.executeUpdate();
stmt.close();
stmt=null;
}
//retrieve message
stmt=DBInterface.doQuery("SELECT content FROM privatemessage WHERE id=?");
stmt.setInt(1,msgid);
ResultSet result=stmt.executeQuery();
//write message out as this method responds to an AJAX request
if (result.next()) {
PrintWriter out=response.getWriter();
out.println(GlobalHelpers.nl2br(result.getString(1)));
} else {
throw new ServletException("Message with ID "+msgid+" not found");
}
} catch (SQLException sql) {
throw new ServletException("Could not retrieve message: "+sql.getMessage());
}
}
}
}