refactor/Redis Log Widget - factor out reusable code

This commit is contained in:
Marko Milić 2024-10-28 10:55:26 +01:00
parent 77d94b26a6
commit 12681890a7
4 changed files with 89 additions and 56 deletions

View File

@ -0,0 +1,11 @@
package com.openbankproject;
// DateTimeUtils.java
import java.time.Instant;
public class DateTimeUtils {
public static String printUtcDateTime() {
Instant now = Instant.now();
return "at UTC Time: " + now.toString();
}
}

View File

@ -0,0 +1,53 @@
package com.openbankproject;
// RequestResponseLogger.java
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RequestResponseLogger {
@Autowired
private RedisService redisService;
public StringBuilder saveRequestInfoToRedis(HttpRequest request, String body) {
StringBuilder logEntry = buildRequestInfo(request, body);
String key = "log-entry-for-session-id: " + SessionUtils.getSessionId();
String value = logEntry.toString();
redisService.saveLogToRedis(key, value);
return logEntry;
}
private StringBuilder buildRequestInfo(HttpRequest request, String body) {
StringBuilder logEntry = new StringBuilder();
logEntry.append("============= Request begin ").append(DateTimeUtils.printUtcDateTime()).append(" =============\n")
.append("=== Session ID: ").append(SessionUtils.getSessionId()).append("\n")
.append("=== Status Line : ").append(request.getRequestLine()).append("\n")
.append("=== Headers : ").append(StringUtils.join(request.getAllHeaders(), "; ")).append("\n")
.append("=== Request body: ").append(body).append("\n")
.append("============= Request end ").append(DateTimeUtils.printUtcDateTime()).append(" =============\n");
return logEntry;
}
public StringBuilder saveResponseInfoToRedis(HttpResponse response, String body) {
StringBuilder logEntry = buildResponseInfo(response, body);
String key = "log-entry-for-session-id: " + SessionUtils.getSessionId();
String value = logEntry.toString();
redisService.saveLogToRedis(key, value);
return logEntry;
}
private StringBuilder buildResponseInfo(HttpResponse response, String body) {
StringBuilder logEntry = new StringBuilder();
logEntry.append("============= Response begin ").append(DateTimeUtils.printUtcDateTime()).append(" =============\n")
.append("=== Session ID: ").append(SessionUtils.getSessionId()).append("\n")
.append("=== Status Line : ").append(response.getStatusLine()).append("\n")
.append("=== Headers : ").append(StringUtils.join(response.getAllHeaders(), "; ")).append("\n")
.append("=== Response body: ").append(body).append("\n")
.append("============= Response end ").append(DateTimeUtils.printUtcDateTime()).append(" =============\n");
return logEntry;
}
}

View File

@ -0,0 +1,16 @@
package com.openbankproject;
// SessionUtils.java
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class SessionUtils {
public static String getSessionId() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null && attributes.getRequest() != null && attributes.getRequest().getSession(false) != null) {
return attributes.getRequest().getSession(false).getId(); // Get the existing session, don't create a new one
}
return "";
}
}

View File

@ -7,6 +7,7 @@ import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.jwk.RSAKey;
import com.openbankproject.JwsUtil;
import com.openbankproject.RedisService;
import com.openbankproject.RequestResponseLogger;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
@ -43,12 +44,13 @@ import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.text.ParseException;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static com.openbankproject.SessionUtils.getSessionId;
@Configuration
public class RestTemplateConfig {
private static final Logger logger = LoggerFactory.getLogger(RestTemplateConfig.class);
@ -66,6 +68,10 @@ public class RestTemplateConfig {
@Value("${force_jws}")
private String forceJws;
@Autowired
private RequestResponseLogger requestResponseLogger;
@Bean
public RestTemplate restTemplate(SSLContext sslContext) {
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
@ -121,59 +127,6 @@ public class RestTemplateConfig {
}
}
private String getSessionId() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null && attributes.getRequest() != null && attributes.getRequest().getSession(false) != null ) {
return attributes.getRequest().getSession(false).getId(); // Get the existing session, don't create a new one
}
return "";
}
@Autowired
private RedisService redisService;
public String printUtcDateTime() {
Instant now = Instant.now();
return "at UTC Time: " + now.toString();
}
private StringBuilder saveRequestInfoToRedis(HttpRequest request, String body) {
StringBuilder logEntry = buildRequestInfo(request, body);
String key = "log-entry-for-session-id: " + getSessionId();
String value = logEntry.toString();
redisService.saveLogToRedis(key, value);
return logEntry;
}
private StringBuilder buildRequestInfo(HttpRequest request, String body) {
StringBuilder logEntry = new StringBuilder();
logEntry.append("============= Request begin " + printUtcDateTime() + " =============\n")
.append("=== Session ID: ").append(getSessionId()).append("\n")
.append("=== Status Line : ").append(request.getRequestLine()).append("\n")
.append("=== Headers : ").append(StringUtils.join(request.getAllHeaders(), "; ")).append("\n")
.append("=== Request body: ").append(body).append("\n")
.append("============= Request end " + printUtcDateTime() + " =============\n");
return logEntry;
}
private StringBuilder saveResponseInfoTRedis(HttpResponse response, String body) {
StringBuilder logEntry = buildResponseInfo(response, body);
String key = "log-entry-for-session-id: " + getSessionId();
String value = logEntry.toString();
redisService.saveLogToRedis(key, value);
return logEntry;
}
private StringBuilder buildResponseInfo(HttpResponse response, String body) {
StringBuilder logEntry = new StringBuilder();
logEntry.append("============= Response begin " + printUtcDateTime() + " =============\n")
.append("=== Session ID: ").append(getSessionId()).append("\n")
.append("=== Status Line : ").append(response.getStatusLine()).append("\n")
.append("=== Headers : ").append(StringUtils.join(response.getAllHeaders(), "; ")).append("\n")
.append("=== Response body: ").append(body).append("\n")
.append("============= Response end " + printUtcDateTime() + " =============\n");
return logEntry;
}
private void traceRequest(HttpRequest request, String body) throws IOException {
// Standard output
logger.info("=========================== request begin ================================================ Session ID : {}", getSessionId());
@ -182,7 +135,7 @@ public class RestTemplateConfig {
logger.info("=== Request body: {}, Session ID : {}", body, getSessionId());
logger.info("============================= request end ================================================ Session ID : {}", getSessionId());
// Save to Redis
saveRequestInfoToRedis(request, body).toString();
requestResponseLogger.saveRequestInfoToRedis(request, body).toString();
}
private void traceResponse(HttpResponse response, String body) throws IOException {
// Standard output
@ -192,7 +145,7 @@ public class RestTemplateConfig {
logger.info("=== Response body: {}, Session ID : {}", body, getSessionId());
logger.info("=========================== response end =================================================== Session ID : {}", getSessionId());
// Save to Redis
saveResponseInfoTRedis(response, body);
requestResponseLogger.saveResponseInfoToRedis(response, body);
}
private void responseIntercept(org.apache.http.HttpResponse response, HttpContext httpContext) throws IOException {
HttpRequest req = (HttpRequest)httpContext.getAttribute("http.request");