Skip to content

Commit

Permalink
feat: CF-00004/CF-00005 케이스 핸들링 (#47)
Browse files Browse the repository at this point in the history
* chore: 로깅 중복 로직 수정

* refactor/style: 리팩토링 및 스타일 포맷팅

* feat: CF-00004/CF-00005 케이스 Exception Handling

* refactor: 로깅부 분리
  • Loading branch information
h-beeen authored Dec 2, 2024
1 parent 6de6b6c commit 4cfd99b
Show file tree
Hide file tree
Showing 17 changed files with 411 additions and 340 deletions.
53 changes: 20 additions & 33 deletions src/main/java/io/codef/api/EasyCodef.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,30 @@
import io.codef.api.storage.MultipleRequestStorage;
import io.codef.api.storage.SimpleAuthStorage;
import io.codef.api.util.RsaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.PublicKey;
import java.util.List;

public class EasyCodef {

private static final Logger log = LoggerFactory.getLogger(EasyCodef.class);

private final SingleReqFacade singleReqFacade;
private final MultipleReqFacade multipleReqFacade;
private final SimpleAuthCertFacade simpleAuthCertFacade;

private final PublicKey publicKey;

protected EasyCodef(EasyCodefBuilder builder) {
this.publicKey = RsaUtil.generatePublicKey(builder.getPublicKey());
protected EasyCodef(EasyCodefBuilder easyCodefBuilder) {
this.publicKey = RsaUtil.generatePublicKey(easyCodefBuilder.getPublicKey());

EasyCodefToken easyCodefToken = new EasyCodefToken(builder);
EasyCodefToken easyCodefToken = new EasyCodefToken(easyCodefBuilder);
SimpleAuthStorage simpleAuthStorage = new SimpleAuthStorage();
MultipleRequestStorage multipleRequestStorage = new MultipleRequestStorage();
CodefExecutorManager executorManager = CodefExecutorManager.create();

this.singleReqFacade = new SingleReqFacade(
easyCodefToken,
simpleAuthStorage,
builder.getClientType()
easyCodefBuilder.getClientType()
);

this.multipleReqFacade = new MultipleReqFacade(
Expand All @@ -51,45 +47,36 @@ protected EasyCodef(EasyCodefBuilder builder) {
multipleRequestStorage
);

logInitializeSuccessfully();
EasyCodefLogger.logInitializeSuccessfully();
}

public String encryptRSA(String requestParam) throws CodefException {
public String encryptRSA(
String requestParam
) throws CodefException {
return RsaUtil.encryptRSA(requestParam, publicKey);
}

public EasyCodefResponse requestProduct(EasyCodefRequest request) throws CodefException {
public EasyCodefResponse requestProduct(
EasyCodefRequest request
) throws CodefException {
return singleReqFacade.requestProduct(request);
}

public EasyCodefResponse requestMultipleProduct(List<EasyCodefRequest> requests) throws CodefException {
public EasyCodefResponse requestMultipleProduct(
List<EasyCodefRequest> requests
) throws CodefException {
return multipleReqFacade.requestMultipleProduct(requests);
}

public EasyCodefResponse requestSimpleAuthCertification(String transactionId) throws CodefException {
public EasyCodefResponse requestSimpleAuthCertification(
String transactionId
) throws CodefException {
return simpleAuthCertFacade.requestSimpleAuthCertification(transactionId);
}

public List<EasyCodefResponse> requestMultipleSimpleAuthCertification(String transactionId) throws CodefException {
public List<EasyCodefResponse> requestMultipleSimpleAuthCertification(
String transactionId
) throws CodefException {
return simpleAuthCertFacade.requestMultipleSimpleAuthCertification(transactionId);
}

public PublicKey getPublicKey() {
return publicKey;
}

private void logInitializeSuccessfully() {
log.info("""
------. ,-----. ,--. ,---.\s
| .---' ,--,--. ,---.,--. ,--.' .--./ ,---. ,-| |,---. / .-'\s
| `--, ' ,-. |( .-' \\ ' / | | | .-. |' .-. | .-. :| `-,\s
| `---.\\ '-' |.-' `) \\ ' ' '--'\\' '-' '\\ `-' \\ --.| .-'\s
`------' `--`--'`----'.-' / `-----' `---' `---' `----'`--' \s
> EasyCodef v2.0.0-beta-005 Successfully Initialized! Hello worlds!
"""
);
}
}
4 changes: 2 additions & 2 deletions src/main/java/io/codef/api/EasyCodefBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import io.codef.api.constants.CodefClientType;
import io.codef.api.error.CodefError;
import io.codef.api.error.CodefException;

import java.util.UUID;

public class EasyCodefBuilder {
Expand All @@ -17,8 +18,7 @@ public static EasyCodefBuilder builder() {
}

public EasyCodefBuilder publicKey(String publicKey) {
this.publicKey = CodefValidator.requireNonNullElseThrow(publicKey,
CodefError.NULL_PUBLIC_KEY);
this.publicKey = CodefValidator.requireNonNullElseThrow(publicKey, CodefError.NULL_PUBLIC_KEY);
return this;
}

Expand Down
42 changes: 9 additions & 33 deletions src/main/java/io/codef/api/EasyCodefConnector.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package io.codef.api;

import static org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION;

import com.alibaba.fastjson2.JSON;
import io.codef.api.constants.CodefHost;
import io.codef.api.constants.CodefPath;
Expand All @@ -11,20 +9,17 @@
import io.codef.api.error.CodefException;
import io.codef.api.util.AuthorizationUtil;
import io.codef.api.util.HttpClientUtil;
import io.codef.api.util.JsonUtil;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EasyCodefConnector {
import java.io.IOException;
import java.nio.charset.StandardCharsets;

private static final Logger log = LoggerFactory.getLogger(EasyCodefConnector.class);
private static final ResponseHandler responseHandler = new ResponseHandler();
import static org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION;

public class EasyCodefConnector {

private EasyCodefConnector() {
}
Expand All @@ -38,7 +33,7 @@ public static EasyCodefResponse requestProduct(
String requestUrl
) throws CodefException {
HttpPost httpRequest = createProductRequest(request, token, requestUrl);
return executeRequest(httpRequest, responseHandler::handleProductResponse);
return executeRequest(httpRequest, ResponseHandler::handleProductResponse);
}

/**
Expand All @@ -48,7 +43,7 @@ public static String requestToken(
String codefOAuthToken
) throws CodefException {
HttpPost request = createTokenRequest(codefOAuthToken);
return executeRequest(request, responseHandler::handleTokenResponse);
return executeRequest(request, ResponseHandler::handleTokenResponse);
}


Expand Down Expand Up @@ -78,38 +73,19 @@ private static <T> T executeRequest(
HttpPost request,
ResponseProcessor<T> processor
) throws CodefException {
logRequest(request);
EasyCodefLogger.logRequest(request);

try (CloseableHttpClient httpClient = HttpClientUtil.createClient()) {
return httpClient.execute(request, response -> {
T result = processor.process(response);
logResponse(request.hashCode(), response, result);
EasyCodefLogger.logResponse(request.hashCode(), response, result);
return result;
});
} catch (IOException exception) {
throw CodefException.of(CodefError.IO_ERROR, exception);
}
}

private static void logRequest(HttpPost request) {
log.info("[{}] Codef API Request", request.hashCode());
log.info("> Request Host: {}://{}",
request.getScheme(),
request.getAuthority()
);
log.info("> Request URI: {}\n", request.getRequestUri());
}

private static void logResponse(
int requestHashCode,
ClassicHttpResponse response,
Object result
) {
log.info("[{}] Codef API Response", requestHashCode);
log.info("> Response Status: {}", response.getCode());
log.info("> Response → \n{}\n", JsonUtil.toPrettyJson(result));
}

@FunctionalInterface
private interface ResponseProcessor<T> {

Expand Down
185 changes: 185 additions & 0 deletions src/main/java/io/codef/api/EasyCodefLogger.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
package io.codef.api;

import com.alibaba.fastjson2.JSON;
import io.codef.api.dto.EasyCodefResponse;
import io.codef.api.util.JsonUtil;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import static io.codef.api.constants.CodefResponseCode.*;

public class EasyCodefLogger {
private static final Logger log = LoggerFactory.getLogger(EasyCodefLogger.class);

private EasyCodefLogger() {
}

public static void logRequest(HttpPost request) {
log.info("[{}] Codef API Request", request.hashCode());
log.info("> Request Host: {}://{}",
request.getScheme(),
request.getAuthority()
);
log.info("> Request URI: {}\n", request.getRequestUri());
}

public static void logResponse(
int requestHashCode,
ClassicHttpResponse response,
Object result
) {
log.info("[{}] Codef API Response", requestHashCode);
log.info("> Response Status: {}", response.getCode());
log.info("> Response → \n{}\n", JsonUtil.toPrettyJson(result));
}

public static void logResponseStatus(EasyCodefResponse response) {
logBasicInfo(response);

switch (response.code()) {
case CF_00000:
logSuccessResponse();
break;

case CF_03002:
logAddAuthRequired(response);
break;

case CF_12872:
logAuthExceeded();
break;

default:
logError(response);
break;
}
}

public static void logStatusSummary(List<EasyCodefResponse> responses) {
long successCount = responses.stream().filter(ResponseHandler::isSuccessResponse).count();
long addAuthCount = responses.stream().filter(ResponseHandler::isAddAuthResponse).count();
long failureCount = responses.stream().filter(ResponseHandler::isFailureResponse).count();

log.info("Total Responses Count = {}\n", responses.size());
logStatus(successCount, addAuthCount, failureCount);
}

private static void logBasicInfo(EasyCodefResponse response) {
log.info("Response Status Code : {}", response.code());
log.info("Transaction Id : {}", response.transactionId());
}

private static void logSuccessResponse() {
log.info("Successfully returned Value from Codef API\n");
}

private static void logAddAuthRequired(EasyCodefResponse response) {
Object data = response.data();
String addAuthMethod = JSON.parseObject(data.toString()).getString("method");
log.warn("Additional authentication required | method : {}\n", addAuthMethod);
}

private static void logAuthExceeded() {
log.error("Retry limit for additional authentication exceeded. "
+ "Please restart the process from the initial request.\n");
}

private static void logError(EasyCodefResponse response) {
log.error("Failed to get proper scrapping response. Check the Error errorMessage And StatusCode");
log.error("> message : {}", response.result().message());
log.error("> extraMessage : {}", response.result().extraMessage());
}

private static void logStatus(
long successCount,
long addAuthCount,
long failureCount
) {
Optional.of(successCount)
.filter(EasyCodefLogger::isExist)
.ifPresent(count -> log.info("Success Response Status [ {} ] Count : {}", CF_00000, count));

Optional.of(addAuthCount)
.filter(EasyCodefLogger::isExist)
.ifPresent(count -> log.info("AddAuth Response Status [ {} ] Count : {}", CF_03002, count));

Optional.of(failureCount)
.filter(EasyCodefLogger::isExist)
.ifPresentOrElse(
count -> log.warn("Failure Response Status [ Else ] Count : {}\n", count),
() -> log.info("No Failure Responses\n")
);
}

private static boolean isExist(Long count) {
return count > 0;
}

protected static void logInitializeSuccessfully() {
log.info("""
------. ,-----. ,--. ,---.\s
| .---' ,--,--. ,---.,--. ,--.' .--./ ,---. ,-| |,---. / .-'\s
| `--, ' ,-. |( .-' \\ ' / | | | .-. |' .-. | .-. :| `-,\s
| `---.\\ '-' |.-' `) \\ ' ' '--'\\' '-' '\\ `-' \\ --.| .-'\s
`------' `--`--'`----'.-' / `-----' `---' `---' `----'`--' \s
> EasyCodef v2.0.0-beta-005 Successfully Initialized! Hello worlds!
"""
);
}

protected static void logOAuthTokenCreation(String oauthToken) {
log.info("Codef OAuth Token : {}", oauthToken);
log.info("Codef OAuth Token successfully initialized.\n");
}

protected static void logAccessTokenCreation(
String accessToken,
LocalDateTime expiresAt
) {
logAccessToken(accessToken);
log.info(
"Codef API AccessToken expiry at {}. Also, EasyCodef will handle automatic renewal.",
expiresAt
);
log.info("Codef API AccessToken successfully initialized.\n");
}

protected static void logTokenRefreshStart(LocalDateTime expiresAt) {
log.info(
"Codef API AccessToken expiry at {} so EasyCodef refresh token",
expiresAt
);
}

public static void logAwaitResponseCounts(List<EasyCodefResponse> results) {
log.info("Await Responses Count = {}", results.size());
}

public static void logAwaitResponse(String transactionId) {
log.info("Await Responses called By transactionId: {}", transactionId);
}

protected static void logTokenRefreshCompletion(
String accessToken,
LocalDateTime expiresAt
) {
logAccessToken(accessToken);
log.info(
"AccessToken Refresh completed. Now, Codef accessToken expiry at {}.",
expiresAt
);
}

private static void logAccessToken(String accessToken) {
log.info("Codef API AccessToken : {}", accessToken);
}
}
Loading

0 comments on commit 4cfd99b

Please sign in to comment.