Repository navigation
Expand file tree
/
Copy pathSimpleJavaDedupApplication.java
More file actions
202 lines (185 loc) · 7.78 KB
/
Copy pathSimpleJavaDedupApplication.java
File metadata and controls
202 lines (185 loc) · 7.78 KB
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package io.keploy.samples.simplededup;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public final class SimpleJavaDedupApplication {
private SimpleJavaDedupApplication() {
}
public static void main(String[] args) throws Exception {
int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080"));
Path baseDir = Files.createTempDirectory("simple-java-dedup-tomcat-");
Tomcat tomcat = new Tomcat();
tomcat.setBaseDir(baseDir.toAbsolutePath().toString());
tomcat.setHostname("0.0.0.0");
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(port);
connector.setProperty("address", "0.0.0.0");
tomcat.setConnector(connector);
Context ctx = tomcat.addContext("", baseDir.toAbsolutePath().toString());
register(ctx, "healthz", "/healthz", new HealthHandler());
register(ctx, "grade", "/grade", new GradeHandler());
register(ctx, "shipping", "/shipping", new ShippingHandler());
register(ctx, "inventory", "/inventory", new InventoryHandler());
register(ctx, "invoice", "/invoice", new InvoiceHandler());
tomcat.start();
System.out.println("simple-java-dedup listening on " + port);
tomcat.getServer().await();
}
private static void register(Context ctx, String name, String path, HttpServlet servlet) {
Tomcat.addServlet(ctx, name, servlet);
ctx.addServletMappingDecoded(path, name);
}
private static final class HealthHandler extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
if (!"GET".equals(req.getMethod())) {
respond(resp, 405, "{\"error\":\"method_not_allowed\"}");
return;
}
respond(resp, 200, "{\"status\":\"ok\"}");
}
}
private static final class GradeHandler extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Map<String, String> query = parseQuery(req.getQueryString());
int score = parseInt(query.get("score"), 0);
String grade;
String message;
if (score >= 90) {
grade = "A";
message = "excellent";
} else if (score >= 75) {
grade = "B";
message = "solid";
} else if (score >= 50) {
grade = "C";
message = "practice";
} else {
grade = "F";
message = "retry";
}
respond(resp, 200, "{\"score\":" + score + ",\"grade\":\"" + grade + "\",\"message\":\"" + message + "\"}");
}
}
private static final class ShippingHandler extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Map<String, String> query = parseQuery(req.getQueryString());
String country = query.getOrDefault("country", "US");
int total = parseInt(query.get("total"), 0);
String tier;
int etaDays;
if (!"US".equalsIgnoreCase(country)) {
tier = "international";
etaDays = 9;
} else if (total >= 100) {
tier = "free";
etaDays = 2;
} else {
tier = "standard";
etaDays = 5;
}
respond(resp, 200, "{\"country\":\"" + country.toUpperCase() + "\",\"total\":" + total + ",\"tier\":\"" + tier + "\",\"etaDays\":" + etaDays + "}");
}
}
private static final class InventoryHandler extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Map<String, String> query = parseQuery(req.getQueryString());
String sku = query.getOrDefault("sku", "BOOK-1").toUpperCase();
int quantity = parseInt(query.get("quantity"), 1);
String lane;
boolean reserved;
if (sku.startsWith("BOOK") && quantity <= 5) {
lane = "priority";
reserved = true;
} else if (sku.startsWith("PEN") && quantity <= 10) {
lane = "standard";
reserved = true;
} else {
lane = "manual-review";
reserved = false;
}
respond(resp, 200, "{\"sku\":\"" + sku + "\",\"quantity\":" + quantity + ",\"lane\":\"" + lane + "\",\"reserved\":" + reserved + "}");
}
}
private static final class InvoiceHandler extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Map<String, String> query = parseQuery(req.getQueryString());
String customer = query.getOrDefault("customer", "guest").toLowerCase();
int subtotal = parseInt(query.get("subtotal"), 0);
int discount;
String segment;
if ("vip".equals(customer) && subtotal >= 200) {
discount = 40;
segment = "vip-large";
} else if ("vip".equals(customer)) {
discount = 15;
segment = "vip";
} else if (subtotal >= 100) {
discount = 10;
segment = "standard-large";
} else {
discount = 0;
segment = "standard";
}
int total = subtotal - discount;
respond(resp, 200, "{\"customer\":\"" + customer + "\",\"subtotal\":" + subtotal + ",\"discount\":" + discount + ",\"total\":" + total + ",\"segment\":\"" + segment + "\"}");
}
}
private static Map<String, String> parseQuery(String rawQuery) {
Map<String, String> query = new HashMap<String, String>();
if (rawQuery == null || rawQuery.isEmpty()) {
return query;
}
String[] pairs = rawQuery.split("&");
for (String pair : pairs) {
int equals = pair.indexOf('=');
if (equals < 0) {
query.put(decode(pair), "");
} else {
query.put(decode(pair.substring(0, equals)), decode(pair.substring(equals + 1)));
}
}
return query;
}
private static int parseInt(String value, int fallback) {
if (value == null || value.trim().isEmpty()) {
return fallback;
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException ignored) {
return fallback;
}
}
private static String decode(String value) {
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
} catch (Exception ignored) {
return value;
}
}
private static void respond(HttpServletResponse resp, int status, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
resp.setStatus(status);
resp.setContentType("application/json");
resp.setContentLength(bytes.length);
OutputStream responseBody = resp.getOutputStream();
responseBody.write(bytes);
responseBody.flush();
}
}