Repository navigation
Expand file tree
/
Copy pathMallWebServer.java
More file actions
633 lines (468 loc) · 17.4 KB
/
Copy pathMallWebServer.java
File metadata and controls
633 lines (468 loc) · 17.4 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class MallWebServer {
static Mall mall = new Mall();
// HTML Page Template
static String page(String title, String content) {
return """
<!DOCTYPE html>
<html>
<head>
<title>""" + escape(title) + """
</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: Arial, sans-serif;
background: #f1f5f9;
margin: 0;
color: #1e293b;
}
header {
background: #172554;
color: white;
padding: 22px;
text-align: center;
}
nav {
background: #1e3a8a;
padding: 15px;
text-align: center;
}
nav a {
color: white;
text-decoration: none;
margin: 12px;
font-weight: bold;
}
main {
max-width: 950px;
margin: 30px auto;
background: white;
padding: 25px;
border-radius: 12px;
}
.menu {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
}
.card {
background: #eff6ff;
padding: 20px;
border-radius: 10px;
border: 1px solid #bfdbfe;
}
a.button, button {
display: inline-block;
background: #2563eb;
color: white;
border: none;
padding: 11px 17px;
border-radius: 6px;
text-decoration: none;
cursor: pointer;
}
input, select {
padding: 10px;
margin: 8px 0 15px;
width: 90%;
max-width: 350px;
border: 1px solid #cbd5e1;
border-radius: 5px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 12px;
border-bottom: 1px solid #ddd;
text-align: left;
}
th {
background: #dbeafe;
}
.success {
color: green;
font-weight: bold;
}
.error {
color: red;
font-weight: bold;
}
footer {
text-align: center;
padding: 20px;
color: #64748b;
}
</style>
</head>
<body>
<header>
<h1>MALL BILLING SYSTEM</h1>
<p>Product and Inventory Management</p>
</header>
<nav>
<a href="/">Home</a>
<a href="/products">Products</a>
<a href="/add-product">Add Product</a>
<a href="/import">Import Stock</a>
<a href="/update">Update Stock</a>
<a href="/bill">Generate Bill</a>
<a href="/exit">Exit</a>
</nav>
<main>
""" + content + """
</main>
<footer>
Java OOP Based Mall Billing System
</footer>
</body>
</html>
""";
}
// Escape HTML Special Characters
static String escape(String value) {
return value.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """)
.replace("'", "'");
}
// Send HTML Response
static void send(HttpExchange exchange, String content)
throws IOException {
byte[] data = content.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set(
"Content-Type", "text/html; charset=UTF-8"
);
exchange.sendResponseHeaders(200, data.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(data);
}
}
// Read Form Data
static Map<String, String> readForm(HttpExchange exchange)
throws IOException {
String data = new String(
exchange.getRequestBody().readAllBytes(),
StandardCharsets.UTF_8
);
Map<String, String> form = new HashMap<>();
for (String pair : data.split("&")) {
String[] parts = pair.split("=", 2);
String key = URLDecoder.decode(
parts[0], StandardCharsets.UTF_8
);
String value = parts.length > 1
? URLDecoder.decode(parts[1], StandardCharsets.UTF_8)
: "";
form.put(key, value);
}
return form;
}
// Product Table
static String productTable() {
StringBuilder html = new StringBuilder();
html.append("""
<h2>Available Products</h2>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Category</th>
<th>Price</th>
<th>Stock</th>
</tr>
""");
for (Product p : mall.getProducts()) {
html.append("<tr>");
html.append("<td>").append(p.getId()).append("</td>");
html.append("<td>").append(escape(p.getName())).append("</td>");
html.append("<td>").append(escape(p.getCategory())).append("</td>");
html.append("<td>Rs. ").append(p.getPrice()).append("</td>");
html.append("<td>").append(p.getStock()).append("</td>");
html.append("</tr>");
}
html.append("</table>");
return html.toString();
}
// Home Page
static String homePage() {
return """
<h2>Welcome to Mall Billing System</h2>
<p>Select a module to continue.</p>
<div class="menu">
<div class="card">
<h3>1. View Products</h3>
<p>View products, prices and stock.</p>
<a class="button" href="/products">Open</a>
</div>
<div class="card">
<h3>2. Add Product</h3>
<p>Add a new grocery or electronics product.</p>
<a class="button" href="/add-product">Open</a>
</div>
<div class="card">
<h3>3. Import Stock</h3>
<p>Add additional product stock.</p>
<a class="button" href="/import">Open</a>
</div>
<div class="card">
<h3>4. Update Stock</h3>
<p>Modify available stock quantity.</p>
<a class="button" href="/update">Open</a>
</div>
<div class="card">
<h3>5. Generate Bill</h3>
<p>Select products and generate a bill.</p>
<a class="button" href="/bill">Open</a>
</div>
<div class="card">
<h3>6. Exit</h3>
<p>Exit the application.</p>
<a class="button" href="/exit">Open</a>
</div>
</div>
""";
}
// Handle Browser Requests
static void handle(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath();
String method = exchange.getRequestMethod();
try {
// HOME MODULE
if (path.equals("/") && method.equals("GET")) {
send(exchange, page("Home", homePage()));
}
// VIEW PRODUCTS MODULE
else if (path.equals("/products") && method.equals("GET")) {
send(exchange, page("Products", productTable()));
}
// ADD PRODUCT FORM
else if (path.equals("/add-product") && method.equals("GET")) {
String html = """
<h2>Add New Product</h2>
<p>Enter the details of the product you want to add.</p>
<form method="POST" action="/add-product">
<label>Product ID</label><br>
<input type="number" name="id" min="1" required><br>
<label>Product Name</label><br>
<input type="text" name="name" maxlength="100" required><br>
<label>Product Category</label><br>
<select name="category" required>
<option value="">Select Category</option>
<option value="Grocery">Grocery</option>
<option value="Electronics">Electronics</option>
</select><br><br>
<label>Product Price (Rs.)</label><br>
<input type="number" name="price" min="0.01" step="0.01" required><br>
<label>Initial Stock Quantity</label><br>
<input type="number" name="stock" min="0" required><br>
<button type="submit">Add Product</button>
</form>
""";
send(exchange, page("Add Product", html));
}
// ADD PRODUCT ACTION
else if (path.equals("/add-product") && method.equals("POST")) {
Map<String, String> form = readForm(exchange);
int id = Integer.parseInt(form.get("id"));
String name = form.get("name");
String category = form.get("category");
double price = Double.parseDouble(form.get("price"));
int stock = Integer.parseInt(form.get("stock"));
mall.addProduct(id, name, price, stock, category);
String html = """
<h2 class='success'>Product Added Successfully!</h2>
<p>The new product is now available in the Products list and Generate Bill module.</p>
<a class='button' href='/add-product'>Add Another Product</a>
<a class='button' href='/products'>View Products</a>
""" + productTable();
send(exchange, page("Product Added", html));
}
// IMPORT STOCK FORM
else if (path.equals("/import") && method.equals("GET")) {
String html = """
<h2>Import Stock</h2>
<form method="POST" action="/import">
<label>Product ID</label><br>
<input type="number" name="id" min="1" required><br>
<label>Import Quantity</label><br>
<input type="number" name="qty" min="1" required><br>
<button type="submit">Import Stock</button>
</form>
""" + productTable();
send(exchange, page("Import Stock", html));
}
// IMPORT STOCK ACTION
else if (path.equals("/import") && method.equals("POST")) {
Map<String, String> form = readForm(exchange);
int id = Integer.parseInt(form.get("id"));
int qty = Integer.parseInt(form.get("qty"));
mall.importStock(id, qty);
send(exchange, page("Success",
"<h2 class='success'>Stock Imported Successfully!</h2>"
+ productTable()));
}
// UPDATE STOCK FORM
else if (path.equals("/update") && method.equals("GET")) {
String html = """
<h2>Update Stock</h2>
<form method="POST" action="/update">
<label>Product ID</label><br>
<input type="number" name="id" min="1" required><br>
<label>New Stock Quantity</label><br>
<input type="number" name="qty" min="0" required><br>
<button type="submit">Update Stock</button>
</form>
""" + productTable();
send(exchange, page("Update Stock", html));
}
// UPDATE STOCK ACTION
else if (path.equals("/update") && method.equals("POST")) {
Map<String, String> form = readForm(exchange);
int id = Integer.parseInt(form.get("id"));
int qty = Integer.parseInt(form.get("qty"));
mall.updateStock(id, qty);
send(exchange, page("Success",
"<h2 class='success'>Stock Updated Successfully!</h2>"
+ productTable()));
}
// GENERATE BILL FORM
else if (path.equals("/bill") && method.equals("GET")) {
StringBuilder html = new StringBuilder();
html.append("""
<h2>Generate Customer Bill</h2>
<form method="POST" action="/bill">
<table>
<tr>
<th>Product</th>
<th>Price</th>
<th>Available Stock</th>
<th>Quantity</th>
</tr>
""");
for (Product p : mall.getProducts()) {
html.append("<tr>");
html.append("<td>")
.append(escape(p.getName()))
.append("</td>");
html.append("<td>Rs. ")
.append(p.getPrice())
.append("</td>");
html.append("<td>")
.append(p.getStock())
.append("</td>");
html.append("<td><input type='number' min='0' max='")
.append(p.getStock())
.append("' name='qty-")
.append(p.getId())
.append("' value='0'></td>");
html.append("</tr>");
}
html.append("""
</table>
<br>
<button type="submit">Generate Bill</button>
</form>
""");
send(exchange, page("Generate Bill", html.toString()));
}
// GENERATE BILL ACTION
else if (path.equals("/bill") && method.equals("POST")) {
Map<String, String> form = readForm(exchange);
Map<Integer, Integer> quantities = new HashMap<>();
for (Product p : mall.getProducts()) {
int qty = Integer.parseInt(
form.getOrDefault("qty-" + p.getId(), "0")
);
quantities.put(p.getId(), qty);
}
Bill bill = mall.generateBill(quantities);
if (bill.getItems().isEmpty()) {
send(exchange, page("Bill Cancelled",
"<h2 class='error'>Bill Cancelled. Cart is Empty!</h2>"));
return;
}
StringBuilder html = new StringBuilder();
html.append("""
<h2>Customer Bill</h2>
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
""");
for (CartItem item : bill.getItems()) {
html.append("<tr>");
html.append("<td>")
.append(escape(item.getProduct().getName()))
.append("</td>");
html.append("<td>")
.append(item.getQuantity())
.append("</td>");
html.append("<td>Rs. ")
.append(item.getProduct().getPrice())
.append("</td>");
html.append("<td>Rs. ")
.append(item.getAmount())
.append("</td>");
html.append("</tr>");
}
html.append("</table>");
html.append("<h3>Total Amount: Rs. ")
.append(bill.getTotal())
.append("</h3>");
html.append("<h3>Discount: Rs. ")
.append(bill.getDiscount())
.append("</h3>");
html.append("<h2>Final Amount: Rs. ")
.append(bill.getFinalAmount())
.append("</h2>");
html.append("<a class='button' href='/bill'>New Bill</a>");
send(exchange, page("Customer Bill", html.toString()));
}
// EXIT MODULE
else if (path.equals("/exit") && method.equals("GET")) {
send(exchange, page("Exit",
"<h2>Thank You for Visiting!</h2>"
+ "<p>You may close this browser tab.</p>"
+ "<p>To stop the server, press Ctrl+C in Terminal.</p>"));
}
else {
send(exchange, page("Not Found",
"<h2>Page Not Found!</h2>"));
}
} catch (Exception e) {
String message = e.getMessage() == null
? "Invalid input" : e.getMessage();
String error = "<h2 class='error'>Error: "
+ escape(message)
+ "</h2><a class='button' href='/'>Go Home</a>";
send(exchange, page("Error", error));
}
}
// Start Web Server
// Start Web Server
public static void main(String[] args) throws IOException
{
int port = Integer.parseInt(
System.getenv().getOrDefault("PORT", "8080")
);
HttpServer server = HttpServer.create(
new InetSocketAddress("0.0.0.0", port), 0
);
server.createContext("/", MallWebServer::handle);
server.start();
System.out.println("Mall Billing Web Application Started!");
System.out.println("Server running on port: " + port);
}
}