PROX-34: Made a sketch of the skeleton of the application (#1)

* PROX-34: Made a sketch of the skeleton of the application

* PROX-34: uncomment Ignore

* PROX-34: uncomment card

* PROX-34: removed snapshot
This commit is contained in:
Anatoly Cherkasov 2016-12-15 13:14:13 +03:00 committed by GitHub
parent 79e813dadb
commit 23d3d5ec9c
58 changed files with 4031 additions and 1 deletions

53
.gitignore vendored Normal file
View File

@ -0,0 +1,53 @@
# Created by .ignore support plugin (hsz.mobi)
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
*.DS_Store
*.iml
## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:
# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml
# Gradle:
# .idea/gradle.xml
# .idea/libraries
# Mongo Explorer plugin:
# .idea/mongoSettings.xml
## File-based project format:
*.ipr
*.iws
## Plugin-specific files:
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
# Target folder
target

4
.gitmodules vendored Normal file
View File

@ -0,0 +1,4 @@
[submodule "build_utils"]
path = build_utils
url = git@github.com:rbkmoney/build_utils.git
branch = master

20
Dockerfile Normal file
View File

@ -0,0 +1,20 @@
FROM dr.rbkmoney.com/rbkmoney/service-java:@dockerfile.base.service.tag@
MAINTAINER Anatoly Cherkasov <a.cherkasov@rbkmoney.com>
COPY @artifactId@-@version@.jar /opt/@artifactId@/@artifactId@.jar
COPY containerpilot.json /etc/containerpilot.json
ENTRYPOINT ["/bin/containerpilot", "-config", "file:///etc/containerpilot.json", "java"]
CMD ["-Xmx512m", "-jar","/opt/@artifactId@/@artifactId@.jar"]
EXPOSE @server.port@
EXPOSE 8080
LABEL com.rbkmoney.@artifactId@.parent=service_java \
com.rbkmoney.@artifactId@.parent_tag=@dockerfile.base.service.tag@ \
com.rbkmoney.@artifactId@.build_img=build \
com.rbkmoney.@artifactId@.build_img_tag=@dockerfile.build.container.tag@ \
com.rbkmoney.@artifactId@.commit_id=@git.revision@ \
com.rbkmoney.@artifactId@.commit_number=@git.commitsCount@ \
com.rbkmoney.@artifactId@.branch=@git.branch@
WORKDIR /opt/@artifactId@

16
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,16 @@
#!groovy
build('proxy-test', 'docker-host') {
checkoutRepo()
loadBuildUtils()
def pipeJavaService
runStage('load Java Service pipeline') {
pipeJavaService = load('build_utils/jenkins_lib/pipeJavaService.groovy')
}
def serviceName = "proxy-test"
def baseImageTag = "f26fcc19d1941ab74f1c72dd8a408be17a769333"
def buildImageTag = "80c38dc638c0879687f6661f4e16e8de9fc0d2c6"
def dbHostName = null
def mvnArgs = '-DjvmArgs="-Xmx256m"'
pipeJavaService(serviceName, baseImageTag, buildImageTag, dbHostName, mvnArgs)
}

View File

@ -1 +1,17 @@
# proxy-test
# Proxy Test
[![Build Status](http://ci.rbkmoney.com/buildStatus/icon?job=rbkmoney_private/proxy_test/master)](http://ci.rbkmoney.com/job/rbkmoney_private/job/proxy_test/job/master/)
Сервис предназначен для эмулирования запросов между процессингом и банковском
### Developers
- [Anatoly Cherkasov](https://github.com/avcherkasov)
### Оглавление:
1. [Техническая документация](docs/tech.md)
1. [Полезные ссылки](docs/useful_links.md)
1. [FAQ](docs/faq.md)

1
build_utils Submodule

@ -0,0 +1 @@
Subproject commit 0a57c5f10795d77ecf121d509fde7c654175c3c1

13
containerpilot.json Normal file
View File

@ -0,0 +1,13 @@
{
"consul": "{{ .CONSUL_ADDR }}",
"services": [
{
"name": "{{ .SERVICE_NAME }}",
"port": "@server.port@",
"health": "/usr/bin/curl --silent --fail --show-error --output /dev/null localhost:@server.port@/health",
"poll": 1,
"ttl": 2,
"interfaces": ["inte6", "inet"]
}
]
}

15
docs/faq.md Normal file
View File

@ -0,0 +1,15 @@
# Proxy Test
## FAQ
Вопросы для обсуждения и ряд полученных ответов на них:
`Вопрос:`
> Описание вопроса
`Ответ:`
Описание ответа
---

3
docs/tech.md Normal file
View File

@ -0,0 +1,3 @@
# Proxy Test
## Техническая документация

46
docs/useful_links.md Normal file
View File

@ -0,0 +1,46 @@
# Proxy Test
## Полезные ссылки
### Java
- [Официальная страница](http://www.oracle.com/technetwork/java/index.html)
- [Страница загрузки](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)
### Maven
- [Официальная страница](https://maven.apache.org/)
- [Maven repository](http://mvnrepository.com/)
### Thrift
- [Официальная страница](https://thrift.apache.org)
- [thrift](https://github.com/rbkmoney/thrift)
### Woody Thrift
- [woody_java](https://github.com/rbkmoney/woody_java)
### Damsel
- [damsel](https://github.com/rbkmoney/damsel)
### CDS
- [cds](https://github.com/rbkmoney/cds)
### Hellgate
- [hellgate](https://github.com/rbkmoney/hellgate)
### Docker
- [Официальная страница](https://www.docker.com/)

110
pom.xml Normal file
View File

@ -0,0 +1,110 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.rbkmoney</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<relativePath/>
</parent>
<artifactId>proxy-test</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>proxy-test</name>
<description>Проксик для тестирования и эмуляции запросов к банку</description>
<properties>
<server.port>8022</server.port>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--Thrirdparty libs-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>4.6</version>
</dependency>
<!--RBK libs-->
<dependency>
<groupId>com.rbkmoney.logback</groupId>
<artifactId>nop-rolling</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.rbkmoney.woody</groupId>
<artifactId>woody-thrift</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>com.rbkmoney</groupId>
<artifactId>damsel</artifactId>
<version>1.99-557f549</version>
</dependency>
<!--Test libs-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>${project.basedir}</directory>
<targetPath>${project.build.directory}</targetPath>
<includes>
<include>Dockerfile</include>
<include>containerpilot.json</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,13 @@
package com.rbkmoney.proxy.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@SpringBootApplication(scanBasePackages = {"com.rbkmoney.proxy.test"})
public class ProxyTestApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(ProxyTestApplication.class, args);
}
}

View File

@ -0,0 +1,45 @@
package com.rbkmoney.proxy.test.configuration;
import com.rbkmoney.damsel.cds.KeyringSrv;
import com.rbkmoney.woody.api.ClientBuilder;
import com.rbkmoney.woody.api.event.ClientEventListener;
import com.rbkmoney.woody.api.event.CompositeClientEventListener;
import com.rbkmoney.woody.thrift.impl.http.THSpawnClientBuilder;
import com.rbkmoney.woody.thrift.impl.http.event.ClientEventLogListener;
import com.rbkmoney.woody.thrift.impl.http.event.HttpClientEventLogListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import java.io.IOException;
@Configuration
public class CdsKeyringConfiguration {
@Value("${cds.url.keyring}")
private Resource resource;
@Bean
public KeyringSrv.Iface keyringSrv(ClientEventListener listenerSrv) throws IOException {
return clientBuilder()
.withEventListener(listenerSrv)
.withAddress(resource.getURI())
.build(KeyringSrv.Iface.class);
}
@Bean
@ConditionalOnMissingBean
public ClientEventListener listenerSrv() {
return new CompositeClientEventListener(
new ClientEventLogListener(),
new HttpClientEventLogListener()
);
}
@Bean(name = "clientBuilderKeyring")
public ClientBuilder clientBuilder() {
return new THSpawnClientBuilder();
}
}

View File

@ -0,0 +1,45 @@
package com.rbkmoney.proxy.test.configuration;
import com.rbkmoney.damsel.cds.StorageSrv;
import com.rbkmoney.woody.api.ClientBuilder;
import com.rbkmoney.woody.api.event.ClientEventListener;
import com.rbkmoney.woody.api.event.CompositeClientEventListener;
import com.rbkmoney.woody.thrift.impl.http.THSpawnClientBuilder;
import com.rbkmoney.woody.thrift.impl.http.event.ClientEventLogListener;
import com.rbkmoney.woody.thrift.impl.http.event.HttpClientEventLogListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import java.io.IOException;
@Configuration
public class CdsStorageConfiguration {
@Value("${cds.url.storage}")
private Resource resource;
@Bean
public StorageSrv.Iface storageSrv(ClientEventListener listenerSrv) throws IOException {
return clientBuilder()
.withEventListener(listenerSrv)
.withAddress(resource.getURI())
.build(StorageSrv.Iface.class);
}
@Bean
@ConditionalOnMissingBean
public ClientEventListener listenerSrv() {
return new CompositeClientEventListener(
new ClientEventLogListener(),
new HttpClientEventLogListener()
);
}
@Bean(name = "clientBuilderStorage")
public ClientBuilder clientBuilder() {
return new THSpawnClientBuilder();
}
}

View File

@ -0,0 +1,46 @@
package com.rbkmoney.proxy.test.configuration;
import com.rbkmoney.damsel.proxy_provider.ProviderProxyHostSrv;
import com.rbkmoney.woody.api.ClientBuilder;
import com.rbkmoney.woody.api.event.ClientEventListener;
import com.rbkmoney.woody.api.event.CompositeClientEventListener;
import com.rbkmoney.woody.thrift.impl.http.THSpawnClientBuilder;
import com.rbkmoney.woody.thrift.impl.http.event.ClientEventLogListener;
import com.rbkmoney.woody.thrift.impl.http.event.HttpClientEventLogListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import java.io.IOException;
@Configuration
public class HellGateConfiguration {
@Value("${hellgate.url}")
private Resource resource;
@Bean
public ProviderProxyHostSrv.Iface providerProxyHost(ClientEventListener listenerSrv) throws IOException {
return clientBuilder()
.withEventListener(listenerSrv)
.withAddress(resource.getURI())
.build(ProviderProxyHostSrv.Iface.class);
}
@Bean
@ConditionalOnMissingBean
public ClientEventListener listenerSrv() {
return new CompositeClientEventListener(
new ClientEventLogListener(),
new HttpClientEventLogListener()
);
}
@Bean(name = "clientBuilderHellgate")
public ClientBuilder clientBuilder() {
return new THSpawnClientBuilder();
}
}

View File

@ -0,0 +1,49 @@
package com.rbkmoney.proxy.test.configuration;
import org.eclipse.jetty.server.NetworkTrafficServerConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.jetty.JettyServerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
public class JettyEmbeddedConfiguration {
private final static Logger LOGGER = LoggerFactory.getLogger(JettyEmbeddedConfiguration.class);
@Value("${server.port}")
private String mainPort;
@Value("#{'${server.secondary.ports}'.split(',')}")
private List<String> secondaryPorts;
@Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
final JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory(Integer.valueOf(mainPort));
// Add customized Jetty configuration with non blocking connection handler
factory.addServerCustomizers((JettyServerCustomizer) server -> {
// Register an additional connector for each secondary port.
for(final String secondaryPort : secondaryPorts) {
final NetworkTrafficServerConnector connector = new NetworkTrafficServerConnector(server);
connector.setPort(Integer.valueOf(secondaryPort));
try {
connector.join();
} catch (InterruptedException e) {
LOGGER.error("Exception in JettyConfiguration", e);
}
server.addConnector(connector);
}
// Additional configuration
});
return factory;
}
}

View File

@ -0,0 +1,48 @@
package com.rbkmoney.proxy.test.configuration;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
@Configuration
public class RestTemplateConfiguration {
@Bean
SSLContext sslContext() throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
return new SSLContextBuilder()
.loadTrustMaterial((x509Certificates, s) -> true)
.build();
}
@Bean
CloseableHttpClient httpClient(SSLContext sslContext) {
return HttpClients.custom()
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(sslContext)
.build();
}
@Bean
HttpComponentsClientHttpRequestFactory requestFactory(CloseableHttpClient httpClient) {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return requestFactory;
}
@Bean
RestTemplate restTemplate(HttpComponentsClientHttpRequestFactory requestFactory) {
return new RestTemplate(requestFactory);
}
}

View File

@ -0,0 +1,61 @@
package com.rbkmoney.proxy.test.controller;
import com.rbkmoney.proxy.test.utils.Converter;
import com.rbkmoney.proxy.test.utils.hellgate.HellGateApi;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Optional;
@RestController
@RequestMapping(value = "/test")
public class TestController {
private final static Logger LOGGER = LoggerFactory.getLogger(TestController.class);
@Autowired
HellGateApi hellGateApi;
@RequestMapping(value = "term_url", method = RequestMethod.POST)
public String receiveIncomingParameters(HttpServletRequest request, HttpServletResponse servletResponse) throws IOException {
String tag = "";
ByteBuffer callback = null;
String resp = "";
try {
callback = Converter.mapToByteBuffer(Converter.mapArrayToMap(request.getParameterMap()));
} catch (IOException e) {
LOGGER.error("Exception Map to ByteBuffer in processCallback", e);
}
if (Optional.ofNullable(request.getParameter("MD")).isPresent()) {
tag = request.getParameter("MD");
} else {
LOGGER.error("Missing a required parameter 'MD' ");
}
try {
ByteBuffer response = hellGateApi.processCallback(tag, callback);
resp = new String(response.array(), "UTF-8");
} catch (TException | UnsupportedEncodingException e) {
LOGGER.error("Exception in processCallback", e);
}
if (!request.getParameter("termination_uri").isEmpty())
servletResponse.sendRedirect(request.getParameter("termination_uri"));
return resp;
}
}

View File

@ -0,0 +1,320 @@
package com.rbkmoney.proxy.test.handler;
import com.rbkmoney.damsel.base.TryLater;
import com.rbkmoney.damsel.cds.CardData;
import com.rbkmoney.damsel.domain.TransactionInfo;
import com.rbkmoney.damsel.proxy.Intent;
import com.rbkmoney.damsel.proxy_provider.*;
import com.rbkmoney.proxy.test.utils.CardUtils;
import com.rbkmoney.proxy.test.utils.Converter;
import com.rbkmoney.proxy.test.utils.cds.CdsApi;
import com.rbkmoney.proxy.test.utils.damsel.*;
import com.rbkmoney.proxy.test.utils.model.Card;
import com.rbkmoney.proxy.test.utils.testmpi.TestMpiApi;
import com.rbkmoney.proxy.test.utils.testmpi.TestMpiUtils;
import com.rbkmoney.proxy.test.utils.testmpi.constant.TestMpiAction;
import com.rbkmoney.proxy.test.utils.testmpi.constant.TestMpiEnrollmentStatus;
import com.rbkmoney.proxy.test.utils.testmpi.constant.TestMpiTransactionStatus;
import com.rbkmoney.proxy.test.utils.testmpi.model.ValidatePaResResponse;
import com.rbkmoney.proxy.test.utils.testmpi.model.VerifyEnrollmentResponse;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import static com.rbkmoney.proxy.test.utils.testmpi.constant.TestMpiAction.*;
@Component
public class TestServerHandler implements ProviderProxySrv.Iface {
private final static Logger LOGGER = LoggerFactory.getLogger(TestServerHandler.class);
private Map<String, String> options;
@Autowired
private CdsApi cds;
@Autowired
TestMpiApi testMpiApi;
@Value("${proxy-test.callbackUrl}")
private String callbackUrl;
@Value("${fixture.cards}")
private Resource fixtureCards;
@Value("${timer.timeout}")
private int timerTimeout;
private List<Card> cardList;
@PostConstruct
public void init() throws IOException {
cardList = CardUtils.getCardListFromFile(fixtureCards.getInputStream());
}
@Override
public ProxyResult processPayment(Context context) throws TryLater, TException {
options = (context.getOptions().size() > 0) ? context.getOptions() : new HashMap<>();
Target target = context.getSession().getTarget();
if (target.isSetProcessed()) {
return processed(context);
} else if (target.isSetCaptured()) {
return captured(context);
} else if (target.isSetCancelled()) {
return cancelled(context);
} else {
LOGGER.error("Error unsupported method");
return ProxyProviderWrapper.makeProxyResultFailure("Unsupported method", "Unsupported method");
}
}
private ProxyResult processed(Context context) {
LOGGER.info("processed start");
com.rbkmoney.damsel.proxy_provider.InvoicePayment invoicePayment = context.getPayment().getPayment();
String session = invoicePayment.getPayer().getSession();
String token = invoicePayment.getPayer().getPaymentTool().getBankCard().getToken();
CardData cardData;
TransactionInfo transactionInfo = null;
com.rbkmoney.damsel.proxy.Intent intent = ProxyWrapper.makeFinishIntentOk();
try {
LOGGER.info("Call CDS in processPayment. Token {}, session: {}", token, session);
cardData = cds.getSessionCardData(token, session);
} catch (TException e) {
LOGGER.error("CDS Exception in processPayment", e);
return ProxyProviderWrapper.makeProxyResultFailure("CDS Exception in processPayment", e.getMessage());
}
CardUtils cardUtils = new CardUtils(cardList);
Optional<Card> card = cardUtils.getCardByPan(cardData.getPan());
if (card.isPresent()) {
TestMpiAction action = TestMpiAction.findByValue(card.get().getAction());
if (!cardUtils.isEnrolled(card)) {
String error = null;
switch (action) {
case INCUFFICIENT_FUNDS:
error = INCUFFICIENT_FUNDS.getAction();
break;
case INVALID_CARD:
error = INVALID_CARD.getAction();
break;
case CVV_MATCH_FAIL:
error = CVV_MATCH_FAIL.getAction();
break;
case EXPIRED_CARD:
error = EXPIRED_CARD.getAction();
break;
case SUCCESS:
transactionInfo = DomainWrapper.makeTransactionInfo(
TestMpiUtils.generateInvoice(context.getPayment()),
Collections.emptyMap()
);
return ProxyProviderWrapper.makeProxyResult(
intent,
"captured".getBytes(),
transactionInfo
);
default:
error = UNKNOWN_FAILURE.getAction();
}
return ProxyProviderWrapper.makeProxyResultFailure(
error,
error
);
}
} else {
return ProxyProviderWrapper.makeProxyResultFailure(
UNSUPPORTED_CARD.getAction(),
UNSUPPORTED_CARD.getAction()
);
}
VerifyEnrollmentResponse verifyEnrollmentResponse = null;
try {
verifyEnrollmentResponse = testMpiApi.verifyEnrollment(
cardData.getPan(),
cardData.getExpDate().getYear(),
cardData.getExpDate().getMonth()
);
} catch (IOException e) {
LOGGER.error("Exception in verifyEnrollment", e);
return ProxyProviderWrapper.makeProxyResultFailure(
UNKNOWN_FAILURE.getAction(),
UNKNOWN_FAILURE.getAction()
);
}
if (verifyEnrollmentResponse.getEnrolled().equals(TestMpiEnrollmentStatus.AUTHENTICATION_AVAILABLE)) {
String tag = "MPI-" + TestMpiUtils.generateInvoice(context.getPayment());
// Prepare response
String url = verifyEnrollmentResponse.getAcsUrl();
Map<String, String> params = new HashMap<>();
params.put("PaReq", verifyEnrollmentResponse.getPaReq());
params.put("MD", tag);
params.put("TermUrl", TestMpiUtils.getCallbackUrl(callbackUrl, "/test/term_url{?termination_uri}"));
intent = ProxyWrapper.makeIntentWithSuspendIntent(
tag, BaseWrapper.makeTimerTimeout(timerTimeout),
UserInteractionWrapper.makeUserInteraction(
UserInteractionWrapper.makeBrowserPostRequest(
url,
params
)
)
);
}
Map<String, String> extra = new HashMap<>();
extra.put(TestMpiUtils.PA_REQ, verifyEnrollmentResponse.getPaReq());
LOGGER.info("Extra map {}", extra);
byte[] state;
try {
state = Converter.mapToByteArray(extra);
} catch (IOException e) {
LOGGER.error("Converter Exception in processPayment", e);
return ProxyProviderWrapper.makeProxyResultFailure("Converter", e.getMessage());
}
return ProxyProviderWrapper.makeProxyResult(intent, state, transactionInfo);
}
private ProxyResult captured(Context context) {
LOGGER.info("captured start");
com.rbkmoney.damsel.proxy_provider.InvoicePayment payment = context.getPayment().getPayment();
TransactionInfo transactionInfoContractor = payment.getTrx();
TransactionInfo transactionInfo = DomainWrapper.makeTransactionInfo(
transactionInfoContractor.getId(),
transactionInfoContractor.getExtra()
);
context.getSession().setState("confirm".getBytes());
Intent intent = ProxyWrapper.makeFinishIntentOk();
LOGGER.info("capturePayment finish");
return ProxyProviderWrapper.makeProxyResult(intent, "confirm".getBytes(), transactionInfo);
}
private ProxyResult cancelled(Context context) {
return ProxyProviderWrapper.makeProxyResultFailure("Unsupported method CANCEL", "Unsupported method CANCEL");
}
@Override
public CallbackResult handlePaymentCallback(ByteBuffer byteBuffer, Context context) throws TryLater, TException {
LOGGER.info("handlePaymentCallback start");
InvoicePayment invoicePayment = context.getPayment().getPayment();
options = context.getOptions();
HashMap<String, String> parameters;
// Merge parameters
try {
parameters = (HashMap<String, String>) Converter.byteArrayToMap(context.getSession().getState());
parameters.putAll(Converter.byteBufferToMap(byteBuffer));
} catch (Exception e) {
LOGGER.error("Parse ByteBuffer Exception in handlePaymentCallback", e);
return ProxyProviderWrapper.makeCallbackResultFailure(
"error".getBytes(),
"Parse ByteBuffer Exception in handlePaymentCallback",
e.getMessage()
);
}
CardData cardData;
try {
LOGGER.info("CDS: handlePaymentCallback get Card Data");
cardData = cds.getSessionCardData(
invoicePayment.getPayer().getPaymentTool().getBankCard().getToken(),
invoicePayment.getPayer().getSession()
);
} catch (TException e) {
LOGGER.error("CDS Exception in handlePaymentCallback", e);
return ProxyProviderWrapper.makeCallbackResultFailure(
"error".getBytes(),
"CDS Exception in handlePaymentCallback",
e.getMessage()
);
}
ValidatePaResResponse validatePaResResponse;
try {
validatePaResResponse = testMpiApi.validatePaRes(cardData.getPan(), parameters.get("paRes"));
} catch (IOException e) {
LOGGER.error("Exception in handlePaymentCallback", e);
return ProxyProviderWrapper.makeCallbackResultFailure(
"error".getBytes(),
"Exception in handlePaymentCallback",
e.getMessage()
);
}
LOGGER.info("validatePaResResponse {}", validatePaResResponse);
if (validatePaResResponse.getTransactionStatus().equals(TestMpiTransactionStatus.AUTHENTICATION_SUCCESSFUL)) {
byte[] callbackResponse = new byte[0];
com.rbkmoney.damsel.proxy.Intent intent = ProxyWrapper.makeFinishIntentOk();
TransactionInfo transactionInfo = DomainWrapper.makeTransactionInfo(
TestMpiUtils.generateInvoice(context.getPayment()),
Collections.emptyMap()
);
return ProxyProviderWrapper.makeCallbackResult(
callbackResponse,
ProxyProviderWrapper.makeProxyResult(
intent, "captured".getBytes(), transactionInfo
)
);
}
CardUtils cardUtils = new CardUtils(cardList);
Optional<Card> card = cardUtils.getCardByPan(cardData.getPan());
TestMpiAction action = TestMpiAction.findByValue(card.get().getAction());
String error;
switch (action) {
case THREE_D_SECURE_FAILURE:
error = THREE_D_SECURE_FAILURE.getAction();
break;
case THREE_D_SECURE_TIMEOUT:
error = THREE_D_SECURE_TIMEOUT.getAction();
break;
default:
error = UNKNOWN_FAILURE.getAction();
}
LOGGER.info("handlePaymentCallback finish");
return ProxyProviderWrapper.makeCallbackResultFailure(
"error".getBytes(),
"Exception in handlePaymentCallback",
error
);
}
}

View File

@ -0,0 +1,39 @@
package com.rbkmoney.proxy.test.servlet;
import com.rbkmoney.damsel.proxy_provider.ProviderProxySrv;
import com.rbkmoney.proxy.test.handler.TestServerHandler;
import com.rbkmoney.woody.api.event.CompositeServiceEventListener;
import com.rbkmoney.woody.thrift.impl.http.THServiceBuilder;
import com.rbkmoney.woody.thrift.impl.http.event.HttpServiceEventLogListener;
import com.rbkmoney.woody.thrift.impl.http.event.ServiceEventLogListener;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/proxy/test")
public class ProxyServlet extends GenericServlet {
@Autowired
private TestServerHandler handler;
private Servlet servlet;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
THServiceBuilder builder = new THServiceBuilder();
builder.withEventListener(new CompositeServiceEventListener<>(
new ServiceEventLogListener(),
new HttpServiceEventLogListener()
));
servlet = builder.build(ProviderProxySrv.Iface.class, handler);
}
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
servlet.service(request, response);
}
}

View File

@ -0,0 +1,54 @@
package com.rbkmoney.proxy.test.utils;
import com.rbkmoney.proxy.test.utils.model.Card;
import com.rbkmoney.proxy.test.utils.testmpi.constant.TestMpiAction;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CardUtils {
List<Card> cardList = Collections.emptyList();
public CardUtils(List<Card> cardList) {
this.cardList = cardList;
}
public static List<Card> getCardListFromFile(InputStream is) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
return br.lines().skip(1).map(mapToCard).collect(Collectors.toList());
}
private static Function<String, Card> mapToCard = (line) -> {
String[] p = line.split(", ");
return new Card(p[0], p[1], p[2]);
};
public Optional<Card> getCardByPan(String pan) {
return cardList.stream().filter(card -> card.getPan().equals(pan)).findFirst();
}
public boolean isEnrolled(Optional<Card> card) {
boolean result = false;
if (card.isPresent()) {
TestMpiAction action = TestMpiAction.findByValue(card.get().getAction());
switch (action) {
case THREE_D_SECURE_FAILURE:
case THREE_D_SECURE_TIMEOUT:
case THREE_D_SECURE_SUCCESS:
result = true;
break;
default:
result = false;
}
}
return result;
}
}

View File

@ -0,0 +1,50 @@
package com.rbkmoney.proxy.test.utils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class Converter {
public static Map<String, String> byteBufferToMap(ByteBuffer byteBuffer) throws IOException {
return new ObjectMapper().readValue(
new String(byteBuffer.array(), "UTF-8"),
new TypeReference<Map<String, String>>() {
}
);
}
public static ByteBuffer mapToByteBuffer(Map<String, String> map) throws IOException {
return ByteBuffer.wrap(new ObjectMapper().writeValueAsString(map).getBytes());
}
public static Map<String, String> mapArrayToMap(Map<String, String[]> map) {
if (!Optional.ofNullable(map).isPresent()) {
return new HashMap<>();
}
Map<String, String> newMap = new HashMap<>();
map.forEach((K, V) -> newMap.put(K.trim(), V[0]));
return newMap;
}
// Convert Map to byte array
public static byte[] mapToByteArray(Map<String, String> map) throws IOException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(map);
return byteOut.toByteArray();
}
// Parse byte array to Map
public static Map<String, String> byteArrayToMap(byte[] data) throws IOException, ClassNotFoundException {
ByteArrayInputStream byteIn = new ByteArrayInputStream(data);
ObjectInputStream in = new ObjectInputStream(byteIn);
return (Map<String, String>) in.readObject();
}
}

View File

@ -0,0 +1,92 @@
package com.rbkmoney.proxy.test.utils.cds;
import com.rbkmoney.damsel.cds.*;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.nio.ByteBuffer;
import java.util.List;
@Component
public class CdsApi {
private final static Logger LOGGER = LoggerFactory.getLogger(CdsApi.class);
@Autowired
private KeyringSrv.Iface keyringSrv;
@Autowired
private StorageSrv.Iface storageSrv;
/**
* Разблокировать ключи
*
* @param key_share ByteBuffer
* @return UnlockStatus
* @throws TException
*/
public UnlockStatus unlock(ByteBuffer key_share) throws TException {
LOGGER.info("Keyring: unlock");
return keyringSrv.unlock(key_share);
}
/**
* Инициализация ключей
*
* @param threshold short
* @param num_shares short
* @return List<ByteBuffer>
* @throws TException
*/
public List<ByteBuffer> init(short threshold, short num_shares) throws TException {
LOGGER.info("Keyring: init");
return keyringSrv.init(threshold, num_shares);
}
/**
* Получить карточные данные без CVV
*
* @param token String
* @return CardData
* @throws TException
*/
public CardData getCardData(String token) throws TException {
LOGGER.info("Storage getCardData: token {}", token);
CardData cardData = storageSrv.getCardData(token);
LOGGER.info("Storage getCardData: response {}", cardData.toString());
return cardData;
}
/**
* Получить карточные данные с CVV
*
* @param token String
* @param session String
* @return CardData
* @throws TException
*/
public CardData getSessionCardData(String token, String session) throws TException {
LOGGER.info("Storage getSessionCardData: token {}, session{} ", token, session);
CardData cardData = storageSrv.getSessionCardData(token, session);
LOGGER.info("Storage getSessionCardData: response {}", cardData.toString());
return cardData;
}
/**
* Положить карточные данные
*
* @param cardData CardData
* @return PutCardDataResult
* @throws TException
*/
public PutCardDataResult putCardData(CardData cardData) throws TException {
LOGGER.info("Storage putCardData: cardData {} ", cardData);
PutCardDataResult result = storageSrv.putCardData(cardData);
LOGGER.info("Storage putCardData: response {}", result.toString());
return result;
}
}

View File

@ -0,0 +1,59 @@
package com.rbkmoney.proxy.test.utils.damsel;
import com.rbkmoney.damsel.base.*;
import com.rbkmoney.damsel.base.Error;
import java.nio.ByteBuffer;
public class BaseWrapper {
public static Content makeContent(String type, byte[] data) {
Content content = new Content();
content.setType(type);
content.setData(data);
return content;
}
public static Content makeContent(String type, ByteBuffer data) {
Content content = new Content();
content.setType(type);
content.setData(data);
return content;
}
public static Rational makeRational(long p, long q) {
Rational rational = new Rational();
rational.setP(p);
rational.setQ(q);
return rational;
}
public static Error makeError(String code, String description) {
Error error = new Error();
error.setCode(code);
error.setDescription(description);
return error;
}
public static Error makeError(String code) {
return BaseWrapper.makeError(code, null);
}
public static Timer makeTimerDeadLine(String deadLine) {
Timer timer = new Timer();
timer.setDeadline(deadLine);
return timer;
}
public static Timer makeTimerTimeout(int timeout) {
Timer timer = new Timer();
timer.setTimeout(timeout);
return timer;
}
public static Ok makeOk() {
return new Ok();
}
}

View File

@ -0,0 +1,50 @@
package com.rbkmoney.proxy.test.utils.damsel;
import com.rbkmoney.damsel.cds.CardData;
import com.rbkmoney.damsel.cds.ExpDate;
import com.rbkmoney.damsel.cds.PutCardDataResult;
import com.rbkmoney.damsel.cds.UnlockStatus;
import com.rbkmoney.damsel.domain.BankCard;
public class CdsWrapper {
public static ExpDate makeExpDate(byte month, short year) {
ExpDate expDate = new ExpDate();
expDate.setMonth(month);
expDate.setYear(year);
return expDate;
}
public static CardData makeCardData(String cardholderName, String cvv, String pan, ExpDate expDate) {
CardData cardData = new CardData();
cardData.setCardholderName(cardholderName);
cardData.setCvv(cvv);
cardData.setPan(pan);
cardData.setExpDate(expDate);
return cardData;
}
public static CardData makeCardDataWithExpDate(String cardholderName, String cvv, String pan, byte month, short year) {
return CdsWrapper.makeCardData(cardholderName, cvv, pan, CdsWrapper.makeExpDate(month, year));
}
public static PutCardDataResult makePutCardDataResult(BankCard bankCard, String session) {
PutCardDataResult putCardDataResult = new PutCardDataResult();
putCardDataResult.setBankCard(bankCard);
putCardDataResult.setSession(session);
return putCardDataResult;
}
public static UnlockStatus makeUnlockStatusOk() {
UnlockStatus unlockStatus = new UnlockStatus();
unlockStatus.setOk(BaseWrapper.makeOk());
return unlockStatus;
}
public static UnlockStatus makeUnlockStatusMoreKeysNeeded(short value) {
UnlockStatus unlockStatus = new UnlockStatus();
unlockStatus.setMoreKeysNeeded(value);
return unlockStatus;
}
}

View File

@ -0,0 +1,73 @@
package com.rbkmoney.proxy.test.utils.damsel;
import com.rbkmoney.damsel.domain.DomainObject;
import com.rbkmoney.damsel.domain_config.*;
import java.util.List;
import java.util.Map;
public class DomainConfigWrapper {
public static InsertOp makeInsertOp(DomainObject domainObject) {
InsertOp insertOp = new InsertOp();
insertOp.setObject(domainObject);
return insertOp;
}
public static UpdateOp makeUpdateOp(DomainObject newObject, DomainObject oldObject) {
UpdateOp updateOp = new UpdateOp();
updateOp.setNewObject(newObject);
updateOp.setOldObject(oldObject);
return updateOp;
}
public static RemoveOp makeRemoveOp(DomainObject domainObject) {
RemoveOp removeOp = new RemoveOp();
removeOp.setObject(domainObject);
return removeOp;
}
public static Operation makeOperationInsert(DomainObject domainObject) {
return Operation.insert(DomainConfigWrapper.makeInsertOp(domainObject));
}
public static Operation makeOperationUpdate(DomainObject newObject, DomainObject oldObject) {
return Operation.update(DomainConfigWrapper.makeUpdateOp(newObject, oldObject));
}
public static Operation makeOperationRemove(DomainObject domainObject) {
return Operation.remove(DomainConfigWrapper.makeRemoveOp(domainObject));
}
public static com.rbkmoney.damsel.domain_config.Reference makeReferenceHead() {
Reference reference = new Reference();
reference.setHead(DomainConfigWrapper.makeHead());
return reference;
}
public static com.rbkmoney.damsel.domain_config.Reference makeReferenceVersion(long version) {
Reference reference = new Reference();
reference.setVersion(version);
return reference;
}
public static Head makeHead() {
return new Head();
}
public static Commit makeCommit(List<Operation> operations) {
Commit commit = new Commit();
commit.setOps(operations);
return commit;
}
public static Snapshot makeSnapshot(long version, Map<com.rbkmoney.damsel.domain.Reference, DomainObject> domain) {
Snapshot snapshot = new Snapshot();
snapshot.setVersion(version);
snapshot.setDomain(domain);
return snapshot;
}
}

View File

@ -0,0 +1,504 @@
package com.rbkmoney.proxy.test.utils.damsel;
import com.rbkmoney.damsel.base.Rational;
import com.rbkmoney.damsel.domain.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DomainWrapper {
public static Cash makeCash(Currency currency, Long amount) {
Cash cash = new Cash();
cash.setAmount(amount);
cash.setCurrency(currency);
return cash;
}
public static Currency makeCurrency(String name, short numericCode, String SymbolicCode, short exponent) {
Currency currency = new Currency();
currency.setName(name);
currency.setNumericCode(numericCode);
currency.setSymbolicCode(SymbolicCode);
currency.setExponent(exponent);
return currency;
}
public static BankCard makeBankCard(String bin, String maskedPan, String token, BankCardPaymentSystem bankCardPaymentSystem) {
BankCard bankCard = new BankCard();
bankCard.setBin(bin);
bankCard.setMaskedPan(maskedPan);
bankCard.setToken(token);
bankCard.setPaymentSystem(bankCardPaymentSystem);
return bankCard;
}
public static InvoicePaymentProcessed makeInvoicePaymentProcessed() {
return new InvoicePaymentProcessed();
}
public static InvoicePaymentCaptured makeInvoicePaymentCaptured() {
return new InvoicePaymentCaptured();
}
public static InvoicePaymentCancelled makeInvoicePaymentCancelled() {
return new InvoicePaymentCancelled();
}
public static InvoicePaymentFailed makeInvoicePaymentFailed() {
return new InvoicePaymentFailed();
}
public static InvoicePaymentPending makeInvoicePaymentPending() {
return new InvoicePaymentPending();
}
// InvoicePaymentStatus
public static InvoicePaymentStatus makeInvoicePaymentStatusPending() {
return InvoicePaymentStatus.pending(DomainWrapper.makeInvoicePaymentPending());
}
public static InvoicePaymentStatus makeInvoicePaymentStatusProcessed() {
return InvoicePaymentStatus.processed(DomainWrapper.makeInvoicePaymentProcessed());
}
public static InvoicePaymentStatus makeInvoicePaymentStatusCaptured() {
return InvoicePaymentStatus.captured(DomainWrapper.makeInvoicePaymentCaptured());
}
public static InvoicePaymentStatus makeInvoicePaymentStatusCanceled() {
return InvoicePaymentStatus.cancelled(DomainWrapper.makeInvoicePaymentCancelled());
}
public static InvoicePaymentStatus makeInvoicePaymentStatusFailed() {
return InvoicePaymentStatus.failed(DomainWrapper.makeInvoicePaymentFailed());
}
// InvoiceStatus
public static InvoiceStatus makeInvoiceStatusUnpaid() {
return InvoiceStatus.unpaid(new InvoiceUnpaid());
}
public static InvoiceStatus makeInvoiceStatusPaid() {
return InvoiceStatus.paid(new InvoicePaid());
}
public static InvoiceStatus makeInvoiceStatusCancelled() {
return InvoiceStatus.cancelled(new InvoiceCancelled());
}
public static InvoiceStatus makeInvoiceStatusFulfilled() {
return InvoiceStatus.fulfilled(new InvoiceFulfilled());
}
// TransactionInfo
public static TransactionInfo makeTransactionInfo(String paymentId, Map<String, String> extra, String timestamp) {
TransactionInfo transactionInfo = new TransactionInfo();
transactionInfo.setId(paymentId);
transactionInfo.setExtra(extra);
transactionInfo.setTimestamp(timestamp);
return transactionInfo;
}
public static TransactionInfo makeTransactionInfo(String paymentId, Map<String, String> extra) {
TransactionInfo transactionInfo = new TransactionInfo();
transactionInfo.setId(paymentId);
transactionInfo.setExtra(extra);
transactionInfo.setTimestamp(null);
return transactionInfo;
}
public static Payer makePayer(ContactInfo contactInfo, ClientInfo clientInfo, PaymentTool paymentTool, String session) {
Payer payer = new Payer();
payer.setContactInfo(contactInfo);
payer.setClientInfo(clientInfo);
payer.setPaymentTool(paymentTool);
payer.setSession(session);
return payer;
}
public static ClientInfo makeClientInfo(String fingerprint, String ipAddress) {
ClientInfo clientInfo = new ClientInfo();
clientInfo.setFingerprint(fingerprint);
clientInfo.setIpAddress(ipAddress);
return clientInfo;
}
public static ContactInfo makeContactInfo(String email, String phoneNumber) {
ContactInfo contactInfo = new ContactInfo();
contactInfo.setEmail(email);
contactInfo.setPhoneNumber(phoneNumber);
return contactInfo;
}
public static PaymentTool makePaymentTool(BankCard bankCard) {
PaymentTool paymentTool = new PaymentTool();
paymentTool.setBankCard(bankCard);
return paymentTool;
}
public static AmountLimit makeAmountLimit(AmountBound min, AmountBound max) {
AmountLimit amountLimit = new AmountLimit();
amountLimit.setMin(min);
amountLimit.setMax(max);
return amountLimit;
}
public static CashVolumeShare makeCashVolumeShare(Rational parts, CashFlowConstant cashFlowConstant) {
CashVolumeShare cashVolumeShare = new CashVolumeShare();
cashVolumeShare.setParts(parts);
cashVolumeShare.setOf(cashFlowConstant);
return cashVolumeShare;
}
public static CashVolume makeCashVolumeOnlyShare(CashVolumeShare cashVolumeShare) {
CashVolume cashVolume = new CashVolume();
cashVolume.setShare(cashVolumeShare);
return cashVolume;
}
public static CashVolume makeCashVolumeOnlyFixed(CashVolumeFixed cashVolumeFixed) {
CashVolume cashVolume = new CashVolume();
cashVolume.setFixed(cashVolumeFixed);
return cashVolume;
}
public static TerminalAccountSet makeTerminalAccountSet(CurrencyRef currencyRef, long receipt, long compensation) {
TerminalAccountSet terminalAccountSet = new TerminalAccountSet();
terminalAccountSet.setCurrency(currencyRef);
terminalAccountSet.setReceipt(receipt);
terminalAccountSet.setCompensation(compensation);
return terminalAccountSet;
}
public static Terminal makeTerminal(String name, String description, CategoryRef categoryRef, PaymentMethodRef paymentMethodRef, List<CashFlowPosting> cashFlowPostings, TerminalAccountSet terminalAccountSet, Map<String, String> options) {
Terminal terminal = new Terminal();
terminal.setName(name);
terminal.setDescription(description);
terminal.setCategory(categoryRef);
terminal.setPaymentMethod(paymentMethodRef);
terminal.setCashFlow(cashFlowPostings);
terminal.setAccounts(terminalAccountSet);
terminal.setOptions(options);
return terminal;
}
public static Provider makeProvider(String name, String description, TerminalSelector terminalSelector, Proxy proxy) {
Provider provider = new Provider();
provider.setName(name);
provider.setDescription(description);
provider.setTerminal(terminalSelector);
provider.setProxy(proxy);
return provider;
}
public static TerminalSelector makeTerminalSelector(Set<TerminalRef> terminalRefs) {
TerminalSelector terminalSelector = new TerminalSelector();
terminalSelector.setValue(terminalRefs);
return terminalSelector;
}
public static Proxy makeProxy(ProxyRef ref, Map<String, String> additional) {
Proxy proxy = new Proxy();
proxy.setRef(ref);
proxy.setAdditional(additional);
return proxy;
}
public static Condition makeCondition(CurrencyRef currencyRef) {
Condition condition = new Condition();
condition.setCurrencyIs(currencyRef);
return condition;
}
public static Predicate makePredicate(Condition condition) {
Predicate predicate = new Predicate();
predicate.setCondition(condition);
return predicate;
}
public static CashFlowAccount makeCashFlowAccount(CashFlowParty cashFlowParty, String designation) {
CashFlowAccount cashFlowAccount = new CashFlowAccount();
cashFlowAccount.setParty(cashFlowParty);
cashFlowAccount.setDesignation(designation);
return cashFlowAccount;
}
public static CashFlowPosting makeCashFlowPosting(CashFlowAccount source, CashFlowAccount destination, CashVolume cashVolume) {
CashFlowPosting cashFlowPosting = new CashFlowPosting();
cashFlowPosting.setSource(source);
cashFlowPosting.setDestination(destination);
cashFlowPosting.setVolume(cashVolume);
return cashFlowPosting;
}
public static CashFlowPosting makeCashFlowPosting(CashFlowAccount cashFlowAccount) {
CashFlowPosting cashFlowPosting = new CashFlowPosting();
cashFlowPosting.setDestination(cashFlowAccount);
return cashFlowPosting;
}
public static CashFlowPosting makeCashFlowPostingDestination(CashVolume cashVolume) {
CashFlowPosting cashFlowPosting = new CashFlowPosting();
cashFlowPosting.setVolume(cashVolume);
return cashFlowPosting;
}
public static SystemAccountSetSelector makeSystemAccountSetSelector(Set<SystemAccountSetRef> value) {
SystemAccountSetSelector systemAccountSetSelector = new SystemAccountSetSelector();
systemAccountSetSelector.setValue(value);
return systemAccountSetSelector;
}
public static ProviderSelector makeProviderSelector(Set<ProviderRef> value) {
ProviderSelector providerSelector = new ProviderSelector();
providerSelector.setValue(value);
return providerSelector;
}
public static CashFlowSelector makeCashFlowSelectorPredicate(Set<CashFlowPredicate> cashFlowPredicatesList) {
CashFlowSelector cashFlowSelector = new CashFlowSelector();
cashFlowSelector.setPredicates(cashFlowPredicatesList);
return cashFlowSelector;
}
public static CashFlowPredicate makeCashFlowPredicate(Predicate _if, CashFlowSelector then) {
CashFlowPredicate cashFlowPredicate = new CashFlowPredicate();
cashFlowPredicate.setIf(_if);
cashFlowPredicate.setThen(then);
return cashFlowPredicate;
}
public static AmountLimitPredicate makeAmountLimitPredicate(Predicate _if, AmountLimitSelector then) {
AmountLimitPredicate amountLimitPredicate = new AmountLimitPredicate();
amountLimitPredicate.setIf(_if);
amountLimitPredicate.setThen(then);
return amountLimitPredicate;
}
public static AmountLimitSelector makeAmountLimitSelectorPredicate(Set<AmountLimitPredicate> predicates) {
AmountLimitSelector amountLimitSelector = new AmountLimitSelector();
amountLimitSelector.setPredicates(predicates);
return amountLimitSelector;
}
public static AmountLimitSelector makeAmountLimitSelectorValue(AmountLimit value) {
AmountLimitSelector amountLimitSelector = new AmountLimitSelector();
amountLimitSelector.setValue(value);
return amountLimitSelector;
}
public static PaymentMethodSelector makePaymentMethodSelector(Set<PaymentMethodRef> paymentMethodRefs) {
PaymentMethodSelector paymentMethodSelector = new PaymentMethodSelector();
paymentMethodSelector.setValue(paymentMethodRefs);
return paymentMethodSelector;
}
public static ShopServices makeShopServices(PaymentsService paymentsService) {
ShopServices shopServices = new ShopServices();
shopServices.setPayments(paymentsService);
return shopServices;
}
public static PaymentsService makePaymentsService(long domain_revision, PaymentsServiceTermsRef paymentsServiceTermsRef) {
PaymentsService paymentsService = new PaymentsService();
paymentsService.setDomainRevision(domain_revision);
paymentsService.setTerms(paymentsServiceTermsRef);
return paymentsService;
}
public static PaymentsServiceTermsRef makePaymentsServiceTermsRef(int id) {
PaymentsServiceTermsRef paymentsServiceTermsRef = new PaymentsServiceTermsRef();
paymentsServiceTermsRef.setId(id);
return paymentsServiceTermsRef;
}
public static PaymentsServiceTerms makePaymentsServiceTerms(PaymentMethodSelector paymentMethodSelector, AmountLimitSelector amountLimitSelector, CashFlowSelector cashFlowSelector) {
PaymentsServiceTerms paymentsServiceTerms = new PaymentsServiceTerms();
paymentsServiceTerms.setPaymentMethods(paymentMethodSelector);
paymentsServiceTerms.setLimits(amountLimitSelector);
paymentsServiceTerms.setFees(cashFlowSelector);
return paymentsServiceTerms;
}
public static DomainObject makeDomainObjectPaymentsServiceTermsObject(PaymentsServiceTermsRef ref, PaymentsServiceTerms data) {
DomainObject domainObject = new DomainObject();
PaymentsServiceTermsObject paymentsServiceTermsObject = new PaymentsServiceTermsObject();
paymentsServiceTermsObject.setRef(ref);
paymentsServiceTermsObject.setData(data);
domainObject.setPaymentsServiceTerms(paymentsServiceTermsObject);
return domainObject;
}
public static Globals makeGlobals(ProviderSelector providerSelector, PartyPrototypeRef partyPrototypeRef, SystemAccountSetSelector systemAccountSetSelector) {
Globals globals = new Globals();
globals.setProviders(providerSelector);
globals.setPartyPrototype(partyPrototypeRef);
globals.setSystemAccounts(systemAccountSetSelector);
return globals;
}
public static PartyPrototype makePartyPrototype(ShopPrototype shopPrototype, ShopServices shopServices) {
PartyPrototype partyPrototype = new PartyPrototype();
partyPrototype.setShop(shopPrototype);
partyPrototype.setDefaultServices(shopServices);
return partyPrototype;
}
public static ShopPrototype makeShopPrototype(CurrencyRef currencyRef, CategoryRef categoryRef, ShopDetails shopDetails) {
ShopPrototype shopPrototype = new ShopPrototype();
shopPrototype.setCurrency(currencyRef);
shopPrototype.setCategory(categoryRef);
shopPrototype.setDetails(shopDetails);
return shopPrototype;
}
public static DomainObject makeDomainObjectProxyObject(ProxyRef ref, ProxyDefinition data) {
DomainObject domainObject = new DomainObject();
ProxyObject proxyObject = new ProxyObject();
proxyObject.setRef(ref);
proxyObject.setData(data);
domainObject.setProxy(proxyObject);
return domainObject;
}
public static DomainObject makeDomainObjectProviderObject(ProviderRef ref, Provider data) {
DomainObject domainObject = new DomainObject();
ProviderObject providerObject = new ProviderObject();
providerObject.setRef(ref);
providerObject.setData(data);
domainObject.setProvider(providerObject);
return domainObject;
}
public static DomainObject makeDomainObjectCategoryObject(CategoryRef ref, Category data) {
DomainObject domainObject = new DomainObject();
CategoryObject categoryObject = new CategoryObject();
categoryObject.setRef(ref);
categoryObject.setData(data);
domainObject.setCategory(categoryObject);
return domainObject;
}
public static DomainObject makeDomainObjectCurrencyObject(CurrencyRef ref, Currency data) {
DomainObject domainObject = new DomainObject();
CurrencyObject currencyObject = new CurrencyObject();
currencyObject.setRef(ref);
currencyObject.setData(data);
domainObject.setCurrency(currencyObject);
return domainObject;
}
public static DomainObject makeDomainObjectPartyPrototypeObject(PartyPrototypeRef ref, PartyPrototype data) {
DomainObject domainObject = new DomainObject();
PartyPrototypeObject partyPrototypeObject = new PartyPrototypeObject();
partyPrototypeObject.setRef(ref);
partyPrototypeObject.setData(data);
domainObject.setPartyPrototype(partyPrototypeObject);
return domainObject;
}
public static DomainObject makeDomainObjectGlobalsObject(GlobalsRef ref, Globals data) {
DomainObject domainObject = new DomainObject();
GlobalsObject globalsObject = new GlobalsObject();
globalsObject.setRef(ref);
globalsObject.setData(data);
domainObject.setGlobals(globalsObject);
return domainObject;
}
public static DomainObject makeDomainObjectTerminalObject(TerminalRef ref, Terminal data) {
DomainObject domainObject = new DomainObject();
TerminalObject terminalObject = new TerminalObject();
terminalObject.setRef(ref);
terminalObject.setData(data);
domainObject.setTerminal(terminalObject);
return domainObject;
}
public static GlobalsRef makeGlobalsRef() {
return new GlobalsRef();
}
public static TerminalRef makeTerminalRef(int id) {
TerminalRef terminalRef = new TerminalRef();
terminalRef.setId(id);
return terminalRef;
}
public static PaymentMethodRef makePaymentMethodRef(BankCardPaymentSystem bankCardPaymentSystem) {
PaymentMethodRef paymentMethodRef = new PaymentMethodRef();
paymentMethodRef.setId(DomainWrapper.makePaymentMethod(bankCardPaymentSystem));
return paymentMethodRef;
}
public static ShopDetails makeShopDetails(String name, String description, String location) {
ShopDetails shopDetails = new ShopDetails();
shopDetails.setName(name);
shopDetails.setDescription(description);
shopDetails.setLocation(location);
return shopDetails;
}
public static ShopDetails makeShopDetails(String name, String description) {
return DomainWrapper.makeShopDetails(name, description, null);
}
public static Category makeCategory(String name, String description) {
Category category = new Category();
category.setName(name);
category.setDescription(description);
return category;
}
public static PaymentMethod makePaymentMethod(BankCardPaymentSystem bankCardPaymentSystem) {
PaymentMethod paymentMethod = new PaymentMethod();
paymentMethod.setBankCard(bankCardPaymentSystem);
return paymentMethod;
}
public static ProxyDefinition makeProxyDefinition(String url, Map<String, String> options) {
ProxyDefinition proxyDefinition = new ProxyDefinition();
proxyDefinition.setUrl(url);
proxyDefinition.setOptions(options);
return proxyDefinition;
}
public static ProxyDefinition makeProxyDefinition(String url) {
return DomainWrapper.makeProxyDefinition(url, null);
}
public static PartyPrototypeRef makePartyPrototypeRef(int id) {
PartyPrototypeRef partyPrototypeRef = new PartyPrototypeRef();
partyPrototypeRef.setId(id);
return partyPrototypeRef;
}
public static CategoryRef makeCategoryRef(int id) {
CategoryRef categoryRef = new CategoryRef();
categoryRef.setId(id);
return categoryRef;
}
public static ProviderRef makeProviderRef(int id) {
ProviderRef providerRef = new ProviderRef();
providerRef.setId(id);
return providerRef;
}
public static ProxyRef makeProxyRef(int id) {
ProxyRef proxyRef = new ProxyRef();
proxyRef.setId(id);
return proxyRef;
}
public static CurrencyRef makeCurrencyRef(String symbolicCode) {
CurrencyRef currencyRef = new CurrencyRef();
currencyRef.setSymbolicCode(symbolicCode);
return currencyRef;
}
}

View File

@ -0,0 +1,37 @@
package com.rbkmoney.proxy.test.utils.damsel;
import com.rbkmoney.damsel.domain.CategoryRef;
import com.rbkmoney.damsel.domain.Contractor;
import com.rbkmoney.damsel.domain.Payer;
import com.rbkmoney.damsel.domain.ShopDetails;
import com.rbkmoney.damsel.payment_processing.InvoicePaymentParams;
import com.rbkmoney.damsel.payment_processing.ShopParams;
import com.rbkmoney.damsel.payment_processing.UserInfo;
public class PaymentProcessingWrapper {
public static UserInfo makeUserInfo(String userId) {
UserInfo userInfo = new UserInfo();
userInfo.setId(userId);
return userInfo;
}
public static ShopParams makeShopParams(ShopDetails shopDetails, CategoryRef categoryRef, Contractor contractor) {
ShopParams shopParams = new ShopParams();
shopParams.setDetails(shopDetails);
shopParams.setContractor(contractor);
shopParams.setCategory(categoryRef);
return shopParams;
}
public static ShopParams makeShopParams(ShopDetails shopDetails, CategoryRef categoryRef) {
return PaymentProcessingWrapper.makeShopParams(shopDetails, categoryRef, null);
}
public static InvoicePaymentParams makeInvoicePaymentParams(Payer payer) {
InvoicePaymentParams invoicePaymentParams = new InvoicePaymentParams();
invoicePaymentParams.setPayer(payer);
return invoicePaymentParams;
}
}

View File

@ -0,0 +1,184 @@
package com.rbkmoney.proxy.test.utils.damsel;
import com.rbkmoney.damsel.cds.CardData;
import com.rbkmoney.damsel.cds.ExpDate;
import com.rbkmoney.damsel.domain.*;
import com.rbkmoney.damsel.proxy.Intent;
import com.rbkmoney.damsel.proxy_provider.*;
import com.rbkmoney.damsel.proxy_provider.Invoice;
import com.rbkmoney.damsel.proxy_provider.InvoicePayment;
import com.rbkmoney.damsel.proxy_provider.Shop;
import java.nio.ByteBuffer;
import java.util.Map;
public class ProxyProviderWrapper {
public static Target makeTargetProcessed() {
Target target = new Target();
target.setProcessed(DomainWrapper.makeInvoicePaymentProcessed());
return target;
}
public static Target makeTargetCaptured() {
Target target = new Target();
target.setCaptured(DomainWrapper.makeInvoicePaymentCaptured());
return target;
}
public static Target makeTargetCancelled() {
Target target = new Target();
target.setCancelled(DomainWrapper.makeInvoicePaymentCancelled());
return target;
}
public static Session makeSession(Target target, byte[] state) {
Session session = new Session();
session.setTarget(target);
session.setState(state);
return session;
}
public static Session makeSession(Target target) {
return ProxyProviderWrapper.makeSession(target, null);
}
// ProxyResult
public static ProxyResult makeProxyResult(Intent intent, byte[] next_state, TransactionInfo trx) {
ProxyResult proxyResult = new ProxyResult();
proxyResult.setIntent(intent);
proxyResult.setNextState(next_state);
proxyResult.setTrx(trx);
return proxyResult;
}
public static ProxyResult makeProxyResult(Intent intent, byte[] next_state) {
return makeProxyResult(intent, next_state, null);
}
public static ProxyResult makeProxyResult(Intent intent) {
return makeProxyResult(intent, null, null);
}
public static ProxyResult makeProxyResultFailure(String code, String description) {
ProxyResult proxyResult = new ProxyResult();
proxyResult.setIntent(ProxyWrapper.makeFinishIntentFailure(code, description));
return proxyResult;
}
public static Currency makeCurrency(String name, short numericCode, String symbolicCode, short exponent) {
return DomainWrapper.makeCurrency(name, numericCode, symbolicCode, exponent);
}
public static ExpDate makeExpDate(byte month, short year) {
return CdsWrapper.makeExpDate(month, year);
}
public static com.rbkmoney.damsel.proxy_provider.Cash makeCash(Currency currency, Long amount) {
com.rbkmoney.damsel.proxy_provider.Cash cash = new com.rbkmoney.damsel.proxy_provider.Cash();
cash.setAmount(amount);
cash.setCurrency(currency);
return cash;
}
public static CardData makeCardData(String cardholderName, String cvv, String pan, ExpDate expDate) {
return CdsWrapper.makeCardData(cardholderName, cvv, pan, expDate);
}
public static BankCard makeBankCard(String bin, String maskedPan, String token, BankCardPaymentSystem bankCardPaymentSystem) {
return DomainWrapper.makeBankCard(bin, maskedPan, token, bankCardPaymentSystem);
}
public static PaymentInfo makePaymentInfo(
com.rbkmoney.damsel.proxy_provider.Invoice invoice,
com.rbkmoney.damsel.proxy_provider.Shop shop,
com.rbkmoney.damsel.proxy_provider.InvoicePayment invoicePayment
) {
PaymentInfo paymentInfo = new PaymentInfo();
paymentInfo.setInvoice(invoice);
paymentInfo.setShop(shop);
paymentInfo.setPayment(invoicePayment);
return paymentInfo;
}
public static Context makeContext(
com.rbkmoney.damsel.proxy_provider.PaymentInfo paymentInfo,
com.rbkmoney.damsel.proxy_provider.Session session,
Map<String, String> options
) {
Context context = new Context();
context.setPayment(paymentInfo);
context.setSession(session);
context.setOptions(options);
return context;
}
public static Shop makeShop(String shopId, Category category, ShopDetails shopDetails) {
Shop shop = new Shop();
shop.setId(shopId);
shop.setCategory(category);
shop.setDetails(shopDetails);
return shop;
}
public static Invoice makeInvoice(String invoiceID, String createdAt, String product, com.rbkmoney.damsel.proxy_provider.Cash cost, String description) {
Invoice invoice = new Invoice();
invoice.setId(invoiceID);
invoice.setCreatedAt(createdAt);
invoice.setProduct(product);
invoice.setCost(cost);
invoice.setDescription(description);
return invoice;
}
public static Invoice makeInvoice(String invoiceId, String createdAt, String product, com.rbkmoney.damsel.proxy_provider.Cash cost) {
return ProxyProviderWrapper.makeInvoice(invoiceId, createdAt, product, cost, null);
}
public static InvoicePayment makeInvoicePayment(String invoicePaymentId, String created_at, com.rbkmoney.damsel.domain.Payer payer, com.rbkmoney.damsel.proxy_provider.Cash cost) {
InvoicePayment invoicePayment = new InvoicePayment();
invoicePayment.setId(invoicePaymentId);
invoicePayment.setCreatedAt(created_at);
invoicePayment.setPayer(payer);
invoicePayment.setCost(cost);
return invoicePayment;
}
public static InvoicePayment makeInvoicePaymentWithTrX(String invoicePaymentId, String created_at, com.rbkmoney.damsel.domain.Payer payer, com.rbkmoney.damsel.proxy_provider.Cash cost, TransactionInfo transactionInfo) {
InvoicePayment invoicePayment = new InvoicePayment();
invoicePayment.setId(invoicePaymentId);
invoicePayment.setCreatedAt(created_at);
invoicePayment.setPayer(payer);
invoicePayment.setCost(cost);
invoicePayment.setTrx(transactionInfo);
return invoicePayment;
}
public static com.rbkmoney.damsel.proxy_provider.Session makeSession(byte[] state) {
com.rbkmoney.damsel.proxy_provider.Session session = new com.rbkmoney.damsel.proxy_provider.Session();
session.setState(state);
return session;
}
public static com.rbkmoney.damsel.proxy_provider.Session makeSession(ByteBuffer state) {
com.rbkmoney.damsel.proxy_provider.Session session = new com.rbkmoney.damsel.proxy_provider.Session();
session.setState(state);
return session;
}
public static CallbackResult makeCallbackResult(byte[] callbackResponse, ProxyResult proxyResult) {
CallbackResult callbackResult = new CallbackResult();
callbackResult.setResponse(callbackResponse);
callbackResult.setResult(proxyResult);
return callbackResult;
}
public static CallbackResult makeCallbackResultFailure(byte[] callbackResponse, String code, String description) {
CallbackResult callbackResult = new CallbackResult();
callbackResult.setResponse(callbackResponse);
callbackResult.setResult(ProxyProviderWrapper.makeProxyResultFailure(code, description));
return callbackResult;
}
}

View File

@ -0,0 +1,67 @@
package com.rbkmoney.proxy.test.utils.damsel;
import com.rbkmoney.damsel.base.Timer;
import com.rbkmoney.damsel.proxy.*;
import com.rbkmoney.damsel.user_interaction.UserInteraction;
public class ProxyWrapper {
// FinishIntent
public static Intent makeFinishIntentOk() {
FinishIntent finishIntent = new FinishIntent();
finishIntent.setStatus(ProxyWrapper.makeFinishStatusOk());
Intent intent = new Intent();
intent.setFinish(finishIntent);
return intent;
}
public static Intent makeFinishIntentFailure(String code, String description) {
FinishIntent finishIntent = new FinishIntent();
finishIntent.setStatus(
ProxyWrapper.makeFinishStatusFailure(
BaseWrapper.makeError(code, description)
)
);
Intent intent = new Intent();
intent.setFinish(finishIntent);
return intent;
}
public static Intent makeIntentWithSleepIntent(Timer timer) {
Intent intent = new Intent();
intent.setSleep(ProxyWrapper.makeSleepIntent(timer));
return intent;
}
public static SleepIntent makeSleepIntent(Timer timer) {
SleepIntent sleepIntent = new SleepIntent();
sleepIntent.setTimer(timer);
return sleepIntent;
}
public static Intent makeIntentWithSuspendIntent(String tag, Timer timer, UserInteraction userInteraction) {
Intent intent = new Intent();
intent.setSuspend(ProxyWrapper.makeSuspendIntent(tag, timer, userInteraction));
return intent;
}
public static Intent makeIntentWithSuspendIntent(String tag, Timer timer) {
return makeIntentWithSuspendIntent(tag, timer, null);
}
public static SuspendIntent makeSuspendIntent(String tag, Timer timer, UserInteraction userInteraction) {
SuspendIntent suspendIntent = new SuspendIntent();
suspendIntent.setTag(tag);
suspendIntent.setTimeout(timer);
suspendIntent.setUserInteraction(userInteraction);
return suspendIntent;
}
public static FinishStatus makeFinishStatusFailure(com.rbkmoney.damsel.base.Error error) {
return FinishStatus.failure(error);
}
public static FinishStatus makeFinishStatusOk() {
return FinishStatus.ok(BaseWrapper.makeOk());
}
}

View File

@ -0,0 +1,35 @@
package com.rbkmoney.proxy.test.utils.damsel;
import com.rbkmoney.damsel.user_interaction.BrowserGetRequest;
import com.rbkmoney.damsel.user_interaction.BrowserHTTPRequest;
import com.rbkmoney.damsel.user_interaction.BrowserPostRequest;
import com.rbkmoney.damsel.user_interaction.UserInteraction;
import java.util.Map;
public class UserInteractionWrapper {
public static UserInteraction makeUserInteraction(BrowserHTTPRequest browserHTTPRequest) {
UserInteraction userInteraction = new UserInteraction();
userInteraction.setRedirect(browserHTTPRequest);
return userInteraction;
}
public static BrowserHTTPRequest makeBrowserGetRequest(String url) {
BrowserGetRequest browserGetRequest = new BrowserGetRequest();
browserGetRequest.setUri(url);
BrowserHTTPRequest browserHTTPRequest = new BrowserHTTPRequest();
browserHTTPRequest.setGetRequest(browserGetRequest);
return browserHTTPRequest;
}
public static BrowserHTTPRequest makeBrowserPostRequest(String url, Map<String, String> form) {
BrowserPostRequest browserPostRequest = new BrowserPostRequest();
browserPostRequest.setUri(url);
browserPostRequest.setForm(form);
BrowserHTTPRequest browserHTTPRequest = new BrowserHTTPRequest();
browserHTTPRequest.setPostRequest(browserPostRequest);
return browserHTTPRequest;
}
}

View File

@ -0,0 +1,27 @@
package com.rbkmoney.proxy.test.utils.hellgate;
import com.rbkmoney.damsel.proxy_provider.ProviderProxyHostSrv;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.nio.ByteBuffer;
@Component
public class HellGateApi {
private final static Logger LOGGER = LoggerFactory.getLogger(HellGateApi.class);
@Autowired
private ProviderProxyHostSrv.Iface providerProxyHostSrv;
public ByteBuffer processCallback(String tag, ByteBuffer callback) throws TException {
LOGGER.info("Hellgate: processCallback start");
ByteBuffer callbackResponse = providerProxyHostSrv.processCallback(tag, callback);
LOGGER.info("Hellgate: processCallback finish");
return callbackResponse;
}
}

View File

@ -0,0 +1,42 @@
package com.rbkmoney.proxy.test.utils.model;
public class Card {
private String pan;
private String action;
private String paymentSystem;
public Card(String pan, String action, String paymentSystem) {
this.pan = pan;
this.action = action;
this.paymentSystem = paymentSystem;
}
public String getPan() {
return pan;
}
public void setPan(String pan) {
this.pan = pan;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getPaymentSystem() {
return paymentSystem;
}
public void setPaymentSystem(String paymentSystem) {
this.paymentSystem = paymentSystem;
}
}

View File

@ -0,0 +1,10 @@
package com.rbkmoney.proxy.test.utils.testmpi;
public interface TestMpi {
public Object verifyEnrollment(String pan, short year, byte month);
public Object validatePaRes();
}

View File

@ -0,0 +1,52 @@
package com.rbkmoney.proxy.test.utils.testmpi;
import com.rbkmoney.proxy.test.utils.testmpi.model.ValidatePaResResponse;
import com.rbkmoney.proxy.test.utils.testmpi.model.VerifyEnrollmentResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
@Component
public class TestMpiApi {
private final static Logger LOGGER = LoggerFactory.getLogger(TestMpiApi.class);
@Autowired
private RestTemplate restTemplate;
@Value("${proxy-test-mpi.url}")
private String url;
public VerifyEnrollmentResponse verifyEnrollment(String pan, short year, byte month) throws IOException {
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("pan", pan);
map.add("year", String.valueOf(year));
map.add("month", String.valueOf(month));
VerifyEnrollmentResponse result;
result = restTemplate.postForObject(prepareUrl("verifyEnrollment"), map, VerifyEnrollmentResponse.class);
return result;
}
public ValidatePaResResponse validatePaRes(String pan, String paRes) throws IOException {
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("pan", pan);
map.add("paRes", String.valueOf(paRes));
ValidatePaResResponse result;
result = restTemplate.postForObject(prepareUrl("validatePaRes"), map, ValidatePaResResponse.class);
return result;
}
private String prepareUrl(String path) throws IOException {
return url + "/mpi/" + path;
}
}

View File

@ -0,0 +1,39 @@
package com.rbkmoney.proxy.test.utils.testmpi;
import com.rbkmoney.damsel.proxy_provider.PaymentInfo;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URISyntaxException;
public class TestMpiUtils {
private final static Logger LOGGER = LoggerFactory.getLogger(TestMpiUtils.class);
public final static String MESSAGE_ID = "messageId";
public final static String PA_REQ = "PaReq";
public final static String PA_RES = "PaRes";
public final static String PA_REQ_CREATION_TIME = "paReqCreationTime";
public final static String ACS_URL = "acsUrl";
public final static String ACCT_ID = "acctId";
public final static String PURCHASE_XID = "purchaseXId";
public static String getCallbackUrl(String callbackUrl, String path) {
String prepareCallbackUrl = null;
try {
URIBuilder b = new URIBuilder(callbackUrl);
prepareCallbackUrl = b.setPath(path)
.build()
.toString();
} catch (URISyntaxException e) {
LOGGER.error("Exception in getCallbackUrl", e);
}
return prepareCallbackUrl;
}
public static String generateInvoice(PaymentInfo payment) {
return payment.getInvoice().getId() + payment.getPayment().getId();
}
}

View File

@ -0,0 +1,36 @@
package com.rbkmoney.proxy.test.utils.testmpi.constant;
import java.util.Arrays;
public enum TestMpiAction {
UNKNOWN("Unknown"),
UNSUPPORTED_CARD("Unsupported Card"),
SUCCESS("Success"),
THREE_D_SECURE_SUCCESS("3-D Secure Success"),
THREE_D_SECURE_FAILURE("3-D Secure Failure"),
THREE_D_SECURE_TIMEOUT("3-D Secure Timeout"),
INCUFFICIENT_FUNDS("Incufficient Funds"),
INVALID_CARD("Invalid Card"),
CVV_MATCH_FAIL("CVV Match Fail"),
EXPIRED_CARD("Expired Card"),
UNKNOWN_FAILURE("Unknown Failure");
private final String action;
TestMpiAction(String action) {
this.action = action;
}
public String getAction() {
return action;
}
public static TestMpiAction findByValue(String value) {
return Arrays.stream(values()).filter((action) -> action.getAction().equals(value))
.findFirst()
.orElse(UNKNOWN);
}
}

View File

@ -0,0 +1,28 @@
package com.rbkmoney.proxy.test.utils.testmpi.constant;
/**
* Indicates the algorithm used to generate the Cardholder Authentication Verification Value.
*/
public class TestMpiCavvAlgorithm {
/**
* 0: HMAC (as per SET TransStain) (no longer in use for version 1.0.2)
*/
public final static String HMAC_AS_PER_SET_TRANS_STAIN = "0";
/**
* 1: CVV (no longer in use for version 1.0.2).
*/
public final static String CVV_NO_LONGER = "1";
/**
* 2: CVV with ATN.
*/
public final static String CVV_WITH_ATN = "2";
/**
* 3: MasterCard SPA algorithm.
*/
public final static String MASTERCARD_SPA_ALGORITHM = "3";
}

View File

@ -0,0 +1,26 @@
package com.rbkmoney.proxy.test.utils.testmpi.constant;
/**
* 3-D Secure enrollment status
*/
public class TestMpiEnrollmentStatus {
/**
* Authentication Available Cardholder is enrolled, Activation During Shopping is
* supported, or proof of attempted authentication available. The merchant uses the
* URL of issuer ACS included in VERes to create the Payer Authentication Request.
*/
public final static String AUTHENTICATION_AVAILABLE = "Y";
/**
* Cardholder Not Participating Cardholder is not enrolled.
*/
public final static String CARDHOLDER_NOT_PARTICIPATING = "N";
/**
* Unable to Authenticate or Card Not Eligible for Attempts
* (such as a Commercial or anonymous Prepaid card).
*/
public final static String UNABLE_TO_AUTHENTICATE = "U";
}

View File

@ -0,0 +1,32 @@
package com.rbkmoney.proxy.test.utils.testmpi.constant;
/**
* Transaction Status
*/
public class TestMpiTransactionStatus {
/**
* The merchant submits an authorization request including the
* ECI and CAVV supplied in the PARes.
*/
public final static String AUTHENTICATION_SUCCESSFUL = "Y";
/**
* The merchant must not submit a failed authentication for
* authorization.
*/
public final static String AUTHENTICATION_FAILED = "N";
/**
* The merchant may process an authorization request using the
* appropriate ECI.
*/
public final static String AUTHENTICATION_COULD_NOT_BE_PERFORMED = "U";
/**
* The merchant submits an authorization request including the
* ECI and CAVV supplied in the PARes.
*/
public final static String ATTEMPTS_PROCESSING_PERFORMED = "A";
}

View File

@ -0,0 +1,32 @@
package com.rbkmoney.proxy.test.utils.testmpi.model;
public class ValidatePaResRequest {
private String pan;
private String paRes;
public String getPan() {
return pan;
}
public void setPan(String pan) {
this.pan = pan;
}
public String getPaRes() {
return paRes;
}
public void setPaRes(String paRes) {
this.paRes = paRes;
}
@Override
public String toString() {
return "ValidatePaResRequest{" +
"pan='" + pan + '\'' +
", paRes='" + paRes + '\'' +
'}';
}
}

View File

@ -0,0 +1,87 @@
package com.rbkmoney.proxy.test.utils.testmpi.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ValidatePaResResponse {
@JsonProperty("eci")
private String eci;
@JsonProperty("cavv")
private String cavv;
@Override
public String toString() {
return "ValidatePaResResponse{" +
"eci='" + eci + '\'' +
", cavv='" + cavv + '\'' +
", cavvAlgorithm='" + cavvAlgorithm + '\'' +
", txId='" + txId + '\'' +
", txTime='" + txTime + '\'' +
", transactionStatus='" + transactionStatus + '\'' +
'}';
}
@JsonProperty("cavvAlgorithm")
private String cavvAlgorithm;
@JsonProperty("txId")
private String txId;
@JsonProperty("txTime")
private String txTime;
@JsonProperty("transactionStatus")
private String transactionStatus;
public String getEci() {
return eci;
}
public void setEci(String eci) {
this.eci = eci;
}
public String getCavv() {
return cavv;
}
public void setCavv(String cavv) {
this.cavv = cavv;
}
public String getCavvAlgorithm() {
return cavvAlgorithm;
}
public void setCavvAlgorithm(String cavvAlgorithm) {
this.cavvAlgorithm = cavvAlgorithm;
}
public String getTxId() {
return txId;
}
public void setTxId(String txId) {
this.txId = txId;
}
public String getTxTime() {
return txTime;
}
public void setTxTime(String txTime) {
this.txTime = txTime;
}
public String getTransactionStatus() {
return transactionStatus;
}
public void setTransactionStatus(String transactionStatus) {
this.transactionStatus = transactionStatus;
}
}

View File

@ -0,0 +1,42 @@
package com.rbkmoney.proxy.test.utils.testmpi.model;
public class VerifyEnrollmentRequest {
private String pan;
private String year;
private String month;
public String getPan() {
return pan;
}
public void setPan(String pan) {
this.pan = pan;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
@Override
public String toString() {
return "VerifyEnrollmentRequest{" +
"pan='" + pan + '\'' +
", year='" + year + '\'' +
", month='" + month + '\'' +
'}';
}
}

View File

@ -0,0 +1,50 @@
package com.rbkmoney.proxy.test.utils.testmpi.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class VerifyEnrollmentResponse {
@JsonProperty("enrolled")
private String enrolled;
@JsonProperty("paReq")
private String paReq;
@JsonProperty("acsUrl")
private String acsUrl;
public String getEnrolled() {
return enrolled;
}
public void setEnrolled(String enrolled) {
this.enrolled = enrolled;
}
public String getPaReq() {
return paReq;
}
public void setPaReq(String paReq) {
this.paReq = paReq;
}
public String getAcsUrl() {
return acsUrl;
}
public void setAcsUrl(String acsUrl) {
this.acsUrl = acsUrl;
}
@Override
public String toString() {
return "VerifyEnrollmentResponse{" +
"enrolled='" + enrolled + '\'' +
", paReq='" + paReq + '\'' +
", acsUrl='" + acsUrl + '\'' +
'}';
}
}

View File

@ -0,0 +1,39 @@
spring:
application:
name: name
description: description
---
info:
version: 1.0.0
responsible: Anatoly Cherkasov
stage: dev
---
endpoints:
health:
sensitive: false
---
server:
port: @server.port@
secondary:
ports: 8080
---
proxy-test-mpi:
url: http://127.0.0.1:8018
---
proxy-test:
callbackUrl: http://127.0.0.1:8019
---
cds:
url:
keyring: http://127.0.0.1:8021/v1/keyring
storage: http://127.0.0.1:8021/v1/storage
---
hellgate:
url: http://127.0.0.1:8023/v1/proxyhost/provider
---
timer:
timeout: 60
---
fixture:
cards: classpath:fixture/cards.csv

View File

@ -0,0 +1,20 @@
cardPan, action, paymentSystem
4242424242424242, Success, Visa
5555555555554444, Success, MasterCard
586824160825533338, Success, Maestro
4012888888881881, 3-D Secure Success, Visa
5169147129584558, 3-D Secure Success, MasterCard
4987654321098769, 3-D Secure Failure, Visa
5123456789012346, 3-D Secure Failure, MasterCard
4342561111111118, 3-D Secure Timeout, Visa
5112000200000002, 3-D Secure Timeout, MasterCard
4000000000000002, Incufficient Funds, Visa
5100000000000412, Incufficient Funds, MasterCard
4222222222222220, Invalid Card, Visa
5100000000000511, Invalid Card, MasterCard
4003830171874018, CVV Match Fail, Visa
5496198584584769, CVV Match Fail, MasterCard
4000000000000069, Expired Card, Visa
5105105105105100, Expired Card, MasterCard
4111110000000112, Unknown Failure, Visa
5124990000000002, Unknown Failure, MasterCard
1 cardPan action paymentSystem
2 4242424242424242 Success Visa
3 5555555555554444 Success MasterCard
4 586824160825533338 Success Maestro
5 4012888888881881 3-D Secure Success Visa
6 5169147129584558 3-D Secure Success MasterCard
7 4987654321098769 3-D Secure Failure Visa
8 5123456789012346 3-D Secure Failure MasterCard
9 4342561111111118 3-D Secure Timeout Visa
10 5112000200000002 3-D Secure Timeout MasterCard
11 4000000000000002 Incufficient Funds Visa
12 5100000000000412 Incufficient Funds MasterCard
13 4222222222222220 Invalid Card Visa
14 5100000000000511 Invalid Card MasterCard
15 4003830171874018 CVV Match Fail Visa
16 5496198584584769 CVV Match Fail MasterCard
17 4000000000000069 Expired Card Visa
18 5105105105105100 Expired Card MasterCard
19 4111110000000112 Unknown Failure Visa
20 5124990000000002 Unknown Failure MasterCard

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property name="LOG_FILE"
value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}/@artifactId@.json}"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="com.rbkmoney.log.appender.NoopRollingPolicy"/>
<triggeringPolicy class="com.rbkmoney.log.appender.RotationBasedTriggeringPolicy">
<checkCachePeriod>5000</checkCachePeriod>
</triggeringPolicy>
<encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<mdc/>
<threadName/>
<message/>
<version/>
<loggerName/>
<context/>
<pattern>
<pattern>
{
"@timestamp": "%date{yyy-MM-dd'T'HH:mm:ss.SSSXXX, UTC}",
"@severity": "%level",
"application": "@artifactId@",
"application_version": "@version@"
}
</pattern>
</pattern>
<stackTrace>
<throwableConverter class="net.logstash.logback.stacktrace.ShortenedThrowableConverter">
<shortenedClassNameLength>20</shortenedClassNameLength>
<rootCauseFirst>true</rootCauseFirst>
</throwableConverter>
</stackTrace>
</providers>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
<logger name="com.rbkmoney" level="ALL"/>
<jmxConfigurator/>
</configuration>

View File

@ -0,0 +1,26 @@
package com.rbkmoney.proxy.test;
import com.rbkmoney.damsel.cds.CardData;
import com.rbkmoney.proxy.test.utils.damsel.CdsWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestData {
private final static Logger LOGGER = LoggerFactory.getLogger(TestData.class);
public static CardData makeCardData() {
byte month = Byte.parseByte("12");
short year = Short.parseShort("2020");
LOGGER.info("Date: {}", Short.toString(year).substring(2));
return CdsWrapper.makeCardData(
"NONAME",
"123",
"4012001011000771",
CdsWrapper.makeExpDate(month, year)
);
}
}

View File

@ -0,0 +1,37 @@
package com.rbkmoney.proxy.test.controller;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import javax.servlet.http.HttpServletResponse;
import static org.junit.Assert.assertEquals;
public class TestControllerTest {
@Mock
TestController controller;
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void receiveIncomingParameters() throws Exception {
Mockito.when(controller.receiveIncomingParameters(request, response)).thenReturn("");
assertEquals("", controller.receiveIncomingParameters(request, response));
}
}

View File

@ -0,0 +1,15 @@
<html>
<head>
</head>
<body>
<form method="POST" action="http://127.0.0.1:8018/mpi/acs">
MD <input type="text" name="MD" value="some_MD"> <br />
TermUrl <input type="text" name="TermUrl" value="http://127.0.0.1:8019/test/term_url"> <br />
PaReq <textarea name="PaReq">eJxVkltTgzAQhf8KwzuGpFSxs8RBS7Xj0NFadfQtJlvA4VIJOK2/3qSlXvK037Kzh3MSuNhWpfOJrS6aOnLpie86WMtGFXUWuY+rmRe6ju5ErUTZ1Bi5O9TuBYdV3iJOH1D2LXJIUWuRoVOoyN2IcE1HSuHaOwsV8wL/nHoC39ALcU1RImNKKJfDXbzEDw6DNjfSJwzIEc3OVuai7jgI+XE5X/CAsfEoBDIgVNjOp5wF7Gwc+hTIgaEWFfLl5W1lfncHZI8gm77u2h0/DUZAjgB9W/K86zYTQspGijJvdAfEdoH8yt/1ttJmy7ZQ/GX1QtP3x6/0a1mmz/fjxXVCF9OMvT4nERA7AUp0yJlPTyllI4eyiR9OggDIvg+isvKc+uYYMweCjRWJ/3362wKTc2vu5ejgSIDbjfFpJkx0PzUo1JIv+7cStZG1AOTXxtWNzVR2Jq04nmezPHlPsjy5nSVP8S6NhxPZpPdDVqQweRlLBxULQOwaMlwiGV6Aqf69jG8oQ8cy</textarea> <br />
<input type="submit" value="send">
</form>
</body>
</html>

View File

@ -0,0 +1,225 @@
package com.rbkmoney.proxy.test.handler;
import com.rbkmoney.damsel.cds.CardData;
import com.rbkmoney.damsel.cds.PutCardDataResult;
import com.rbkmoney.damsel.cds.UnlockStatus;
import com.rbkmoney.damsel.domain.TransactionInfo;
import com.rbkmoney.damsel.proxy_provider.Context;
import com.rbkmoney.damsel.proxy_provider.PaymentInfo;
import com.rbkmoney.damsel.proxy_provider.ProxyResult;
import com.rbkmoney.damsel.proxy_provider.Target;
import com.rbkmoney.proxy.test.utils.Converter;
import com.rbkmoney.proxy.test.utils.cds.CdsApi;
import com.rbkmoney.proxy.test.utils.damsel.CdsWrapper;
import com.rbkmoney.proxy.test.utils.damsel.DomainWrapper;
import com.rbkmoney.proxy.test.utils.damsel.ProxyProviderWrapper;
import org.apache.thrift.TException;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = {
"merchant.id=24275801",
"merchant.name=RBKmoney1",
"merchant.url=http://localhost",
"merchant.acquirerBin=422538",
"merchant.password=",
"merchant.countryCode=643",
}
)
@Ignore("Integration test")
public class TestServerHandlerFailIntegrationTest {
private final static Logger LOGGER = LoggerFactory.getLogger(TestServerHandlerFailIntegrationTest.class);
@Autowired
private TestServerHandler handler;
@Autowired
private CdsApi cds;
@Value("${merchant.id}")
private String merchantId;
@Value("${merchant.name}")
private String merchantName;
@Value("${merchant.url}")
private String merchantUrl;
@Value("${merchant.acquirerBin}")
private String merchantAcquirerBin;
@Value("${merchant.password}")
private String merchantPassword;
@Value("${merchant.countryCode}")
private String merchantCountryCode;
private String invoiceId = "TEST_INVOICE" + (int) (Math.random() * 50 + 1);
private String paymentId = "TEST_PAYMENT" + (int) (Math.random() * 50 + 1);
@Before
public void setUp() {
// Connect to CDS
// TODO используется лишь в первый раз при запуске теста для разблокировки ключа
// UnlockStatus unlockStatus = cdsUnlockKey((short) 1, (short) 1);
}
@Test
public void testProcessPaymentFail() throws TException, IOException, URISyntaxException {
String[] cards = {
"4000000000000002",
"5100000000000412",
"4222222222222220",
"5100000000000511",
"4003830171874018",
"5496198584584769",
"4000000000000069",
"5105105105105100",
"4111110000000112",
"5124990000000002",
};
// Put the card and save the response to a subsequent request
for (String card: cards) {
CardData cardData = CdsWrapper.makeCardDataWithExpDate(
"NONAME",
"123",
card,
Byte.parseByte("12"),
Short.parseShort("2020")
);
processPaymentFail(cardData);
}
}
private void processPaymentFail(CardData cardData) throws TException, URISyntaxException, IOException {
PutCardDataResult putCardDataResponse = cdsPutCardData(cardData);
ProxyResult processResultPayment = handler.processPayment(
getContext(
putCardDataResponse,
ProxyProviderWrapper.makeTargetProcessed(),
null
)
);
assertTrue("Process payment ", processResultPayment.getIntent().getFinish().getStatus().getFailure().isSetCode());
}
private Map<String, String> getOptionsProxy() {
Map<String, String> options = new HashMap<>();
options.put("merchantId", merchantId);
options.put("merchantName", merchantName);
options.put("merchantUrl", merchantUrl);
options.put("merchantAcquirerBin", merchantAcquirerBin);
options.put("merchantPassword", merchantPassword);
options.put("merchantCountryCode", merchantCountryCode);
return options;
}
private PaymentInfo getPaymentInfo(PutCardDataResult putCardDataResponse, TransactionInfo transactionInfo) {
return ProxyProviderWrapper.makePaymentInfo(
ProxyProviderWrapper.makeInvoice(
invoiceId,
"2016-06-02",
"product",
getCost(),
"Invoice description"
),
ProxyProviderWrapper.makeShop(
"shopId",
DomainWrapper.makeCategory("CategoryName", "Category description"),
DomainWrapper.makeShopDetails("ShopName", "Shop description")
),
ProxyProviderWrapper.makeInvoicePaymentWithTrX(
paymentId,
"2016-06-02",
DomainWrapper.makePayer(
DomainWrapper.makeContactInfo("email", "phone"),
DomainWrapper.makeClientInfo("fingerprint", "ip"),
DomainWrapper.makePaymentTool(putCardDataResponse.getBankCard()),
putCardDataResponse.getSession()
),
getCost(),
transactionInfo
)
);
}
private byte[] getSessionState() throws IOException {
return Converter.mapToByteArray(Collections.emptyMap());
}
private Context getContext(PutCardDataResult putCardDataResult, Target target, TransactionInfo transactionInfo) throws IOException {
return ProxyProviderWrapper.makeContext(
getPaymentInfo(putCardDataResult, transactionInfo),
ProxyProviderWrapper.makeSession(
target,
getSessionState()
),
getOptionsProxy()
);
}
private com.rbkmoney.damsel.proxy_provider.Cash getCost() {
return ProxyProviderWrapper.makeCash(
ProxyProviderWrapper.makeCurrency("Rubles", (short) 643, "RUB", (short) 2),
10000L
);
}
private PutCardDataResult cdsPutCardData(CardData cardData) throws TException, URISyntaxException, IOException {
LOGGER.info("CDS: put card");
PutCardDataResult putCardDataResponse = cds.putCardData(cardData);
LOGGER.info(putCardDataResponse.toString());
return putCardDataResponse;
}
/**
* CDS unlock Key
* <p>
* TODO: Игнорируем, если ключи уже разблокированы
*
* @param thres_hold short
* @param num_shares short
* @return UnlockStatus
* @throws URISyntaxException
* @throws TException
*/
private UnlockStatus cdsUnlockKey(short thres_hold, short num_shares) throws URISyntaxException, TException, IOException {
LOGGER.info("CDS: init");
List<ByteBuffer> key = cds.init(thres_hold, num_shares);
LOGGER.info("CDS: init response {}", key.toString());
LOGGER.info("CDS: unlock");
UnlockStatus unlockStatus = cds.unlock(key.get(0));
LOGGER.info("CDS: unlock res {}", unlockStatus.toString());
return unlockStatus;
}
}

View File

@ -0,0 +1,224 @@
package com.rbkmoney.proxy.test.handler;
import com.rbkmoney.damsel.cds.CardData;
import com.rbkmoney.damsel.cds.PutCardDataResult;
import com.rbkmoney.damsel.cds.UnlockStatus;
import com.rbkmoney.damsel.domain.TransactionInfo;
import com.rbkmoney.damsel.proxy_provider.*;
import com.rbkmoney.proxy.test.utils.Converter;
import com.rbkmoney.proxy.test.utils.cds.CdsApi;
import com.rbkmoney.proxy.test.utils.damsel.CdsWrapper;
import com.rbkmoney.proxy.test.utils.damsel.DomainWrapper;
import com.rbkmoney.proxy.test.utils.damsel.ProxyProviderWrapper;
import org.apache.thrift.TException;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = {
"merchant.id=24275801",
"merchant.name=RBKmoney1",
"merchant.url=http://localhost",
"merchant.acquirerBin=422538",
"merchant.password=",
"merchant.countryCode=643",
}
)
@Ignore("Integration test")
public class TestServerHandlerFailWith3DSIntegrationTest {
private final static Logger LOGGER = LoggerFactory.getLogger(TestServerHandlerFailWith3DSIntegrationTest.class);
@Autowired
private TestServerHandler handler;
@Autowired
private CdsApi cds;
@Value("${merchant.id}")
private String merchantId;
@Value("${merchant.name}")
private String merchantName;
@Value("${merchant.url}")
private String merchantUrl;
@Value("${merchant.acquirerBin}")
private String merchantAcquirerBin;
@Value("${merchant.password}")
private String merchantPassword;
@Value("${merchant.countryCode}")
private String merchantCountryCode;
private String invoiceId = "TEST_INVOICE" + (int) (Math.random() * 50 + 1);
private String paymentId = "TEST_PAYMENT" + (int) (Math.random() * 50 + 1);
@Before
public void setUp() {
// Connect to CDS
// TODO используется лишь в первый раз при запуске теста для разблокировки ключа
// UnlockStatus unlockStatus = cdsUnlockKey((short) 1, (short) 1);
}
@Test
public void testProcessPaymentFail() throws TException, IOException, URISyntaxException {
String[] cards = {
"4987654321098769",
"5123456789012346",
"4342561111111118",
"5112000200000002",
};
// Put the card and save the response to a subsequent request
for (String card: cards) {
CardData cardData = CdsWrapper.makeCardDataWithExpDate(
"NONAME", "123", card, Byte.parseByte("12"), Short.parseShort("2020")
);
processPaymentFail(cardData);
}
}
private void processPaymentFail(CardData cardData) throws TException, URISyntaxException, IOException {
PutCardDataResult putCardDataResponse = cdsPutCardData(cardData);
ProxyResult processResultPayment = handler.processPayment(
getContext(
putCardDataResponse,
ProxyProviderWrapper.makeTargetProcessed(),
null
)
);
// Process Payment
assertTrue("Process payment ", !processResultPayment.getIntent().getSuspend().getTag().isEmpty());
// Prepare handlePaymentCallback
Map<String, String> mapCallback = new HashMap<>();
mapCallback.put("MD", "MD-TAG");
mapCallback.put("paRes", "SomePaRes");
ByteBuffer callbackMap = Converter.mapToByteBuffer(mapCallback);
// handlePaymentCallback
CallbackResult callbackResult = handler.handlePaymentCallback(
callbackMap, getContext(putCardDataResponse, null, null)
);
assertTrue("CallbackResult ", callbackResult.getResult().getIntent().getFinish().getStatus().getFailure().isSetCode());
}
private Map<String, String> getOptionsProxy() {
return Collections.emptyMap();
}
private PaymentInfo getPaymentInfo(PutCardDataResult putCardDataResponse, TransactionInfo transactionInfo) {
return ProxyProviderWrapper.makePaymentInfo(
ProxyProviderWrapper.makeInvoice(
invoiceId,
"2016-06-02",
"product",
getCost(),
"Invoice description"
),
ProxyProviderWrapper.makeShop(
"shopId",
DomainWrapper.makeCategory("CategoryName", "Category description"),
DomainWrapper.makeShopDetails("ShopName", "Shop description")
),
ProxyProviderWrapper.makeInvoicePaymentWithTrX(
paymentId,
"2016-06-02",
DomainWrapper.makePayer(
DomainWrapper.makeContactInfo("email", "phone"),
DomainWrapper.makeClientInfo("fingerprint", "ip"),
DomainWrapper.makePaymentTool(putCardDataResponse.getBankCard()),
putCardDataResponse.getSession()
),
getCost(),
transactionInfo
)
);
}
private byte[] getSessionState() throws IOException {
Map<String, String> extra = new HashMap<>();
extra.put("paReq","paReq");
return Converter.mapToByteArray(extra);
}
private Context getContext(PutCardDataResult putCardDataResult, Target target, TransactionInfo transactionInfo) throws IOException {
return ProxyProviderWrapper.makeContext(
getPaymentInfo(putCardDataResult, transactionInfo),
ProxyProviderWrapper.makeSession(
target,
getSessionState()
),
getOptionsProxy()
);
}
private com.rbkmoney.damsel.proxy_provider.Cash getCost() {
return ProxyProviderWrapper.makeCash(
ProxyProviderWrapper.makeCurrency("Rubles", (short) 643, "RUB", (short) 2),
10000L
);
}
private PutCardDataResult cdsPutCardData(CardData cardData) throws TException, URISyntaxException, IOException {
LOGGER.info("CDS: put card");
PutCardDataResult putCardDataResponse = cds.putCardData(cardData);
LOGGER.info(putCardDataResponse.toString());
return putCardDataResponse;
}
/**
* CDS unlock Key
* <p>
* TODO: Игнорируем, если ключи уже разблокированы
*
* @param thres_hold short
* @param num_shares short
* @return UnlockStatus
* @throws URISyntaxException
* @throws TException
*/
private UnlockStatus cdsUnlockKey(short thres_hold, short num_shares) throws URISyntaxException, TException, IOException {
LOGGER.info("CDS: init");
List<ByteBuffer> key = cds.init(thres_hold, num_shares);
LOGGER.info("CDS: init response {}", key.toString());
LOGGER.info("CDS: unlock");
UnlockStatus unlockStatus = cds.unlock(key.get(0));
LOGGER.info("CDS: unlock res {}", unlockStatus.toString());
return unlockStatus;
}
}

View File

@ -0,0 +1,243 @@
package com.rbkmoney.proxy.test.handler;
import com.rbkmoney.damsel.cds.CardData;
import com.rbkmoney.damsel.cds.PutCardDataResult;
import com.rbkmoney.damsel.cds.UnlockStatus;
import com.rbkmoney.damsel.domain.TransactionInfo;
import com.rbkmoney.damsel.proxy_provider.Context;
import com.rbkmoney.damsel.proxy_provider.PaymentInfo;
import com.rbkmoney.damsel.proxy_provider.ProxyResult;
import com.rbkmoney.damsel.proxy_provider.Target;
import com.rbkmoney.proxy.test.utils.Converter;
import com.rbkmoney.proxy.test.utils.cds.CdsApi;
import com.rbkmoney.proxy.test.utils.damsel.CdsWrapper;
import com.rbkmoney.proxy.test.utils.damsel.DomainWrapper;
import com.rbkmoney.proxy.test.utils.damsel.ProxyProviderWrapper;
import com.rbkmoney.proxy.test.utils.damsel.ProxyWrapper;
import org.apache.thrift.TException;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = {
"merchant.id=24275801",
"merchant.name=RBKmoney1",
"merchant.url=http://localhost",
"merchant.acquirerBin=422538",
"merchant.password=",
"merchant.countryCode=643",
}
)
@Ignore("Integration test")
public class TestServerHandlerSuccessIntegrationTest {
private final static Logger LOGGER = LoggerFactory.getLogger(TestServerHandlerSuccessIntegrationTest.class);
@Autowired
private TestServerHandler handler;
@Autowired
private CdsApi cds;
@Value("${merchant.id}")
private String merchantId;
@Value("${merchant.name}")
private String merchantName;
@Value("${merchant.url}")
private String merchantUrl;
@Value("${merchant.acquirerBin}")
private String merchantAcquirerBin;
@Value("${merchant.password}")
private String merchantPassword;
@Value("${merchant.countryCode}")
private String merchantCountryCode;
private String invoiceId = "TEST_INVOICE" + (int) (Math.random() * 50 + 1);
private String paymentId = "TEST_PAYMENT" + (int) (Math.random() * 50 + 1);
@Before
public void setUp() {
// Connect to CDS
// TODO используется лишь в первый раз при запуске теста для разблокировки ключа
// UnlockStatus unlockStatus = cdsUnlockKey((short) 1, (short) 1);
}
@Test
public void testProcessPaymentSuccess() throws TException, IOException, URISyntaxException {
String[] cards = {
"4242424242424242",
"5555555555554444",
"586824160825533338",
};
// Put the card and save the response to a subsequent request
for (String card: cards) {
CardData cardData = CdsWrapper.makeCardDataWithExpDate(
"NONAME",
"123",
card,
Byte.parseByte("12"),
Short.parseShort("2020")
);
processPaymentSuccess(cardData);
}
}
private void processPaymentSuccess(CardData cardData) throws TException, URISyntaxException, IOException {
PutCardDataResult putCardDataResponse = cdsPutCardData(cardData);
ProxyResult processResultPayment = handler.processPayment(
getContext(
putCardDataResponse,
ProxyProviderWrapper.makeTargetProcessed(),
null
)
);
assertEquals("Process payment ", ProxyWrapper.makeFinishStatusOk(), processResultPayment.getIntent().getFinish().getStatus());
if (processResultPayment.getIntent().getFinish().getStatus().equals(ProxyWrapper.makeFinishStatusOk())) {
LOGGER.info("Call capture payment");
// Обрабатываем ответ и вызываем CapturePayment
ProxyResult processResultCapture = handler.processPayment(
getContext(
putCardDataResponse,
ProxyProviderWrapper.makeTargetCaptured(),
DomainWrapper.makeTransactionInfo(
processResultPayment.getTrx().getId(),
Collections.emptyMap()
)
)
);
assertEquals("Process Capture ", ProxyWrapper.makeFinishStatusOk(), processResultCapture.getIntent().getFinish().getStatus());
// Обрабатываем ответ
LOGGER.info("Response capture payment {}", processResultCapture.toString());
}
}
private Map<String, String> getOptionsProxy() {
Map<String, String> options = new HashMap<>();
options.put("merchantId", merchantId);
options.put("merchantName", merchantName);
options.put("merchantUrl", merchantUrl);
options.put("merchantAcquirerBin", merchantAcquirerBin);
options.put("merchantPassword", merchantPassword);
options.put("merchantCountryCode", merchantCountryCode);
return options;
}
private PaymentInfo getPaymentInfo(PutCardDataResult putCardDataResponse, TransactionInfo transactionInfo) {
return ProxyProviderWrapper.makePaymentInfo(
ProxyProviderWrapper.makeInvoice(
invoiceId,
"2016-06-02",
"product",
getCost(),
"Invoice description"
),
ProxyProviderWrapper.makeShop(
"shopId",
DomainWrapper.makeCategory("CategoryName", "Category description"),
DomainWrapper.makeShopDetails("ShopName", "Shop description")
),
ProxyProviderWrapper.makeInvoicePaymentWithTrX(
paymentId,
"2016-06-02",
DomainWrapper.makePayer(
DomainWrapper.makeContactInfo("email", "phone"),
DomainWrapper.makeClientInfo("fingerprint", "ip"),
DomainWrapper.makePaymentTool(putCardDataResponse.getBankCard()),
putCardDataResponse.getSession()
),
getCost(),
transactionInfo
)
);
}
private byte[] getSessionState() throws IOException {
return Converter.mapToByteArray(Collections.emptyMap());
}
private Context getContext(PutCardDataResult putCardDataResult, Target target, TransactionInfo transactionInfo) throws IOException {
return ProxyProviderWrapper.makeContext(
getPaymentInfo(putCardDataResult, transactionInfo),
ProxyProviderWrapper.makeSession(
target,
getSessionState()
),
getOptionsProxy()
);
}
private com.rbkmoney.damsel.proxy_provider.Cash getCost() {
return ProxyProviderWrapper.makeCash(
ProxyProviderWrapper.makeCurrency("Rubles", (short) 643, "RUB", (short) 2),
10000L
);
}
private PutCardDataResult cdsPutCardData(CardData cardData) throws TException, URISyntaxException, IOException {
LOGGER.info("CDS: prepare card");
// CardData cardData = TestData.makeCardData();
LOGGER.info("CDS: put card");
PutCardDataResult putCardDataResponse = cds.putCardData(cardData);
LOGGER.info(putCardDataResponse.toString());
return putCardDataResponse;
}
/**
* CDS unlock Key
* <p>
* TODO: Игнорируем, если ключи уже разблокированы
*
* @param thres_hold short
* @param num_shares short
* @return UnlockStatus
* @throws URISyntaxException
* @throws TException
*/
private UnlockStatus cdsUnlockKey(short thres_hold, short num_shares) throws URISyntaxException, TException, IOException {
LOGGER.info("CDS: init");
List<ByteBuffer> key = cds.init(thres_hold, num_shares);
LOGGER.info("CDS: init response {}", key.toString());
LOGGER.info("CDS: unlock");
UnlockStatus unlockStatus = cds.unlock(key.get(0));
LOGGER.info("CDS: unlock res {}", unlockStatus.toString());
return unlockStatus;
}
}

View File

@ -0,0 +1,241 @@
package com.rbkmoney.proxy.test.handler;
import com.rbkmoney.damsel.cds.CardData;
import com.rbkmoney.damsel.cds.PutCardDataResult;
import com.rbkmoney.damsel.cds.UnlockStatus;
import com.rbkmoney.damsel.domain.TransactionInfo;
import com.rbkmoney.damsel.proxy_provider.*;
import com.rbkmoney.proxy.test.utils.Converter;
import com.rbkmoney.proxy.test.utils.cds.CdsApi;
import com.rbkmoney.proxy.test.utils.damsel.CdsWrapper;
import com.rbkmoney.proxy.test.utils.damsel.DomainWrapper;
import com.rbkmoney.proxy.test.utils.damsel.ProxyProviderWrapper;
import com.rbkmoney.proxy.test.utils.damsel.ProxyWrapper;
import org.apache.thrift.TException;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = {
"merchant.id=24275801",
"merchant.name=RBKmoney1",
"merchant.url=http://localhost",
"merchant.acquirerBin=422538",
"merchant.password=",
"merchant.countryCode=643",
}
)
@Ignore("Integration test")
public class TestServerHandlerSuccessWith3DSIntegrationTest {
private final static Logger LOGGER = LoggerFactory.getLogger(TestServerHandlerSuccessWith3DSIntegrationTest.class);
@Autowired
private TestServerHandler handler;
@Autowired
private CdsApi cds;
@Value("${merchant.id}")
private String merchantId;
@Value("${merchant.name}")
private String merchantName;
@Value("${merchant.url}")
private String merchantUrl;
@Value("${merchant.acquirerBin}")
private String merchantAcquirerBin;
@Value("${merchant.password}")
private String merchantPassword;
@Value("${merchant.countryCode}")
private String merchantCountryCode;
private String invoiceId = "TEST_INVOICE" + (int) (Math.random() * 50 + 1);
private String paymentId = "TEST_PAYMENT" + (int) (Math.random() * 50 + 1);
@Before
public void setUp() {
// Connect to CDS
// TODO используется лишь в первый раз при запуске теста для разблокировки ключа
// UnlockStatus unlockStatus = cdsUnlockKey((short) 1, (short) 1);
}
@Test
public void testProcessPaymentSuccess() throws TException, IOException, URISyntaxException {
String[] cards = {
"4012888888881881",
"5169147129584558",
};
// Put the card and save the response to a subsequent request
for (String card: cards) {
CardData cardData = CdsWrapper.makeCardDataWithExpDate(
"NONAME", "123", card, Byte.parseByte("12"), Short.parseShort("2020")
);
processPaymentSuccess(cardData);
}
}
private void processPaymentSuccess(CardData cardData) throws TException, URISyntaxException, IOException {
PutCardDataResult putCardDataResponse = cdsPutCardData(cardData);
ProxyResult processResultPayment = handler.processPayment(
getContext(
putCardDataResponse,
ProxyProviderWrapper.makeTargetProcessed(),
null
)
);
// Process Payment
assertTrue("Process payment ", !processResultPayment.getIntent().getSuspend().getTag().isEmpty());
// Prepare handlePaymentCallback
Map<String, String> mapCallback = new HashMap<>();
mapCallback.put("MD", "MD-TAG");
mapCallback.put("paRes", "SomePaRes");
ByteBuffer callbackMap = Converter.mapToByteBuffer(mapCallback);
// handlePaymentCallback
CallbackResult callbackResult = handler.handlePaymentCallback(
callbackMap, getContext(putCardDataResponse, null, null)
);
assertTrue("CallbackResult ", callbackResult.getResult().getIntent().getFinish().getStatus().isSetOk());
LOGGER.info("Call capture payment");
// Обрабатываем ответ и вызываем CapturePayment
ProxyResult processResultCapture = handler.processPayment(
getContext(
putCardDataResponse,
ProxyProviderWrapper.makeTargetCaptured(),
DomainWrapper.makeTransactionInfo(
callbackResult.getResult().getTrx().getId(),
Collections.emptyMap()
)
)
);
assertEquals("Process Capture ", ProxyWrapper.makeFinishStatusOk(), processResultCapture.getIntent().getFinish().getStatus());
// Обрабатываем ответ
LOGGER.info("Response capture payment {}", processResultCapture.toString());
}
private Map<String, String> getOptionsProxy() {
return Collections.emptyMap();
}
private PaymentInfo getPaymentInfo(PutCardDataResult putCardDataResponse, TransactionInfo transactionInfo) {
return ProxyProviderWrapper.makePaymentInfo(
ProxyProviderWrapper.makeInvoice(
invoiceId,
"2016-06-02",
"product",
getCost(),
"Invoice description"
),
ProxyProviderWrapper.makeShop(
"shopId",
DomainWrapper.makeCategory("CategoryName", "Category description"),
DomainWrapper.makeShopDetails("ShopName", "Shop description")
),
ProxyProviderWrapper.makeInvoicePaymentWithTrX(
paymentId,
"2016-06-02",
DomainWrapper.makePayer(
DomainWrapper.makeContactInfo("email", "phone"),
DomainWrapper.makeClientInfo("fingerprint", "ip"),
DomainWrapper.makePaymentTool(putCardDataResponse.getBankCard()),
putCardDataResponse.getSession()
),
getCost(),
transactionInfo
)
);
}
private byte[] getSessionState() throws IOException {
Map<String, String> extra = new HashMap<>();
extra.put("paReq","paReq");
return Converter.mapToByteArray(extra);
}
private Context getContext(PutCardDataResult putCardDataResult, Target target, TransactionInfo transactionInfo) throws IOException {
return ProxyProviderWrapper.makeContext(
getPaymentInfo(putCardDataResult, transactionInfo),
ProxyProviderWrapper.makeSession(
target,
getSessionState()
),
getOptionsProxy()
);
}
private Cash getCost() {
return ProxyProviderWrapper.makeCash(
ProxyProviderWrapper.makeCurrency("Rubles", (short) 643, "RUB", (short) 2),
10000L
);
}
private PutCardDataResult cdsPutCardData(CardData cardData) throws TException, URISyntaxException, IOException {
LOGGER.info("CDS: put card");
PutCardDataResult putCardDataResponse = cds.putCardData(cardData);
LOGGER.info(putCardDataResponse.toString());
return putCardDataResponse;
}
/**
* CDS unlock Key
* <p>
* TODO: Игнорируем, если ключи уже разблокированы
*
* @param thres_hold short
* @param num_shares short
* @return UnlockStatus
* @throws URISyntaxException
* @throws TException
*/
private UnlockStatus cdsUnlockKey(short thres_hold, short num_shares) throws URISyntaxException, TException, IOException {
LOGGER.info("CDS: init");
List<ByteBuffer> key = cds.init(thres_hold, num_shares);
LOGGER.info("CDS: init response {}", key.toString());
LOGGER.info("CDS: unlock");
UnlockStatus unlockStatus = cds.unlock(key.get(0));
LOGGER.info("CDS: unlock res {}", unlockStatus.toString());
return unlockStatus;
}
}

View File

@ -0,0 +1,51 @@
package com.rbkmoney.proxy.test.handler;
import com.rbkmoney.damsel.proxy_provider.CallbackResult;
import com.rbkmoney.damsel.proxy_provider.Context;
import com.rbkmoney.damsel.proxy_provider.ProxyResult;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.nio.ByteBuffer;
import static org.junit.Assert.assertEquals;
public class TestServerHandlerTest {
@Mock
ProxyResult proxyResult;
@Mock
CallbackResult callbackResult;
@Mock
ByteBuffer byteBuffer;
@Mock
Context context;
@Mock
TestServerHandler handler;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testAuthPayment() throws Exception {
Mockito.when(handler.processPayment(context)).thenReturn(proxyResult);
assertEquals(proxyResult, handler.processPayment(context));
}
@Test
public void testHandleAuthCallback() throws Exception {
Mockito.when(handler.handlePaymentCallback(byteBuffer, context)).thenReturn(callbackResult);
assertEquals(callbackResult, handler.handlePaymentCallback(byteBuffer, context));
}
}

View File

@ -0,0 +1,87 @@
package com.rbkmoney.proxy.test.utils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class ConverterTest {
private final static Logger LOGGER = LoggerFactory.getLogger(ConverterTest.class);
@Test
public void byteBufferToMap() throws IOException {
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
ByteBuffer byteBuffer = ByteBuffer.wrap(new ObjectMapper().writeValueAsString(map).getBytes());
Map<String, String> mapExpected = Converter.byteBufferToMap(byteBuffer);
assertEquals(map, mapExpected);
assertEquals("value1", mapExpected.get("key1"));
}
@Test
public void mapToByteBuffer() throws IOException {
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
ByteBuffer expected = ByteBuffer.wrap(new ObjectMapper().writeValueAsString(map).getBytes());
assertEquals(expected, Converter.mapToByteBuffer(map));
}
@Test
public void testMapArrayToMap() {
Map<String, String[]> mapArray = new HashMap<>();
mapArray.put("key1", new String[]{"value1"});
mapArray.put("key2", new String[]{"value2"});
Map<String, String> expected = new HashMap<>();
expected.put("key1", "value1");
expected.put("key2", "value2");
Map<String, String> actual = Converter.mapArrayToMap(mapArray);
assertEquals(expected, actual);
}
@Test
public void testMapObject() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
String json = objectMapper.writeValueAsString(map);
byte[] bytes = json.getBytes();
LOGGER.info(json);
LOGGER.info(bytes.toString());
LOGGER.info(new String(bytes));
ByteBuffer buffer = ByteBuffer.wrap(json.getBytes());
Map<String, Object> mapObject = objectMapper.readValue(new String(buffer.array(), "UTF-8"),
new TypeReference<Map<String, Object>>() {
});
LOGGER.info("Expected mapObject key1={}", mapObject.get("key1"));
assertEquals("value1", mapObject.get("key1"));
}
}

View File

@ -0,0 +1,64 @@
package com.rbkmoney.proxy.test.utils.cds;
import com.rbkmoney.damsel.base.Ok;
import com.rbkmoney.damsel.cds.CardData;
import com.rbkmoney.damsel.cds.PutCardDataResult;
import com.rbkmoney.damsel.cds.UnlockStatus;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class CdsApiTest {
@Mock
private CdsApi cds;
@Mock
private Ok ok;
@Mock
private CardData cardData;
@Mock
private PutCardDataResult putCardDataResult;
@Before
public void setUp() throws Exception {
// this must be called for the @Mock annotations above to be processed
// and for the mock service to be injected into the controller under test.
MockitoAnnotations.initMocks(this);
}
@Test
public void testUnlock() throws Exception {
ByteBuffer bbuf = ByteBuffer.allocate(10);
UnlockStatus status = UnlockStatus.ok(ok);
Mockito.when(cds.unlock(bbuf)).thenReturn(status);
assertEquals(status, cds.unlock(bbuf));
}
@Test
public void testInit() throws Exception {
short threshold = 1;
short num_shares = 1;
List<ByteBuffer> list = new LinkedList<>();
ByteBuffer bbuf = ByteBuffer.allocate(10);
list.add(bbuf);
Mockito.when(cds.init(threshold, num_shares)).thenReturn(list);
assertEquals(list, cds.init(threshold, num_shares));
}
}

View File

@ -0,0 +1,37 @@
package com.rbkmoney.proxy.test.utils.hellgate;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.nio.ByteBuffer;
import static org.junit.Assert.assertEquals;
public class HellGateApiTest {
@Mock
private HellGateApi hellGate;
@Before
public void setUp() throws Exception {
// this must be called for the @Mock annotations above to be processed
// and for the mock service to be injected into the controller under test.
MockitoAnnotations.initMocks(this);
}
@Test
public void testProcessCallback() throws Exception {
ByteBuffer bbuf = ByteBuffer.wrap("some_byte".getBytes());
ByteBuffer response = ByteBuffer.wrap("some_response_byte".getBytes());
String tag = "some_tag";
Mockito.when(hellGate.processCallback(tag, bbuf)).thenReturn(response);
assertEquals(response, hellGate.processCallback(tag, bbuf));
}
}