diff --git a/src/main/java/launch/Main.java b/src/main/java/launch/Main.java index 28c023a..e78d6f9 100644 --- a/src/main/java/launch/Main.java +++ b/src/main/java/launch/Main.java @@ -22,7 +22,8 @@ public class Main { private static File getRootFolder() { try { File root; - String runningJarPath = Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath().replaceAll("\\\\", "/"); + String runningJarPath = Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath() + .replaceAll("\\\\", "/"); int lastIndexOf = runningJarPath.lastIndexOf("/target/"); if (lastIndexOf < 0) { root = new File(""); @@ -63,8 +64,8 @@ public class Main { Path tempPath = Files.createTempDirectory("tomcat-base-dir"); tomcat.setBaseDir(tempPath.toString()); - //The port that we should run on can be set into an environment variable - //Look for that variable and default to 8080 if it isn't there. + // The port that we should run on can be set into an environment variable + // Look for that variable and default to 8080 if it isn't there. String webPort = System.getenv("PORT"); if (webPort == null || webPort.isEmpty()) { webPort = "8080"; @@ -79,7 +80,8 @@ public class Main { } StandardContext ctx = (StandardContext) tomcat.addWebapp("", webContentFolder.getAbsolutePath()); ctx.setDocBase(webContentFolder.getAbsolutePath() + File.separator + "static"); - //Set execution independent of current thread context classloader (compatibility with exec:java mojo) + // Set execution independent of current thread context classloader + // (compatibility with exec:java mojo) ctx.setParentClassLoader(Main.class.getClassLoader()); System.out.println("configuring app with basedir: " + webContentFolder.getAbsolutePath()); @@ -91,16 +93,19 @@ public class Main { WebResourceSet resourceSet; if (additionWebInfClassesFolder.exists()) { - resourceSet = new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClassesFolder.getAbsolutePath(), "/"); - System.out.println("loading WEB-INF resources from as '" + additionWebInfClassesFolder.getAbsolutePath() + "'"); + resourceSet = new DirResourceSet(resources, "/WEB-INF/classes", + additionWebInfClassesFolder.getAbsolutePath(), "/"); + System.out.println( + "loading WEB-INF resources from as '" + additionWebInfClassesFolder.getAbsolutePath() + "'"); } else { resourceSet = new EmptyResourceSet(resources); } resources.addPreResources(resourceSet); - resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/jsp", webContentFolder.getAbsolutePath() + File.separator + "jsp", "/")); + resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/jsp", + webContentFolder.getAbsolutePath() + File.separator + "jsp", "/")); ctx.setResources(resources); tomcat.getConnector(); - + tomcat.start(); System.out.println("Listening to port " + webPort); diff --git a/src/main/java/model/HelloJspViewModel.java b/src/main/java/model/HelloJspViewModel.java index 84b24b8..1af57bb 100644 --- a/src/main/java/model/HelloJspViewModel.java +++ b/src/main/java/model/HelloJspViewModel.java @@ -4,6 +4,7 @@ import java.util.List; public class HelloJspViewModel { private final List data; + public HelloJspViewModel(List data) { this.data = data; } diff --git a/src/main/java/servlet/Dump.java b/src/main/java/servlet/Dump.java index 9047920..973031a 100644 --- a/src/main/java/servlet/Dump.java +++ b/src/main/java/servlet/Dump.java @@ -10,103 +10,111 @@ import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - - /** * Servlet implementation class Survey. */ @WebServlet("/Dump") public class Dump extends HttpServlet { private static final long serialVersionUID = 1L; - - // Define states + + // Define states private static final int NEED_NAME = 0; private static final int NEED_PROJECT_DATA = 2; - - private FormGenerator formGenerator = new FormGenerator(); - - - /** - * Default constructor. - */ - public Dump() { - } - - /* - * Checks first if name includes characters (i.e. is longer than zero characters) and then - * if so if the name is possible to add to - * the database. It is not possible to add an already existing name to the database. - */ - boolean nameOk(Database db, String name){ - boolean result = !name.equals(""); - if (result) result = db.addName(name); - return result; - } - boolean answerOk(Database db, String answerOne, String answerTwo, String answerThree, String answerFour) { - boolean result = !answerOne.equals("") && !answerTwo.equals("") && !answerThree.equals("") && !answerFour.equals(""); - if(result) result = db.addAnswer(answerFour, answerOne, answerTwo, answerThree, answerFour); - return result; - } - - /* - * Checks if a value entered as answer is OK. Answers should be between 1 and 10. - */ - boolean valueOk(int value){ - return value > 0 && value <11; - } - - protected boolean updateAnswers(String answerOne, String answerTwo) { - return true; - } + private FormGenerator formGenerator = new FormGenerator(); /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) + * Default constructor. */ - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - // Try with resources to create a connection, will ensure close is always called. - try(Database db = new Database()) { + public Dump() { + } + + /* + * Checks first if name includes characters (i.e. is longer than zero + * characters) and then + * if so if the name is possible to add to + * the database. It is not possible to add an already existing name to the + * database. + */ + boolean nameOk(Database db, String name) { + boolean result = !name.equals(""); + if (result) + result = db.addName(name); + return result; + } + + boolean answerOk(Database db, String answerOne, String answerTwo, String answerThree, String answerFour) { + boolean result = !answerOne.equals("") && !answerTwo.equals("") && !answerThree.equals("") + && !answerFour.equals(""); + if (result) + result = db.addAnswer(answerFour, answerOne, answerTwo, answerThree, answerFour); + return result; + } + + /* + * Checks if a value entered as answer is OK. Answers should be between 1 and + * 10. + */ + boolean valueOk(int value) { + return value > 0 && value < 11; + } + + protected boolean updateAnswers(String answerOne, String answerTwo) { + return true; + } + + /** + * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse + * response) + */ + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + // Try with resources to create a connection, will ensure close is always + // called. + try (Database db = new Database()) { // Get the session HttpSession session = request.getSession(true); - + int state = 0; String name; boolean sessionShouldBeEnded = false; - + // Decide which state the session is in if (session.isNew()) state = NEED_NAME; else { state = (Integer) session.getAttribute("state"); } - - // Get a writer, which will be used to write the next page for the user + + // Get a writer, which will be used to write the next page for the user PrintWriter out = response.getWriter(); - + // Start the page, print the HTML header and start the body part of the page out.println(""); out.println(" FANTASTIC WEB APPLICATION "); out.println(""); - + // Save the state in the session until next time doGet is requested session.setAttribute("state", state); - + // Print the end of the HTML-page out.println(""); - + if (sessionShouldBeEnded) - session.invalidate(); - } catch(SQLException ex) { + session.invalidate(); + } catch (SQLException ex) { // If Database.close for any reason fails. throw new ServletException(ex); } } /** - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse + * response) */ - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { doGet(request, response); } } diff --git a/src/main/java/servlet/FormGenerator.java b/src/main/java/servlet/FormGenerator.java index d70cfcd..dc704d8 100644 --- a/src/main/java/servlet/FormGenerator.java +++ b/src/main/java/servlet/FormGenerator.java @@ -1,60 +1,59 @@ package servlet; + /* * This class provides forms to be displayed to the user */ public class FormGenerator { - - private String formElement(String par) { - return '"' + par + '"'; - } - - - /* - * Form for requesting user name - */ - public String nameRequestForm() { - String html = "Please enter your name"; - html += "

'; - html += "

'; - return html; - } + private String formElement(String par) { + return '"' + par + '"'; + } + + /* + * Form for requesting user name + */ + public String nameRequestForm() { + String html = "Please enter your name"; + html += "

'; + html += "

'; + return html; + } public String projectDetailsRequestForm() { - String[][] variables = {{"Project Name", "proj_name"}, {"Project Description", "proj_desc"}}; - String html = "

Please give us some information about your project"; + String[][] variables = { { "Project Name", "proj_name" }, { "Project Description", "proj_desc" } }; + String html = "

Please give us some information about your project"; html += "

'; + return html; + } + + /* + * Form for requesting success with respect to four factors + */ + public String projectDataRequestForm() { + String[][] variables = { + { "Met operational performance", "s11" }, + { "Met technical performance", "s12" }, + { "Met project schedule", "s13" }, + { "Stayed on budget", "s14" } }; + String html = "

Please assess the importance of the following factors (1-10, where 1 is least important)"; + html += "

'; return html; } - /* - * Form for requesting success with respect to four factors - */ - public String projectDataRequestForm() { - String[][] variables = { - {"Met operational performance", "s11"}, - {"Met technical performance", "s12"}, - {"Met project schedule", "s13"}, - {"Stayed on budget", "s14"}}; - String html = "

Please assess the importance of the following factors (1-10, where 1 is least important)"; - html += "

'; - return html; - } - } diff --git a/src/main/java/servlet/HelloJsp.java b/src/main/java/servlet/HelloJsp.java index 8963eae..f789725 100644 --- a/src/main/java/servlet/HelloJsp.java +++ b/src/main/java/servlet/HelloJsp.java @@ -14,12 +14,12 @@ import java.util.*; public class HelloJsp extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - + RequestDispatcher requestDispatcher = this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/example.jsp"); - + req.setAttribute("simple", "example"); - req.setAttribute("complex", new model.HelloJspViewModel(List.of(5,4,3,2,1))); - + req.setAttribute("complex", new model.HelloJspViewModel(List.of(5, 4, 3, 2, 1))); + requestDispatcher.include(req, resp); } } diff --git a/src/main/java/servlet/Survey.java b/src/main/java/servlet/Survey.java index 024cfbe..3a564e2 100644 --- a/src/main/java/servlet/Survey.java +++ b/src/main/java/servlet/Survey.java @@ -10,165 +10,170 @@ import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - - /** * Servlet implementation class Survey. */ @WebServlet("/Survey") public class Survey extends HttpServlet { private static final long serialVersionUID = 1L; - - // Define states + + // Define states private static final int NEED_NAME = 0; private static final int NEED_PROJECT_INFO = 1; private static final int NEED_PROJECT_DATA = 2; - - private FormGenerator formGenerator = new FormGenerator(); - - - /** - * Default constructor. - */ - public Survey() { - } - - /* - * Checks first if name includes characters (i.e. is longer than zero characters) and then - * if so if the name is possible to add to - * the database. It is not possible to add an already existing name to the database. - */ - boolean nameOk(Database db, String name){ - boolean result = !name.equals(""); - if (result) - result = db.addName(name); - return result; - } - - /* - * Checks if a value entered as answer is OK. Answers should be between 1 and 10. - */ - boolean valueOk(int value){ - return value > 0 && value <11; - } - + + private FormGenerator formGenerator = new FormGenerator(); + /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) + * Default constructor. */ - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - // Try with resources to create a connection, will ensure close is always called. - try(Database db = new Database()) { + public Survey() { + } + + /* + * Checks first if name includes characters (i.e. is longer than zero + * characters) and then + * if so if the name is possible to add to + * the database. It is not possible to add an already existing name to the + * database. + */ + boolean nameOk(Database db, String name) { + boolean result = !name.equals(""); + if (result) + result = db.addName(name); + return result; + } + + /* + * Checks if a value entered as answer is OK. Answers should be between 1 and + * 10. + */ + boolean valueOk(int value) { + return value > 0 && value < 11; + } + + /** + * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse + * response) + */ + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + // Try with resources to create a connection, will ensure close is always + // called. + try (Database db = new Database()) { // Get the session HttpSession session = request.getSession(true); - + int state = 0; String name; boolean sessionShouldBeEnded = false; - + // Decide which state the session is in if (session.isNew()) state = NEED_NAME; else { state = (Integer) session.getAttribute("state"); } - - // Get a writer, which will be used to write the next page for the user + + // Get a writer, which will be used to write the next page for the user PrintWriter out = response.getWriter(); - + // Start the page, print the HTML header and start the body part of the page out.println(""); out.println(" FANTASTIC WEB APPLICATION "); out.println(""); - - switch (state){ - case NEED_NAME: // First state: get user name - name = request.getParameter("user"); // get the string that the user entered in the form - if (name != null) { - if (nameOk(db, name)) { - session.setAttribute("name", name); // save the name in the session - state = NEED_PROJECT_INFO; + + switch (state) { + case NEED_NAME: // First state: get user name + name = request.getParameter("user"); // get the string that the user entered in the form + if (name != null) { + if (nameOk(db, name)) { + session.setAttribute("name", name); // save the name in the session + state = NEED_PROJECT_INFO; + out.println(formGenerator.projectDetailsRequestForm()); + } else { + out.println("That was not a valid name. Maybe it is already taken by someone else."); + out.println(formGenerator.nameRequestForm()); + } + } else { // name was null, probably because no form has been filled out yet. Display + // form. + out.println(formGenerator.nameRequestForm()); + } + break; + case NEED_PROJECT_INFO: + name = (String) session.getAttribute("name"); + String description = request.getParameter("proj_desc"); + String proj_name = request.getParameter("proj_name"); + System.out.println("description: " + description); + if (description != null) { + state = NEED_PROJECT_DATA; + db.addProjectDetails(proj_name, description); + out.println(formGenerator.projectDataRequestForm()); + } else { out.println(formGenerator.projectDetailsRequestForm()); } + break; + case NEED_PROJECT_DATA: + int s11 = 0, s12 = 0, s13 = 0, s14 = 0; + name = (String) session.getAttribute("name"); + String s11String = request.getParameter("s11"); + String s14String = request.getParameter("s14"); + String s12String = request.getParameter("s12"); + String s13String = request.getParameter("s13"); + if (s11String == null) + out.println(formGenerator.projectDataRequestForm()); // first time else { - out.println("That was not a valid name. Maybe it is already taken by someone else."); - out.println(formGenerator.nameRequestForm()); - } - }else{ // name was null, probably because no form has been filled out yet. Display form. - out.println(formGenerator.nameRequestForm()); - } - break; - case NEED_PROJECT_INFO: - name = (String) session.getAttribute("name"); - String description = request.getParameter("proj_desc"); - String proj_name = request.getParameter("proj_name"); - System.out.println("description: " + description); - if (description != null) { - state = NEED_PROJECT_DATA; - db.addProjectDetails(proj_name, description); - out.println(formGenerator.projectDataRequestForm()); - } else { - out.println(formGenerator.projectDetailsRequestForm()); - } - break; - case NEED_PROJECT_DATA: - int s11 = 0, s12 = 0, s13 = 0, s14 = 0; - name = (String) session.getAttribute("name"); - String s11String = request.getParameter("s11"); - String s14String = request.getParameter("s14"); - String s12String = request.getParameter("s12"); - String s13String = request.getParameter("s13"); - if (s11String==null) - out.println(formGenerator.projectDataRequestForm()); // first time - else { - boolean valuesOk = true; - try { - s11 = Integer.parseInt(s11String); - s12 = Integer.parseInt(s12String); - s13 = Integer.parseInt(s13String); - s14 = Integer.parseInt(s14String); + boolean valuesOk = true; + try { + s11 = Integer.parseInt(s11String); + s12 = Integer.parseInt(s12String); + s13 = Integer.parseInt(s13String); + s14 = Integer.parseInt(s14String); - String str = s11String+s12String+s13String; - } catch (NumberFormatException e) { - valuesOk = false; + String str = s11String + s12String + s13String; + } catch (NumberFormatException e) { + valuesOk = false; + } + valuesOk = valuesOk && valueOk(s11) && valueOk(s12) && valueOk(s13) && valueOk(s14); + + // display the next page + if (valuesOk) { + int sum = s11 + s12 + s13 + s14; + db.addAnswer(name, s11String, s12String, s13String, s14String); + // This is only to show that it is possible to do something with the values. + // It is of course meaningless to calculate the sum. + out.println("

Hello " + name); + out.println("

The sum of the values you entered is " + sum); + sessionShouldBeEnded = true; + } else { + out.println("The values you entered were not OK"); + out.println(formGenerator.projectDataRequestForm()); + } } - valuesOk = valuesOk && valueOk(s11) && valueOk(s12) && valueOk(s13) && valueOk(s14); - - // display the next page - if (valuesOk){ - int sum = s11 + s12 + s13 + s14; - db.addAnswer(name, s11String, s12String, s13String, s14String); - // This is only to show that it is possible to do something with the values. - // It is of course meaningless to calculate the sum. - out.println("

Hello " + name); - out.println("

The sum of the values you entered is " + sum); - sessionShouldBeEnded = true; - } else { - out.println("The values you entered were not OK"); - out.println(formGenerator.projectDataRequestForm()); - } - } - break; + break; } - + // Save the state in the session until next time doGet is requested session.setAttribute("state", state); - + // Print the end of the HTML-page out.println(""); - + if (sessionShouldBeEnded) - session.invalidate(); - } catch(SQLException ex) { + session.invalidate(); + } catch (SQLException ex) { // If Database.close for any reason fails. throw new ServletException(ex); } } /** - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse + * response) */ - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { doGet(request, response); } }