package whiteboard.poll;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.util.ServletContextAware;
import whiteboard.HomePage;
import whiteboard.course.Course;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.ServletContext;
import javax.sql.DataSource;
/**
* Action to delete course from DB and homepage instance.
*
* @author John
*
*/
public class DeletePoll extends ActionSupport implements ServletContextAware {
private ServletContext servletContext;
private String pollid; // the poll to be delete from db and object
private HomePage homePage;
public String execute() {
homePage = getHomePage();
Course currCourse = homePage.getSelectedCourse();
String pollToBeDeleted = getPollid();
/* only admins can delete */
if (homePage.getAccountType().compareTo("administrator") == 0) {
DataSource dbcp = (DataSource) servletContext
.getAttribute("dbpool");
boolean removedFromDB = removePollFromDB(pollToBeDeleted, dbcp);
if (currCourse.removePoll(pollToBeDeleted) && removedFromDB) {
return SUCCESS;
}
}
validate();
return INPUT;
}
/**
* Delete the entry of the poll and its poll options with poll id pollid
* from the database.
*
* @param courseid
* @param user
*/
public static boolean removePollFromDB(String pollid, DataSource dbcp) {
Connection con = null;
boolean wasError = false;
try {
con = dbcp.getConnection();
PreparedStatement prepStatement;
// DELETE POLL
String sql = "DELETE FROM polls WHERE pollid = ?";
prepStatement = con.prepareStatement(sql);
prepStatement.setInt(1, Integer.parseInt(pollid));
prepStatement.executeUpdate();
// DELETE POLL OPTIONS
sql = "DELETE FROM polloptions WHERE pollid = ?";
prepStatement = con.prepareStatement(sql);
prepStatement.setInt(1, Integer.parseInt(pollid));
prepStatement.executeUpdate();
prepStatement.close();
} catch (Exception ex) {
ex.printStackTrace();
wasError = true;
} finally {
if (con != null)
try {
con.close();
} catch (Exception e) {
}
}
return wasError;
}
private HomePage getHomePage() {
return (HomePage) this.servletContext.getAttribute("homePage");
}
public void setServletContext(ServletContext arg0) {
this.servletContext = arg0;
}
public void validate() {
homePage = getHomePage();
/* Can't perform this action */
if (homePage == null)
System.out.println("homepage is null");
if (homePage.getAccountType().compareTo("administrator") != 0) {
System.out.println("homepage <><><>");
addFieldError(
"pollid",
getText("You cannot perform that because you are not admin."));
}
}
public void setPollid(String pollid) {
this.pollid = pollid;
}
public String getPollid() {
return pollid;
}
}
|