Friday, December 28, 2012

Java JDBC

ILookup.java

import java.util.List;

public interface ILookup {
void SaveStudentSurveyFormData(StudentBean postData);
StudentBean GetStudentSurveyData(String studentId);
Surveys GetSurveys();
List<String> GetSurveyIds();
}

StudentDbDAO.java

package gmu.swe642.hw6;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class StudentDbDAO implements ILookup {
private Connection con;

public StudentDbDAO(){
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection ( "jdbc:oracle:thin:@",
dbusername, dbpassword);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

public void SaveStudentSurveyFormData(StudentBean postData){
try {
PreparedStatement pstat = con.prepareStatement("insert into survey values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pstat.setString(1, postData.getStudentId());
pstat.setString(2, postData.getFirstName());
pstat.setString(3, postData.getLastName());
pstat.setString(4, postData.getStreet());
pstat.setString(5, postData.getZip());
pstat.setString(6, postData.getCity());
pstat.setString(7, postData.getState());
pstat.setString(8, postData.getTelephone());
pstat.setString(9, postData.getEmail());
pstat.setString(10, postData.getUrl());
pstat.setString(11, postData.getDateOfSurvey());
pstat.setString(12, postData.getGraduationMonth());
pstat.setString(13, postData.getGraduationYear());
pstat.setString(14, postData.getLikes());
pstat.setString(15, postData.getInterests());
pstat.setString(16, postData.getRecommendation());
pstat.setString(17, postData.getComments());
pstat.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}

public StudentBean GetStudentSurveyData(String studentId){
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
if(survey.getStudentId().equalsIgnoreCase(studentId)){
return survey;
}
}
return null;
}

public Surveys GetSurveys(){
Surveys surveys = new Surveys();
surveys.data = new ArrayList<StudentBean>();
Statement stmt;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from survey");

while (rs.next())
{
String studentId = rs.getString(Consts.STUDENTID);
String firstName = rs.getString(Consts.FIRSTNAME);
String lastName = rs.getString(Consts.LASTNAME);
String street = rs.getString(Consts.STREET);
String zip = rs.getString(Consts.ZIP);
String city = rs.getString(Consts.CITY);
String state = rs.getString(Consts.STATE);
String telephone = rs.getString(Consts.TELEPHONE);
String email = rs.getString(Consts.EMAIL);
String url = rs.getString(Consts.URL);
String dateOfSurvey = rs.getString(Consts.DATEOFSURVEY);
String graduationMonth = rs.getString(Consts.GRADUATIONMONTH);
String graduationYear = rs.getString(Consts.GRADUATIONYEAR);
String likes = rs.getString(Consts.LIKES);
String interests = rs.getString(Consts.INTERESTS);
String recommendation = rs.getString(Consts.RECOMMENDATION);
String comments = rs.getString(Consts.COMMENTS);

StudentBean s = new StudentBean(studentId, firstName, lastName, street, zip, city, state,
telephone, email, url, dateOfSurvey, graduationMonth,
graduationYear, likes, interests, recommendation, comments);
surveys.data.add(s);
}
} catch (SQLException e) {
e.printStackTrace();
}

return surveys;
}

public List<String> GetSurveyIds(){
List<String> surveyIds = new ArrayList<String>();
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
surveyIds.add(survey.getStudentId());
}
return surveyIds;
}
}


Apache Struts with Actions and Form Beans

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>swe642hw5khuc</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <servlet-name>action</servlet-name>
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  <init-param>
  <param-name>config</param-name>
  <param-value>/WEB-INF/struts-config.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
    <form-beans>
    <form-bean name="surveyFormBean" type="package.SurveyFormBean"/>
    <form-bean name="surveyLookupFormBean" type="package.SurveyLookupFormBean"/>
    </form-beans>

    <action-mappings>
        <action path="/submitSurvey" type="package.SubmitSurveyAction" name="surveyFormBean" scope="session">        
        <forward name="simple-ack" path="/jsp/SimpleAcknowledgementJSP.jsp" />
        <forward name="winner-ack" path="/jsp/WinnerAcknowledgementJSP.jsp" />
        </action>
        <action path="/displaySurvey" type="package.DisplaySurveyAction" scope="session">
        <forward name="survey-found" path="/jsp/StudentJSP.jsp" />
        <forward name="survey-not-found" path="/jsp/NoSuchStudentJSP.jsp" />
        </action>
    </action-mappings>
</struts-config>

SubmitSurveyAction.java
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class SubmitSurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
SurveyFormBean formBean = (SurveyFormBean)form;

StudentBean studentBean = new StudentBean(formBean.getStudentId(),formBean.getFirstName(), formBean.getLastName(),
formBean.getStreet(), formBean.getZip(), formBean.getCity(), formBean.getState(),
formBean.getTelephone(), formBean.getEmail(), formBean.getUrl(), formBean.getDateOfSurvey(),
formBean.getGraduationMonth(), formBean.getGraduationYear(), formBean.getLikes(),
formBean.getInterests(), formBean.getRecommendation(), formBean.getComments());

StudentDAO.SaveStudentSurveyFormData(studentBean);

DataBean dataBean = DataProcessor.ComputeMeanAndStandardDeviation(formBean.getData());

List<String> surveyIdsBean = StudentDAO.GetSurveyIds();

HttpSession session = request.getSession();

session.setAttribute("student", studentBean);
session.setAttribute("data", dataBean);
session.setAttribute("surveys", surveyIdsBean);

if(dataBean.getMean() > 90){
return mapping.findForward("winner-ack");
}
return mapping.findForward("simple-ack");
}
}

DisplaySurveyAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class DisplaySurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
String studentId = request.getParameter("studentId");
StudentBean studentBean = null;

if(studentId != null){
studentBean = StudentDAO.GetStudentSurveyData(studentId);
}

HttpSession session = request.getSession();

if(studentBean == null){
session.setAttribute("badId", studentId);
return mapping.findForward("survey-not-found");
}
else{
session.setAttribute("student", studentBean);
return mapping.findForward("survey-found");
}
}
}

SurveyFormBean.java
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class SurveyFormBean extends ActionForm {
private String studentId;
private String firstName;
private String lastName;
private String street;
private String zip;
private String city;
private String state;
private String telephone;
private String email;
private String url;
private String dateOfSurvey;
private String graduationMonth;
private String graduationYear;
private String[] likes;
private String interests;
private String recommendation;
private String comments;
private String data;

public String getStudentId(){
return this.studentId;
}

public void setStudentId(String studentId){
this.studentId = studentId;
}

public String getFirstName(){
return this.firstName;
}

public void setFirstName(String firstName){
this.firstName = firstName;
}

public String getLastName(){
return this.lastName;
}

public void setLastName(String lastName){
this.lastName = lastName;
}

public String getStreet(){
return this.street;
}

public void setStreet(String street){
this.street = street;
}

public String getZip(){
return this.zip;
}

public void setZip(String zip){
this.zip = zip;
}

public String getCity(){
return this.city;
}

public void setCity(String city){
this.city = city;
}

public String getState(){
return this.state;
}

public void setState(String state){
this.state = state;
}

public String getTelephone(){
return this.telephone;
}

public void setTelephone(String telephone){
this.telephone = telephone;
}

public String getEmail(){
return this.email;
}

public void setEmail(String email){
this.email = email;
}

public String getUrl(){
return this.url;
}

public void setUrl(String url){
this.url = url;
}

public String getDateOfSurvey(){
return this.dateOfSurvey;
}

public void setDateOfSurvey(String dateOfSurvey){
this.dateOfSurvey = dateOfSurvey;
}

public String getGraduationMonth(){
return this.graduationMonth;
}

public void setGraduationMonth(String graduationMonth){
this.graduationMonth = graduationMonth;
}

public String getGraduationYear(){
return this.graduationYear;
}

public void setGraduationYear(String graduationYear){
this.graduationYear = graduationYear;
}

public String[] getLikes(){
return this.likes;
}

public void setLikes(String[] likes){
this.likes = likes;
}

public String getInterests(){
return this.interests;
}

public void setInterests(String interests){
this.interests = interests;
}

public String getRecommendation(){
return this.recommendation;
}

public void setRecommendation(String recommendation){
this.recommendation = recommendation;
}

public String getComments(){
return this.comments;
}

public void setComments(String comments){
this.comments = comments;
}

public String getData(){
return this.data;
}

public void setData(String data){
this.data = data;
}
}

StudentDAO with FileReader and FilerWriter


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.*;

public class StudentDAO {
public static String fileName = "//data//temp//SurveyData.txt";

public static void SaveStudentSurveyFormData(StudentBean postData) throws IOException{
Surveys surveys = GetSurveys();
surveys.data.add(postData);
SaveFile(new Gson().toJson(surveys));
}

public static StudentBean GetStudentSurveyData(String studentId) throws IOException{
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
if(survey.getStudentId().equalsIgnoreCase(studentId)){
return survey;
}
}
return null;
}

public static Surveys GetSurveys() throws IOException{
Surveys surveys = null;
String fileText = ReadFile();
if(fileText.length() > 0){
surveys = new Gson().fromJson(fileText, Surveys.class);
}
else{
surveys = new Surveys();
surveys.data = new ArrayList<StudentBean>();
}
return surveys;
}

public static List<String> GetSurveyIds() throws IOException{
List<String> surveyIds = new ArrayList<String>();
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
surveyIds.add(survey.getStudentId());
}
return surveyIds;
}

public static String ReadFile() throws IOException{
BufferedReader file = new BufferedReader(new FileReader(fileName));
String line;
StringBuffer fileText = new StringBuffer();
while((line=file.readLine()) != null){
fileText.append(line);
}
file.close();
return fileText.toString();
}

public static void SaveFile(String fileText) throws IOException{
FileWriter fWriter = new FileWriter(fileName,false);
BufferedWriter writer = new BufferedWriter(fWriter);
fWriter.append(fileText);
writer.flush();
writer.close();
}
}


import java.util.ArrayList;

public class Surveys {
public ArrayList<StudentBean> data;
}


public class StudentBean {
private String studentId;
private String firstName;
private String lastName;
private String street;
private String zip;
private String city;
private String state;
private String telephone;
private String email;
private String url;
private String dateOfSurvey;
private String graduationMonth;
private String graduationYear;
private String likes;
private String interests;
private String recommendation;
private String comments;

public StudentBean(String studentId, String firstName, String lastName, String street, String zip,
String city, String state, String telephone, String email, String url, String dateOfSurvey,
String graduationMonth, String graduationYear, String likes, String interests,
String recommendation, String comments){
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
this.street = street;
this.zip = zip;
this.city = city;
this.state = state;
this.telephone = telephone;
this.email = email;
this.url = url;
this.dateOfSurvey = dateOfSurvey;
this.graduationMonth = graduationMonth;
this.graduationYear = graduationYear;
this.likes = likes;
this.interests = interests;
this.recommendation = recommendation;
this.comments = comments;
}

public String getStudentId(){
return this.studentId;
}

public String getFirstName(){
return this.firstName;
}

public String getLastName(){
return this.lastName;
}

public String getStreet(){
return this.street;
}

public String getZip(){
return this.zip;
}

public String getCity(){
return this.city;
}

public String getState(){
return this.state;
}

public String getTelephone(){
return this.telephone;
}

public String getEmail(){
return this.email;
}

public String getUrl(){
return this.url;
}

public String getDateOfSurvey(){
return this.dateOfSurvey;
}

public String getGraduationMonth(){
return this.graduationMonth;
}

public String getGraduationYear(){
return this.graduationYear;
}

public String getLikes(){
return this.likes;
}

public String getInterests(){
return this.interests;
}

public String getRecommendation(){
return this.recommendation;
}

public String getComments(){
return this.comments;
}
}


Java Servlet with RequestDispatcher


import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
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;

@WebServlet("/Display")
public class Display extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String studentId = request.getParameter("studentid");
String address = "jsp/StudentJSP.jsp";
StudentBean studentBean = null;

if(studentId != null){
studentBean = StudentDAO.GetStudentSurveyData(studentId);
}

HttpSession session = request.getSession();

if(studentBean == null){
address = "jsp/NoSuchStudentJSP.jsp";
session.setAttribute("badId", studentId);
}
else{
session.setAttribute("student", studentBean);
}

RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String studentId = request.getParameter("studentId");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String street = request.getParameter("street");
String zip = request.getParameter("zip");
String city = request.getParameter("city");
String state = request.getParameter("state");
String telephone = request.getParameter("telephone");
String email = request.getParameter("email");
String url = request.getParameter("url");
String dateOfSurvey = request.getParameter("dateOfSurvey");
String graduationMonth = request.getParameter("graduationMonth");
String graduationYear = request.getParameter("graduationYear");
String[] likes = request.getParameterValues("likes");
String interests = request.getParameter("interests");
String recommendation  = request.getParameter("recommendation");
String comments = request.getParameter("comments");
String data = request.getParameter("data");

String likesString = "";
for(int i=0; i< likes.length; i++){
likesString += likes[i] + ", ";
}
likesString = likesString.substring(0, likesString.length() - 2);

StudentBean studentBean = new StudentBean(studentId, firstName, lastName, street, zip, city, state,
telephone, email, url, dateOfSurvey, graduationMonth,
graduationYear, likesString, interests, recommendation, comments);

StudentDAO.SaveStudentSurveyFormData(studentBean);

DataBean dataBean = DataProcessor.ComputeMeanAndStandardDeviation(data);

List<String> surveyIdsBean = StudentDAO.GetSurveyIds();

HttpSession session = request.getSession();

session.setAttribute("student", studentBean);
session.setAttribute("data", dataBean);
session.setAttribute("surveys", surveyIdsBean);

String address = "jsp/SimpleAcknowledgementJSP.jsp";
if(dataBean.getMean() > 90){
address = "jsp/WinnerAcknowledgementJSP.jsp";
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}