-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPaymentServlet.java
156 lines (125 loc) · 6.36 KB
/
PaymentServlet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package main.java;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@WebServlet(name = "PaymentServlet", urlPatterns = "/api/payment")
public class PaymentServlet extends HttpServlet {
private static final long serialVersionUID = 3L;
// Create a dataSource which registered in web.xml
private DataSource dataSource;
public void init(ServletConfig config) {
try {
dataSource = (DataSource) new InitialContext().lookup("java:comp/env/master");
} catch (NamingException e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
response.setContentType("application/json"); // Response mime type
// Output stream to STDOUT
PrintWriter out = response.getWriter();
try (Connection conn = dataSource.getConnection()) {
String firstName = request.getParameter("first-name");
String lastName = request.getParameter("last-name");
String creditCard = request.getParameter("credit-card");
Date expiration = Date.valueOf(request.getParameter("expiration"));
Optional<Date> dateOptional = Optional.ofNullable(expiration);
if (firstName == null || lastName == null || creditCard == null || dateOptional.isEmpty() || firstName.isEmpty() || lastName.isEmpty() || creditCard.isEmpty()) {
JsonObject responseJsonObject = new JsonObject();
// Login fail
responseJsonObject.addProperty("status", "fail");
// Log to localhost log
request.getServletContext().log("Payment failed");
// sample error messages. in practice, it is not a good idea to tell user which one is incorrect/not exist.
responseJsonObject.addProperty("message", "Invalid payment credentials.");
response.getWriter().write(responseJsonObject.toString());
out.close();
return;
}
String query = "SELECT * FROM creditcards c WHERE c.firstName = ? AND c.lastName = ? AND c.id = ? AND c.expiration = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, firstName);
statement.setString(2, lastName);
statement.setString(3, creditCard);
statement.setDate(4, expiration);
ResultSet rs = statement.executeQuery();
/* This example only allows username/password to be test/test
/ in the real project, you should talk to the database to verify username/password
*/
JsonObject responseJsonObject = new JsonObject();
if (rs.next()) {
Map<String, Integer> cart = (HashMap<String, Integer>) session.getAttribute("cart");
if (cart == null || cart.keySet().isEmpty()) {
responseJsonObject.addProperty("status", "fail");
// Log to localhost log
request.getServletContext().log("Cart is empty");
// sample error messages. in practice, it is not a good idea to tell user which one is incorrect/not exist.
responseJsonObject.addProperty("message", "Your cart is empty.");
}
else {
// Login success:
// set this user into the session
// Add all current cart items to sale
int currentTimeMillis = (int) System.currentTimeMillis();
session.setAttribute("saletime", currentTimeMillis);
for (Map.Entry<String, Integer> entry : cart.entrySet()) {
String saleInsert = "INSERT INTO sales (customerId, movieId, saleDate, quantity, saleTime) VALUES(?, ?, ?, ?, ?)";
PreparedStatement saleInsertStatement = conn.prepareStatement(saleInsert);
saleInsertStatement.setString(1, (String) session.getAttribute("customerid"));
saleInsertStatement.setString(2, entry.getKey());
saleInsertStatement.setDate(3, Date.valueOf(LocalDate.now()));
saleInsertStatement.setInt(4, entry.getValue());
saleInsertStatement.setInt(5, currentTimeMillis);
saleInsertStatement.execute();
}
responseJsonObject.addProperty("status", "success");
responseJsonObject.addProperty("message", "success");
session.removeAttribute("cart");
}
} else {
// Login fail
responseJsonObject.addProperty("status", "fail");
// Log to localhost log
request.getServletContext().log("Payment failed");
// sample error messages. in practice, it is not a good idea to tell user which one is incorrect/not exist.
responseJsonObject.addProperty("message", "Invalid payment credentials.");
}
rs.close();
statement.close();
response.getWriter().write(responseJsonObject.toString());
}
catch (Exception e) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("errorMessage", e.getMessage());
out.write(jsonObject.toString());
request.getServletContext().log("Error:", e);
response.setStatus(500);
}
finally {
out.close();
}
}
}