Formatting

This commit is contained in:
Imbus 2024-02-14 19:58:12 +01:00
parent dae126f721
commit 66ff5c2efd
6 changed files with 242 additions and 224 deletions

View file

@ -22,7 +22,8 @@ public class Main {
private static File getRootFolder() { private static File getRootFolder() {
try { try {
File root; 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/"); int lastIndexOf = runningJarPath.lastIndexOf("/target/");
if (lastIndexOf < 0) { if (lastIndexOf < 0) {
root = new File(""); root = new File("");
@ -63,8 +64,8 @@ public class Main {
Path tempPath = Files.createTempDirectory("tomcat-base-dir"); Path tempPath = Files.createTempDirectory("tomcat-base-dir");
tomcat.setBaseDir(tempPath.toString()); tomcat.setBaseDir(tempPath.toString());
//The port that we should run on can be set into an environment variable // 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. // Look for that variable and default to 8080 if it isn't there.
String webPort = System.getenv("PORT"); String webPort = System.getenv("PORT");
if (webPort == null || webPort.isEmpty()) { if (webPort == null || webPort.isEmpty()) {
webPort = "8080"; webPort = "8080";
@ -79,7 +80,8 @@ public class Main {
} }
StandardContext ctx = (StandardContext) tomcat.addWebapp("", webContentFolder.getAbsolutePath()); StandardContext ctx = (StandardContext) tomcat.addWebapp("", webContentFolder.getAbsolutePath());
ctx.setDocBase(webContentFolder.getAbsolutePath() + File.separator + "static"); 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()); ctx.setParentClassLoader(Main.class.getClassLoader());
System.out.println("configuring app with basedir: " + webContentFolder.getAbsolutePath()); System.out.println("configuring app with basedir: " + webContentFolder.getAbsolutePath());
@ -91,13 +93,16 @@ public class Main {
WebResourceSet resourceSet; WebResourceSet resourceSet;
if (additionWebInfClassesFolder.exists()) { if (additionWebInfClassesFolder.exists()) {
resourceSet = new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClassesFolder.getAbsolutePath(), "/"); resourceSet = new DirResourceSet(resources, "/WEB-INF/classes",
System.out.println("loading WEB-INF resources from as '" + additionWebInfClassesFolder.getAbsolutePath() + "'"); additionWebInfClassesFolder.getAbsolutePath(), "/");
System.out.println(
"loading WEB-INF resources from as '" + additionWebInfClassesFolder.getAbsolutePath() + "'");
} else { } else {
resourceSet = new EmptyResourceSet(resources); resourceSet = new EmptyResourceSet(resources);
} }
resources.addPreResources(resourceSet); 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); ctx.setResources(resources);
tomcat.getConnector(); tomcat.getConnector();

View file

@ -4,6 +4,7 @@ import java.util.List;
public class HelloJspViewModel { public class HelloJspViewModel {
private final List<Integer> data; private final List<Integer> data;
public HelloJspViewModel(List<Integer> data) { public HelloJspViewModel(List<Integer> data) {
this.data = data; this.data = data;
} }

View file

@ -10,8 +10,6 @@ import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
/** /**
* Servlet implementation class Survey. * Servlet implementation class Survey.
*/ */
@ -25,7 +23,6 @@ public class Dump extends HttpServlet {
private FormGenerator formGenerator = new FormGenerator(); private FormGenerator formGenerator = new FormGenerator();
/** /**
* Default constructor. * Default constructor.
*/ */
@ -33,27 +30,33 @@ public class Dump extends HttpServlet {
} }
/* /*
* Checks first if name includes characters (i.e. is longer than zero characters) and then * 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 * 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. * the database. It is not possible to add an already existing name to the
* database.
*/ */
boolean nameOk(Database db, String name){ boolean nameOk(Database db, String name) {
boolean result = !name.equals(""); boolean result = !name.equals("");
if (result) result = db.addName(name); if (result)
result = db.addName(name);
return result; return result;
} }
boolean answerOk(Database db, String answerOne, String answerTwo, String answerThree, String answerFour) { boolean answerOk(Database db, String answerOne, String answerTwo, String answerThree, String answerFour) {
boolean result = !answerOne.equals("") && !answerTwo.equals("") && !answerThree.equals("") && !answerFour.equals(""); boolean result = !answerOne.equals("") && !answerTwo.equals("") && !answerThree.equals("")
if(result) result = db.addAnswer(answerFour, answerOne, answerTwo, answerThree, answerFour); && !answerFour.equals("");
if (result)
result = db.addAnswer(answerFour, answerOne, answerTwo, answerThree, answerFour);
return result; return result;
} }
/* /*
* Checks if a value entered as answer is OK. Answers should be between 1 and 10. * Checks if a value entered as answer is OK. Answers should be between 1 and
* 10.
*/ */
boolean valueOk(int value){ boolean valueOk(int value) {
return value > 0 && value <11; return value > 0 && value < 11;
} }
protected boolean updateAnswers(String answerOne, String answerTwo) { protected boolean updateAnswers(String answerOne, String answerTwo) {
@ -61,11 +64,14 @@ public class Dump extends HttpServlet {
} }
/** /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/ */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doGet(HttpServletRequest request, HttpServletResponse response)
// Try with resources to create a connection, will ensure close is always called. throws ServletException, IOException {
try(Database db = new Database()) { // Try with resources to create a connection, will ensure close is always
// called.
try (Database db = new Database()) {
// Get the session // Get the session
HttpSession session = request.getSession(true); HttpSession session = request.getSession(true);
@ -97,16 +103,18 @@ public class Dump extends HttpServlet {
if (sessionShouldBeEnded) if (sessionShouldBeEnded)
session.invalidate(); session.invalidate();
} catch(SQLException ex) { } catch (SQLException ex) {
// If Database.close for any reason fails. // If Database.close for any reason fails.
throw new ServletException(ex); 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); doGet(request, response);
} }
} }

View file

@ -1,22 +1,21 @@
package servlet; package servlet;
/* /*
* This class provides forms to be displayed to the user * This class provides forms to be displayed to the user
*/ */
public class FormGenerator { public class FormGenerator {
private String formElement(String par) { private String formElement(String par) {
return '"' + par + '"'; return '"' + par + '"';
} }
/* /*
* Form for requesting user name * Form for requesting user name
*/ */
public String nameRequestForm() { public String nameRequestForm() {
String html = "Please enter your name"; String html = "Please enter your name";
html += "<p> <form name=" + formElement("input"); html += "<p> <form name=" + formElement("input");
//html += " action=" + formElement(myURL); // html += " action=" + formElement(myURL);
html += " method=" + formElement("get"); html += " method=" + formElement("get");
html += "<p> Name: <input type=" + formElement("text") + " name=" + formElement("user") + '>'; html += "<p> Name: <input type=" + formElement("text") + " name=" + formElement("user") + '>';
html += "<p> <input type=" + formElement("submit") + "value=" + formElement("Submit") + '>'; html += "<p> <input type=" + formElement("submit") + "value=" + formElement("Submit") + '>';
@ -24,13 +23,13 @@ public class FormGenerator {
} }
public String projectDetailsRequestForm() { public String projectDetailsRequestForm() {
String[][] variables = {{"Project Name", "proj_name"}, {"Project Description", "proj_desc"}}; String[][] variables = { { "Project Name", "proj_name" }, { "Project Description", "proj_desc" } };
String html = "<p>Please give us some information about your project"; String html = "<p>Please give us some information about your project";
html += "<p> <form name=" + formElement("input"); html += "<p> <form name=" + formElement("input");
html += " method=" + formElement("get"); html += " method=" + formElement("get");
for (int i=0; i<2; i++) { for (int i = 0; i < 2; i++) {
html += "<p> " + variables[i][0]; html += "<p> " + variables[i][0];
html += ": <input type="+ formElement("text") + "name =" + variables[i][1] + '>'; html += ": <input type=" + formElement("text") + "name =" + variables[i][1] + '>';
} }
html += "<p> <input type=" + formElement("submit") + "value=" + formElement("Submit") + '>'; html += "<p> <input type=" + formElement("submit") + "value=" + formElement("Submit") + '>';
return html; return html;
@ -41,17 +40,17 @@ public class FormGenerator {
*/ */
public String projectDataRequestForm() { public String projectDataRequestForm() {
String[][] variables = { String[][] variables = {
{"Met operational performance", "s11"}, { "Met operational performance", "s11" },
{"Met technical performance", "s12"}, { "Met technical performance", "s12" },
{"Met project schedule", "s13"}, { "Met project schedule", "s13" },
{"Stayed on budget", "s14"}}; { "Stayed on budget", "s14" } };
String html = "<p>Please assess the importance of the following factors (1-10, where 1 is least important)"; String html = "<p>Please assess the importance of the following factors (1-10, where 1 is least important)";
html += "<p> <form name=" + formElement("input2"); html += "<p> <form name=" + formElement("input2");
html += " method=" + formElement("get"); html += " method=" + formElement("get");
//html += " action=" + formElement(myURL); // html += " action=" + formElement(myURL);
for (int i=0; i<4; i++) { for (int i = 0; i < 4; i++) {
html += "<p> " + variables[i][0]; html += "<p> " + variables[i][0];
html += ": <input type="+ formElement("text") + "name =" + variables[i][1] + '>'; html += ": <input type=" + formElement("text") + "name =" + variables[i][1] + '>';
} }
html += "<p> <input type=" + formElement("submit") + "value=" + formElement("Submit") + '>'; html += "<p> <input type=" + formElement("submit") + "value=" + formElement("Submit") + '>';
return html; return html;

View file

@ -18,7 +18,7 @@ public class HelloJsp extends HttpServlet {
RequestDispatcher requestDispatcher = this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/example.jsp"); RequestDispatcher requestDispatcher = this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/example.jsp");
req.setAttribute("simple", "example"); 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); requestDispatcher.include(req, resp);
} }

View file

@ -10,8 +10,6 @@ import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
/** /**
* Servlet implementation class Survey. * Servlet implementation class Survey.
*/ */
@ -26,7 +24,6 @@ public class Survey extends HttpServlet {
private FormGenerator formGenerator = new FormGenerator(); private FormGenerator formGenerator = new FormGenerator();
/** /**
* Default constructor. * Default constructor.
*/ */
@ -34,11 +31,13 @@ public class Survey extends HttpServlet {
} }
/* /*
* Checks first if name includes characters (i.e. is longer than zero characters) and then * 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 * 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. * the database. It is not possible to add an already existing name to the
* database.
*/ */
boolean nameOk(Database db, String name){ boolean nameOk(Database db, String name) {
boolean result = !name.equals(""); boolean result = !name.equals("");
if (result) if (result)
result = db.addName(name); result = db.addName(name);
@ -46,18 +45,22 @@ public class Survey extends HttpServlet {
} }
/* /*
* Checks if a value entered as answer is OK. Answers should be between 1 and 10. * Checks if a value entered as answer is OK. Answers should be between 1 and
* 10.
*/ */
boolean valueOk(int value){ boolean valueOk(int value) {
return value > 0 && value <11; return value > 0 && value < 11;
} }
/** /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/ */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doGet(HttpServletRequest request, HttpServletResponse response)
// Try with resources to create a connection, will ensure close is always called. throws ServletException, IOException {
try(Database db = new Database()) { // Try with resources to create a connection, will ensure close is always
// called.
try (Database db = new Database()) {
// Get the session // Get the session
HttpSession session = request.getSession(true); HttpSession session = request.getSession(true);
@ -81,7 +84,7 @@ public class Survey extends HttpServlet {
out.println("<head><title> FANTASTIC WEB APPLICATION </title></head>"); out.println("<head><title> FANTASTIC WEB APPLICATION </title></head>");
out.println("<body>"); out.println("<body>");
switch (state){ switch (state) {
case NEED_NAME: // First state: get user name case NEED_NAME: // First state: get user name
name = request.getParameter("user"); // get the string that the user entered in the form name = request.getParameter("user"); // get the string that the user entered in the form
if (name != null) { if (name != null) {
@ -89,12 +92,12 @@ public class Survey extends HttpServlet {
session.setAttribute("name", name); // save the name in the session session.setAttribute("name", name); // save the name in the session
state = NEED_PROJECT_INFO; state = NEED_PROJECT_INFO;
out.println(formGenerator.projectDetailsRequestForm()); out.println(formGenerator.projectDetailsRequestForm());
} } else {
else {
out.println("That was not a valid name. Maybe it is already taken by someone else."); out.println("That was not a valid name. Maybe it is already taken by someone else.");
out.println(formGenerator.nameRequestForm()); out.println(formGenerator.nameRequestForm());
} }
}else{ // name was null, probably because no form has been filled out yet. Display form. } else { // name was null, probably because no form has been filled out yet. Display
// form.
out.println(formGenerator.nameRequestForm()); out.println(formGenerator.nameRequestForm());
} }
break; break;
@ -118,7 +121,7 @@ public class Survey extends HttpServlet {
String s14String = request.getParameter("s14"); String s14String = request.getParameter("s14");
String s12String = request.getParameter("s12"); String s12String = request.getParameter("s12");
String s13String = request.getParameter("s13"); String s13String = request.getParameter("s13");
if (s11String==null) if (s11String == null)
out.println(formGenerator.projectDataRequestForm()); // first time out.println(formGenerator.projectDataRequestForm()); // first time
else { else {
boolean valuesOk = true; boolean valuesOk = true;
@ -128,14 +131,14 @@ public class Survey extends HttpServlet {
s13 = Integer.parseInt(s13String); s13 = Integer.parseInt(s13String);
s14 = Integer.parseInt(s14String); s14 = Integer.parseInt(s14String);
String str = s11String+s12String+s13String; String str = s11String + s12String + s13String;
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
valuesOk = false; valuesOk = false;
} }
valuesOk = valuesOk && valueOk(s11) && valueOk(s12) && valueOk(s13) && valueOk(s14); valuesOk = valuesOk && valueOk(s11) && valueOk(s12) && valueOk(s13) && valueOk(s14);
// display the next page // display the next page
if (valuesOk){ if (valuesOk) {
int sum = s11 + s12 + s13 + s14; int sum = s11 + s12 + s13 + s14;
db.addAnswer(name, s11String, s12String, s13String, s14String); db.addAnswer(name, s11String, s12String, s13String, s14String);
// This is only to show that it is possible to do something with the values. // This is only to show that it is possible to do something with the values.
@ -159,16 +162,18 @@ public class Survey extends HttpServlet {
if (sessionShouldBeEnded) if (sessionShouldBeEnded)
session.invalidate(); session.invalidate();
} catch(SQLException ex) { } catch (SQLException ex) {
// If Database.close for any reason fails. // If Database.close for any reason fails.
throw new ServletException(ex); 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); doGet(request, response);
} }
} }