remove adapter-flow-lib usages, remove adapter model (#29)

* remove adapter-flow-lib usages, remove adapter model

refactoring packages, remove unused (mpi)
add readme

* asd
This commit is contained in:
Anatoly Karlov 2022-05-13 20:03:20 +07:00 committed by GitHub
parent 66c87c8352
commit 440f40ab27
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
115 changed files with 99 additions and 2227 deletions

View File

@ -1,7 +1,19 @@
# Adapter-common-lib
Библиотека, которая включает общие для всех адаптеров классы.
Бибилиотека включает в себя
### Оглавление:
1. [Общие данные по проекту при написании адаптера](docs/common.md)
+ функционал архивированной https://github.com/valitydev/adapter-client-lib
+ функционал архивированной https://github.com/valitydev/adapter-thrift-lib
+ функционал архивированной https://github.com/valitydev/error-mapping-java
+ компоненты
```
├── component
├── LoggingInterceptor.class
├── NetworkFilterComponent.class
├── RequestLoggingAspect.class
├── RestTemplateComponent.class
├── SimpleErrorMapping.class
└── SimpleObjectMapper.class
```
+ аспект логгирование
+ базовые утилиты

View File

@ -12,7 +12,7 @@
</parent>
<artifactId>adapter-common-lib</artifactId>
<version>1.0.6</version>
<version>1.1.0</version>
<packaging>jar</packaging>
<name>adapter-common-lib</name>

View File

@ -1,7 +0,0 @@
package dev.vality.adapter.common;
public interface Validator<O> {
void validate(O object);
}

View File

@ -1,9 +1,9 @@
package dev.vality.adapter.common.utils.cds.creators;
package dev.vality.adapter.common.cds;
import com.github.javafaker.Faker;
import com.github.javafaker.Name;
import dev.vality.adapter.common.cds.model.CardDataProxyModel;
import dev.vality.adapter.common.exception.CdsStorageExpDateException;
import dev.vality.adapter.common.utils.cds.model.CardDataProxyModel;
import dev.vality.cds.storage.CardData;
import dev.vality.damsel.domain.BankCard;
import lombok.AccessLevel;

View File

@ -9,7 +9,7 @@ import org.apache.thrift.TException;
@Slf4j
@RequiredArgsConstructor
public class CdsClientIDStorage {
public class CdsIdStorageClient {
private final IdentityDocumentStorageSrv.Iface cdsIDStorageApi;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.cds.creators;
package dev.vality.adapter.common.cds;
import dev.vality.cds.storage.*;
import lombok.AccessLevel;

View File

@ -1,8 +1,7 @@
package dev.vality.adapter.common.cds;
import dev.vality.adapter.common.cds.model.CardDataProxyModel;
import dev.vality.adapter.common.exception.CdsStorageException;
import dev.vality.adapter.common.utils.cds.creators.BankCardExtractor;
import dev.vality.adapter.common.utils.cds.model.CardDataProxyModel;
import dev.vality.cds.storage.CardData;
import dev.vality.cds.storage.SessionData;
import dev.vality.cds.storage.StorageSrv;
@ -18,11 +17,11 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TException;
import org.springframework.cache.annotation.Cacheable;
import static dev.vality.adapter.common.utils.damsel.extractors.ProxyProviderPackageExtractors.*;
import static dev.vality.adapter.common.damsel.ProxyProviderPackageExtractors.*;
@Slf4j
@RequiredArgsConstructor
public class CdsClientStorage {
public class CdsStorageClient {
private final StorageSrv.Iface storageSrv;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.cds.model;
package dev.vality.adapter.common.cds.model;
import lombok.Builder;
import lombok.Data;

View File

@ -1,7 +1,7 @@
package dev.vality.adapter.common.logging.aspect;
package dev.vality.adapter.common.component;
import dev.vality.adapter.common.logging.annotation.GetLogging;
import dev.vality.adapter.common.logging.annotation.PostLogging;
import dev.vality.adapter.common.logging.GetLogging;
import dev.vality.adapter.common.logging.PostLogging;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
@ -17,7 +17,7 @@ public class RequestLoggingAspect {
private static final String REQUEST_LOG = "Request [{} {}]: {}";
private static final String RESPONSE_LOG = "Response [{} {}]: {}";
@Around("@annotation(dev.vality.adapter.common.logging.annotation.GetLogging)")
@Around("@annotation(dev.vality.adapter.common.logging.GetLogging)")
public Object logGetRequest(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
GetLogging getLogging = AnnotationUtils.findAnnotation(signature.getMethod(), GetLogging.class);
@ -28,7 +28,7 @@ public class RequestLoggingAspect {
return log(joinPoint, method, endpoint);
}
@Around("@annotation(dev.vality.adapter.common.logging.annotation.PostLogging)")
@Around("@annotation(dev.vality.adapter.common.logging.PostLogging)")
public Object logPostRequest(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
PostLogging postLogging = AnnotationUtils.findAnnotation(signature.getMethod(), PostLogging.class);

View File

@ -1,7 +1,8 @@
package dev.vality.adapter.common.mapper;
package dev.vality.adapter.common.component;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.vality.adapter.common.mapper.ErrorMapping;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;

View File

@ -1,11 +1,11 @@
package dev.vality.adapter.common.mapper;
package dev.vality.adapter.common.component;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import dev.vality.adapter.common.mapper.naming.strategy.UpperSnakeCaseStrategy;
import dev.vality.adapter.common.utils.UpperSnakeCaseStrategy;
public class SimpleObjectMapper {

View File

@ -1,19 +0,0 @@
package dev.vality.adapter.common.constants;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public enum ThreeDsFields {
MD("MD"),
PA_REQ("PaReq"),
PA_RES("PaRes"),
TERM_URL("TermUrl"),
THREE_DS_METHOD_DATA("ThreeDsMethodData"),
C_REQ("creq"),
THREE_DS_SESSION_DATA("threeDSSessionData");
private final String value;
}

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.converter;
package dev.vality.adapter.common.damsel;
import dev.vality.damsel.domain.BankCardExpDate;
import lombok.AccessLevel;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.creators;
package dev.vality.adapter.common.damsel;
import dev.vality.damsel.base.Timer;
import lombok.AccessLevel;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.creators;
package dev.vality.adapter.common.damsel;
import dev.vality.damsel.domain.*;
import lombok.AccessLevel;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.extractors;
package dev.vality.adapter.common.damsel;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

View File

@ -1,6 +1,6 @@
package dev.vality.adapter.common.utils.damsel.extractors;
package dev.vality.adapter.common.damsel;
import dev.vality.adapter.common.utils.damsel.constant.PaymentResourceType;
import dev.vality.adapter.common.damsel.model.PaymentResourceType;
import dev.vality.damsel.proxy_provider.PaymentContext;
import dev.vality.damsel.proxy_provider.PaymentResource;
import lombok.AccessLevel;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.creators;
package dev.vality.adapter.common.damsel;
import dev.vality.damsel.base.Timer;
import dev.vality.damsel.domain.*;
@ -21,10 +21,10 @@ import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import static dev.vality.adapter.common.utils.damsel.constant.Error.DEFAULT_ERROR_CODE;
import static dev.vality.adapter.common.utils.damsel.creators.BasePackageCreators.createTimerTimeout;
import static dev.vality.adapter.common.utils.damsel.extractors.ProxyProviderPackageExtractors.extractInvoiceId;
import static dev.vality.adapter.common.utils.damsel.extractors.ProxyProviderPackageExtractors.extractPaymentId;
import static dev.vality.adapter.common.damsel.BasePackageCreators.createTimerTimeout;
import static dev.vality.adapter.common.damsel.ProxyProviderPackageExtractors.extractInvoiceId;
import static dev.vality.adapter.common.damsel.ProxyProviderPackageExtractors.extractPaymentId;
import static dev.vality.adapter.common.damsel.model.Error.DEFAULT_ERROR_CODE;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ProxyProviderPackageCreators {

View File

@ -1,5 +1,6 @@
package dev.vality.adapter.common.utils.damsel.extractors;
package dev.vality.adapter.common.damsel;
import dev.vality.adapter.common.damsel.model.Error;
import dev.vality.damsel.domain.*;
import dev.vality.damsel.proxy_provider.Cash;
import dev.vality.damsel.proxy_provider.*;
@ -8,8 +9,6 @@ import lombok.NoArgsConstructor;
import java.util.Map;
import static dev.vality.adapter.common.utils.damsel.constant.Error.UNKNOWN;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ProxyProviderPackageExtractors {
@ -145,7 +144,7 @@ public class ProxyProviderPackageExtractors {
}
public static String extractTargetInvoicePaymentStatus(TargetInvoicePaymentStatus targetInvoicePaymentStatus) {
String state = UNKNOWN;
String state = Error.UNKNOWN;
if (targetInvoicePaymentStatus.isSetProcessed()) {
state = TargetInvoicePaymentStatus._Fields.PROCESSED.getFieldName();
} else if (targetInvoicePaymentStatus.isSetCaptured()) {

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.verification;
package dev.vality.adapter.common.damsel;
import dev.vality.damsel.proxy_provider.*;
import dev.vality.woody.api.flow.error.WErrorDefinition;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.creators;
package dev.vality.adapter.common.damsel;
import dev.vality.damsel.base.Timer;
import dev.vality.damsel.domain.Failure;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.verification;
package dev.vality.adapter.common.damsel;
import dev.vality.damsel.withdrawals.provider_adapter.ProcessResult;
import lombok.AccessLevel;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.constant;
package dev.vality.adapter.common.damsel.model;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.constant;
package dev.vality.adapter.common.damsel.model;
import lombok.AccessLevel;
import lombok.Getter;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.domain;
package dev.vality.adapter.common.damsel.model;
public enum TargetInvoicePaymentStatus {

View File

@ -1,6 +0,0 @@
package dev.vality.adapter.common.enums;
public enum PaymentResourceType {
RECURRENT,
PAYMENT
}

View File

@ -1,35 +0,0 @@
package dev.vality.adapter.common.enums;
public enum Step {
PRE_AUTH,
AUTH,
AUTH_MOBILE_PAY,
FINISH_THREE_DS,
FINISH_THREE_DS_V1,
FINISH_THREE_DS_V2,
AWAIT_CALLBACK,
CANCEL,
REFUND,
CHECK_STATUS,
CHECK_CAPTURE_STATUS,
CHECK_REFUND_STATUS,
CAPTURE,
DO_NOTHING,
RECURRENT,
AUTH_RECURRENT,
GENERATE_TOKEN_AUTH,
GENERATE_TOKEN_AUTH_MOBILE_PAY,
GENERATE_TOKEN_FINISH_THREE_DS,
GENERATE_TOKEN_FINISH_THREE_DS_V1,
GENERATE_TOKEN_FINISH_THREE_DS_V2,
GENERATE_TOKEN_AWAIT_CALLBACK,
GENERATE_TOKEN_CAPTURE,
GENERATE_TOKEN_CANCEL,
GENERATE_TOKEN_REFUND,
GENERATE_TOKEN_CHECK_STATUS,
GENERATE_TOKEN_FINISH
}

View File

@ -1,8 +0,0 @@
package dev.vality.adapter.common.enums;
public enum TargetStatus {
PROCESSED,
CAPTURED,
CANCELLED,
REFUNDED
}

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.mapper;
package dev.vality.adapter.common.exception;
/**
* Handy class for wrapping runtime {@code Exceptions} with a root cause.

View File

@ -1,11 +0,0 @@
package dev.vality.adapter.common.handler;
import org.apache.thrift.TException;
public interface CommonHandler<T, E> {
boolean isHandle(E model);
T handle(E context) throws TException;
}

View File

@ -1,25 +0,0 @@
package dev.vality.adapter.common.handler;
import dev.vality.adapter.common.processor.Processor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import java.util.function.Function;
@Slf4j
@RequiredArgsConstructor
public abstract class CommonHandlerImpl<P, R, E, T> implements CommonHandler<T, E> {
private final Function<P, R> requestFunction;
private final Converter<E, P> converter;
private final Processor<T, R, E> processor;
@Override
public T handle(E entryStateModel) {
P request = converter.convert(entryStateModel);
R response = requestFunction.apply(request);
return processor.process(response, entryStateModel);
}
}

View File

@ -1,83 +0,0 @@
package dev.vality.adapter.common.handler;
import dev.vality.adapter.common.utils.converter.PaymentResourceTypeResolver;
import dev.vality.adapter.common.utils.damsel.extractors.ProxyProviderPackageExtractors;
import dev.vality.damsel.proxy_provider.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TException;
import java.nio.ByteBuffer;
import static dev.vality.adapter.common.utils.damsel.verification.ProxyProviderVerification.isUndefinedResultOrUnavailable;
@Slf4j
@RequiredArgsConstructor
public class ServerHandlerLogDecorator implements ProviderProxySrv.Iface {
private final ProviderProxySrv.Iface handler;
@Override
public RecurrentTokenProxyResult generateToken(RecurrentTokenContext context) throws TException {
String recurrentId = ProxyProviderPackageExtractors.extractRecurrentId(context);
log.info("Generate token started with recurrentId {}", recurrentId);
try {
RecurrentTokenProxyResult proxyResult = handler.generateToken(context);
log.info("Generate token finished {} with recurrentId {}", proxyResult, recurrentId);
return proxyResult;
} catch (Exception ex) {
String message = "Failed handle generate token with recurrentId " + recurrentId;
logMessage(ex, message);
throw ex;
}
}
@Override
public RecurrentTokenCallbackResult handleRecurrentTokenCallback(ByteBuffer byteBuffer,
RecurrentTokenContext context) throws TException {
String recurrentId = ProxyProviderPackageExtractors.extractRecurrentId(context);
log.info("handleRecurrentTokenCallback: start with recurrentId {}", recurrentId);
RecurrentTokenCallbackResult result = handler.handleRecurrentTokenCallback(byteBuffer, context);
log.info("handleRecurrentTokenCallback end {} with recurrentId {}", result, recurrentId);
return result;
}
@Override
public PaymentProxyResult processPayment(PaymentContext context) throws TException {
String invoiceId = ProxyProviderPackageExtractors.extractInvoiceId(context);
String invoicePaymentStatus = ProxyProviderPackageExtractors.extractTargetInvoicePaymentStatus(context);
String paymentResourceType = PaymentResourceTypeResolver.extractPaymentResourceType(context);
log.info("Process payment handle resource='{}', status='{}' start with invoiceId {}", paymentResourceType,
invoicePaymentStatus, invoiceId);
try {
PaymentProxyResult proxyResult = handler.processPayment(context);
log.info("Process payment handle resource='{}', status='{}' finished with invoiceId {} and proxyResult {}",
paymentResourceType, invoicePaymentStatus, invoiceId, proxyResult);
return proxyResult;
} catch (Exception e) {
String message = String.format(
"Failed handle resource=%s, status=%s process payment for operation with invoiceId %s",
paymentResourceType, invoicePaymentStatus, invoiceId);
logMessage(e, message);
throw e;
}
}
@Override
public PaymentCallbackResult handlePaymentCallback(ByteBuffer byteBuffer,
PaymentContext context) throws TException {
String invoiceId = ProxyProviderPackageExtractors.extractInvoiceId(context);
log.info("handlePaymentCallback start with invoiceId {}", invoiceId);
PaymentCallbackResult result = handler.handlePaymentCallback(byteBuffer, context);
log.info("handlePaymentCallback finish {} with invoiceId {}", result, invoiceId);
return result;
}
private static void logMessage(Exception ex, String message) {
if (isUndefinedResultOrUnavailable(ex)) {
log.warn(message, ex);
} else {
log.error(message, ex);
}
}
}

View File

@ -1,58 +0,0 @@
package dev.vality.adapter.common.handler;
import dev.vality.adapter.common.logback.mdc.MdcContext;
import dev.vality.damsel.proxy_provider.*;
import lombok.RequiredArgsConstructor;
import org.apache.thrift.TException;
import org.slf4j.MDC;
import java.nio.ByteBuffer;
@RequiredArgsConstructor
public class ServerHandlerMdcDecorator implements ProviderProxySrv.Iface {
private final ProviderProxySrv.Iface serverHandlerLogDecorator;
public RecurrentTokenProxyResult generateToken(RecurrentTokenContext recurrentTokenContext) throws TException {
MdcContext.mdcPutContext(recurrentTokenContext);
try {
return serverHandlerLogDecorator.generateToken(recurrentTokenContext);
} finally {
MDC.clear();
}
}
@Override
public RecurrentTokenCallbackResult handleRecurrentTokenCallback(ByteBuffer byteBuffer,
RecurrentTokenContext recurrentTokenContext)
throws TException {
MdcContext.mdcPutContext(recurrentTokenContext);
try {
return serverHandlerLogDecorator.handleRecurrentTokenCallback(byteBuffer, recurrentTokenContext);
} finally {
MDC.clear();
}
}
@Override
public PaymentProxyResult processPayment(PaymentContext paymentContext) throws TException {
MdcContext.mdcPutContext(paymentContext);
try {
return serverHandlerLogDecorator.processPayment(paymentContext);
} finally {
MDC.clear();
}
}
@Override
public PaymentCallbackResult handlePaymentCallback(ByteBuffer byteBuffer, PaymentContext paymentContext)
throws TException {
MdcContext.mdcPutContext(paymentContext);
try {
return serverHandlerLogDecorator.handlePaymentCallback(byteBuffer, paymentContext);
} finally {
MDC.clear();
}
}
}

View File

@ -1,9 +0,0 @@
package dev.vality.adapter.common.handler.callback;
import java.nio.ByteBuffer;
public interface CallbackHandler<T, R> {
T handleCallback(ByteBuffer byteBuffer, R context);
}

View File

@ -1,45 +0,0 @@
package dev.vality.adapter.common.handler.callback;
import dev.vality.adapter.common.enums.Step;
import dev.vality.adapter.common.model.AdapterContext;
import dev.vality.adapter.common.model.Callback;
import dev.vality.adapter.common.state.deserializer.AdapterDeserializer;
import dev.vality.adapter.common.state.deserializer.CallbackDeserializer;
import dev.vality.adapter.common.state.serializer.AdapterSerializer;
import dev.vality.adapter.common.state.utils.AdapterStateUtils;
import dev.vality.damsel.proxy_provider.PaymentCallbackProxyResult;
import dev.vality.damsel.proxy_provider.PaymentCallbackResult;
import dev.vality.damsel.proxy_provider.PaymentContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.nio.ByteBuffer;
import static dev.vality.adapter.common.utils.damsel.creators.ProxyProviderPackageCreators.createCallbackResult;
import static dev.vality.adapter.common.utils.damsel.creators.ProxyProviderPackageCreators.createIntentWithSleepIntent;
@Slf4j
@RequiredArgsConstructor
public class PaymentCallbackHandler implements CallbackHandler<PaymentCallbackResult, PaymentContext> {
private final AdapterDeserializer adapterDeserializer;
private final AdapterSerializer adapterSerializer;
private final CallbackDeserializer callbackDeserializer;
@Override
public PaymentCallbackResult handleCallback(ByteBuffer callback, PaymentContext context) {
AdapterContext adapterContext = AdapterStateUtils.getAdapterContext(context, adapterDeserializer);
adapterContext.setStep(Step.FINISH_THREE_DS);
Callback callbackObj = callbackDeserializer.read(callback.array());
adapterContext.setPaRes(callbackObj.getPaRes());
adapterContext.setMd(callbackObj.getMd());
byte[] callbackResponse = new byte[0];
return createCallbackResult(
callbackResponse,
new PaymentCallbackProxyResult()
.setIntent(createIntentWithSleepIntent(0))
.setNextState(adapterSerializer.writeByte(adapterContext))
);
}
}

View File

@ -1,48 +0,0 @@
package dev.vality.adapter.common.handler.callback;
import dev.vality.adapter.common.enums.Step;
import dev.vality.adapter.common.model.AdapterContext;
import dev.vality.adapter.common.model.Callback;
import dev.vality.adapter.common.state.deserializer.AdapterDeserializer;
import dev.vality.adapter.common.state.deserializer.CallbackDeserializer;
import dev.vality.adapter.common.state.serializer.AdapterSerializer;
import dev.vality.adapter.common.state.utils.AdapterStateUtils;
import dev.vality.damsel.proxy_provider.RecurrentTokenCallbackResult;
import dev.vality.damsel.proxy_provider.RecurrentTokenContext;
import dev.vality.damsel.proxy_provider.RecurrentTokenIntent;
import dev.vality.damsel.proxy_provider.RecurrentTokenProxyResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.nio.ByteBuffer;
import static dev.vality.adapter.common.utils.damsel.creators.BasePackageCreators.createTimerTimeout;
import static dev.vality.adapter.common.utils.damsel.creators.ProxyProviderPackageCreators.createRecurrentTokenCallbackResult;
import static dev.vality.adapter.common.utils.damsel.creators.ProxyProviderPackageCreators.createSleepIntent;
@Slf4j
@RequiredArgsConstructor
public class RecurrentTokenCallbackHandler
implements CallbackHandler<RecurrentTokenCallbackResult, RecurrentTokenContext> {
private final AdapterDeserializer adapterDeserializer;
private final AdapterSerializer adapterSerializer;
private final CallbackDeserializer callbackDeserializer;
@Override
public RecurrentTokenCallbackResult handleCallback(ByteBuffer callback, RecurrentTokenContext context) {
AdapterContext adapterContext = AdapterStateUtils.getAdapterContext(context, adapterDeserializer);
adapterContext.setStep(Step.GENERATE_TOKEN_FINISH_THREE_DS);
Callback callbackObj = callbackDeserializer.read(callback.array());
adapterContext.setPaRes(callbackObj.getPaRes());
adapterContext.setMd(callbackObj.getMd());
byte[] callbackResponse = new byte[0];
return createRecurrentTokenCallbackResult(
callbackResponse,
new RecurrentTokenProxyResult()
.setIntent(RecurrentTokenIntent.sleep(createSleepIntent(createTimerTimeout(0))))
.setNextState(adapterSerializer.writeByte(adapterContext))
);
}
}

View File

@ -1,92 +0,0 @@
package dev.vality.adapter.common.logback.mask;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.LoggerContextVO;
import lombok.RequiredArgsConstructor;
import org.slf4j.Marker;
import java.util.Map;
@RequiredArgsConstructor
public class MaskedEvent implements ILoggingEvent {
private final ILoggingEvent event;
private final String message;
@Override
public String getThreadName() {
return event.getThreadName();
}
@Override
public Level getLevel() {
return event.getLevel();
}
@Override
public String getMessage() {
return event.getMessage();
}
@Override
public Object[] getArgumentArray() {
return new Object[0];
}
@Override
public String getFormattedMessage() {
return message;
}
@Override
public String getLoggerName() {
return event.getLoggerName();
}
@Override
public LoggerContextVO getLoggerContextVO() {
return event.getLoggerContextVO();
}
@Override
public IThrowableProxy getThrowableProxy() {
return event.getThrowableProxy();
}
@Override
public StackTraceElement[] getCallerData() {
return new StackTraceElement[0];
}
@Override
public boolean hasCallerData() {
return true;
}
@Override
public Marker getMarker() {
return event.getMarker();
}
@Override
public Map<String, String> getMDCPropertyMap() {
return event.getMDCPropertyMap();
}
@Override
public Map<String, String> getMdc() {
return event.getMDCPropertyMap();
}
@Override
public long getTimeStamp() {
return event.getTimeStamp();
}
@Override
public void prepareForDeferredProcessing() {
// Do nothing
}
}

View File

@ -1,30 +0,0 @@
package dev.vality.adapter.common.logback.mask;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MaskingMessageWithPattern {
public static String maskMessage(String message, Pattern multilinePattern) {
if (multilinePattern == null) {
return message;
}
StringBuilder sb = new StringBuilder(message);
Matcher matcher = multilinePattern.matcher(sb);
while (matcher.find()) {
IntStream.rangeClosed(1, matcher.groupCount())
.filter(group -> matcher.group(group) != null)
.forEach(
group -> IntStream.range(matcher.start(group), matcher.end(group))
.forEach(i -> sb.setCharAt(i, '*'))
);
}
return sb.toString();
}
}

View File

@ -1,26 +0,0 @@
package dev.vality.adapter.common.logback.mask;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class PatternMaskingLayout extends PatternLayout {
private Pattern multilinePattern;
private List<String> maskPatterns = new ArrayList<>();
private static final String DELIMITER = "|";
public void addMaskPattern(String maskPattern) {
maskPatterns.add(maskPattern);
multilinePattern = Pattern.compile(String.join(DELIMITER, maskPatterns), Pattern.MULTILINE);
}
@Override
public String doLayout(ILoggingEvent event) {
return super.doLayout(new MaskedEvent(event,
MaskingMessageWithPattern.maskMessage(event.getFormattedMessage(), multilinePattern)));
}
}

View File

@ -1,42 +0,0 @@
package dev.vality.adapter.common.logback.mask;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.fasterxml.jackson.core.JsonGenerator;
import net.logstash.logback.composite.AbstractFieldJsonProvider;
import net.logstash.logback.composite.FieldNamesAware;
import net.logstash.logback.composite.JsonWritingUtils;
import net.logstash.logback.fieldnames.LogstashFieldNames;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class PatternMaskingMessageJsonProvider extends AbstractFieldJsonProvider<ILoggingEvent>
implements FieldNamesAware<LogstashFieldNames> {
private Pattern multilinePattern;
private List<String> maskPatterns = new ArrayList<>();
private static final String FIELD_MESSAGE = "message";
private static final String DELIMITER = "|";
public void addMaskPattern(String maskPattern) {
maskPatterns.add(maskPattern);
multilinePattern = Pattern.compile(String.join(DELIMITER, maskPatterns), Pattern.MULTILINE);
}
public PatternMaskingMessageJsonProvider() {
setFieldName(FIELD_MESSAGE);
}
@Override
public void writeTo(JsonGenerator generator, ILoggingEvent event) throws IOException {
JsonWritingUtils.writeStringField(generator, getFieldName(),
MaskingMessageWithPattern.maskMessage(event.getFormattedMessage(), multilinePattern)
);
}
@Override
public void setFieldNames(LogstashFieldNames fieldNames) {
setFieldName(fieldNames.getMessage());
}
}

View File

@ -1,63 +0,0 @@
package dev.vality.adapter.common.logback.mdc;
import dev.vality.damsel.domain.TransactionInfo;
import dev.vality.damsel.proxy_provider.PaymentContext;
import dev.vality.damsel.proxy_provider.RecurrentTokenContext;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.slf4j.MDC;
import java.util.Map;
import java.util.regex.Pattern;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MdcContext {
public static void mdcPutContext(RecurrentTokenContext context, String[] fieldsToPutInMdc) {
TransactionInfo transactionInfo = context.getTokenInfo().getTrx();
mdcPutContextTransactionInfo(transactionInfo, fieldsToPutInMdc);
}
public static void mdcPutContext(PaymentContext context, String[] fieldsToPutInMdc) {
TransactionInfo transactionInfo = context.getPaymentInfo().getPayment().getTrx();
mdcPutContextTransactionInfo(transactionInfo, fieldsToPutInMdc);
}
public static void mdcPutContext(PaymentContext context) {
TransactionInfo transactionInfo = context.getPaymentInfo().getPayment().getTrx();
mdcPutContextTransactionInfo(transactionInfo);
}
public static void mdcPutContext(RecurrentTokenContext context) {
TransactionInfo transactionInfo = context.getTokenInfo().getTrx();
mdcPutContextTransactionInfo(transactionInfo);
}
public static void mdcPutContextTransactionInfo(TransactionInfo transactionInfo, String[] fieldsToPutInMdc) {
if (transactionInfo != null) {
Map<String, String> trxextra = transactionInfo.getExtra();
for (String field : fieldsToPutInMdc) {
MDC.put(field, trxextra.get(field));
}
}
}
public static void mdcPutContextTransactionInfo(TransactionInfo transactionInfo) {
if (transactionInfo != null) {
Map<String, String> trxextra = transactionInfo.getExtra();
String maskPattern = "\\b\\d{6}([\\d\\s]{2,9})\\d{4}\\b";
Pattern pattern = Pattern.compile(maskPattern);
for (Map.Entry<String, String> extra : trxextra.entrySet()) {
if (pattern.matcher(extra.getValue()).find()) {
MDC.put(extra.getKey(), extra.getValue());
}
}
}
}
public static void mdcRemoveContext(String[] fieldsToPutInMdc) {
for (String field : fieldsToPutInMdc) {
MDC.remove(field);
}
}
}

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.logging.annotation;
package dev.vality.adapter.common.logging;
import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMethod;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.logging.annotation;
package dev.vality.adapter.common.logging;
import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMethod;

View File

@ -4,6 +4,9 @@ import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.vality.adapter.common.exception.ErrorMappingException;
import dev.vality.adapter.common.mapper.model.Error;
import dev.vality.adapter.common.mapper.model.MappingExceptions;
import dev.vality.damsel.domain.Failure;
import dev.vality.geck.serializer.kit.tbase.TErrorUtil;
import dev.vality.woody.api.flow.error.*;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.mapper;
package dev.vality.adapter.common.mapper.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.mapper;
package dev.vality.adapter.common.mapper.model;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

View File

@ -1,32 +0,0 @@
package dev.vality.adapter.common.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import dev.vality.adapter.common.enums.Step;
import lombok.Data;
import java.util.Map;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class AdapterContext {
private String md;
private String paReq;
private String paRes;
private String acsUrl;
private String termUrl;
private String terminationUri;
@JsonProperty("cReq")
private String creq;
private String threeDsMethodData;
private String threeDsSessionData;
private String trxId;
private Step step;
private Map<String, String> options;
@JsonUnwrapped
private PollingInfo pollingInfo;
}

View File

@ -1,18 +0,0 @@
package dev.vality.adapter.common.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class Callback {
@JsonProperty(value = "MD")
private String md;
@JsonProperty(value = "PaRes")
private String paRes;
@JsonProperty(value = "termination_uri")
private String terminationUri;
}

View File

@ -1,21 +0,0 @@
package dev.vality.adapter.common.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.time.Instant;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class PollingInfo {
@JsonProperty(value = "start_date_time_polling")
private Instant startDateTimePolling;
@JsonProperty(value = "max_date_time_polling")
private Instant maxDateTimePolling;
}

View File

@ -1,16 +0,0 @@
package dev.vality.adapter.common.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Map;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RecToken {
private Map<String, String> recTokenMap;
}

View File

@ -1,7 +0,0 @@
package dev.vality.adapter.common.processor;
public interface Processor<R, T, E> {
R process(T response, E context);
}

View File

@ -1,25 +0,0 @@
package dev.vality.adapter.common.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotEmpty;
@Getter
@Setter
@Validated
public class CommonAdapterProperties {
@NotEmpty
private String url;
private String callbackUrl;
private String pathCallbackUrl;
private String pathRecurrentCallbackUrl;
private String tagPrefix;
}

View File

@ -1,35 +0,0 @@
package dev.vality.adapter.common.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
@Getter
@Setter
@Validated
public class CommonTimerProperties {
@NotNull
private int redirectTimeout;
@NotNull
private int maxTimePolling;
@NotNull
private int pollingDelay;
@NotNull
private int exponential;
@NotNull
private int defaultInitialExponential;
@NotNull
private int maxTimeBackOff;
@NotNull
private int maxTimeCoefficient;
}

View File

@ -1,9 +0,0 @@
package dev.vality.adapter.common.service;
import java.util.Map;
public interface ThreeDsPropertiesService<T> {
Map<String, String> initProperties(T stateModel);
}

View File

@ -1,5 +0,0 @@
package dev.vality.adapter.common.state.backoff;
public interface BackOff {
BackOffExecution start();
}

View File

@ -1,6 +0,0 @@
package dev.vality.adapter.common.state.backoff;
@FunctionalInterface
public interface BackOffExecution {
Long nextBackOff();
}

View File

@ -1,72 +0,0 @@
package dev.vality.adapter.common.state.backoff;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class ExponentialBackOff implements BackOff {
public static final Integer DEFAULT_MUTIPLIER = 2;
public static final Integer DEFAULT_INITIAL_INTERVAL = 2;
public static final Integer DEFAULT_MAX_INTERVAL = 300;
private Integer multiplier = DEFAULT_MUTIPLIER;
private Integer initialInterval = DEFAULT_INITIAL_INTERVAL;
private Integer maxInterval = DEFAULT_MAX_INTERVAL;
private Long startTime;
private Long currentTime;
public ExponentialBackOff(
Long startTime,
Long currentTime,
Integer multiplier,
Integer initialInterval,
Integer maxInterval) {
this.startTime = startTime;
this.currentTime = currentTime;
this.multiplier = multiplier;
this.initialInterval = initialInterval;
this.maxInterval = maxInterval;
}
@Override
public BackOffExecution start() {
return new ExponentialBackOffExecution();
}
private class ExponentialBackOffExecution implements BackOffExecution {
@Override
public Long nextBackOff() {
if (ExponentialBackOff.this.currentTime.equals(ExponentialBackOff.this.startTime)) {
return Long.valueOf(ExponentialBackOff.this.initialInterval);
}
long nextBackOff = computeNextInterval(
ExponentialBackOff.this.multiplier,
ExponentialBackOff.this.startTime,
ExponentialBackOff.this.currentTime);
if (nextBackOff > ExponentialBackOff.this.maxInterval) {
nextBackOff = (long) ExponentialBackOff.this.maxInterval;
}
return nextBackOff;
}
private long computeNextInterval(int multiplier, Long startTime, Long currentTime) {
long diff = (currentTime - startTime) / 1000;
if (diff < 1 || multiplier == 1) {
return initialInterval;
}
long result = initialInterval;
int step = 0;
while (diff >= result) {
long pow = (long) Math.pow(multiplier, step++);
result = initialInterval * pow;
}
return result;
}
}
}

View File

@ -1,29 +0,0 @@
# Поллинг для адаптеров
## Настройки
Название параметра | Описание | Пример
------------ | ------------- | -------------
**exponential** | экспонента | 2
**max_time_backoff** | максимальное время для ограничения роста экспоненты | 600 (10 минут)
**default_initial_exponential** | экспонента по умолчанию | 2
## Пример использования:
```
int nextPollingInterval = BackOffUtils.prepareNextPollingInterval(adapterState, options);
```
или
```
BackOffExecution backOffExecution = BackOffUtils.prepareBackOffExecution(adapterState, options);
int nextPollingInterval = backOffExecution.nextBackOff().intValue();
```
или
```
ExponentialBackOff exponentialBackOff = new ExponentialBackOff(adapterState, options);
int nextPollingInterval = exponentialBackOff.start().nextBackOff().intValue();
```

View File

@ -1,28 +0,0 @@
package dev.vality.adapter.common.state.backoff;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TimeOptionsExtractors {
public static final String TIMER_EXPONENTIAL = "exponential";
public static final String MAX_TIME_BACKOFF = "max_time_backoff";
public static final String DEFAULT_INITIAL_EXPONENTIAL = "default_initial_exponential";
public static Integer extractExponent(Map<String, String> options, int maxTimePolling) {
return Integer.parseInt(options.getOrDefault(TIMER_EXPONENTIAL, String.valueOf(maxTimePolling)));
}
public static Integer extractMaxTimeBackOff(Map<String, String> options, int maxTimeBackOff) {
return Integer.parseInt(options.getOrDefault(MAX_TIME_BACKOFF, String.valueOf(maxTimeBackOff)));
}
public static Integer extractDefaultInitialExponential(Map<String, String> options, int defaultInitialExponential) {
return Integer.parseInt(
options.getOrDefault(DEFAULT_INITIAL_EXPONENTIAL, String.valueOf(defaultInitialExponential)));
}
}

View File

@ -1,34 +0,0 @@
package dev.vality.adapter.common.state.deserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.vality.adapter.common.model.AdapterContext;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.io.IOException;
@Getter
@Setter
@AllArgsConstructor
public class AdapterDeserializer implements Deserializer<AdapterContext> {
private final ObjectMapper mapper;
public AdapterContext read(byte[] data) {
if (data == null) {
return new AdapterContext();
}
try {
return getMapper().readValue(data, AdapterContext.class);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public AdapterContext read(String data) {
throw new DeserializationException("Deserialization not supported");
}
}

View File

@ -1,48 +0,0 @@
package dev.vality.adapter.common.state.deserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.vality.adapter.common.model.Callback;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@Getter
@Setter
@AllArgsConstructor
public class CallbackDeserializer implements Deserializer<Callback> {
private final ObjectMapper mapper;
@Override
public Callback read(byte[] data) {
if (data == null) {
return new Callback();
}
try {
return getMapper().readValue(data, Callback.class);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public Callback read(String data) {
throw new DeserializationException("Deserialization not supported");
}
public Callback read(HttpServletRequest request) {
Map<String, String> stringMap = Optional.ofNullable(request.getParameterMap())
.orElseGet(HashMap::new)
.entrySet().stream()
.collect(Collectors.toMap(k -> k.getKey().trim(),
v -> v.getValue()[0]));
return mapper.convertValue(stringMap, Callback.class);
}
}

View File

@ -1,19 +0,0 @@
package dev.vality.adapter.common.state.deserializer;
public class DeserializationException extends RuntimeException {
public DeserializationException() {
super();
}
public DeserializationException(String message) {
super(message);
}
public DeserializationException(Throwable cause) {
super(cause);
}
public DeserializationException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -1,9 +0,0 @@
package dev.vality.adapter.common.state.deserializer;
public interface Deserializer<T> {
T read(byte[] data);
T read(String data);
}

View File

@ -1,35 +0,0 @@
package dev.vality.adapter.common.state.deserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.vality.adapter.common.model.RecToken;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.io.IOException;
import java.util.Base64;
@Getter
@Setter
@AllArgsConstructor
public class RecurrentTokenDeserializer implements Deserializer<RecToken> {
private final ObjectMapper mapper;
@Override
public RecToken read(byte[] data) {
throw new DeserializationException("Deserialization not supported");
}
@Override
public RecToken read(String data) {
if (data == null) {
return new RecToken();
}
try {
return getMapper().readValue(Base64.getDecoder().decode(data), RecToken.class);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}

View File

@ -1,12 +0,0 @@
package dev.vality.adapter.common.state.serializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.vality.adapter.common.model.AdapterContext;
public class AdapterSerializer extends StateSerializer<AdapterContext> {
public AdapterSerializer(ObjectMapper mapper) {
super(mapper);
}
}

View File

@ -1,12 +0,0 @@
package dev.vality.adapter.common.state.serializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.vality.adapter.common.model.Callback;
public class CallbackSerializer extends StateSerializer<Callback> {
public CallbackSerializer(ObjectMapper mapper) {
super(mapper);
}
}

View File

@ -1,12 +0,0 @@
package dev.vality.adapter.common.state.serializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.vality.adapter.common.model.RecToken;
public class RecurrentTokenSerializer extends StateSerializer<RecToken> {
public RecurrentTokenSerializer(ObjectMapper mapper) {
super(mapper);
}
}

View File

@ -1,19 +0,0 @@
package dev.vality.adapter.common.state.serializer;
public class SerializationException extends RuntimeException {
public SerializationException() {
super();
}
public SerializationException(String message) {
super(message);
}
public SerializationException(Throwable cause) {
super(cause);
}
public SerializationException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -1,9 +0,0 @@
package dev.vality.adapter.common.state.serializer;
public interface Serializer<T> {
byte[] writeByte(T obj);
String writeString(T obj);
}

View File

@ -1,36 +0,0 @@
package dev.vality.adapter.common.state.serializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.io.IOException;
import java.util.Base64;
@Getter
@Setter
@AllArgsConstructor
public abstract class StateSerializer<T> implements Serializer<T> {
protected final ObjectMapper mapper;
@Override
public byte[] writeByte(Object obj) {
try {
return mapper.writeValueAsBytes(obj);
} catch (IOException e) {
throw new SerializationException(e);
}
}
@Override
public String writeString(Object obj) {
try {
return Base64.getEncoder().encodeToString(getMapper().writeValueAsBytes(obj));
} catch (IOException e) {
throw new SerializationException(e);
}
}
}

View File

@ -1,32 +0,0 @@
package dev.vality.adapter.common.state.utils;
import dev.vality.adapter.common.model.AdapterContext;
import dev.vality.adapter.common.state.deserializer.AdapterDeserializer;
import dev.vality.damsel.proxy_provider.PaymentContext;
import dev.vality.damsel.proxy_provider.RecurrentTokenContext;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class AdapterStateUtils {
public static AdapterContext getAdapterContext(Object context, AdapterDeserializer adapterDeserializer) {
AdapterContext adapterContext = new AdapterContext();
byte[] state = getState(context);
if (state != null && state.length > 0) {
return adapterDeserializer.read(state);
}
return adapterContext;
}
private static byte[] getState(Object context) {
if (context instanceof RecurrentTokenContext) {
if (((RecurrentTokenContext) context).getSession() == null) {
return new byte[0];
}
return ((RecurrentTokenContext) context).getSession().getState();
}
return ((PaymentContext) context).getSession().getState();
}
}

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.converter;
package dev.vality.adapter.common.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

View File

@ -1,6 +1,6 @@
package dev.vality.adapter.common.utils.converter;
package dev.vality.adapter.common.utils;
import dev.vality.adapter.common.utils.cds.model.CardDataProxyModel;
import dev.vality.adapter.common.cds.model.CardDataProxyModel;
import dev.vality.cds.storage.CardData;
import dev.vality.cds.storage.ExpDate;
import dev.vality.damsel.domain.BankCard;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.converter;
package dev.vality.adapter.common.utils;
/**
* @see "https://github.com/dukky/Base62/blob/master/base62/src/im/duk/base62/Base62.java"

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.converter;
package dev.vality.adapter.common.utils;
import dev.vality.cds.storage.SessionData;
import lombok.AccessLevel;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.converter;
package dev.vality.adapter.common.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.encryption;
package dev.vality.adapter.common.utils;
import jakarta.xml.bind.DatatypeConverter;
import lombok.AccessLevel;

View File

@ -1,7 +1,8 @@
package dev.vality.adapter.common.utils.encryption;
package dev.vality.adapter.common.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.springframework.util.MultiValueMap;
@ -23,26 +24,20 @@ public final class HmacEncryption {
return calculateHmac(data, key, HmacAlgorithms.HMAC_SHA_256.getName());
}
@SneakyThrows
public static String calculateHmac(String data, String hexEncodedKey, String algorithm) {
try {
byte[] decodedKey = Hex.decodeHex(hexEncodedKey.toCharArray());
return calculateHmac(data, decodedKey, algorithm);
} catch (Exception ex) {
throw new HmacEncryptionException(ex);
}
}
@SneakyThrows
public static String calculateHmac(String data, byte[] key, String algorithm) {
try {
SecretKeySpec keySpec = new SecretKeySpec(key, algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(keySpec);
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
byte[] resultBytes = mac.doFinal(dataBytes);
return new String(new Hex().encode(resultBytes));
} catch (Exception ex) {
throw new HmacEncryptionException(ex);
}
}
public static String prepareDataForHmac(String[] fields, MultiValueMap<String, String> params) {

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.generator;
package dev.vality.adapter.common.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.converter;
package dev.vality.adapter.common.utils;
import dev.vality.damsel.proxy_provider.PaymentInfo;
import lombok.AccessLevel;

View File

@ -1,7 +1,8 @@
package dev.vality.adapter.common.utils.converter;
package dev.vality.adapter.common.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
@ -9,22 +10,18 @@ import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.util.MultiValueMap;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PostBodyConverter {
@SneakyThrows
public static String getUrlEncodedString(MultiValueMap<String, String> paramsMap) {
FormHttpMessageConverter converter = new FormHttpMessageConverter();
ByteArrayOutputStream os = new ByteArrayOutputStream();
HttpOutputMessage outputMessage = prepareOutputMessage(os);
try {
converter.write(paramsMap, MediaType.APPLICATION_FORM_URLENCODED, outputMessage);
return os.toString();
} catch (IOException e) {
throw new ConverterException(e);
}
}
private static HttpOutputMessage prepareOutputMessage(ByteArrayOutputStream os) {

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.converter;
package dev.vality.adapter.common.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.mapper.naming.strategy;
package dev.vality.adapter.common.utils;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.cfg.MapperConfig;

View File

@ -1,4 +1,4 @@
package dev.vality.adapter.common.utils.damsel.converter;
package dev.vality.adapter.common.utils;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;

View File

@ -1,19 +0,0 @@
package dev.vality.adapter.common.utils.converter;
public class ConverterException extends RuntimeException {
public ConverterException() {
super();
}
public ConverterException(String message) {
super(message);
}
public ConverterException(Throwable cause) {
super(cause);
}
public ConverterException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -1,27 +0,0 @@
package dev.vality.adapter.common.utils.converter;
import dev.vality.adapter.common.enums.PaymentResourceType;
import dev.vality.damsel.proxy_provider.PaymentContext;
import dev.vality.damsel.proxy_provider.PaymentResource;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PaymentResourceTypeResolver {
public static String extractPaymentResourceType(PaymentContext paymentContext) {
if (paymentContext == null) {
throw new IllegalArgumentException("PaymentContext cannot be empty");
} else if (paymentContext.getSession() == null) {
throw new IllegalArgumentException("Payment context session cannot be empty");
}
return extractPaymentResourceType(paymentContext.getPaymentInfo().getPayment().getPaymentResource());
}
public static String extractPaymentResourceType(PaymentResource paymentResource) {
return (paymentResource.isSetRecurrentPaymentResource())
? PaymentResourceType.RECURRENT.name()
: PaymentResourceType.PAYMENT.name();
}
}

View File

@ -1,37 +0,0 @@
package dev.vality.adapter.common.utils.converter;
import dev.vality.adapter.common.enums.TargetStatus;
import dev.vality.adapter.common.exception.UnknownTargetStatusException;
import dev.vality.damsel.domain.TargetInvoicePaymentStatus;
import dev.vality.damsel.proxy_provider.PaymentContext;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class TargetStatusResolver {
public static TargetStatus extractTargetStatus(PaymentContext paymentContext) {
if (paymentContext == null) {
throw new IllegalArgumentException("PaymentContext cannot be empty");
} else if (paymentContext.getSession() == null) {
throw new IllegalArgumentException("Payment context session cannot be empty");
} else {
return extractTargetStatus(paymentContext.getSession().getTarget());
}
}
public static TargetStatus extractTargetStatus(TargetInvoicePaymentStatus targetInvoicePaymentStatus) {
if (targetInvoicePaymentStatus != null) {
if (targetInvoicePaymentStatus.isSetProcessed()) {
return TargetStatus.PROCESSED;
} else if (targetInvoicePaymentStatus.isSetCancelled()) {
return TargetStatus.CANCELLED;
} else if (targetInvoicePaymentStatus.isSetCaptured()) {
return TargetStatus.CAPTURED;
} else if (targetInvoicePaymentStatus.isSetRefunded()) {
return TargetStatus.REFUNDED;
}
}
throw new UnknownTargetStatusException();
}
}

View File

@ -1,16 +0,0 @@
package dev.vality.adapter.common.utils.damsel.constant;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public enum CardHolderName {
NONAME("NONAME"),
UNKNOWN("UNKNOWN");
private final String value;
}

View File

@ -1,19 +0,0 @@
package dev.vality.adapter.common.utils.damsel.constant;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MpiState {
public static final String MPI_STATE = "mpi_state";
public static final String ENABLE = "true";
public static final String DISABLE = "false";
public static boolean isMpiEnabled(Map<String, String> options) {
String mpiState = options.getOrDefault(MpiState.MPI_STATE, MpiState.ENABLE);
return MpiState.ENABLE.equalsIgnoreCase(mpiState);
}
}

View File

@ -1,20 +0,0 @@
package dev.vality.adapter.common.utils.damsel.constant;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PaymentState {
public static final String INIT = "init";
public static final String PAY = "block";
public static final String SLEEP = "sleep";
public static final String CAPTURED = "captured";
public static final String REDIRECT = "redirect";
public static final String PENDING = "pending";
public static final String CANCELLED = "cancelled";
public static final String REFUNDED = "refunded";
public static final String CONFIRM = "confirm";
public static final String RECURRENT_INIT = "recurrent_init";
}

View File

@ -1,12 +0,0 @@
package dev.vality.adapter.common.utils.damsel.constant;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Tag {
public static final String RECURRENT = "REC-";
public static final String PAYMENT = "PAY-";
}

View File

@ -1,19 +0,0 @@
package dev.vality.adapter.common.utils.encryption;
public class HmacEncryptionException extends RuntimeException {
public HmacEncryptionException() {
super();
}
public HmacEncryptionException(String message) {
super(message);
}
public HmacEncryptionException(Throwable cause) {
super(cause);
}
public HmacEncryptionException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -1,20 +0,0 @@
package dev.vality.adapter.common.utils.mpi.constant;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class EciDecodeState {
public static final String ECI_DECODE = "eci_decode_state";
public static final String ENABLED = "true";
public static final String DISABLED = "false";
public static boolean isEnabled(Map<String, String> options) {
String eciDecode = options.getOrDefault(EciDecodeState.ECI_DECODE, EciDecodeState.DISABLED);
return EciDecodeState.ENABLED.equalsIgnoreCase(eciDecode);
}
}

View File

@ -1,19 +0,0 @@
package dev.vality.adapter.common.utils.mpi.exception;
public class ThreeDSecureException extends RuntimeException {
public ThreeDSecureException() {
super();
}
public ThreeDSecureException(String message) {
super(message);
}
public ThreeDSecureException(Throwable cause) {
super(cause);
}
public ThreeDSecureException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -1,21 +0,0 @@
package dev.vality.adapter.common.utils.mpi.model;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Message")
public class Message {
@XmlElement(name = "PARes")
private PaRes paRes;
}

View File

@ -1,21 +0,0 @@
package dev.vality.adapter.common.utils.mpi.model;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "PARes")
public class PaRes {
@XmlElement(name = "TX")
private TX tx;
}

View File

@ -1,21 +0,0 @@
package dev.vality.adapter.common.utils.mpi.model;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "TX")
public class TX {
@XmlElement(name = "eci")
private String eci;
}

View File

@ -1,21 +0,0 @@
package dev.vality.adapter.common.utils.mpi.model;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "ThreeDSecure")
public class ThreeDSecure {
@XmlElement(name = "Message")
private Message message;
}

View File

@ -1,52 +0,0 @@
package dev.vality.adapter.common.utils.mpi.utils;
import dev.vality.adapter.common.utils.mpi.exception.ThreeDSecureException;
import dev.vality.adapter.common.utils.mpi.model.Message;
import dev.vality.adapter.common.utils.mpi.model.PaRes;
import dev.vality.adapter.common.utils.mpi.model.TX;
import dev.vality.adapter.common.utils.mpi.model.ThreeDSecure;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.io.StringReader;
import java.util.Optional;
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ThreeDSecureUtils {
private static JAXBContext jaxbContext;
static {
try {
jaxbContext = JAXBContext.newInstance(ThreeDSecure.class);
} catch (JAXBException ex) {
log.error("Failed to create jaxb context", ex);
throw new RuntimeException("Failed to create jaxb context", ex);
}
}
public static ThreeDSecure extractThreeDSecure(String str) {
try {
Unmarshaller jaxbMarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(str);
return (ThreeDSecure) jaxbMarshaller.unmarshal(reader);
} catch (JAXBException ex) {
log.error("Can't extract ThreeDSecure", ex);
throw new ThreeDSecureException(ex);
}
}
public static String extractEciFromPaRes(ThreeDSecure threeDSecure) {
return Optional.ofNullable(threeDSecure)
.map(ThreeDSecure::getMessage)
.map(Message::getPaRes)
.map(PaRes::getTx)
.map(TX::getEci).orElse("");
}
}

View File

@ -1,45 +0,0 @@
package dev.vality.adapter.common.utils.mpi.utils;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.zip.Inflater;
@Slf4j
public class UncompressDecoder {
private static final int START_OFFSET_IN_DATA = 0;
public static String decodePaRes(String str) {
return UncompressDecoder.decode(str);
}
public static String decode(String str) {
byte[] decode = Base64.getDecoder().decode(str.getBytes());
return new String(gzuncompress(decode));
}
private static byte[] gzuncompress(byte[] data) {
byte[] unCompressed = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
Inflater deCompressor = new Inflater();
try {
deCompressor.setInput(data);
final byte[] buf = new byte[1024];
while (!deCompressor.finished()) {
int count = deCompressor.inflate(buf);
bos.write(buf, START_OFFSET_IN_DATA, count);
}
unCompressed = bos.toByteArray();
bos.close();
} catch (Exception e) {
log.error("UnCompress Exception", e);
} finally {
deCompressor.end();
}
return unCompressed;
}
}

Some files were not shown because too many files have changed in this diff Show More