Repository navigation
Expand file tree
/
Copy pathPaymentAuthorizationState.java
More file actions
764 lines (683 loc) · 26.3 KB
/
Copy pathPaymentAuthorizationState.java
File metadata and controls
764 lines (683 loc) · 26.3 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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
/*
* Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Universal Permissive License v 1.0 as shown
* at http://oss.oracle.com/licenses/upl
*
* DESCRIPTION
* Demonstrates how an application can use TimesTen as a fast store for
* real-time payment authorization state. The application keeps hot
* authorization decisions close to the service that needs them, applies
* deterministic authorization rules, stores the resulting decision and
* metadata in JSON, and cleans up expired state.
*
* The sample uses simulated authorization rules. It does not call an
* external payment gateway, perform fraud-model inference, or depend on an
* external service.
*
* The sample performs the following steps:
* - Creates a 'payment_authorizations' table
* - Creates indexes for tenant/account, payment id, and expiration lookups
* - Seeds one expired authorization record
* - Processes payment authorization requests
* - Shows a repeated request being replayed from the existing state
* - Rereads the stored decision if concurrent requests insert the same key
* - Stores request and decision metadata in JSON
* - Summarizes active authorizations by tenant/account/status
* - Deletes expired authorization records
* - Drops the table
*/
package jdbc.demo;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Provides a JDBC-based demonstration of a real-time payment authorization
* state store backed by TimesTen.
*/
public class PaymentAuthorizationState
{
private static final String PROGRAM_NAME = "PaymentAuthorizationState";
private static final String DEFAULT_USERNAME = "appuser";
private static final String TIMESTEN_DIRECT_DRIVER = "com.timesten.jdbc.TimesTenDriver";
private static final String TIMESTEN_CLIENT_DRIVER = "com.timesten.jdbc.TimesTenClientDriver";
private static final String DIRECT_URL_PREFIX = "jdbc:timesten:direct:";
private static final String CLIENT_URL_PREFIX = "jdbc:timesten:client:";
private static final String TABLE_NAME = "payment_authorizations";
private static final String CREATE_TABLE_SQL =
"CREATE TABLE " + TABLE_NAME + " ("
+ "authorization_key VARCHAR2(64) NOT NULL PRIMARY KEY, "
+ "tenant_id VARCHAR2(30) NOT NULL, "
+ "account_id VARCHAR2(30) NOT NULL, "
+ "merchant_id VARCHAR2(60) NOT NULL, "
+ "payment_id VARCHAR2(40) NOT NULL, "
+ "amount_cents TT_INT NOT NULL, "
+ "currency VARCHAR2(3) NOT NULL, "
+ "payment_method VARCHAR2(20) NOT NULL, "
+ "risk_score NUMBER(5,2) NOT NULL, "
+ "status VARCHAR2(20) NOT NULL, "
+ "decision_reason VARCHAR2(120) NOT NULL, "
+ "request_payload JSON, "
+ "decision_payload JSON, "
+ "created_at TIMESTAMP NOT NULL, "
+ "updated_at TIMESTAMP NOT NULL, "
+ "expires_at TIMESTAMP NOT NULL)";
private static final String CREATE_TENANT_ACCOUNT_INDEX_SQL =
"CREATE INDEX idx_pay_auth_tenant_acct "
+ "ON " + TABLE_NAME + " (tenant_id, account_id)";
private static final String CREATE_PAYMENT_ID_INDEX_SQL =
"CREATE INDEX idx_payment_auth_payment_id "
+ "ON " + TABLE_NAME + " (payment_id)";
private static final String CREATE_EXPIRES_INDEX_SQL =
"CREATE INDEX idx_payment_auth_expires "
+ "ON " + TABLE_NAME + " (expires_at)";
private static final String INSERT_AUTHORIZATION_SQL =
"INSERT INTO " + TABLE_NAME + " ("
+ "authorization_key, tenant_id, account_id, merchant_id, payment_id, "
+ "amount_cents, currency, payment_method, risk_score, status, "
+ "decision_reason, request_payload, decision_payload, created_at, "
+ "updated_at, expires_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String SELECT_EXISTING_AUTHORIZATION_SQL =
"SELECT status, decision_reason, expires_at "
+ "FROM " + TABLE_NAME + " "
+ "WHERE authorization_key = ? "
+ " AND expires_at > ?";
private static final String DELETE_EXPIRED_AUTHORIZATION_FOR_KEY_SQL =
"DELETE FROM " + TABLE_NAME + " "
+ "WHERE authorization_key = ? "
+ " AND expires_at <= ?";
private static final String SELECT_ACTIVE_SUMMARY_SQL =
"SELECT tenant_id, account_id, status, COUNT(*), SUM(amount_cents) "
+ "FROM " + TABLE_NAME + " "
+ "WHERE expires_at > ? "
+ "GROUP BY tenant_id, account_id, status "
+ "ORDER BY tenant_id, account_id, status";
private static final String SELECT_ACTIVE_DETAILS_SQL =
"SELECT payment_id, merchant_id, status, decision_reason, amount_cents, risk_score, "
+ " TO_CHAR(expires_at, 'YYYY-MM-DD HH24:MI:SS.FF3') "
+ "FROM " + TABLE_NAME + " "
+ "WHERE expires_at > ? "
+ "ORDER BY tenant_id, account_id, payment_id";
private static final String DELETE_EXPIRED_SQL =
"DELETE FROM " + TABLE_NAME + " WHERE expires_at <= ?";
private static final String DROP_TABLE_SQL =
"DROP TABLE " + TABLE_NAME;
private static final PaymentRequest[] PAYMENT_REQUESTS = new PaymentRequest[] {
new PaymentRequest("retail_app", "acct_1001", "orchard-books", "pay_1001",
4995, "USD", "debit_card", 0.12, 25000, 0.75, 15),
new PaymentRequest("retail_app", "acct_1001", "orchard-books", "pay_1001",
4995, "USD", "debit_card", 0.12, 25000, 0.75, 15),
new PaymentRequest("retail_app", "acct_1002", "pro-office-supplies", "pay_2001",
39900, "USD", "credit_card", 0.08, 25000, 0.75, 10),
new PaymentRequest("field_service", "acct_2001", "route-parts", "pay_3001",
14900, "USD", "mobile_wallet", 0.87, 20000, 0.75, 20),
new PaymentRequest("field_service", "acct_2001", "depot-supplies", "pay_3002",
8600, "USD", "debit_card", 0.18, 20000, 0.75, 20)
};
private static final PaymentRequest EXPIRED_AUTHORIZATION =
new PaymentRequest("retail_app", "acct_9999", "legacy-outlet", "pay_expired_0001",
2599, "USD", "debit_card", 0.18, 15000, 0.70, 5);
private final IOLibrary ioLibrary;
private String userOverride;
private String passwordOverride;
private static final class PaymentRequest
{
private final String tenantId;
private final String accountId;
private final String merchantId;
private final String paymentId;
private final int amountCents;
private final String currency;
private final String paymentMethod;
private final double riskScore;
private final int spendLimitCents;
private final double riskThreshold;
private final int holdMinutes;
PaymentRequest(String tenantId, String accountId, String merchantId, String paymentId,
int amountCents, String currency, String paymentMethod, double riskScore,
int spendLimitCents, double riskThreshold, int holdMinutes)
{
this.tenantId = tenantId;
this.accountId = accountId;
this.merchantId = merchantId;
this.paymentId = paymentId;
this.amountCents = amountCents;
this.currency = currency;
this.paymentMethod = paymentMethod;
this.riskScore = riskScore;
this.spendLimitCents = spendLimitCents;
this.riskThreshold = riskThreshold;
this.holdMinutes = holdMinutes;
}
}
private static final class AuthorizationDecision
{
private final String status;
private final String reason;
private final int ttlMinutes;
AuthorizationDecision(String status, String reason, int ttlMinutes)
{
this.status = status;
this.reason = reason;
this.ttlMinutes = ttlMinutes;
}
}
public PaymentAuthorizationState()
{
ioLibrary = new IOLibrary(System.err);
}
public static void main(String[] args)
{
int exitCode = new PaymentAuthorizationState().run(args);
if (exitCode != 0)
{
System.exit(exitCode);
}
}
private int run(String[] args)
{
String usage = buildUsage();
if (!parseOptions(args, usage))
{
return 1;
}
if (ioLibrary.opt_doTrace)
{
DriverManager.setLogWriter(new PrintWriter(System.out, true));
}
if (!loadDrivers())
{
return 1;
}
AccessControl accessControl = new AccessControl();
String username = (userOverride != null) ? userOverride : resolveUsername(accessControl);
String password = passwordOverride;
if (password == null)
{
password = System.getenv("TT_PASSWORD");
}
if (password == null || password.isEmpty())
{
password = accessControl.getPassword(username);
}
String url = buildJdbcUrl();
System.out.println("=== Payment authorization demo ===");
System.out.println();
System.out.println("Connecting to TimesTen");
try (Connection connection = DriverManager.getConnection(url, username, password))
{
connection.setAutoCommit(true);
System.out.println("✓ Connected");
boolean demoSucceeded = false;
try
{
runDemo(connection);
demoSucceeded = true;
}
finally
{
dropTable(connection, demoSucceeded);
}
}
catch (SQLException e)
{
printSQLException(e);
return 1;
}
System.out.println("✓ Completed payment authorization sample operations");
return 0;
}
private boolean parseOptions(String[] args, String usage)
{
List<String> forwardedArgs = new ArrayList<String>();
for (int i = 0; i < args.length; i++)
{
String arg = args[i];
if ("-u".equals(arg) || "-user".equals(arg) || "-username".equals(arg))
{
if (i + 1 >= args.length)
{
System.err.println("Missing value for " + arg);
System.err.println(usage);
return false;
}
userOverride = args[++i];
}
else if ("-p".equals(arg) || "-password".equals(arg) || "-pwd".equals(arg))
{
if (i + 1 >= args.length)
{
System.err.println("Missing value for " + arg);
System.err.println(usage);
return false;
}
passwordOverride = args[++i];
}
else
{
forwardedArgs.add(arg);
}
}
String[] ioArgs = forwardedArgs.toArray(new String[forwardedArgs.size()]);
return ioLibrary.parseOpts(ioArgs, usage);
}
private String buildUsage()
{
String baseUsage = ioLibrary.getUsageString(PROGRAM_NAME);
String userOption = "\n -u, -user <name> supply username non-interactively";
String pwdOption = "\n -p, -password <pw> supply password, or set TT_PASSWORD";
return baseUsage + userOption + pwdOption;
}
private boolean loadDrivers()
{
try
{
Class.forName(TIMESTEN_DIRECT_DRIVER);
if (ioLibrary.opt_doClient)
{
Class.forName(TIMESTEN_CLIENT_DRIVER);
}
return true;
}
catch (ClassNotFoundException e)
{
String drivers = ioLibrary.opt_doClient
? TIMESTEN_DIRECT_DRIVER + ", " + TIMESTEN_CLIENT_DRIVER
: TIMESTEN_DIRECT_DRIVER;
System.err.println("Unable to load TimesTen JDBC driver(s): " + drivers + ". " + e.getMessage());
return false;
}
}
private String resolveUsername(AccessControl accessControl)
{
String username = accessControl.getUsername();
if (username == null || username.isEmpty())
{
return DEFAULT_USERNAME;
}
return username;
}
private String buildJdbcUrl()
{
String prefix = ioLibrary.opt_doClient ? CLIENT_URL_PREFIX : DIRECT_URL_PREFIX;
return prefix + ioLibrary.opt_connstr;
}
private void runDemo(Connection connection) throws SQLException
{
// Recreate the table so the authorization trail starts cleanly.
dropTable(connection, false);
createTable(connection);
// Seed one expired row so the TTL cleanup path is visible.
seedExpiredAuthorization(connection);
// Each request exercises either a replay or a fresh authorization decision.
for (PaymentRequest request : PAYMENT_REQUESTS)
{
authorizePayment(connection, request);
}
// Show the active decisions before stale rows are removed.
summarizeActiveAuthorizations(connection);
cleanupExpiredAuthorizations(connection);
}
private void createTable(Connection connection) throws SQLException
{
executeStatement(connection, CREATE_TABLE_SQL);
System.out.println("✓ Table " + TABLE_NAME + " created");
executeStatement(connection, CREATE_TENANT_ACCOUNT_INDEX_SQL);
System.out.println("✓ Index IDX_PAY_AUTH_TENANT_ACCT created");
executeStatement(connection, CREATE_PAYMENT_ID_INDEX_SQL);
System.out.println("✓ Index IDX_PAYMENT_AUTH_PAYMENT_ID created");
executeStatement(connection, CREATE_EXPIRES_INDEX_SQL);
System.out.println("✓ Index IDX_PAYMENT_AUTH_EXPIRES created");
}
private void seedExpiredAuthorization(Connection connection) throws SQLException
{
PaymentRequest request = EXPIRED_AUTHORIZATION;
Timestamp now = currentTimestamp();
Timestamp expiredAt = new Timestamp(now.getTime() - 60_000L);
String authorizationKey = buildAuthorizationKey(request);
String requestPayload = requestPayloadToJson(request);
String decisionPayload = decisionPayloadToJson(request, "EXPIRED", "seeded_expired_state",
expiredAt.toString());
try (PreparedStatement statement = connection.prepareStatement(INSERT_AUTHORIZATION_SQL))
{
bindAuthorization(statement, authorizationKey, request, "EXPIRED", "seeded_expired_state",
requestPayload, decisionPayload, now, now, expiredAt);
statement.executeUpdate();
}
System.out.println("✓ Seeded 1 expired authorization record");
}
private String buildAuthorizationKey(PaymentRequest request)
{
try
{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
String keyText = request.tenantId + "|" + request.accountId + "|" +
request.merchantId + "|" + request.paymentId;
byte[] hash = digest.digest(keyText.getBytes(StandardCharsets.UTF_8));
return toHex(hash);
}
catch (NoSuchAlgorithmException e)
{
throw new IllegalStateException("Unable to create authorization key", e);
}
}
private String requestPayloadToJson(PaymentRequest request)
{
return "{"
+ "\"tenantId\":\"" + request.tenantId + "\","
+ "\"accountId\":\"" + request.accountId + "\","
+ "\"merchantId\":\"" + request.merchantId + "\","
+ "\"paymentId\":\"" + request.paymentId + "\","
+ "\"amountCents\":" + request.amountCents + ","
+ "\"currency\":\"" + request.currency + "\","
+ "\"paymentMethod\":\"" + request.paymentMethod + "\","
+ "\"riskScore\":" + request.riskScore + ","
+ "\"spendLimitCents\":" + request.spendLimitCents + ","
+ "\"riskThreshold\":" + request.riskThreshold
+ "}";
}
private String decisionPayloadToJson(PaymentRequest request, String status,
String reason, String expiresAtText)
{
return "{"
+ "\"tenantId\":\"" + request.tenantId + "\","
+ "\"accountId\":\"" + request.accountId + "\","
+ "\"merchantId\":\"" + request.merchantId + "\","
+ "\"paymentId\":\"" + request.paymentId + "\","
+ "\"decision\":\"" + status + "\","
+ "\"reason\":\"" + reason + "\","
+ "\"holdMinutes\":" + request.holdMinutes + ","
+ "\"expiresAt\":\"" + expiresAtText + "\","
+ "\"ruleVersion\":\"payment-auth-rules-v1\","
+ "\"simulatedRiskService\":true"
+ "}";
}
private AuthorizationDecision evaluatePayment(PaymentRequest request)
{
if (request.amountCents > request.spendLimitCents)
{
return new AuthorizationDecision("DECLINED", "amount_exceeds_limit", 10);
}
if (request.riskScore >= request.riskThreshold)
{
return new AuthorizationDecision("REVIEW", "risk_score_requires_review", 20);
}
return new AuthorizationDecision("APPROVED", "within_limit_and_low_risk", request.holdMinutes);
}
private void authorizePayment(Connection connection, PaymentRequest request) throws SQLException
{
Timestamp now = currentTimestamp();
String authorizationKey = buildAuthorizationKey(request);
long startNanos = System.nanoTime();
deleteExpiredAuthorizationForKey(connection, authorizationKey, now);
String[] existing = findExistingAuthorization(connection, authorizationKey, now);
if (existing != null)
{
printAuthorizationReplay(request, existing[0], existing[1], existing[2], startNanos);
return;
}
AuthorizationDecision decision = evaluatePayment(request);
Timestamp expiresAt = new Timestamp(now.getTime() + decision.ttlMinutes * 60_000L);
String requestPayload = requestPayloadToJson(request);
String decisionPayload = decisionPayloadToJson(request, decision.status, decision.reason,
expiresAt.toString());
// A concurrent copy of this request can win the insert. Reread its stored
// decision instead of treating that duplicate key as an application error.
try (PreparedStatement insert = connection.prepareStatement(INSERT_AUTHORIZATION_SQL))
{
bindAuthorization(insert, authorizationKey, request, decision.status, decision.reason,
requestPayload, decisionPayload, now, now, expiresAt);
insert.executeUpdate();
}
catch (SQLException exception)
{
if (!isDuplicateKeyError(exception))
{
throw exception;
}
existing = findExistingAuthorization(connection, authorizationKey, currentTimestamp());
if (existing == null)
{
throw exception;
}
printAuthorizationReplay(request, existing[0], existing[1], existing[2], startNanos);
return;
}
System.out.println(
"→ Authorization decision: tenant=" + request.tenantId
+ " account=" + request.accountId
+ " merchant=" + request.merchantId
+ " payment_id=" + request.paymentId
+ " status=" + decision.status
+ " amount=" + formatMoney(request.amountCents)
+ " risk=" + String.format("%.2f", request.riskScore)
+ " reason=" + decision.reason
+ " hold_expires=" + formatTimestamp(expiresAt)
+ " elapsed_ms=" + String.format("%.2f", (System.nanoTime() - startNanos) / 1_000_000.0));
}
private void deleteExpiredAuthorizationForKey(Connection connection, String authorizationKey,
Timestamp now) throws SQLException
{
try (PreparedStatement statement = connection.prepareStatement(DELETE_EXPIRED_AUTHORIZATION_FOR_KEY_SQL))
{
statement.setString(1, authorizationKey);
statement.setTimestamp(2, now);
statement.executeUpdate();
}
}
private String[] findExistingAuthorization(Connection connection, String authorizationKey,
Timestamp now) throws SQLException
{
try (PreparedStatement statement = connection.prepareStatement(SELECT_EXISTING_AUTHORIZATION_SQL))
{
statement.setString(1, authorizationKey);
statement.setTimestamp(2, now);
try (ResultSet resultSet = statement.executeQuery())
{
if (!resultSet.next())
{
return null;
}
return new String[] {
resultSet.getString(1), resultSet.getString(2), formatTimestamp(resultSet.getTimestamp(3))
};
}
}
}
private void printAuthorizationReplay(PaymentRequest request, String status, String reason,
String expiresAtText, long startNanos)
{
System.out.println(
"→ Authorization replay: tenant=" + request.tenantId
+ " account=" + request.accountId
+ " merchant=" + request.merchantId
+ " payment_id=" + request.paymentId
+ " status=" + status
+ " reason=" + reason
+ " expires_at=" + expiresAtText
+ " elapsed_ms=" + String.format("%.2f", (System.nanoTime() - startNanos) / 1_000_000.0));
}
private boolean isDuplicateKeyError(SQLException exception)
{
return exception.getErrorCode() == 1
|| (exception.getMessage() != null && exception.getMessage().contains("ORA-00001"));
}
private void bindAuthorization(PreparedStatement statement, String authorizationKey,
PaymentRequest request, String status, String decisionReason,
String requestPayload, String decisionPayload,
Timestamp createdAt, Timestamp updatedAt, Timestamp expiresAt)
throws SQLException
{
statement.setString(1, authorizationKey);
statement.setString(2, request.tenantId);
statement.setString(3, request.accountId);
statement.setString(4, request.merchantId);
statement.setString(5, request.paymentId);
statement.setInt(6, request.amountCents);
statement.setString(7, request.currency);
statement.setString(8, request.paymentMethod);
statement.setDouble(9, request.riskScore);
statement.setString(10, status);
statement.setString(11, decisionReason);
statement.setString(12, requestPayload);
statement.setString(13, decisionPayload);
statement.setTimestamp(14, createdAt);
statement.setTimestamp(15, updatedAt);
statement.setTimestamp(16, expiresAt);
}
private void summarizeActiveAuthorizations(Connection connection) throws SQLException
{
// Show both the grouped view and the detailed authorization state.
System.out.println("⋯ Active authorizations by tenant/account/status:");
try (PreparedStatement statement = connection.prepareStatement(SELECT_ACTIVE_SUMMARY_SQL))
{
statement.setTimestamp(1, currentTimestamp());
try (ResultSet resultSet = statement.executeQuery())
{
while (resultSet.next())
{
String tenantId = resultSet.getString(1);
String accountId = resultSet.getString(2);
String status = resultSet.getString(3);
long rowCount = resultSet.getLong(4);
long amountCents = resultSet.getLong(5);
System.out.println(
" tenant=" + padRight(tenantId, 12)
+ " account=" + padRight(accountId, 10)
+ " status=" + padRight(status, 8)
+ " rows=" + padRight(Long.toString(rowCount), 2)
+ " total=" + formatMoney(amountCents));
}
}
}
System.out.println("⋯ Active authorization details:");
try (PreparedStatement statement = connection.prepareStatement(SELECT_ACTIVE_DETAILS_SQL))
{
statement.setTimestamp(1, currentTimestamp());
try (ResultSet resultSet = statement.executeQuery())
{
while (resultSet.next())
{
String paymentId = resultSet.getString(1);
String merchantId = resultSet.getString(2);
String status = resultSet.getString(3);
String reason = resultSet.getString(4);
int amountCents = resultSet.getInt(5);
double riskScore = resultSet.getDouble(6);
String expiresAtText = resultSet.getString(7);
System.out.println(
" payment_id=" + padRight(paymentId, 10)
+ " merchant=" + padRight(merchantId, 20)
+ " status=" + padRight(status, 8)
+ " amount=" + padRight(formatMoney(amountCents), 8)
+ " risk=" + String.format("%.2f", riskScore)
+ " reason=" + padRight(reason, 28)
+ " expires_at=" + expiresAtText);
}
}
}
}
private void cleanupExpiredAuthorizations(Connection connection) throws SQLException
{
try (PreparedStatement statement = connection.prepareStatement(DELETE_EXPIRED_SQL))
{
statement.setTimestamp(1, currentTimestamp());
int rows = statement.executeUpdate();
System.out.println("✓ Deleted " + rows + " expired authorization record" + (rows == 1 ? "" : "s"));
}
}
private void dropTable(Connection connection, boolean reportFailure) throws SQLException
{
if (connection == null)
{
return;
}
try (PreparedStatement statement = connection.prepareStatement(DROP_TABLE_SQL))
{
statement.execute();
System.out.println("✓ Table " + TABLE_NAME + " dropped");
}
catch (SQLException e)
{
if (reportFailure)
{
System.out.println("⚠ Table " + TABLE_NAME + " not dropped: " + e.getMessage());
throw e;
}
}
}
private void executeStatement(Connection connection, String sql) throws SQLException
{
try (PreparedStatement statement = connection.prepareStatement(sql))
{
statement.execute();
}
}
private void printSQLException(SQLException e)
{
while (e != null)
{
System.err.println("SQLException: " + e.getMessage());
System.err.println("SQLState: " + e.getSQLState());
System.err.println("ErrorCode: " + e.getErrorCode());
e = e.getNextException();
if (e != null)
{
System.err.println();
}
}
}
private Timestamp currentTimestamp()
{
return new Timestamp(System.currentTimeMillis());
}
private String formatMoney(long amountCents)
{
return formatMoney((int) amountCents);
}
private String formatMoney(int amountCents)
{
return String.format("$%.2f", amountCents / 100.0);
}
private String formatTimestamp(Timestamp timestamp)
{
return (timestamp == null) ? "" : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(timestamp);
}
private String padRight(String text, int width)
{
if (text == null)
{
text = "";
}
if (text.length() >= width)
{
return text;
}
StringBuilder builder = new StringBuilder(text);
while (builder.length() < width)
{
builder.append(' ');
}
return builder.toString();
}
private String toHex(byte[] bytes)
{
StringBuilder builder = new StringBuilder(bytes.length * 2);
for (byte value : bytes)
{
builder.append(String.format("%02x", value));
}
return builder.toString();
}
}