IDatabaseDAO
public interface IDatabaseDAO {
public void connect();
public void add(String input);
public String call(int id);
public ArrayList<String> callALl();
public void close();
}
------------------------------------------------------------------
DatabaseDAO
public class DatabaseDAO implements IDatabaseDAO {
private Connection con;
public void connect() {
try {
// Verbindung zum DBMS aufbauen
this.con = DriverManager.getConnection("jdbc:h2:\~/test", "sa", "");
// Statement erzeugen
Statement statement = con.createStatement();
String sql = "CREATE TABLE school " +
"(id INTEGER not NULL, " +
"date VARCHAR(19) not NULL," +
"entrytype VARCHAR(255) not NULL," +
"entrytext VARCHAR(255) not NULL," +
"teacher VARCHAR(255) not NULL)";
// Statement ausführen
statement.execute(sql);
// Aufräumarbeiten
statement.close(); // Statement schließen
} catch (SQLException e) {
e.printStackTrace();
}
}
public void add(String input) {
String[] ar = input.split(";");
try {
Statement statement = con.createStatement();
String sql = "INSERT INTO school " + "VALUES (" + Integer.parseInt(ar[0]) + "," + ar[1] + "," + ar[2] + "," + ar[3] + "," + ar[4] + ");";
statement.execute(sql);
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public String call(int id) {
String help = "";
try {
Statement statement = con.createStatement();
String sql = "SELECT * FROM school WHERE ID=" + id + ";";
statement.close();
ResultSet resultSet = statement.executeQuery(sql);
help = resultSet.getString(id);
} catch (SQLException e) {
e.printStackTrace();
}
return help;
}
@Override
public ArrayList<String> callALl() {
ArrayList<String> ar = new ArrayList<>();
try {
Statement statement = con.createStatement();
String sql = "SELECT * FROM school";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
ar.add(String.valueOf(resultSet.getInt("id")));
ar.add(resultSet.getString("date"));
ar.add(resultSet.getString("entrytype"));
ar.add(resultSet.getString("entrytext"));
ar.add(resultSet.getString("teacher"));
}
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return ar;
}
public void close() {
try {
Statement statement = con.createStatement();
statement.execute("DROP TABLE school");
statement.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
------------------------------------------------------------------
DATA
public class DataStore {
private static DataStore instance;
private Set<Pupil> pupils = new HashSet<>();
private DataStore() {
}
public static DataStore getInstance() {
if (instance == null) {
instance = new DataStore();
}
return instance;
}
public void setPupils(Set<Pupil> pupils) {
this.pupils.addAll(pupils);
}
public Set<Pupil> getPupils() {
return pupils;
}
public Pupil getPupilById(UUID id) {
for (Pupil pupil : pupils) {
if (pupil.getId().equals(id)) {
return pupil;
}
}
return null;
}
}
------------------------------------------------------------------
Interfaces
@mutia keyza ("/importData")
public interface IImportData {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Set<Pupil> importDataFromJSON(Set<Pupil> pupils);
}
@mutia keyza ("/pupil")
public interface IResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@mutia keyza ("/{pupil_id}/absence")
Absence newAbsence(@PathParam("pupil_id") String id,
Absence absence);
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{pupil_id}/absence/{absence_id}")
Absence getAbsenceById(@PathParam("pupil_id") String stId,
@PathParam("absence_id") String abId);
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{pupil_id}/absence/{absence_id}/excuse")
boolean excuseAbsence(@PathParam("pupil_id") String stId,
@PathParam("absence_id") String abId);
}
------------------------------------------------------------------
Resource.java
public class Resource implements IResource {
@Override
public Absence newAbsence(String id, Absence absence) {
DataStore.getInstance().getPupilById(UUID.fromString(id)).addAbsence(absence);
return DataStore.getInstance().getPupilById(UUID.fromString(id)).getAbsenceById(absence.getId());
}
@Override
public Absence getAbsenceById(String stId, String abId) {
return DataStore.getInstance().getPupilById(UUID.fromString(stId)).getAbsenceById(UUID.fromString(abId));
}
@Override
public boolean excuseAbsence(String stId, String abId) {
DataStore.getInstance().getPupilById(UUID.fromString(stId)).getAbsenceById(UUID.fromString(abId)).setExcused(true);
return DataStore.getInstance().getPupilById(UUID.fromString(stId)).getAbsenceById(UUID.fromString(abId)).isExcused();
}
}
------------------------------------------------------------------
ImportData.java
public class ImportData implements IImportData {
@Override
public Set<Pupil> importDataFromJSON(Set<Pupil> pupils) {
DataStore.getInstance().setPupils(pupils);
return DataStore.getInstance().getPupils();
}
}
------------------------------------------------------------------
index.jsp
<body>
<h1><%= "Hello World!" %>
</h1>
<br/>
<a href="${pageContext.request.contextPath}/PupilListServlet">Pupil list</a>
</body>
------------------------------------------------------------------
dropdownList.jsp
<%@ page import="com.example.test.model.Pupil" %>
<%@ page import="com.example.test.data.DataStore" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="pupils" class="com.example.test.PupilsBean" scope="request"/>
<html>
<head>
<title>Pupil list</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/AbsenceServlet" method="get">
<select name="pupilselect">
<% for (Pupil pupil : pupils.getPupils()) {%>
<option value="<%=pupil.getId()%>"><%=pupil.getFirstName() + " " + pupil.getLastName()%></option>
<%}%>
</select>
<input type="submit" name="Submit">
</form>
</body>
</html>
absenceList.jsp
<%@ page import="com.example.test.model.Pupil" %>
<%@ page import="com.example.test.model.Absence" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="a" class="com.example.test.model.Pupil" scope="request"/>
<html>
<head>
<title>Absence List</title>
</head>
<body>
<table>
<% for (Absence absence : a.getAbsences()) {%>
<tr>
<td><%=absence.toString()%>
</td>
</tr>
<%}%>
</table>
</body>
</html>
------------------------------------------------------------------
PupilListServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("pupils", new PupilsBean(DataStore.getInstance().getPupils()));
request.getRequestDispatcher("dropdownList.jsp").forward(request, response);
}
AbsenceServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String s = request.getParameter("pupilselect");
request.setAttribute("a", DataStore.instance.getPupilById(UUID.fromString(s)));
request.getRequestDispatcher("absenceList.jsp").forward(request, response);
}
------------------------------------------------------------------
HTTP Test
Add import data
POST http://localhost:8080/{<!-- -->{deployment_name}}/api/importData
Content-Type: application/json
< testdata.json
{%
client.test("Request executed successfully", function() {
client.assert(response.status === 204, "Response status is not 200")
});
%}
Add new absence
POST http://localhost:8080/{<!-- -->{deployment_name}}/api/pupil/0cb39981-442e-4e57-89e2-6c0128bf055b/absence
Content-Type: application/json
{
"excused": false,
"from": "2022-05-09",
"reason": "Exam anxiety",
"to": "2022-05-09"
}
{%
client.test("Request executed successfully", function() {
client.assert(response.status === 200, "Response status is not 200")
client.assert(response.body.hasOwnProperty("id"), "Cannot find 'id' option in response");
client.global.set("new_absence_id", response.body.id);
});
%}
Get added absence
GET http://localhost:8080/{<!-- -->{deployment_name}}/api/pupil/0cb39981-442e-4e57-89e2-6c0128bf055b/absence/{<!-- -->{new_absence_id}}
Accept: application/json
{%
client.test("Request executed successfully", function() {
client.assert(response.status === 200, "Response status is not 200");
client.assert(response.body.reason === "Exam anxiety", "Response JSON content not correct");
});
%}
Get added pupil
PUT http://localhost:8080/{<!-- -->{deployment_name}}/api/pupil/0cb39981-442e-4e57-89e2-6c0128bf055b/absence/{<!-- -->{new_absence_id}}/excuse
Accept: application/json
{%
client.test("Request executed successfully", function() {
client.assert(response.status === 204, "Response status is not 200, for excuse action");
});
%}
Get updated absence
GET http://localhost:8080/{<!-- -->{deployment_name}}/api/pupil/0cb39981-442e-4e57-89e2-6c0128bf055b/absence/{<!-- -->{new_absence_id}}
Accept: application/json
{%
client.test("Request executed successfully", function() {
client.assert(response.status === 200, "Response status is not 200");
client.assert(response.body.excused === true, "Absence not correctly excused");
});
%}
Microclient, add to servlet:
ITest itest = RestClientBuilder.newBuilder().baseUri(URI.create("http://localhost:8080/rest-1.0-SNAPSHOT/api")).followRedirects(true).build(ITest.class);