file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
AspspMapperTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-aspsp-registry/src/test/java/de/adorsys/xs2a/adapter/registry/mapper/AspspMapperTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.registry.mapper;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.registry.AspspCsvRecord;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import static org.assertj.core.api.Assertions.assertThat;
class AspspMapperTest {
private final AspspMapper aspspMapper = Mappers.getMapper(AspspMapper.class);
private static final String ID = "42";
private static final String ADAPTER_ID = "test-adapter";
@Test
void toAspspCsvRecord() {
Aspsp aspsp = new Aspsp();
aspsp.setId(ID);
aspsp.setAdapterId(ADAPTER_ID);
AspspCsvRecord aspspCsvRecord = aspspMapper.toAspspCsvRecord(aspsp);
assertThat(aspspCsvRecord).isNotNull();
assertThat(aspspCsvRecord.getId()).isEqualTo(ID);
assertThat(aspspCsvRecord.getAdapterId()).isEqualTo(ADAPTER_ID);
}
}
| 1,736 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
LuceneAspspRepository.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-aspsp-registry/src/main/java/de/adorsys/xs2a/adapter/registry/LuceneAspspRepository.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.registry;
import de.adorsys.xs2a.adapter.api.AspspRepository;
import de.adorsys.xs2a.adapter.api.exception.IbanException;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.api.model.AspspScaApproach;
import de.adorsys.xs2a.adapter.registry.exception.RegistryIOException;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.iban4j.Iban;
import org.iban4j.Iban4jException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
public class LuceneAspspRepository implements AspspRepository {
private static final Logger logger = LoggerFactory.getLogger(LuceneAspspRepository.class);
private static final String SEMICOLON_SEPARATOR = ";";
private static final String ZERO_OR_MORE_OF_ANY_CHARS_REGEX = ".*";
private static final float HIGH_PRIORITY = 1.5f;
private static final float MEDIUM_PRIORITY = 1;
private static final float LOW_PRIORITY = 0.5f;
private static final String ID_FIELD_NAME = "id";
private static final String NAME_FIELD_NAME = "name";
private static final String URL_FIELD_NAME = "url";
private static final String BIC_FIELD_NAME = "bic";
private static final String BANK_CODE_FIELD_NAME = "bankCode";
private static final String ADAPTER_ID_FIELD_NAME = "adapterId";
private static final String IDP_URL_FIELD_NAME = "idpUrl";
private static final String SCA_APPROACHES_FIELD_NAME = "scaApproaches";
private Directory directory;
public LuceneAspspRepository(Directory directory) {
this.directory = directory;
}
public Aspsp save(Aspsp aspsp) {
IndexWriterConfig indexWriterConfig = new IndexWriterConfig();
try (IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig)) {
return save(indexWriter, aspsp);
} catch (IOException e) {
throw new RegistryIOException(e);
}
}
@Override
public void deleteById(String aspspId) {
IndexWriterConfig indexWriterConfig = new IndexWriterConfig();
try (IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig)) {
indexWriter.deleteDocuments(new Term(ID_FIELD_NAME, aspspId));
} catch (IOException e) {
throw new RegistryIOException(e);
}
}
@Override
public void deleteAll() {
IndexWriterConfig indexWriterConfig = new IndexWriterConfig();
try (IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig)) {
indexWriter.deleteAll();
} catch (IOException e) {
throw new RegistryIOException(e);
}
}
private Aspsp save(IndexWriter indexWriter, Aspsp aspsp) throws IOException {
Optional<Aspsp> storedAspsp = Optional.empty();
if (aspsp.getId() == null) {
aspsp.setId(UUID.randomUUID().toString());
} else {
storedAspsp = findById(aspsp.getId());
}
Document document = new Document();
document.add(new StringField(ID_FIELD_NAME, serialize(aspsp.getId()), Field.Store.YES));
document.add(new TextField(NAME_FIELD_NAME, serialize(aspsp.getName()), Field.Store.YES));
document.add(new StringField(URL_FIELD_NAME, serialize(aspsp.getUrl()), Field.Store.YES));
document.add(new StringField(BIC_FIELD_NAME, serialize(aspsp.getBic()), Field.Store.YES));
document.add(new StringField(BANK_CODE_FIELD_NAME, serialize(aspsp.getBankCode()), Field.Store.YES));
document.add(new StringField(ADAPTER_ID_FIELD_NAME, serialize(aspsp.getAdapterId()), Field.Store.YES));
document.add(new StringField(IDP_URL_FIELD_NAME, serialize(aspsp.getIdpUrl()), Field.Store.YES));
document.add(new StringField(SCA_APPROACHES_FIELD_NAME, serialize(aspsp.getScaApproaches()), Field.Store.YES));
if (storedAspsp.isPresent()) {
indexWriter.updateDocument(new Term(ID_FIELD_NAME, aspsp.getId()), document);
} else {
indexWriter.addDocument(document);
}
return aspsp;
}
private String serialize(String s) {
return String.valueOf(s); // null -> "null"
}
private <T extends Enum<T>> String serialize(List<T> data) {
if (data == null) {
return "null";
}
return data.stream()
.map(Enum::toString)
.collect(Collectors.joining(SEMICOLON_SEPARATOR));
}
@Override
public void saveAll(List<Aspsp> aspsps) {
IndexWriterConfig indexWriterConfig = new IndexWriterConfig();
try (IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig)) {
for (Aspsp aspsp : aspsps) {
save(indexWriter, aspsp);
}
} catch (IOException e) {
throw new RegistryIOException(e);
}
}
@Override
public Optional<Aspsp> findById(String id) {
logger.debug("Searching for ASPSPs: by ID [{}]", id);
List<Aspsp> aspsps = find(new TermQuery(new Term(ID_FIELD_NAME, id)), null, 1);
if (aspsps.isEmpty()) {
return Optional.empty();
}
return Optional.of(aspsps.get(0));
}
private Optional<Document> getDocument(int docId) {
try (IndexReader indexReader = DirectoryReader.open(directory)) {
if (docId < 0 || docId >= indexReader.maxDoc()) {
return Optional.empty(); // index reader throws IllegalArgumentException if docID is out of bounds
}
Document document = indexReader.document(docId);
return Optional.of(document);
} catch (IOException e) {
throw new RegistryIOException(e);
}
}
private String deserialize(String s) {
if ("null".equals(s)) {
return null;
}
return s;
}
/*
* Possible incoming strings are:
* - "null"
* - ""
* - "DECOUPLED,REDIRECT"
* - "DECOUPLED, REDIRECT" (with space)
* - "decoupled,redirect"
* - "decoupled, redirect" (with space)
* - "decoupled,blablabla" (with unknown enum value)
*/
private <T extends Enum<T>> List<T> deserialize(String s, Class<T> klass) {
if ("null".equals(s)) {
return null;
}
if (s == null || s.isEmpty()) {
return Collections.emptyList();
}
String[] values = s.split(SEMICOLON_SEPARATOR);
return Arrays.stream(values)
// .trim() to handle strings with spaces (like "DECOUPLED, REDIRECT")
// .toUpperCase() to handle lowercase strings (like "redirect")
.map(value -> Enum.valueOf(klass, value.trim().toUpperCase()))
.collect(Collectors.toList());
}
@Override
public List<Aspsp> findByBic(String bic, String after, int size) {
logger.debug("Searching for ASPSPs: by BIC [{}]", bic);
Query query = getBicQuery(bic);
return find(query, after, size);
}
private Query getBicQuery(String bic) {
return new PrefixQuery(new Term(BIC_FIELD_NAME, bic));
}
private List<Aspsp> find(Query query, String after, int size) {
try (IndexReader indexReader = DirectoryReader.open(directory)) {
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
ScoreDoc afterDoc = parseScoreDoc(after);
TopDocs topDocs = indexSearcher.searchAfter(afterDoc, query, size);
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
List<Aspsp> aspsps = Arrays.stream(scoreDocs)
.map(this::getDocumentAsAspsp)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toList());
logger.debug("Searching for ASPSPs: {} record(s) have been found", aspsps.size());
return aspsps;
} catch (IndexNotFoundException e) {
logger.debug("Searching for ASPSPs: no records have been found");
return Collections.emptyList();
} catch (IOException e) {
throw new RegistryIOException(e);
}
}
private Optional<Aspsp> getDocumentAsAspsp(ScoreDoc scoreDoc) {
return getDocument(scoreDoc.doc)
.map(document -> {
Aspsp aspsp = new Aspsp();
aspsp.setId(deserialize(document.get(ID_FIELD_NAME)));
aspsp.setName(deserialize(document.get(NAME_FIELD_NAME)));
aspsp.setUrl(deserialize(document.get(URL_FIELD_NAME)));
aspsp.setBic(deserialize(document.get(BIC_FIELD_NAME)));
aspsp.setBankCode(deserialize(document.get(BANK_CODE_FIELD_NAME)));
aspsp.setAdapterId(deserialize(document.get(ADAPTER_ID_FIELD_NAME)));
aspsp.setIdpUrl(deserialize(document.get(IDP_URL_FIELD_NAME)));
aspsp.setScaApproaches(deserialize(document.get(SCA_APPROACHES_FIELD_NAME), AspspScaApproach.class));
aspsp.setPaginationId(scoreDoc.doc + ":" + scoreDoc.score);
return aspsp;
});
}
private ScoreDoc parseScoreDoc(String id) {
if (id == null) {
return null;
}
// id should consist of a document id and search score separated by a colon
// both components are required for org.apache.lucene.search.IndexSearcher.searchAfter to work properly
String[] components = id.split(":");
if (components.length != 2) {
return null;
}
try {
int docId = Integer.parseInt(components[0]);
float score = Float.parseFloat(components[1]);
return new ScoreDoc(docId, score);
} catch (NumberFormatException e) {
return null;
}
}
@Override
public List<Aspsp> findByBankCode(String bankCode, String after, int size) {
logger.debug("Searching for ASPSPs: by bank code [{}}", bankCode);
Query query = getBankCodeQuery(bankCode);
return find(query, after, size);
}
private Query getBankCodeQuery(String bankCode) {
return new PrefixQuery(new Term(BANK_CODE_FIELD_NAME, bankCode));
}
@Override
public List<Aspsp> findByName(String name, String after, int size) {
logger.debug("Searching for ASPSPs: by name [{}]", name);
BooleanQuery.Builder queryBuilder = new BooleanQuery.Builder();
queryBuilder.add(getNameFuzzyQuery(name), BooleanClause.Occur.SHOULD);
queryBuilder.add(getNameRegexpQuery(name), BooleanClause.Occur.SHOULD);
return find(queryBuilder.build(), after, size);
}
private Query getNameFuzzyQuery(String name) {
return new FuzzyQuery(new Term(NAME_FIELD_NAME, name));
}
private Query getNameRegexpQuery(String name) {
return new RegexpQuery(
new Term(
NAME_FIELD_NAME,
name + ZERO_OR_MORE_OF_ANY_CHARS_REGEX
)
);
}
@Override
public List<Aspsp> findAll(String after, int size) {
logger.debug("Searching for ASPSPs: any {} records", size);
Query query = new MatchAllDocsQuery();
return find(query, after, size);
}
@Override
public List<Aspsp> findLike(Aspsp aspsp, String after, int size) {
if (logger.isDebugEnabled()) {
logger.debug(buildFindLikeLoggingMessage(aspsp));
}
BooleanQuery.Builder queryBuilder = new BooleanQuery.Builder();
if (aspsp.getName() != null) {
queryBuilder.add(buildQueryWithPriority(getNameFuzzyQuery(aspsp.getName()), LOW_PRIORITY), BooleanClause.Occur.SHOULD);
queryBuilder.add(buildQueryWithPriority(getNameRegexpQuery(aspsp.getName()), LOW_PRIORITY), BooleanClause.Occur.SHOULD);
}
if (aspsp.getBic() != null && aspsp.getBankCode() != null) {
String bic = aspsp.getBic();
String bankCode = aspsp.getBankCode();
queryBuilder.add(buildQueryWithPriority(getBicAndBankCodeQuery(bic, bankCode), HIGH_PRIORITY), BooleanClause.Occur.SHOULD);
queryBuilder.add(buildQueryWithPriority(getBicAndEmptyBankCodeQuery(bic), MEDIUM_PRIORITY), BooleanClause.Occur.SHOULD);
queryBuilder.add(buildQueryWithPriority(getEmptyBicAndBankCodeQuery(bankCode), LOW_PRIORITY), BooleanClause.Occur.SHOULD);
} else {
if (aspsp.getBic() != null) {
queryBuilder.add(getBicQuery(aspsp.getBic()), BooleanClause.Occur.SHOULD);
}
if (aspsp.getBankCode() != null) {
queryBuilder.add(getBankCodeQuery(aspsp.getBankCode()), BooleanClause.Occur.SHOULD);
}
}
return find(queryBuilder.build(), after, size);
}
private String buildFindLikeLoggingMessage(Aspsp aspsp) {
StringBuilder messageBuilder = new StringBuilder("Searching for ASPSPs: by");
if (aspsp.getName() != null) {
messageBuilder.append(" name [")
.append(aspsp.getName())
.append("] ,");
}
if (aspsp.getBic() != null) {
messageBuilder.append(" BIC [")
.append(aspsp.getBic())
.append("] ,");
}
if (aspsp.getBankCode() != null) {
messageBuilder.append(" bank code [")
.append(aspsp.getBankCode())
.append("] ,");
}
// .substring(0, messageBuilder.length() - 1) to remove the comma
return messageBuilder.toString().substring(0, messageBuilder.length() - 1);
}
@Override
public List<Aspsp> findByIban(String iban, String after, int size) {
String bankCode;
try {
bankCode = Iban.valueOf(iban).getBankCode();
} catch (Iban4jException e) {
// iban4j exception not used as the cause because the message might contain account number
throw new IbanException("Invalid iban");
}
if (bankCode == null) {
throw new IbanException("Failed to extract the bank code from the iban");
}
return findByBankCode(bankCode, after, size);
}
private BoostQuery buildQueryWithPriority(Query query, float priority) {
return new BoostQuery(query, priority);
}
private Query getBicAndBankCodeQuery(String bic, String bankCode) {
return new BooleanQuery.Builder()
.add(getBicQuery(bic), BooleanClause.Occur.MUST)
.add(getBankCodeQuery(bankCode), BooleanClause.Occur.MUST)
.build();
}
private Query getBicAndEmptyBankCodeQuery(String bic) {
return new BooleanQuery.Builder()
.add(getBicQuery(bic), BooleanClause.Occur.MUST)
.add(getBankCodeQuery("null"), BooleanClause.Occur.MUST)
.build();
}
private Query getEmptyBicAndBankCodeQuery(String bankCode) {
return new BooleanQuery.Builder()
.add(getBicQuery("null"), BooleanClause.Occur.MUST)
.add(getBankCodeQuery(bankCode), BooleanClause.Occur.MUST)
.build();
}
}
| 16,593 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
LuceneAspspRepositoryFactory.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-aspsp-registry/src/main/java/de/adorsys/xs2a/adapter/registry/LuceneAspspRepositoryFactory.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.registry;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import de.adorsys.xs2a.adapter.api.PropertyUtil;
import de.adorsys.xs2a.adapter.api.exception.Xs2aAdapterException;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.registry.exception.RegistryIOException;
import de.adorsys.xs2a.adapter.registry.mapper.AspspMapper;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.mapstruct.factory.Mappers;
import java.io.*;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
public class LuceneAspspRepositoryFactory {
private static final String LUCENE_DIR_PATH_PROPERTY = "csv.aspsp.adapter.lucene.dir.path";
private static final String CSV_ASPSP_ADAPTER_CONFIG_FILE_PATH_PROPERTY = "csv.aspsp.adapter.config.file.path";
private static final String DEFAULT_LUCENE_DIR_PATH = "lucene";
private static final String DEFAULT_CSV_ASPSP_ADAPTER_CONFIG_FILE = "aspsp-adapter-config.csv";
private final AspspMapper aspspMapper = Mappers.getMapper(AspspMapper.class);
public LuceneAspspRepository newLuceneAspspRepository() {
try {
return newLuceneAspspRepositoryInternal();
} catch (IOException e) {
throw new RegistryIOException(e);
}
}
private LuceneAspspRepository newLuceneAspspRepositoryInternal() throws IOException {
String luceneDirPath = PropertyUtil.readProperty(LUCENE_DIR_PATH_PROPERTY, DEFAULT_LUCENE_DIR_PATH);
Directory directory = FSDirectory.open(Paths.get(luceneDirPath, "index"));
LuceneAspspRepository luceneAspspRepository = new LuceneAspspRepository(directory);
byte[] csv = getCsvFileAsByteArray();
MessageDigest messageDigest = getMessageDigest();
String computedDigest = new BigInteger(1, messageDigest.digest(csv)).toString(16);
Path digestPath = Paths.get(luceneDirPath, "digest.sha256");
boolean changed;
if (Files.exists(digestPath)) {
String storedDigest = new String(Files.readAllBytes(digestPath));
changed = !computedDigest.equals(storedDigest);
} else {
changed = true;
}
if (changed) {
for (String f : directory.listAll()) {
directory.deleteFile(f);
}
List<Aspsp> aspsps = readAllRecords(csv);
luceneAspspRepository.saveAll(aspsps);
Files.write(digestPath, computedDigest.getBytes());
}
return luceneAspspRepository;
}
@SuppressWarnings("java:S4790") // hashing is not used in security context
private MessageDigest getMessageDigest() {
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new Xs2aAdapterException(e);
}
return messageDigest;
}
private byte[] getCsvFileAsByteArray() {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[8192];
try (InputStream is = getCsvFileAsStream()) {
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
} catch (IOException e) {
throw new RegistryIOException(e);
}
}
private InputStream getCsvFileAsStream() {
String csvConfigFileProperty = PropertyUtil.readProperty(CSV_ASPSP_ADAPTER_CONFIG_FILE_PATH_PROPERTY);
InputStream inputStream;
if (csvConfigFileProperty.isEmpty()) {
inputStream = getResourceAsStream(DEFAULT_CSV_ASPSP_ADAPTER_CONFIG_FILE);
} else {
inputStream = getFileAsStream(csvConfigFileProperty);
}
return inputStream;
}
private InputStream getResourceAsStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
}
private InputStream getFileAsStream(String filePath) {
try {
return new FileInputStream(filePath);
} catch (FileNotFoundException e) {
throw new RegistryIOException(e);
}
}
private List<Aspsp> readAllRecords(byte[] csv) {
ObjectReader objectReader = new CsvMapper()
.readerWithTypedSchemaFor(AspspCsvRecord.class)
.withHandler(new DeserializationProblemHandler() {
@Override
public Object handleWeirdStringValue(DeserializationContext ctxt, Class<?> targetType, String valueToConvert, String failureMsg) {
if (targetType.isEnum()) {
return Enum.valueOf((Class<Enum>) targetType, valueToConvert.trim().toUpperCase());
}
return DeserializationProblemHandler.NOT_HANDLED;
}
});
List<AspspCsvRecord> aspsps;
try {
aspsps = objectReader
.<AspspCsvRecord>readValues(csv)
.readAll();
} catch (IOException e) {
throw new RegistryIOException(e);
}
return aspspMapper.toAspsps(aspsps);
}
}
| 6,473 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AspspCsvRecord.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-aspsp-registry/src/main/java/de/adorsys/xs2a/adapter/registry/AspspCsvRecord.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.registry;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import de.adorsys.xs2a.adapter.api.model.AspspScaApproach;
import java.util.List;
import java.util.Objects;
@JsonPropertyOrder({"id", "aspspName", "bic", "url", "adapterId", "bankCode", "idpUrl", "aspspScaApproaches"})
public class AspspCsvRecord {
private String id;
private String aspspName;
private String bic;
private String url;
private String bankCode;
private String adapterId;
private String idpUrl;
private List<AspspScaApproach> aspspScaApproaches;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAspspName() {
return aspspName;
}
public void setAspspName(String aspspName) {
this.aspspName = aspspName;
}
public String getBic() {
return bic;
}
public void setBic(String bic) {
this.bic = bic;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getBankCode() {
return bankCode;
}
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getAdapterId() {
return adapterId;
}
public void setAdapterId(String adapterId) {
this.adapterId = adapterId;
}
public String getIdpUrl() {
return idpUrl;
}
public void setIdpUrl(String idpUrl) {
this.idpUrl = idpUrl;
}
public List<AspspScaApproach> getAspspScaApproaches() {
return aspspScaApproaches;
}
public void setAspspScaApproaches(List<AspspScaApproach> aspspScaApproaches) {
this.aspspScaApproaches = aspspScaApproaches;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AspspCsvRecord that = (AspspCsvRecord) o;
return Objects.equals(id, that.id) &&
Objects.equals(aspspName, that.aspspName) &&
Objects.equals(bic, that.bic) &&
Objects.equals(url, that.url) &&
Objects.equals(bankCode, that.bankCode) &&
Objects.equals(adapterId, that.adapterId) &&
Objects.equals(idpUrl, that.idpUrl) &&
Objects.equals(aspspScaApproaches, that.aspspScaApproaches);
}
@Override
public int hashCode() {
return Objects.hash(id, aspspName, bic, url, bankCode, adapterId, idpUrl, aspspScaApproaches);
}
@Override
public String toString() {
return "AspspCsvRecord{" +
"id='" + id + '\'' +
", aspspName='" + aspspName + '\'' +
", bic='" + bic + '\'' +
", url='" + url + '\'' +
", bankCode='" + bankCode + '\'' +
", adapterId='" + adapterId + '\'' +
", idpUrl='" + idpUrl + '\'' +
", aspspScaApproaches=" + aspspScaApproaches +
'}';
}
}
| 3,969 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AspspMapper.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-aspsp-registry/src/main/java/de/adorsys/xs2a/adapter/registry/mapper/AspspMapper.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.registry.mapper;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.registry.AspspCsvRecord;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import java.util.List;
@Mapper
public interface AspspMapper {
List<Aspsp> toAspsps(List<AspspCsvRecord> aspspCsvRecords);
@Mapping(source = "aspspName", target = "name")
@Mapping(target = "scaApproaches", source = "aspspScaApproaches")
@Mapping(target = "paginationId", ignore = true)
Aspsp toAspsp(AspspCsvRecord aspspCsvRecord);
@Mapping(target = "aspspScaApproaches", source = "scaApproaches")
@Mapping(source = "name", target = "aspspName")
AspspCsvRecord toAspspCsvRecord(Aspsp aspsp);
}
| 1,573 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
RegistryIOException.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-aspsp-registry/src/main/java/de/adorsys/xs2a/adapter/registry/exception/RegistryIOException.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.registry.exception;
import java.io.IOException;
import java.util.Objects;
public class RegistryIOException extends RuntimeException {
public RegistryIOException(IOException cause) {
super(Objects.requireNonNull(cause));
}
}
| 1,105 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
TestModelBuilder.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/TestModelBuilder.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl;
import de.adorsys.xs2a.adapter.api.model.*;
import java.util.*;
public class TestModelBuilder {
private TestModelBuilder() {
}
public static final String MESSAGE = "message";
public static final String CONSTENT_ID = "constent-ID";
public static final String AUTHORISATION_ID = "authorisation-ID";
public static final String PAYMENT_ID = "payment-ID";
public static final String NAME = "SMS OTP on phone +49160 xxxxx 28";
public static final String TYPE = "SMS_OTP";
public static final String EXPLANATION = "some explanation";
public static final String VERSION = "v1.2";
public static final String METHOD_ID = "authMethodId3";
public static final String ADDITIONAL_INFO = "additionalInfo";
public static final List<String> DATA = Collections.singletonList("data");
public static final String IMAGE = "image";
public static final String LINK = "http://link-to-image";
public static final int LENGTH = 123;
public static final String AUTHENTICATION_METHOD_ID = "authentication-method-ID";
public static final String SCA_AUTHENTICATION_DATA = "sca-authentication-data";
public static final String ACCESS_TOKEN = "asdb34nasnd1124fdflsdnasdnw.access.token";
public static final String REFRESH_TOKEN = "asdasd2141rfgdgjh5656s.refresh.token";
public static final String SCOPE = "ais:dsadsdasd";
public static final String TOKEN_TYPE = "type";
public static final long exripesInSeconds = 3600L;
public static ConsentsResponse201 buildConsentCreationResponse() {
ConsentsResponse201 response = new ConsentsResponse201();
response.setPsuMessage(MESSAGE);
response.setConsentId(CONSTENT_ID);
response.setConsentStatus(ConsentStatus.RECEIVED);
Map<String, HrefType> links = new HashMap<>();
HrefType link = new HrefType();
link.setHref(MESSAGE);
links.put(CONSTENT_ID, link);
response.setLinks(links);
response.setScaMethods(Collections.singletonList(buildAuthenticationObject()));
response.setChosenScaMethod(buildAuthenticationObject());
response.setChallengeData(buildChallengeData());
return response;
}
public static AuthenticationObject buildAuthenticationObject() {
AuthenticationObject authenticationObject = new AuthenticationObject();
authenticationObject.setName(NAME);
authenticationObject.setAuthenticationType(TYPE);
authenticationObject.setExplanation(EXPLANATION);
authenticationObject.setAuthenticationVersion(VERSION);
authenticationObject.setAuthenticationMethodId(METHOD_ID);
return authenticationObject;
}
public static ChallengeData buildChallengeData() {
ChallengeData data = new ChallengeData();
data.setAdditionalInformation(ADDITIONAL_INFO);
data.setData(DATA);
data.setImageLink(LINK);
data.setOtpFormat(ChallengeData.OtpFormat.CHARACTERS);
data.setOtpMaxLength(LENGTH);
data.setImage(IMAGE.getBytes());
return data;
}
public static ConsentInformationResponse200Json buildConsentInformationResponse() {
ConsentInformationResponse200Json consentInformation = new ConsentInformationResponse200Json();
consentInformation.setConsentStatus(ConsentStatus.RECEIVED);
consentInformation.setFrequencyPerDay(4);
consentInformation.setRecurringIndicator(true);
return consentInformation;
}
public static ConsentStatusResponse200 buildConsentStatusResponse() {
ConsentStatusResponse200 consentStatusResponse = new ConsentStatusResponse200();
consentStatusResponse.setConsentStatus(ConsentStatus.RECEIVED);
consentStatusResponse.setPsuMessage(MESSAGE);
return consentStatusResponse;
}
public static Authorisations buildConsentAuthorisationResponse() {
Authorisations authorisations = new Authorisations();
authorisations.setAuthorisationIds(Collections.singletonList(AUTHORISATION_ID));
return authorisations;
}
public static StartScaprocessResponse buildStartScaprocessResponse() {
StartScaprocessResponse startScaprocessResponse = new StartScaprocessResponse();
startScaprocessResponse.setAuthorisationId(AUTHORISATION_ID);
startScaprocessResponse.setPsuMessage(MESSAGE);
startScaprocessResponse.setScaStatus(ScaStatus.STARTED);
return startScaprocessResponse;
}
public static UpdatePsuAuthentication buildUpdatePsuAuthentication() {
UpdatePsuAuthentication updatePsuAuthentication = new UpdatePsuAuthentication();
updatePsuAuthentication.setPsuData(new PsuData());
return updatePsuAuthentication;
}
public static UpdatePsuAuthenticationResponse buildUpdatePsuAuthenticationResponse() {
UpdatePsuAuthenticationResponse updatePsuAuthenticationResponse = new UpdatePsuAuthenticationResponse();
updatePsuAuthenticationResponse.setPsuMessage(MESSAGE);
updatePsuAuthenticationResponse.setScaStatus(ScaStatus.STARTED);
updatePsuAuthenticationResponse.setAuthorisationId(AUTHORISATION_ID);
return updatePsuAuthenticationResponse;
}
public static SelectPsuAuthenticationMethodResponse buildSelectPsuAuthenticationMethodResponse() {
SelectPsuAuthenticationMethodResponse response = new SelectPsuAuthenticationMethodResponse();
response.setScaStatus(ScaStatus.SCAMETHODSELECTED);
response.setPsuMessage(MESSAGE);
return response;
}
public static SelectPsuAuthenticationMethod buildSelectPsuAuthenticationMethod() {
SelectPsuAuthenticationMethod selectPsuAuthenticationMethod = new SelectPsuAuthenticationMethod();
selectPsuAuthenticationMethod.setAuthenticationMethodId(AUTHENTICATION_METHOD_ID);
return selectPsuAuthenticationMethod;
}
public static ScaStatusResponse buildScaStatusResponse() {
ScaStatusResponse scaStatusResponse = new ScaStatusResponse();
scaStatusResponse.setScaStatus(ScaStatus.FINALISED);
return scaStatusResponse;
}
public static TransactionAuthorisation buildTransactionAuthorisation() {
TransactionAuthorisation transactionAuthorisation = new TransactionAuthorisation();
transactionAuthorisation.setScaAuthenticationData(SCA_AUTHENTICATION_DATA);
return transactionAuthorisation;
}
public static AccountList buildAccountList() {
AccountList accountList = new AccountList();
accountList.setAccounts(Arrays.asList(new AccountDetails(), new AccountDetails()));
return accountList;
}
public static OK200AccountDetails buildAccountDetails() {
OK200AccountDetails accountDetails = new OK200AccountDetails();
accountDetails.setAccount(new AccountDetails());
return accountDetails;
}
public static TransactionsResponse200Json buildTransactionsResponse() {
TransactionsResponse200Json transactionsResponse200Json = new TransactionsResponse200Json();
Map<String, HrefType> links = new HashMap<>();
HrefType link = new HrefType();
link.setHref(MESSAGE);
links.put(CONSTENT_ID, link);
transactionsResponse200Json.setLinks(links);
return transactionsResponse200Json;
}
public static ReadCardAccountBalanceResponse200 buildReadCardAccountBalanceResponse() {
ReadCardAccountBalanceResponse200 readCardAccountBalanceResponse200
= new ReadCardAccountBalanceResponse200();
readCardAccountBalanceResponse200.setBalances(Arrays.asList(new Balance(), new Balance()));
return readCardAccountBalanceResponse200;
}
public static CardAccountsTransactionsResponse200 buildCardAccountsTransactionsResponse() {
CardAccountsTransactionsResponse200 cardAccountsTransactionsResponse200
= new CardAccountsTransactionsResponse200();
Map<String, HrefType> links = new HashMap<>();
HrefType link = new HrefType();
link.setHref(MESSAGE);
links.put(CONSTENT_ID, link);
cardAccountsTransactionsResponse200.setLinks(links);
return cardAccountsTransactionsResponse200;
}
public static ReadAccountBalanceResponse200 buildReadAccountBalanceResponse() {
ReadAccountBalanceResponse200 readAccountBalanceResponse200 =
new ReadAccountBalanceResponse200();
readAccountBalanceResponse200.setBalances(Arrays.asList(new Balance(), new Balance()));
return readAccountBalanceResponse200;
}
public static TokenResponse buildTokenResponse() {
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setAccessToken(ACCESS_TOKEN);
tokenResponse.setExpiresInSeconds(exripesInSeconds);
tokenResponse.setRefreshToken(REFRESH_TOKEN);
tokenResponse.setScope(SCOPE);
tokenResponse.setTokenType(TOKEN_TYPE);
return tokenResponse;
}
public static PaymentInitationRequestResponse201 buildPaymentInitationRequestResponse() {
PaymentInitationRequestResponse201 paymentInitationRequestResponse201
= new PaymentInitationRequestResponse201();
paymentInitationRequestResponse201.setPaymentId(PAYMENT_ID);
Map<String, HrefType> links = new HashMap<>();
HrefType link = new HrefType();
link.setHref(MESSAGE);
links.put(PAYMENT_ID, link);
paymentInitationRequestResponse201.setLinks(links);
paymentInitationRequestResponse201.setPsuMessage(MESSAGE);
paymentInitationRequestResponse201.setTransactionFeeIndicator(true);
return paymentInitationRequestResponse201;
}
public static PaymentInitiationStatusResponse200Json buildPaymentInitiationStatusResponse() {
PaymentInitiationStatusResponse200Json paymentInitiationStatusResponse200Json
= new PaymentInitiationStatusResponse200Json();
paymentInitiationStatusResponse200Json.setTransactionStatus(TransactionStatus.ACCC);
paymentInitiationStatusResponse200Json.setFundsAvailable(true);
paymentInitiationStatusResponse200Json.setPsuMessage(MESSAGE);
return paymentInitiationStatusResponse200Json;
}
}
| 11,143 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
IngOptionalParametersFilterTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/config/IngOptionalParametersFilterTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.config;
import de.adorsys.xs2a.adapter.api.AccountInformationService;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.exception.OAuthException;
import de.adorsys.xs2a.adapter.api.model.ErrorResponse;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import de.adorsys.xs2a.adapter.rest.impl.controller.ConsentController;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class IngOptionalParametersFilterTest {
private MockMvc mockMvc;
@InjectMocks
private ConsentController controller;
@Mock
private AccountInformationService accountInformationService;
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(new MappingJackson2HttpMessageConverter())
.setControllerAdvice(new RestExceptionHandler(new HeadersMapper()))
.addFilters(new IngOptionalParametersFilter())
.build();
}
@Test
void doFilter() throws Exception {
ArgumentCaptor<RequestParams> paramsCaptor = ArgumentCaptor.forClass(RequestParams.class);
when(accountInformationService.createConsent(any(), paramsCaptor.capture(), any()))
.thenThrow(new OAuthException(ResponseHeaders.emptyResponseHeaders(), new ErrorResponse(), ""));
mockMvc.perform(post(ConsentController.CONSENTS)
.contentType(APPLICATION_JSON_VALUE)
.content("{}"))
.andExpect(status().is(HttpStatus.FORBIDDEN.value()));
RequestParams params = paramsCaptor.getValue();
assertThat(params.toMap())
.containsKey("balanceTypes")
.containsKey("limit");
}
}
| 3,467 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
MimeHeadersSupportFilterTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/config/MimeHeadersSupportFilterTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.config;
import de.adorsys.xs2a.adapter.api.AccountInformationService;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.exception.AspspRegistrationNotFoundException;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import de.adorsys.xs2a.adapter.rest.impl.controller.ConsentController;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class MimeHeadersSupportFilterTest {
private MockMvc mockMvc;
@InjectMocks
private ConsentController controller;
@Mock
private AccountInformationService accountInformationService;
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(new MappingJackson2HttpMessageConverter())
.setControllerAdvice(new RestExceptionHandler(new HeadersMapper()))
.addFilters(new MimeHeadersSupportFilter())
.build();
}
@Test
void doFilter() throws Exception {
String encodedUmlauts = "=?UTF-8?B?w6Qgw7Ygw7w=?="; // ä ö ü
ArgumentCaptor<RequestHeaders> headersCaptor = ArgumentCaptor.forClass(RequestHeaders.class);
when(accountInformationService.createConsent(headersCaptor.capture(), any(), any()))
.thenThrow(new AspspRegistrationNotFoundException(""));
mockMvc.perform(post(ConsentController.CONSENTS)
.header(RequestHeaders.PSU_ID, encodedUmlauts)
.contentType(APPLICATION_JSON_VALUE)
.content("{}"))
.andExpect(status().is(HttpStatus.BAD_REQUEST.value()))
.andReturn();
RequestHeaders headers = headersCaptor.getValue();
assertThat(headers.get(RequestHeaders.PSU_ID)).contains("ä ö ü");
}
}
| 3,552 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
RestExceptionHandlerTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/config/RestExceptionHandlerTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.config;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.exception.AccessTokenException;
import de.adorsys.xs2a.adapter.api.exception.ErrorResponseException;
import de.adorsys.xs2a.adapter.api.exception.RequestAuthorizationValidationException;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.api.validation.RequestValidationException;
import de.adorsys.xs2a.adapter.api.validation.ValidationError;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.List;
import static de.adorsys.xs2a.adapter.api.ResponseHeaders.emptyResponseHeaders;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
class RestExceptionHandlerTest {
private static final String OAUTH_ERROR_RESPONSE = "{\n" +
" \"timestamp\": \"2019-10-17T13:12:15.171+0000\",\n" +
" \"status\": 400,\n" +
" \"error\": \"Bad Request\",\n" +
" \"message\": \"Missing request header 'code' for method parameter of type String\",\n" +
" \"path\": \"/oauth/token\"\n" +
"}";
private static final String X_GTW_ERROR_ORIGINATION = "X-GTW-Error-Origination";
private static final String EMBEDDED_PRE_AUTH = "embeddedPreAuth";
private static final String PRE_AUTH_TOKEN_URI = "/v1/embedded-pre-auth/token";
public static final String ADAPTER = "ADAPTER";
private RestExceptionHandler exceptionHandler;
@BeforeEach
void setUp() {
exceptionHandler = new RestExceptionHandler(new HeadersMapper());
}
@Test
void handleErrorResponseExceptionReturnsOriginalMessageWhenXs2aErrorResponseFieldsAreAbsent() {
ErrorResponseException ex =
new ErrorResponseException(400, emptyResponseHeaders(), new ErrorResponse(), OAUTH_ERROR_RESPONSE);
RestExceptionHandler exceptionHandler = this.exceptionHandler;
ResponseEntity<?> responseEntity = exceptionHandler.handle(ex);
assertThat(responseEntity.getBody()).isEqualTo(OAUTH_ERROR_RESPONSE);
}
@Test
void requestValidationException() {
RequestValidationException requestValidationException =
new RequestValidationException(singletonList(new ValidationError(ValidationError.Code.REQUIRED,
RequestHeaders.TPP_REDIRECT_URI,
"...")));
ResponseEntity<ErrorResponse> responseEntity = exceptionHandler.handle(requestValidationException);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(responseEntity.getHeaders().get(X_GTW_ERROR_ORIGINATION)).isEqualTo(singletonList(ADAPTER));
assertThat(responseEntity.getBody().getTppMessages()).hasSize(1);
TppMessage tppMessage = responseEntity.getBody().getTppMessages().get(0);
assertThat(tppMessage.getCategory()).isEqualTo(TppMessageCategory.ERROR);
assertThat(tppMessage.getCode()).isEqualTo(MessageCode.FORMAT_ERROR.toString());
assertThat(tppMessage.getPath()).isEqualTo(requestValidationException.getValidationErrors().get(0).getPath());
assertThat(tppMessage.getText()).isEqualTo(requestValidationException.getValidationErrors().get(0).getMessage());
}
@Test
void preAuthorisationException() {
RequestAuthorizationValidationException requestAuthorizationValidationException
= new RequestAuthorizationValidationException(getErrorResponse(), "test error");
ResponseEntity<?> actualResponse = exceptionHandler.handle(requestAuthorizationValidationException);
assertThat(actualResponse)
.isNotNull()
.matches(res -> res.getStatusCodeValue() == 401)
.matches(res -> {
HttpHeaders headers = res.getHeaders();
List<String> originator = headers.get(X_GTW_ERROR_ORIGINATION);
if (originator != null) {
return originator.contains(ADAPTER);
}
return false;
})
.extracting(ResponseEntity::getBody)
.isInstanceOf(ErrorResponse.class)
.matches(body -> ((ErrorResponse) body)
.getLinks()
.get(EMBEDDED_PRE_AUTH)
.getHref()
.equals(PRE_AUTH_TOKEN_URI));
}
@Test
void accessTokenException_internalError() {
var actualResponse = exceptionHandler.handle(new AccessTokenException("foo"));
assertThat(actualResponse)
.isNotNull()
.matches(resp -> HttpStatus.INTERNAL_SERVER_ERROR == resp.getStatusCode())
.matches(resp -> {
var headers = resp.getHeaders();
assertThat(headers).isNotEmpty();
return headers.containsValue(List.of("ADAPTER"));
})
.extracting(ResponseEntity::getBody)
.extracting(ErrorResponse::getTppMessages, InstanceOfAssertFactories.list(TppMessage.class))
.hasSize(1)
.element(0)
.matches(tppMessage -> "Server error".equals(tppMessage.getText()));
}
@Test
void accessTokenException_bankError() {
final String originalMessage = "bank message";
var actualResponse
= exceptionHandler.handle(new AccessTokenException("foo", 400, originalMessage, true));
assertThat(actualResponse)
.isNotNull()
.matches(resp -> HttpStatus.BAD_REQUEST == resp.getStatusCode())
.matches(resp -> {
var headers = resp.getHeaders();
assertThat(headers).isNotEmpty();
return headers.containsValue(List.of("BANK"));
})
.extracting(ResponseEntity::getBody)
.extracting(ErrorResponse::getTppMessages, InstanceOfAssertFactories.list(TppMessage.class))
.hasSize(1)
.element(0)
.matches(tppMessage -> originalMessage.equals(tppMessage.getText()));
}
private ErrorResponse getErrorResponse() {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setLinks(singletonMap(EMBEDDED_PRE_AUTH, getHrefType()));
return errorResponse;
}
private HrefType getHrefType() {
HrefType hrefType = new HrefType();
hrefType.setHref(PRE_AUTH_TOKEN_URI);
return hrefType;
}
}
| 7,580 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PeriodicPaymentInitiationMultipartBodyHttpMessageConverterTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/config/PeriodicPaymentInitiationMultipartBodyHttpMessageConverterTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.config;
import de.adorsys.xs2a.adapter.api.model.*;
import org.junit.jupiter.api.Test;
import org.springframework.mock.http.MockHttpOutputMessage;
import java.io.IOException;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
class PeriodicPaymentInitiationMultipartBodyHttpMessageConverterTest {
@Test
void write() throws IOException {
PeriodicPaymentInitiationMultipartBodyHttpMessageConverter converter =
new PeriodicPaymentInitiationMultipartBodyHttpMessageConverter(WebMvcConfig.newConfiguredObjectMapper()) {
@Override
protected byte[] generateMultipartBoundary() {
return "r3kG3pY8rRua0pHMuWCLa2TESC--Kne".getBytes();
}
};
PeriodicPaymentInitiationMultipartBody body = new PeriodicPaymentInitiationMultipartBody();
body.setXml_sct("<xml></xml>");
PeriodicPaymentInitiationXmlPart2StandingorderTypeJson json =
new PeriodicPaymentInitiationXmlPart2StandingorderTypeJson();
json.setDayOfExecution(DayOfExecution._2);
json.setFrequency(FrequencyCode.QUARTERLY);
json.setStartDate(LocalDate.of(2020, 1, 1));
json.setEndDate(LocalDate.of(2021, 1, 1));
json.setExecutionRule(ExecutionRule.PRECEDING);
body.setJson_standingorderType(json);
MockHttpOutputMessage out = new MockHttpOutputMessage();
converter.write(body, null, out);
assertThat(out.getBodyAsString())
.isEqualTo("--r3kG3pY8rRua0pHMuWCLa2TESC--Kne\r\n" +
"Content-Disposition: form-data; name=\"xml_sct\"\r\n" +
"Content-Type: application/xml\r\n" +
"Content-Length: 11\r\n" +
"\r\n" +
"<xml></xml>\r\n" +
"--r3kG3pY8rRua0pHMuWCLa2TESC--Kne\r\n" +
"Content-Disposition: form-data; name=\"json_standingorderType\"\r\n" +
"Content-Type: application/json\r\n" +
"\r\n" +
"{\n" +
" \"startDate\" : \"2020-01-01\",\n" +
" \"endDate\" : \"2021-01-01\",\n" +
" \"executionRule\" : \"preceding\",\n" +
" \"frequency\" : \"Quarterly\",\n" +
" \"dayOfExecution\" : \"2\"\n" +
"}\r\n" +
"--r3kG3pY8rRua0pHMuWCLa2TESC--Kne--\r\n");
}
}
| 3,309 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PropertyEditorControllerAdviceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/config/PropertyEditorControllerAdviceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.config;
import de.adorsys.xs2a.adapter.api.AccountInformationService;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.exception.NotAcceptableException;
import de.adorsys.xs2a.adapter.api.model.BookingStatusCard;
import de.adorsys.xs2a.adapter.api.model.BookingStatusGeneric;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import de.adorsys.xs2a.adapter.rest.impl.controller.ConsentController;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(MockitoExtension.class)
class PropertyEditorControllerAdviceTest {
MockMvc mockMvc;
@InjectMocks
private ConsentController consentController;
@Mock
private AccountInformationService accountInformationService;
@Captor
private ArgumentCaptor<RequestParams> paramsCaptor;
@Spy
PropertyEditorControllerAdvice propertyEditorControllerAdvice
= new PropertyEditorControllerAdvice(new ApplicationConversionService());
@BeforeEach
void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(consentController)
.setControllerAdvice(propertyEditorControllerAdvice,
new RestExceptionHandler(new HeadersMapper()))
.build();
}
@Test
void setAsText_bookingStatus() throws Exception {
when(accountInformationService.getTransactionList(anyString(), any(RequestHeaders.class), paramsCaptor.capture()))
.thenThrow(new NotAcceptableException("error message"));
mockMvc.perform(get("/v1/accounts/1/transactions")
.accept(APPLICATION_JSON_VALUE)
.param("bookingStatus", "booked"))
.andExpect(status().isNotAcceptable());
verify(propertyEditorControllerAdvice, atLeastOnce()).initBinder(any());
RequestParams actualParams = paramsCaptor.getValue();
assertNotNull(actualParams);
assertEquals(BookingStatusGeneric.BOOKED.toString(), actualParams.bookingStatus());
}
@Test
void setAsText_cardBookingStatus() throws Exception {
when(accountInformationService.getCardAccountTransactionList(anyString(), any(RequestHeaders.class), paramsCaptor.capture()))
.thenThrow(new NotAcceptableException("error message"));
mockMvc.perform(get("/v1/card-accounts/1/transactions")
.accept(APPLICATION_JSON_VALUE)
.param("bookingStatus", "booked"))
.andExpect(status().isNotAcceptable());
verify(propertyEditorControllerAdvice, atLeastOnce()).initBinder(any());
RequestParams actualParams = paramsCaptor.getValue();
assertNotNull(actualParams);
assertEquals(BookingStatusCard.BOOKED.toString(), actualParams.bookingStatus());
}
}
| 4,500 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
EmbeddedPreAuthorisationControllerTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/controller/EmbeddedPreAuthorisationControllerTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.adorsys.xs2a.adapter.api.EmbeddedPreAuthorisationService;
import de.adorsys.xs2a.adapter.api.model.TokenResponse;
import de.adorsys.xs2a.adapter.mapper.Oauth2Mapper;
import de.adorsys.xs2a.adapter.rest.api.model.EmbeddedPreAuthorisationRequestTO;
import de.adorsys.xs2a.adapter.rest.api.model.TokenResponseTO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class EmbeddedPreAuthorisationControllerTest {
private MockMvc mockMvc;
private final Oauth2Mapper mapper = Mappers.getMapper(Oauth2Mapper.class);
@Mock
private EmbeddedPreAuthorisationService authorisationService;
@InjectMocks
private EmbeddedPreAuthorisationController controller;
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(new MappingJackson2HttpMessageConverter())
.build();
}
@Test
void getToken() throws Exception {
EmbeddedPreAuthorisationRequestTO request = new EmbeddedPreAuthorisationRequestTO();
TokenResponse token = new TokenResponse();
token.setAccessToken("access-token");
token.setScope("scope");
token.setRefreshToken("refresh-token");
token.setExpiresInSeconds(3600L);
token.setTokenType("token-type");
when(authorisationService.getToken(any(), any()))
.thenReturn(token);
MvcResult mvcResult = mockMvc.perform(post("/v1/embedded-pre-auth/token")
.contentType(MediaType.APPLICATION_JSON)
.content(writeValueAsString(request)))
.andExpect(status().is(HttpStatus.OK.value()))
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
TokenResponseTO actual = jsonStringToObject(response.getContentAsString());
assertThat(actual).isEqualTo(mapper.map(token));
}
private <T> String writeValueAsString(T value) throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(value);
}
private TokenResponseTO jsonStringToObject(String json) throws JsonProcessingException {
return new ObjectMapper().readValue(json, TokenResponseTO.class);
}
}
| 4,278 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AspspSearchControllerTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/controller/AspspSearchControllerTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.adorsys.xs2a.adapter.api.AspspReadOnlyRepository;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.api.model.AspspScaApproach;
import de.adorsys.xs2a.adapter.mapper.AspspMapper;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import de.adorsys.xs2a.adapter.rest.api.AspspSearchApi;
import de.adorsys.xs2a.adapter.rest.api.model.AspspTO;
import de.adorsys.xs2a.adapter.rest.impl.config.RestExceptionHandler;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import pro.javatar.commons.reader.JsonReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class AspspSearchControllerTest {
private static final String ASPSP_ID = "aspsp-id";
private MockMvc mockMvc;
private AspspMapper mapper = Mappers.getMapper(AspspMapper.class);
@InjectMocks
private AspspSearchController controller;
@Mock
private AspspReadOnlyRepository repository;
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(new MappingJackson2HttpMessageConverter())
.setControllerAdvice(new RestExceptionHandler(new HeadersMapper()))
.build();
}
@Test
void getById() throws Exception {
Aspsp aspsp = buildAspsp();
AspspTO aspspTO = mapper.toAspspTO(aspsp);
String aspspTOJson = new ObjectMapper().writeValueAsString(aspspTO);
when(repository.findById(ASPSP_ID)).thenReturn(Optional.of(aspsp));
MvcResult mvcResult = mockMvc.perform(get(AspspSearchApi.V1_APSPS_BY_ID, ASPSP_ID).content(aspspTOJson))
.andExpect(status().is(HttpStatus.OK.value()))
.andReturn();
AspspTO response = JsonReader.getInstance()
.getObjectFromString(mvcResult.getResponse().getContentAsString(), AspspTO.class);
assertThat(response).isEqualTo(aspspTO);
}
@Test
void getByIdNotFound() throws Exception {
when(repository.findById(ASPSP_ID)).thenReturn(Optional.empty());
mockMvc.perform(get(AspspSearchApi.V1_APSPS_BY_ID, ASPSP_ID).content("{}"))
.andExpect(status().is(HttpStatus.NOT_FOUND.value()))
.andReturn();
}
@Test
void getAspsp_byIban() throws Exception {
Aspsp aspsp = buildAspsp();
AspspTO aspspTO = mapper.toAspspTO(aspsp);
when(repository.findByIban(anyString(), any(), anyInt()))
.thenReturn(Collections.singletonList(aspsp));
MvcResult mvcResult = mockMvc.perform(get(AspspSearchApi.V1_APSPS)
.queryParam("iban", "DE8749999960000000512"))
.andExpect(status().isOk())
.andReturn();
verify(repository, times(1)).findByIban(anyString(), any(), anyInt());
List<AspspTO> response = getListFromString(mvcResult);
assertThat(response).contains(aspspTO);
}
@Test
void getAspsp_all() throws Exception {
Aspsp aspsp = buildAspsp();
List<Aspsp> aspsps = Arrays.asList(aspsp, aspsp);
when(repository.findAll(any(), anyInt())).thenReturn(aspsps);
MvcResult mvcResult = mockMvc.perform(get(AspspSearchApi.V1_APSPS))
.andExpect(status().isOk())
.andReturn();
List<AspspTO> response = getListFromString(mvcResult);
verify(repository, times(1)).findAll(any(), anyInt());
assertThat(response).hasSize(2)
.contains(mapper.toAspspTO(aspsp));
}
@Test
void getAspsp_byName() throws Exception {
String bankName = "bank name";
Aspsp aspsp = buildAspsp();
aspsp.setName(bankName);
when(repository.findLike(any(Aspsp.class), any(), anyInt()))
.thenReturn(Collections.singletonList(aspsp));
MvcResult mvcResult = mockMvc.perform(get(AspspSearchApi.V1_APSPS)
.queryParam("name", bankName))
.andExpect(status().isOk())
.andReturn();
verify(repository, times(1)).findLike(any(Aspsp.class), any(), anyInt());
List<AspspTO> response = getListFromString(mvcResult);
assertThat(response).contains(mapper.toAspspTO(aspsp));
}
private List<AspspTO> getListFromString(MvcResult mvcResult) throws IOException {
return JsonReader.getInstance()
.getListFromString(mvcResult.getResponse().getContentAsString(), AspspTO.class);
}
private Aspsp buildAspsp() {
Aspsp aspsp = new Aspsp();
aspsp.setAdapterId("adapterId");
aspsp.setBankCode("bankCode");
aspsp.setBic("bic");
aspsp.setId(ASPSP_ID);
aspsp.setName("bankName");
aspsp.setUrl("https://online-banking.url");
aspsp.setIdpUrl("https://idp.bank.url");
aspsp.setScaApproaches(Collections.singletonList(AspspScaApproach.OAUTH));
return aspsp;
}
}
| 6,687 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PaymentControllerTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/controller/PaymentControllerTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.adorsys.xs2a.adapter.api.PaymentInitiationService;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import de.adorsys.xs2a.adapter.rest.impl.TestModelBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.Collections;
import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class PaymentControllerTest {
protected static final PaymentService PAYMENT_SERVICE = PaymentService.PAYMENTS;
protected static final PaymentProduct PAYMENT_PRODUCT = PaymentProduct.SEPA_CREDIT_TRANSFERS;
private static final String PAYMENT_URL = "/v1/" + PAYMENT_SERVICE + "/" + PAYMENT_PRODUCT;
private static final FormattingConversionService conversionService = buildFormattingConversionService();
@InjectMocks
private PaymentController controller;
@Mock
private PaymentInitiationService paymentInitiationService;
@Mock
private HeadersMapper headersMapper;
@Spy
private ObjectMapper objectMapper;
MockMvc mockMvc;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(new MappingJackson2HttpMessageConverter())
.setConversionService(conversionService)
.build();
}
@Test
void initiatePayment_multipart() throws Exception {
PeriodicPaymentInitiationMultipartBody body = new PeriodicPaymentInitiationMultipartBody();
when(paymentInitiationService.initiatePayment(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), any(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildPaymentInitationRequestResponse()));
mockMvc.perform(post(PAYMENT_URL)
.content(writeValueAsString(body))
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isCreated())
.andExpect(jsonPath(format("$._links.%s.href", TestModelBuilder.PAYMENT_ID),
containsString(TestModelBuilder.MESSAGE)))
.andExpect(jsonPath("$.paymentId", containsString(TestModelBuilder.PAYMENT_ID)))
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)))
.andExpect(jsonPath("$.transactionFeeIndicator", is(true)));
verify(paymentInitiationService, times(1))
.initiatePayment(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), any(), any(), any());
}
@Test
void initiatePayment_json() throws Exception {
when(paymentInitiationService.initiatePayment(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), any(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildPaymentInitationRequestResponse()));
mockMvc.perform(post(PAYMENT_URL)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content("{}"))
.andExpect(status().isCreated())
.andExpect(jsonPath(format("$._links.%s.href", TestModelBuilder.PAYMENT_ID),
containsString(TestModelBuilder.MESSAGE)))
.andExpect(jsonPath("$.paymentId", containsString(TestModelBuilder.PAYMENT_ID)))
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)))
.andExpect(jsonPath("$.transactionFeeIndicator", is(true)));
verify(paymentInitiationService, times(1))
.initiatePayment(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), any(), any(), any());
}
@Test
void getPaymentInformation() throws Exception {
String response = "response-message";
when(paymentInitiationService.getPaymentInformationAsString(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
any(),
any()))
.thenReturn(buildResponse(response));
mockMvc.perform(get(PAYMENT_URL + "/foo"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", containsString(response)));
verify(paymentInitiationService, times(1))
.getPaymentInformationAsString(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), anyString(), any(), any());
}
@Test
void getPaymentInitiationScaStatus() throws Exception {
when(paymentInitiationService.getPaymentInitiationScaStatus(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
anyString(),
any(),
any()))
.thenReturn(buildResponse(TestModelBuilder.buildScaStatusResponse()));
mockMvc.perform(get(PAYMENT_URL + "/foo/authorisations/boo"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.FINALISED.toString())));
verify(paymentInitiationService, times(1))
.getPaymentInitiationScaStatus(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), anyString(), anyString(), any(), any());
}
@Test
void getPaymentInitiationStatus_json() throws Exception {
when(paymentInitiationService.getPaymentInitiationStatus(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildPaymentInitiationStatusResponse()));
mockMvc.perform(get(PAYMENT_URL + "/foo/status")
.accept(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.transactionStatus", containsString(TransactionStatus.ACCC.toString())))
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)))
.andExpect(jsonPath("$.fundsAvailable", is(true)));
verify(paymentInitiationService, times(1))
.getPaymentInitiationStatus(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), anyString(), any(), any());
}
@Test
void getPaymentInitiationStatus_xml() throws Exception {
String response = "<Test>";
when(paymentInitiationService.getPaymentInitiationStatusAsString(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
any(),
any()))
.thenReturn(buildResponse(response));
mockMvc.perform(get(PAYMENT_URL + "/foo/status"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", containsString(response)));
verify(paymentInitiationService, times(1))
.getPaymentInitiationStatusAsString(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), anyString(), any(), any());
}
@Test
void getPaymentInitiationAuthorisation() throws Exception {
when(paymentInitiationService.getPaymentInitiationAuthorisation(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
any(),
any()))
.thenReturn(buildResponse(new Authorisations()));
mockMvc.perform(get(PAYMENT_URL + "/foo/authorisations"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.authorisationIds", nullValue()));
verify(paymentInitiationService, times(1))
.getPaymentInitiationAuthorisation(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), anyString(), any(), any());
}
@Test
void startPaymentAuthorisation_updatePsuAuthentication() throws Exception {
when(paymentInitiationService
.startPaymentAuthorisation(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
any(),
any(),
any(UpdatePsuAuthentication.class)))
.thenReturn(buildResponse(TestModelBuilder.buildStartScaprocessResponse()));
mockMvc.perform(post(PAYMENT_URL + "/foo/authorisations")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(writeValueAsString(TestModelBuilder.buildUpdatePsuAuthentication())))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.authorisationId", containsString(TestModelBuilder.AUTHORISATION_ID)))
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)))
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.STARTED.toString())));
verify(paymentInitiationService, times(1))
.startPaymentAuthorisation(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
any(),
any(),
any(UpdatePsuAuthentication.class));
}
@Test
void startPaymentAuthorisation_emptyAuthorisationBody() throws Exception {
when(paymentInitiationService
.startPaymentAuthorisation(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildStartScaprocessResponse()));
mockMvc.perform(post(PAYMENT_URL + "/foo/authorisations")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content("{}"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.authorisationId", containsString(TestModelBuilder.AUTHORISATION_ID)))
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)))
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.STARTED.toString())));
verify(paymentInitiationService, times(1))
.startPaymentAuthorisation(eq(PAYMENT_SERVICE), eq(PAYMENT_PRODUCT), anyString(), any(), any());
}
@Test
void updatePaymentPsuData_updatePsuAuthentication() throws Exception {
when(paymentInitiationService
.updatePaymentPsuData(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
anyString(),
any(),
any(),
any(UpdatePsuAuthentication.class)))
.thenReturn(buildResponse(TestModelBuilder.buildUpdatePsuAuthenticationResponse()));
mockMvc.perform(put(PAYMENT_URL + "/foo/authorisations/boo")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(writeValueAsString(TestModelBuilder.buildUpdatePsuAuthentication())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.authorisationId", containsString(TestModelBuilder.AUTHORISATION_ID)))
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)))
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.STARTED.toString())));
verify(paymentInitiationService, times(1))
.updatePaymentPsuData(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
anyString(),
any(),
any(),
any(UpdatePsuAuthentication.class));
}
@Test
void updatePaymentPsuData_selectPsuAuthenticationMethod() throws Exception {
when(paymentInitiationService
.updatePaymentPsuData(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
anyString(),
any(),
any(),
any(SelectPsuAuthenticationMethod.class)))
.thenReturn(buildResponse(TestModelBuilder.buildSelectPsuAuthenticationMethodResponse()));
mockMvc.perform(put(PAYMENT_URL + "/foo/authorisations/boo")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(writeValueAsString(TestModelBuilder.buildSelectPsuAuthenticationMethod())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)))
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.SCAMETHODSELECTED.toString())));
verify(paymentInitiationService, times(1))
.updatePaymentPsuData(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
anyString(),
any(),
any(),
any(SelectPsuAuthenticationMethod.class));
}
@Test
void updatePaymentPsuData_transactionAuthorisation() throws Exception {
when(paymentInitiationService
.updatePaymentPsuData(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
anyString(),
any(),
any(),
any(TransactionAuthorisation.class)))
.thenReturn(buildResponse(TestModelBuilder.buildScaStatusResponse()));
mockMvc.perform(put(PAYMENT_URL + "/foo/authorisations/boo")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(writeValueAsString(TestModelBuilder.buildTransactionAuthorisation())))
.andExpect(status().isOk())
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.FINALISED.toString())));
verify(paymentInitiationService, times(1))
.updatePaymentPsuData(eq(PAYMENT_SERVICE),
eq(PAYMENT_PRODUCT),
anyString(),
anyString(),
any(),
any(),
any(TransactionAuthorisation.class));
}
private <T> Response<T> buildResponse(T response) {
return new Response<>(200, response, ResponseHeaders.fromMap(Collections.emptyMap()));
}
private <T> String writeValueAsString(T value) throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(value);
}
private static FormattingConversionService buildFormattingConversionService() {
FormattingConversionService service = new FormattingConversionService();
service.addConverter(new Converter<String, PaymentProduct>() {
@Override
public PaymentProduct convert(String source) {
return PaymentProduct.fromValue(source);
}
});
service.addConverter(new Converter<String, PaymentService>() {
@Override
public PaymentService convert(String source) {
return PaymentService.fromValue(source);
}
});
return service;
}
}
| 16,166 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Oauth2ControllerTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/controller/Oauth2ControllerTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import de.adorsys.xs2a.adapter.api.Oauth2Service;
import de.adorsys.xs2a.adapter.rest.api.Oauth2Api;
import de.adorsys.xs2a.adapter.rest.impl.TestModelBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.net.URI;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class Oauth2ControllerTest {
public static final String AUTHORISATION_URL = "https://authorisation.url";
@InjectMocks
private Oauth2Controller oauth2Controller;
@Mock
private Oauth2Service oauth2Service;
MockMvc mockMvc;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(oauth2Controller).build();
}
@Test
void getAuthorizationUrl() throws Exception {
when(oauth2Service.getAuthorizationRequestUri(anyMap(), any()))
.thenReturn(URI.create(AUTHORISATION_URL));
mockMvc.perform(get(Oauth2Api.AUTHORIZATION_REQUEST_URI))
.andExpect(status().isOk())
.andExpect(jsonPath("$.href", containsString(AUTHORISATION_URL)));
verify(oauth2Service, times(1))
.getAuthorizationRequestUri(anyMap(), any());
}
@Test
void getToken() throws Exception {
when(oauth2Service.getToken(anyMap(), any()))
.thenReturn(TestModelBuilder.buildTokenResponse());
mockMvc.perform(post("/oauth2/token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.access_token", containsString(TestModelBuilder.ACCESS_TOKEN)))
.andExpect(jsonPath("$.refresh_token", containsString(TestModelBuilder.REFRESH_TOKEN)))
.andExpect(jsonPath("$.scope", containsString(TestModelBuilder.SCOPE)))
.andExpect(jsonPath("$.expires_in", equalTo((int) TestModelBuilder.exripesInSeconds)))
.andExpect(jsonPath("$.token_type", containsString(TestModelBuilder.TOKEN_TYPE)));
verify(oauth2Service, times(1))
.getToken(anyMap(), any());
}
}
| 3,669 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ConsentControllerTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/controller/ConsentControllerTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.adorsys.xs2a.adapter.api.AccountInformationService;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.exception.AdapterNotFoundException;
import de.adorsys.xs2a.adapter.api.exception.AspspRegistrationNotFoundException;
import de.adorsys.xs2a.adapter.api.exception.ErrorResponseException;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import de.adorsys.xs2a.adapter.rest.impl.TestModelBuilder;
import de.adorsys.xs2a.adapter.rest.impl.config.RestExceptionHandler;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import pro.javatar.commons.reader.JsonReader;
import java.util.Collections;
import java.util.UUID;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class ConsentControllerTest {
private static final int HTTP_CODE_200 = 200;
private static final String ACCOUNTS = "/v1/accounts";
private static final String CARD_ACCOUNTS = "/v1/card-accounts";
private static final FormattingConversionService conversionService = buildFormattingConversionService();
private MockMvc mockMvc;
@InjectMocks
private ConsentController controller;
@Mock
private AccountInformationService accountInformationService;
@Mock
private HeadersMapper headersMapper;
@Spy
private ObjectMapper objectMapper;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(new MappingJackson2HttpMessageConverter())
.setControllerAdvice(new RestExceptionHandler(new HeadersMapper()))
.setConversionService(conversionService)
.build();
}
@Test
void createConsent() throws Exception {
ConsentsResponse201 response = TestModelBuilder.buildConsentCreationResponse();
when(accountInformationService.createConsent(any(), any(), any()))
.thenReturn(buildResponse(response));
when(headersMapper.toHttpHeaders(any()))
.thenReturn(new HttpHeaders());
MvcResult mvcResult = mockMvc.perform(post(ConsentController.CONSENTS)
.header(RequestHeaders.X_GTW_ASPSP_ID, "db")
.header(RequestHeaders.X_REQUEST_ID, UUID.randomUUID())
.contentType(APPLICATION_JSON_UTF8_VALUE)
.content(writeValueAsString(response)))
.andExpect(status().is(HttpStatus.CREATED.value()))
.andReturn();
ConsentsResponse201 response201 = JsonReader.getInstance()
.getObjectFromString(mvcResult.getResponse().getContentAsString(), ConsentsResponse201.class);
assertThat(response201.getConsentId()).isEqualTo(TestModelBuilder.CONSTENT_ID);
assertThat(response201.getPsuMessage()).isEqualTo(TestModelBuilder.MESSAGE);
assertThat(response201.getConsentStatus()).isEqualTo(ConsentStatus.RECEIVED);
assertThat(response201.getLinks()).hasSize(1);
assertThat(response201.getChosenScaMethod()).isNotNull();
assertThat(response201.getScaMethods()).isNotNull();
assertThat(response201.getChallengeData()).isNotNull();
}
@Test
void createConsentRequiredFieldIsMissing() throws Exception {
when(accountInformationService.createConsent(any(), any(), any()))
.thenThrow(new AspspRegistrationNotFoundException(""));
mockMvc.perform(post(ConsentController.CONSENTS)
.contentType(APPLICATION_JSON_UTF8_VALUE)
.content("{}"))
.andExpect(status().is(HttpStatus.BAD_REQUEST.value()))
.andReturn();
}
@Test
void getTransactionWithoutBookingStatusParamRespondsWithBadRequestAndClearErrorMessage() throws Exception {
mockMvc.perform(get("/v1/accounts/resource-id/transactions"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.tppMessages[0].text").value("Required parameter 'bookingStatus' is missing"));
}
@Test
@SuppressWarnings("squid:S2699")
void createConsentsRespondsWithBadRequestIfAdapterNotFound() throws Exception {
String adpaterId = "test-psd2-adapter";
when(accountInformationService.createConsent(any(), any(), any()))
.thenThrow(new AdapterNotFoundException(adpaterId));
mockMvc.perform(post(ConsentController.CONSENTS)
.header(RequestHeaders.X_GTW_ASPSP_ID, adpaterId)
.header(RequestHeaders.X_REQUEST_ID, UUID.randomUUID())
.contentType(APPLICATION_JSON_UTF8_VALUE)
.content("{}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.tppMessages[0].text", containsString(adpaterId)));
}
@Test
void createConsent_preOauth() throws Exception {
when(accountInformationService.createConsent(any(), any(), any()))
.thenThrow(new ErrorResponseException(403, ResponseHeaders.emptyResponseHeaders(), new ErrorResponse(), "TOKEN_INVALID"));
mockMvc.perform(post(ConsentController.CONSENTS)
.header(RequestHeaders.X_GTW_ASPSP_ID, "adapterId")
.header(RequestHeaders.X_REQUEST_ID, UUID.randomUUID())
.contentType(APPLICATION_JSON_UTF8_VALUE)
.content("{}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$._links.preOauth.href", containsString(Oauth2Controller.AUTHORIZATION_REQUEST_URI)));
}
@Test
void createConsent_oauthConsent() throws Exception {
ConsentsResponse201 response = TestModelBuilder.buildConsentCreationResponse();
response.setConsentId(null);
response.setLinks(null);
when(accountInformationService.createConsent(any(), any(), any()))
.thenReturn(buildResponse(response));
mockMvc.perform(post(ConsentController.CONSENTS)
.header(RequestHeaders.X_GTW_ASPSP_ID, "adapterId")
.header(RequestHeaders.X_REQUEST_ID, UUID.randomUUID())
.contentType(APPLICATION_JSON_UTF8_VALUE)
.content("{}"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$._links.oauthConsent.href", containsString(Oauth2Controller.AUTHORIZATION_REQUEST_URI)));
}
@Test
void getConsentInformation() throws Exception {
when(accountInformationService.getConsentInformation(anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildConsentInformationResponse()));
mockMvc.perform(get(ConsentController.CONSENTS + "/foo"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.consentStatus", containsString(ConsentStatus.RECEIVED.toString())))
.andExpect(jsonPath("$.frequencyPerDay", equalTo(4)))
.andExpect(jsonPath("$.recurringIndicator", is(true)));
verify(accountInformationService, times(1))
.getConsentInformation(anyString(), any(), any());
}
@Test
void deleteConsent() throws Exception {
when(accountInformationService.deleteConsent(anyString(), any(), any()))
.thenReturn(buildResponse(null));
mockMvc.perform(delete(ConsentController.CONSENTS + "/1"))
.andExpect(status().isNoContent());
}
@Test
void getConsentStatus() throws Exception {
when(accountInformationService.getConsentStatus(anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildConsentStatusResponse()));
mockMvc.perform(get(ConsentController.CONSENTS + "/foo/status"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.consentStatus", containsString(ConsentStatus.RECEIVED.toString())))
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)));
verify(accountInformationService, times(1))
.getConsentStatus(anyString(), any(), any());
}
@Test
void getConsentAuthorisation() throws Exception {
when(accountInformationService.getConsentAuthorisation(anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildConsentAuthorisationResponse()));
mockMvc.perform(get(ConsentController.CONSENTS + "/foo/authorisations"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.authorisationIds[0]", containsString(TestModelBuilder.AUTHORISATION_ID)));
verify(accountInformationService, times(1))
.getConsentAuthorisation(anyString(), any(), any());
}
@Test
void startConsentAuthorisation_updatePsuAuthentication() throws Exception {
UpdatePsuAuthentication requestBody = TestModelBuilder.buildUpdatePsuAuthentication();
when(accountInformationService.startConsentAuthorisation(anyString(), any(), any(), any(UpdatePsuAuthentication.class)))
.thenReturn(buildResponse(TestModelBuilder.buildStartScaprocessResponse()));
mockMvc.perform(post(ConsentController.CONSENTS + "/foo/authorisations")
.contentType(APPLICATION_JSON_UTF8_VALUE)
.content(writeValueAsString(requestBody)))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.STARTED.toString())))
.andExpect(jsonPath("$.authorisationId", containsString(TestModelBuilder.AUTHORISATION_ID)))
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)));
verify(accountInformationService, times(1))
.startConsentAuthorisation(anyString(), any(), any(), any());
}
@Test
void startConsentAuthorisation_startAuthorisation() throws Exception {
when(accountInformationService.startConsentAuthorisation(anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildStartScaprocessResponse()));
mockMvc.perform(post(ConsentController.CONSENTS + "/foo/authorisations")
.contentType(APPLICATION_JSON_UTF8_VALUE)
.content("{}"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.STARTED.toString())))
.andExpect(jsonPath("$.authorisationId", containsString(TestModelBuilder.AUTHORISATION_ID)))
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)));
verify(accountInformationService, times(1))
.startConsentAuthorisation(anyString(), any(), any());
}
@Test
void updateConsentsPsuData_updatePsuAuthentication() throws Exception {
UpdatePsuAuthentication requestBody = TestModelBuilder.buildUpdatePsuAuthentication();
when(accountInformationService.updateConsentsPsuData(anyString(), anyString(), any(), any(), any(UpdatePsuAuthentication.class)))
.thenReturn(buildResponse(TestModelBuilder.buildUpdatePsuAuthenticationResponse()));
mockMvc.perform(put(ConsentController.CONSENTS + "/foo/authorisations/boo")
.contentType(APPLICATION_JSON_UTF8_VALUE)
.content(writeValueAsString(requestBody)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.STARTED.toString())))
.andExpect(jsonPath("$.authorisationId", containsString(TestModelBuilder.AUTHORISATION_ID)))
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)));
verify(accountInformationService, times(1))
.updateConsentsPsuData(anyString(), anyString(), any(), any(), any(UpdatePsuAuthentication.class));
}
@Test
void updateConsentsPsuData_selectPsuAuthenticationMethod() throws Exception {
SelectPsuAuthenticationMethod requestBody = TestModelBuilder.buildSelectPsuAuthenticationMethod();
when(accountInformationService.updateConsentsPsuData(anyString(), anyString(), any(), any(), any(SelectPsuAuthenticationMethod.class)))
.thenReturn(buildResponse(TestModelBuilder.buildSelectPsuAuthenticationMethodResponse()));
mockMvc.perform(put(ConsentController.CONSENTS + "/foo/authorisations/boo")
.contentType(APPLICATION_JSON_UTF8_VALUE)
.content(writeValueAsString(requestBody)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.SCAMETHODSELECTED.toString())))
.andExpect(jsonPath("$.psuMessage", containsString(TestModelBuilder.MESSAGE)));
verify(accountInformationService, times(1))
.updateConsentsPsuData(anyString(), anyString(), any(), any(), any(SelectPsuAuthenticationMethod.class));
}
@Test
void updateConsentsPsuData_transactionAuthorisation() throws Exception {
TransactionAuthorisation requestBody = TestModelBuilder.buildTransactionAuthorisation();
when(accountInformationService.updateConsentsPsuData(anyString(), anyString(), any(), any(), any(TransactionAuthorisation.class)))
.thenReturn(buildResponse(TestModelBuilder.buildScaStatusResponse()));
mockMvc.perform(put(ConsentController.CONSENTS + "/foo/authorisations/boo")
.contentType(APPLICATION_JSON_UTF8_VALUE)
.content(writeValueAsString(requestBody)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.FINALISED.toString())));
verify(accountInformationService, times(1))
.updateConsentsPsuData(anyString(), anyString(), any(), any(), any(TransactionAuthorisation.class));
}
@Test
void getAccountList() throws Exception {
when(accountInformationService.getAccountList(any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildAccountList()));
mockMvc.perform(get(ACCOUNTS))
.andExpect(status().isOk())
.andExpect(jsonPath("$.accounts", hasSize(2)));
verify(accountInformationService, times(1))
.getAccountList(any(), any());
}
@Test
void readAccountDetails() throws Exception {
when(accountInformationService.readAccountDetails(anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildAccountDetails()));
mockMvc.perform(get(ACCOUNTS + "/accountId"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.account", notNullValue()));
verify(accountInformationService, times(1))
.readAccountDetails(anyString(), any(), any());
}
@Test
void getTransactionList_json() throws Exception {
when(accountInformationService.getTransactionList(anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildTransactionsResponse()));
mockMvc.perform(get(ACCOUNTS + "/foo/transactions")
.queryParam("bookingStatus", "booked")
.accept(APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath(format("$._links.%s.href", TestModelBuilder.CONSTENT_ID),
containsString(TestModelBuilder.MESSAGE)));
verify(accountInformationService, times(1))
.getTransactionList(anyString(), any(), any());
}
@Test
void getTransactionList_string() throws Exception {
String response = "<Test>";
when(accountInformationService.getTransactionListAsString(anyString(), any(), any()))
.thenReturn(buildResponse(response));
mockMvc.perform(get(ACCOUNTS + "/foo/transactions")
.queryParam("bookingStatus", "booked"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", containsString(response)));
verify(accountInformationService, times(1))
.getTransactionListAsString(anyString(), any(), any());
}
@Test
void getTransactionDetails() throws Exception {
when(accountInformationService.getTransactionDetails(anyString(), anyString(), any(), any()))
.thenReturn(buildResponse(new OK200TransactionDetails()));
mockMvc.perform(get(ACCOUNTS + "/foo/transactions/boo"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.transactionsDetails", nullValue()));
verify(accountInformationService, times(1))
.getTransactionDetails(anyString(), anyString(), any(), any());
}
@Test
void getCardAccount() throws Exception {
when(accountInformationService.getCardAccountList(any(), any()))
.thenReturn(buildResponse(new CardAccountList()));
mockMvc.perform(get(CARD_ACCOUNTS))
.andExpect(status().isOk())
.andExpect(jsonPath("$.cardAccounts", nullValue()));
verify(accountInformationService, times(1)).getCardAccountList(any(), any());
}
@Test
void readCardAccount() throws Exception {
when(accountInformationService.getCardAccountDetails(anyString(), any(), any()))
.thenReturn(buildResponse(new OK200CardAccountDetails()));
mockMvc.perform(get(CARD_ACCOUNTS + "/foo"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.cardAccount", nullValue()));
verify(accountInformationService, times(1)).getCardAccountDetails(anyString(), any(), any());
}
@Test
void getCardAccountBalances() throws Exception {
when(accountInformationService.getCardAccountBalances(anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildReadCardAccountBalanceResponse()));
mockMvc.perform(get(CARD_ACCOUNTS + "/foo/balances"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.balances", hasSize(2)));
verify(accountInformationService, times(1))
.getCardAccountBalances(anyString(), any(), any());
}
@Test
void getCardAccountTransactionList() throws Exception {
when(accountInformationService.getCardAccountTransactionList(anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildCardAccountsTransactionsResponse()));
mockMvc.perform(get(CARD_ACCOUNTS + "/foo/transactions")
.param("bookingStatus", BookingStatusCard.BOOKED.toString()))
.andExpect(status().isOk())
.andExpect(jsonPath(format("$._links.%s.href", TestModelBuilder.CONSTENT_ID),
containsString(TestModelBuilder.MESSAGE)));
verify(accountInformationService, times(1))
.getCardAccountTransactionList(anyString(), any(), any());
}
@Test
void getConsentScaStatus() throws Exception {
when(accountInformationService.getConsentScaStatus(anyString(), anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildScaStatusResponse()));
mockMvc.perform(get(ConsentController.CONSENTS + "/foo/authorisations/boo"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.scaStatus", containsString(ScaStatus.FINALISED.toString())));
verify(accountInformationService, times(1))
.getConsentScaStatus(anyString(), anyString(), any(), any());
}
@Test
void getBalances() throws Exception {
when(accountInformationService.getBalances(anyString(), any(), any()))
.thenReturn(buildResponse(TestModelBuilder.buildReadAccountBalanceResponse()));
mockMvc.perform(get(ACCOUNTS + "/foo/balances"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.balances", hasSize(2)));
verify(accountInformationService, times(1))
.getBalances(anyString(), any(), any());
}
private <T> Response<T> buildResponse(T response) {
return new Response<>(HTTP_CODE_200, response, ResponseHeaders.fromMap(Collections.emptyMap()));
}
private <T> String writeValueAsString(T value) throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(value);
}
private static FormattingConversionService buildFormattingConversionService() {
FormattingConversionService service = new FormattingConversionService();
service.addConverter(new Converter<String, BookingStatusGeneric>() {
@Override
public BookingStatusGeneric convert(String source) {
return BookingStatusGeneric.fromValue(source);
}
});
service.addConverter(new Converter<String, BookingStatusCard>() {
@Override
public BookingStatusCard convert(String source) {
return BookingStatusCard.fromValue(source);
}
});
return service;
}
}
| 22,981 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
DownloadControllerTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/test/java/de/adorsys/xs2a/adapter/rest/impl/controller/DownloadControllerTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import de.adorsys.xs2a.adapter.api.DownloadService;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import de.adorsys.xs2a.adapter.rest.impl.config.RestExceptionHandler;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class DownloadControllerTest {
private static final String DOWNLOAD_URL = "https://www.example.com";
private static final int HTTP_CODE_200 = 200;
private static final byte[] RESPONSE_BODY = "response body".getBytes();
private static final ResponseHeaders RESPONSE_HEADERS = ResponseHeaders.emptyResponseHeaders();
private static final Response<byte[]> RESPONSE = new Response<>(HTTP_CODE_200, RESPONSE_BODY, RESPONSE_HEADERS);
private MockMvc mockMvc;
@Mock
private DownloadService downloadService;
@Mock
private HeadersMapper headersMapper;
@InjectMocks
private DownloadController controller;
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setMessageConverters(new ByteArrayHttpMessageConverter())
.setControllerAdvice(new RestExceptionHandler(new HeadersMapper()))
.build();
}
@Test
void download() throws Exception {
when(downloadService.download(eq(DOWNLOAD_URL), any()))
.thenReturn(RESPONSE);
when(headersMapper.toHttpHeaders(any()))
.thenReturn(new HttpHeaders());
MvcResult mvcResult = mockMvc.perform(get("/v1/download")
.param("url", DOWNLOAD_URL)
.header(RequestHeaders.X_GTW_ASPSP_ID, "db")
.header(RequestHeaders.X_REQUEST_ID, UUID.randomUUID()))
.andExpect(status().is(HttpStatus.OK.value()))
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertThat(response.getStatus()).isEqualTo(HTTP_CODE_200);
assertThat(response.getContentAsByteArray()).isEqualTo(RESPONSE_BODY);
}
}
| 3,931 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
WebMvcConfig.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/config/WebMvcConfig.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import de.adorsys.xs2a.adapter.api.model.BookingStatusCard;
import de.adorsys.xs2a.adapter.api.model.BookingStatusGeneric;
import de.adorsys.xs2a.adapter.api.model.PaymentProduct;
import de.adorsys.xs2a.adapter.api.model.PaymentService;
import de.adorsys.xs2a.adapter.api.model.PeriodicPaymentInitiationXmlPart2StandingorderTypeJson;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private static final String SWAGGER_URL = "/swagger-ui.html";
private final ObjectMapper objectMapper = newConfiguredObjectMapper();
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("", SWAGGER_URL);
}
@Override
public void addFormatters(FormatterRegistry registry) {
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(registry);
registry.addConverter(new Converter<String, BookingStatusGeneric>() {
@Override
public BookingStatusGeneric convert(String source) {
return BookingStatusGeneric.fromValue(source);
}
});
registry.addConverter(new Converter<BookingStatusGeneric, String>() {
@Override
public String convert(BookingStatusGeneric source) {
return source.toString();
}
});
registry.addConverter(new Converter<String, BookingStatusCard>() {
@Override
public BookingStatusCard convert(String source) {
return BookingStatusCard.fromValue(source);
}
});
registry.addConverter(new Converter<BookingStatusCard, String>() {
@Override
public String convert(BookingStatusCard source) {
return source.toString();
}
});
registry.addConverter(new Converter<String, PaymentService>() {
@Override
public PaymentService convert(String source) {
return PaymentService.fromValue(source);
}
});
registry.addConverter(new Converter<PaymentProduct, String>() {
@Override
public String convert(PaymentProduct source) {
return source.toString();
}
});
registry.addConverter(new Converter<PaymentService, String>() {
@Override
public String convert(PaymentService source) {
return source.toString();
}
});
registry.addConverter(new Converter<String, PaymentProduct>() {
@Override
public PaymentProduct convert(String source) {
return PaymentProduct.fromValue(source);
}
});
registry.addConverter(new Converter<String, PeriodicPaymentInitiationXmlPart2StandingorderTypeJson>() {
@Override
public PeriodicPaymentInitiationXmlPart2StandingorderTypeJson convert(String source) {
try {
return objectMapper.readValue(source, PeriodicPaymentInitiationXmlPart2StandingorderTypeJson.class);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
});
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(0, new PeriodicPaymentInitiationMultipartBodyHttpMessageConverter(objectMapper));
}
@Bean
public ObjectMapper objectMapper() {
return objectMapper;
}
public static ObjectMapper newConfiguredObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
return objectMapper;
}
}
| 5,979 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
RestExceptionHandler.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/config/RestExceptionHandler.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.config;
import de.adorsys.xs2a.adapter.api.exception.*;
import de.adorsys.xs2a.adapter.api.model.ErrorResponse;
import de.adorsys.xs2a.adapter.api.model.MessageCode;
import de.adorsys.xs2a.adapter.api.model.TppMessage;
import de.adorsys.xs2a.adapter.api.model.TppMessageCategory;
import de.adorsys.xs2a.adapter.api.validation.RequestValidationException;
import de.adorsys.xs2a.adapter.api.validation.ValidationError;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import org.slf4j.MDC;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.io.UncheckedIOException;
import java.util.*;
import java.util.stream.Collectors;
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
private static final String ERROR_ORIGINATION_HEADER_NAME = "X-GTW-Error-Origination";
private static final String SERVER_ERROR_MESSAGE = "Server error";
private final HeadersMapper headersMapper;
public RestExceptionHandler(HeadersMapper headersMapper) {
this.headersMapper = headersMapper;
}
@ExceptionHandler
@SuppressWarnings({"java:S3740", "rawtypes"})
ResponseEntity handle(ErrorResponseException exception) {
logError(exception);
HttpHeaders responseHeaders = addErrorOriginationHeader(
headersMapper.toHttpHeaders(exception.getResponseHeaders()),
ErrorOrigination.BANK
);
HttpStatus status = HttpStatus.valueOf(exception.getStatusCode());
return exception.getErrorResponse()
.map(response -> {
String originalResponse = exception.getMessage();
if (response.getTppMessages() == null && response.getLinks() == null
&& originalResponse != null && !originalResponse.isEmpty()) {
return new ResponseEntity<>(originalResponse, responseHeaders, status);
}
return new ResponseEntity<>(response, responseHeaders, status);
})
.orElseGet(() -> new ResponseEntity<>(responseHeaders, status));
}
@ExceptionHandler
ResponseEntity<Object> handle(RequestAuthorizationValidationException exception) {
logError(exception);
HttpHeaders headers = addErrorOriginationHeader(
new HttpHeaders(),
ErrorOrigination.ADAPTER);
return new ResponseEntity<>(exception.getErrorResponse(), headers, HttpStatus.UNAUTHORIZED);
}
@ExceptionHandler
ResponseEntity<Object> handle(OAuthException exception) {
logError(exception);
HttpHeaders responseHeaders = addErrorOriginationHeader(
headersMapper.toHttpHeaders(exception.getResponseHeaders()),
ErrorOrigination.BANK
);
String originalResponse = exception.getMessage();
ErrorResponse errorResponse = exception.getErrorResponse();
ResponseEntity.BodyBuilder responseBuilder = ResponseEntity
.status(HttpStatus.FORBIDDEN)
.headers(responseHeaders);
if (errorResponse != null && (errorResponse.getTppMessages() != null || errorResponse.getLinks() != null)) {
return responseBuilder
.body(errorResponse);
}
if (originalResponse != null && !originalResponse.trim().isEmpty()) {
return responseBuilder
.body(originalResponse);
}
return responseBuilder
.build();
}
@ExceptionHandler
ResponseEntity<Object> handle(NotAcceptableException exception) {
logError(exception);
return ResponseEntity
.status(HttpStatus.NOT_ACCEPTABLE)
.headers(addErrorOriginationHeader(new HttpHeaders(), ErrorOrigination.BANK))
.build();
}
@ExceptionHandler
ResponseEntity<ErrorResponse> handle(HttpRequestSigningException exception) {
logError(exception);
ErrorResponse errorResponse = buildErrorResponse("Exception during the request signing process");
HttpHeaders headers = addErrorOriginationHeader(new HttpHeaders(), ErrorOrigination.ADAPTER);
return new ResponseEntity<>(errorResponse, headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler
ResponseEntity<ErrorResponse> handle(UncheckedSSLHandshakeException exception) {
logError(exception);
ErrorResponse errorResponse = buildErrorResponse("Exception during the SSL handshake process");
HttpHeaders headers = addErrorOriginationHeader(new HttpHeaders(), ErrorOrigination.BANK);
return new ResponseEntity<>(errorResponse, headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler
ResponseEntity<ErrorResponse> handle(UncheckedIOException exception) {
logError(exception);
ErrorResponse errorResponse = buildErrorResponse("Exception during the IO process");
HttpHeaders headers = addErrorOriginationHeader(new HttpHeaders(), ErrorOrigination.ADAPTER);
return new ResponseEntity<>(errorResponse, headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler
ResponseEntity<ErrorResponse> handle(UnsupportedOperationException exception) {
logError(exception);
ErrorResponse errorResponse = buildErrorResponse("This endpoint is not supported yet");
HttpHeaders headers = addErrorOriginationHeader(new HttpHeaders(), ErrorOrigination.ADAPTER);
return new ResponseEntity<>(errorResponse, headers, HttpStatus.NOT_IMPLEMENTED);
}
@ExceptionHandler
ResponseEntity<ErrorResponse> handle(RequestValidationException exception) {
logError(exception);
ErrorResponse errorResponse = new ErrorResponse();
ArrayList<TppMessage> tppMessages = new ArrayList<>();
for (ValidationError validationError : exception.getValidationErrors()) {
TppMessage tppMessage = new TppMessage();
tppMessage.setCategory(TppMessageCategory.ERROR);
tppMessage.setCode(MessageCode.FORMAT_ERROR.toString());
tppMessage.setPath(validationError.getPath());
tppMessage.setText(validationError.getMessage());
tppMessages.add(tppMessage);
}
errorResponse.setTppMessages(tppMessages);
HttpHeaders headers = addErrorOriginationHeader(new HttpHeaders(), ErrorOrigination.ADAPTER);
return new ResponseEntity<>(errorResponse, headers, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler({
BadRequestException.class,
AspspRegistrationException.class,
AspspRegistrationNotFoundException.class,
AdapterNotFoundException.class,
IbanException.class
})
ResponseEntity<Object> handleAsBadRequest(Exception exception) {
logError(exception);
return handleAsBadRequest(exception.getMessage());
}
private ResponseEntity<Object> handleAsBadRequest(String errorText) {
ErrorResponse errorResponse = buildErrorResponse(errorText);
HttpHeaders headers = addErrorOriginationHeader(new HttpHeaders(), ErrorOrigination.ADAPTER);
return new ResponseEntity<>(errorResponse, headers, HttpStatus.BAD_REQUEST);
}
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
logError(ex);
return handleAsBadRequest("Required parameter '" + ex.getParameterName() + "' is missing");
}
@Override
protected ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
if (ex instanceof MethodArgumentTypeMismatchException) {
logError(ex);
MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex;
String errorMessage = "Illegal value '" + exception.getValue() + "' for parameter '" + exception.getName() + "'";
Class<?> parameterType = exception.getParameter().getParameterType();
if (parameterType.isEnum()) {
errorMessage += ", allowed values: " + Arrays.stream(parameterType.getEnumConstants())
.map(Objects::toString)
.collect(Collectors.joining(", "));
}
return handleAsBadRequest(errorMessage);
}
return super.handleTypeMismatch(ex, headers, status, request);
}
@ExceptionHandler
ResponseEntity<ErrorResponse> handle(PsuPasswordEncodingException exception) {
logError(exception);
ErrorResponse errorResponse = buildErrorResponse("Exception during PSU password encryption");
HttpHeaders headers = addErrorOriginationHeader(new HttpHeaders(), ErrorOrigination.ADAPTER);
return new ResponseEntity<>(errorResponse, headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler
ResponseEntity<ErrorResponse> handle(Exception exception) {
logError(exception);
ErrorResponse errorResponse = buildErrorResponse(SERVER_ERROR_MESSAGE);
HttpHeaders headers = addErrorOriginationHeader(new HttpHeaders(), ErrorOrigination.ADAPTER);
return new ResponseEntity<>(errorResponse, headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler
ResponseEntity<ErrorResponse> handle(AccessTokenException exception) {
logError(exception);
var originalMessage = exception.getOriginalMessage();
var errorResponse = buildErrorResponse(originalMessage == null ? SERVER_ERROR_MESSAGE : originalMessage);
var headers
= addErrorOriginationHeader(new HttpHeaders(), exception.isBankOriginator() ? ErrorOrigination.BANK : ErrorOrigination.ADAPTER);
var statusCode = exception.getOriginalStatusCode();
return new ResponseEntity<>(errorResponse, headers, statusCode == null ? HttpStatus.INTERNAL_SERVER_ERROR : HttpStatus.valueOf(statusCode));
}
private ErrorResponse buildErrorResponse(String text) {
TppMessage tppMessage = new TppMessage();
tppMessage.setCategory(TppMessageCategory.ERROR);
tppMessage.setText(text);
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setTppMessages(Collections.singletonList(tppMessage));
return errorResponse;
}
private HttpHeaders addErrorOriginationHeader(HttpHeaders httpHeaders, ErrorOrigination errorOrigination) {
httpHeaders.add(ERROR_ORIGINATION_HEADER_NAME, errorOrigination.name());
return httpHeaders;
}
private void logError(Exception exception) {
String errorMessage = exception.getMessage() == null ? "" : exception.getMessage();
logger.error(errorMessage, exception);
MDC.put("errorMessage", errorMessage);
}
private enum ErrorOrigination {
BANK,
ADAPTER
}
}
| 12,975 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PeriodicPaymentInitiationMultipartBodyHttpMessageConverter.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/config/PeriodicPaymentInitiationMultipartBodyHttpMessageConverter.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.adorsys.xs2a.adapter.api.model.PeriodicPaymentInitiationMultipartBody;
import de.adorsys.xs2a.adapter.api.model.PeriodicPaymentInitiationXmlPart2StandingorderTypeJson;
import org.springframework.http.*;
import org.springframework.http.converter.*;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.util.MimeTypeUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* @see FormHttpMessageConverter
*/
public class PeriodicPaymentInitiationMultipartBodyHttpMessageConverter
implements HttpMessageConverter<PeriodicPaymentInitiationMultipartBody> {
private final List<MediaType> supportedMediaTypes = Collections.singletonList(MediaType.MULTIPART_FORM_DATA);
private final List<HttpMessageConverter<?>> partConverters = new ArrayList<>();
private final Charset charset = StandardCharsets.UTF_8;
public PeriodicPaymentInitiationMultipartBodyHttpMessageConverter(ObjectMapper objectMapper) {
this.partConverters.add(new StringHttpMessageConverter());
this.partConverters.add(new MappingJackson2HttpMessageConverter(objectMapper));
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return this.supportedMediaTypes;
}
@Override
public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) {
// reading is not supported by the spring framework: a multipart request doesn't have a body
// see AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters
return false;
}
@Override
public PeriodicPaymentInitiationMultipartBody read(
Class<? extends PeriodicPaymentInitiationMultipartBody> clazz,
HttpInputMessage inputMessage
) throws IOException, HttpMessageNotReadableException {
throw new UnsupportedOperationException();
}
@Override
public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
return PeriodicPaymentInitiationMultipartBody.class.isAssignableFrom(clazz);
}
@Override
public void write(PeriodicPaymentInitiationMultipartBody body,
MediaType contentType,
HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
if (contentType == null) {
contentType = MediaType.MULTIPART_FORM_DATA;
}
byte[] boundary = generateMultipartBoundary();
Map<String, String> parameters = new LinkedHashMap<>(2);
parameters.put("charset", this.charset.name());
parameters.put("boundary", new String(boundary, StandardCharsets.US_ASCII));
contentType = new MediaType(contentType, parameters);
outputMessage.getHeaders().setContentType(contentType);
if (outputMessage instanceof StreamingHttpOutputMessage) {
StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
streamingOutputMessage.setBody(outputStream -> {
writeParts(outputStream, body, boundary);
writeEnd(outputStream, boundary);
});
} else {
writeParts(outputMessage.getBody(), body, boundary);
writeEnd(outputMessage.getBody(), boundary);
}
}
protected byte[] generateMultipartBoundary() {
return MimeTypeUtils.generateMultipartBoundary();
}
private void writeParts(OutputStream os,
PeriodicPaymentInitiationMultipartBody body,
byte[] boundary) throws IOException {
writeBoundary(os, boundary);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
HttpEntity<Object> xmlPart = new HttpEntity<>(body.getXml_sct(), headers);
writePart("xml_sct", xmlPart, os);
writeNewLine(os);
writeBoundary(os, boundary);
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<PeriodicPaymentInitiationXmlPart2StandingorderTypeJson> jsonPart =
new HttpEntity<>(body.getJson_standingorderType(), headers);
writePart("json_standingorderType", jsonPart, os);
writeNewLine(os);
}
@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
Object partBody = partEntity.getBody();
if (partBody == null) {
throw new IllegalStateException("Empty body for part '" + name + "': " + partEntity);
}
Class<?> partType = partBody.getClass();
HttpHeaders partHeaders = partEntity.getHeaders();
MediaType partContentType = partHeaders.getContentType();
for (HttpMessageConverter<?> messageConverter : this.partConverters) {
if (messageConverter.canWrite(partType, partContentType)) {
HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os, this.charset);
multipartMessage.getHeaders().setContentDispositionFormData(name, null);
if (!partHeaders.isEmpty()) {
multipartMessage.getHeaders().putAll(partHeaders);
}
((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage);
return;
}
}
throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter " +
"found for request type [" + partType.getName() + "]");
}
private void writeBoundary(OutputStream os, byte[] boundary) throws IOException {
os.write('-');
os.write('-');
os.write(boundary);
writeNewLine(os);
}
private static void writeEnd(OutputStream os, byte[] boundary) throws IOException {
os.write('-');
os.write('-');
os.write(boundary);
os.write('-');
os.write('-');
writeNewLine(os);
}
private static void writeNewLine(OutputStream os) throws IOException {
os.write('\r');
os.write('\n');
}
private static class MultipartHttpOutputMessage implements HttpOutputMessage {
private final OutputStream outputStream;
private final Charset charset;
private final HttpHeaders headers = new HttpHeaders();
private boolean headersWritten = false;
MultipartHttpOutputMessage(OutputStream outputStream, Charset charset) {
this.outputStream = outputStream;
this.charset = charset;
}
@Override
public HttpHeaders getHeaders() {
return (this.headersWritten ? HttpHeaders.readOnlyHttpHeaders(this.headers) : this.headers);
}
@Override
public OutputStream getBody() throws IOException {
writeHeaders();
return this.outputStream;
}
private void writeHeaders() throws IOException {
if (!this.headersWritten) {
for (Map.Entry<String, List<String>> entry : this.headers.entrySet()) {
byte[] headerName = getBytes(entry.getKey());
for (String headerValueString : entry.getValue()) {
byte[] headerValue = getBytes(headerValueString);
this.outputStream.write(headerName);
this.outputStream.write(':');
this.outputStream.write(' ');
this.outputStream.write(headerValue);
writeNewLine(this.outputStream);
}
}
writeNewLine(this.outputStream);
this.headersWritten = true;
}
}
private byte[] getBytes(String name) {
return name.getBytes(this.charset);
}
}
}
| 9,008 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
MimeHeadersSupportFilter.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/config/MimeHeadersSupportFilter.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.config;
import org.apache.commons.fileupload.util.mime.MimeUtility;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
@ConditionalOnProperty(prefix = "xs2a-adapter.rest", name = "mime-headers-support-enabled", havingValue = "true", matchIfMissing = true)
@Component
public class MimeHeadersSupportFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequestWrapper request = new MimeHeaderRequestWrapper(req);
chain.doFilter(request, res);
}
private static class MimeHeaderRequestWrapper extends HttpServletRequestWrapper {
/**
* Constructs a request object wrapping the given request.
*
* @param request the {@link HttpServletRequest} to be wrapped.
* @throws IllegalArgumentException if the request is null
*/
MimeHeaderRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String getHeader(String name) {
String header = super.getHeader(name);
return decodeHeader(header);
}
private String decodeHeader(String header) {
if (header == null) {
return null;
}
try {
return MimeUtility.decodeText(header);
} catch (UnsupportedEncodingException e) {
return header;
}
}
@Override
public Enumeration<String> getHeaders(String name) {
Enumeration<String> headers = super.getHeaders(name);
List<String> decodedHeaders = new ArrayList<>();
while (headers.hasMoreElements()) {
String s = headers.nextElement();
decodedHeaders.add(decodeHeader(s));
}
return Collections.enumeration(decodedHeaders);
}
}
}
| 3,411 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PropertyEditorControllerAdvice.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/config/PropertyEditorControllerAdvice.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.config;
import de.adorsys.xs2a.adapter.api.model.BookingStatusCard;
import de.adorsys.xs2a.adapter.api.model.BookingStatusGeneric;
import de.adorsys.xs2a.adapter.api.model.PaymentProduct;
import de.adorsys.xs2a.adapter.api.model.PaymentService;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.ConvertingPropertyEditorAdapter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
@ControllerAdvice
public class PropertyEditorControllerAdvice {
private final ConversionService conversionService;
public PropertyEditorControllerAdvice(ConversionService conversionService) {
this.conversionService = conversionService;
}
@InitBinder
void initBinder(WebDataBinder dataBinder) {
registerCustomEditor(dataBinder, BookingStatusGeneric.class);
registerCustomEditor(dataBinder, BookingStatusCard.class);
registerCustomEditor(dataBinder, PaymentService.class);
registerCustomEditor(dataBinder, PaymentProduct.class);
}
private <T> void registerCustomEditor(WebDataBinder dataBinder, Class<T> type) {
dataBinder.registerCustomEditor(type,
new StrictConvertingPropertyEditorAdapter(conversionService, TypeDescriptor.valueOf(type)));
}
}
class StrictConvertingPropertyEditorAdapter extends ConvertingPropertyEditorAdapter {
private final ConversionService conversionService;
private final TypeDescriptor targetDescriptor;
StrictConvertingPropertyEditorAdapter(ConversionService conversionService, TypeDescriptor targetDescriptor) {
super(conversionService, targetDescriptor);
this.conversionService = conversionService;
this.targetDescriptor = targetDescriptor;
}
@Override
public void setAsText(String text) {
Object value = this.conversionService.convert(text, TypeDescriptor.valueOf(String.class), this.targetDescriptor);
if (value == null) {
throw new IllegalArgumentException(text);
}
setValue(value);
}
}
| 3,104 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
IngOptionalParametersFilter.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/config/IngOptionalParametersFilter.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.config;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* This filter adds optional parameters for successful ING sandbox calls that normally would not be required.
*
* ING FAQ https://developer.ing.com/openbanking/support
* <pre>
* I am using the Sandbox, but I am getting a 404 error. What is wrong ?
* You are getting this error because your request does not exactly match the requests that are simulated in the Sandbox.
* When, for example, the query parameters or their values differ from what is being simulated, you will get a 404.
* Make sure you use the exact same query parameters and values as used in the Get started documentation.
* </pre>
*/
@Component
@Profile("sandbox")
public class IngOptionalParametersFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
IngRequestWrapper request = new IngRequestWrapper(req);
chain.doFilter(request, res);
}
private static class IngRequestWrapper extends HttpServletRequestWrapper {
private static final Map<String, String[]> parameters = new HashMap<>(2);
static {
parameters.put("limit", new String[]{"10"});
parameters.put("balanceTypes", new String[]{"interimBooked"});
}
IngRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> parameterMap = new HashMap<>(super.getParameterMap());
parameterMap.putAll(parameters);
return parameterMap;
}
@Override
public String getParameter(String name) {
String[] parameterValues = getParameterValues(name);
return parameterValues == null ? null : parameterValues[0];
}
@Override
public String[] getParameterValues(String name) {
return getParameterMap().get(name);
}
@Override
public Enumeration<String> getParameterNames() {
return Collections.enumeration(getParameterMap().keySet());
}
}
}
| 3,606 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
EmbeddedPreAuthorisationController.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/controller/EmbeddedPreAuthorisationController.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import de.adorsys.xs2a.adapter.api.EmbeddedPreAuthorisationService;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.model.TokenResponse;
import de.adorsys.xs2a.adapter.mapper.EmbeddedPreAuthorisationMapper;
import de.adorsys.xs2a.adapter.mapper.Oauth2Mapper;
import de.adorsys.xs2a.adapter.rest.api.EmbeddedPreAuthorisationApi;
import de.adorsys.xs2a.adapter.rest.api.model.EmbeddedPreAuthorisationRequestTO;
import de.adorsys.xs2a.adapter.rest.api.model.TokenResponseTO;
import org.mapstruct.factory.Mappers;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class EmbeddedPreAuthorisationController implements EmbeddedPreAuthorisationApi {
private final EmbeddedPreAuthorisationService preAuthorisationService;
private final Oauth2Mapper mapper = Mappers.getMapper(Oauth2Mapper.class);
private final EmbeddedPreAuthorisationMapper preAuthorisationMapper = Mappers.getMapper(EmbeddedPreAuthorisationMapper.class);
public EmbeddedPreAuthorisationController(EmbeddedPreAuthorisationService preAuthorisationService) {
this.preAuthorisationService = preAuthorisationService;
}
@Override
public TokenResponseTO getToken(Map<String, String> headers, EmbeddedPreAuthorisationRequestTO request) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
TokenResponse tokenResponse
= preAuthorisationService.getToken(preAuthorisationMapper.toEmbeddedPreAuthorisationRequest(request), requestHeaders);
return mapper.map(tokenResponse);
}
}
| 2,502 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ConsentController.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/controller/ConsentController.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import de.adorsys.xs2a.adapter.api.AccountInformationService;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.exception.ErrorResponseException;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import de.adorsys.xs2a.adapter.rest.api.AccountApi;
import de.adorsys.xs2a.adapter.rest.api.ConsentApi;
import de.adorsys.xs2a.adapter.rest.api.Oauth2Api;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.util.Map;
import static java.util.Collections.singletonMap;
@RestController
public class ConsentController extends AbstractController implements ConsentApi, AccountApi {
public static final String CONSENTS = "/v1/consents";
private final AccountInformationService accountInformationService;
private final HeadersMapper headersMapper;
public ConsentController(AccountInformationService accountInformationService, ObjectMapper objectMapper, HeadersMapper headersMapper) {
super(objectMapper);
this.accountInformationService = accountInformationService;
this.headersMapper = headersMapper;
}
@Override
public ResponseEntity<ConsentsResponse201> createConsent(Map<String, String> parameters,
Map<String, String> headers,
Consents body) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<ConsentsResponse201> response;
try {
response = accountInformationService.createConsent(requestHeaders,
requestParams,
body);
} catch (ErrorResponseException e) {
if (e.getStatusCode() == 403 && e.getMessage() != null && e.getMessage().contains("TOKEN_INVALID")) {
ConsentsResponse201 consentsResponse = new ConsentsResponse201();
HrefType preOauthHref = new HrefType();
preOauthHref.setHref(Oauth2Api.AUTHORIZATION_REQUEST_URI);
Map<String, HrefType> preOauth = singletonMap("preOauth", preOauthHref);
consentsResponse.setLinks(preOauth);
return ResponseEntity.ok(consentsResponse);
}
throw e;
}
ConsentsResponse201 consentsResponse = response.getBody();
if (consentsResponse.getConsentId() == null && consentsResponse.getLinks() == null) {
HrefType oauthConsentHref = new HrefType();
oauthConsentHref.setHref(Oauth2Api.AUTHORIZATION_REQUEST_URI);
consentsResponse.setLinks(
singletonMap("oauthConsent", oauthConsentHref)
);
}
return ResponseEntity.status(HttpStatus.CREATED)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(consentsResponse);
}
@Override
public ResponseEntity<ConsentInformationResponse200Json> getConsentInformation(String consentId,
Map<String, String> parameters,
Map<String, String> headers) {
RequestParams requestParams = RequestParams.fromMap(parameters);
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
Response<ConsentInformationResponse200Json> response =
accountInformationService.getConsentInformation(consentId, requestHeaders, requestParams);
return ResponseEntity
.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<Void> deleteConsent(String consentId,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<Void> response = accountInformationService.deleteConsent(consentId, requestHeaders, requestParams);
return new ResponseEntity<>(headersMapper.toHttpHeaders(response.getHeaders()), HttpStatus.NO_CONTENT);
}
@Override
public ResponseEntity<ConsentStatusResponse200> getConsentStatus(String consentId,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<ConsentStatusResponse200> response =
accountInformationService.getConsentStatus(consentId, requestHeaders, requestParams);
return ResponseEntity
.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<Authorisations> getConsentAuthorisation(String consentId,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<Authorisations> response =
accountInformationService.getConsentAuthorisation(consentId, requestHeaders, requestParams);
return ResponseEntity
.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<StartScaprocessResponse> startConsentAuthorisation(String consentId,
Map<String, String> parameters,
Map<String, String> headers,
ObjectNode body) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<StartScaprocessResponse> response = handleAuthorisationBody(body,
(UpdatePsuAuthenticationHandler) updatePsuAuthentication ->
accountInformationService.startConsentAuthorisation(consentId,
requestHeaders,
requestParams,
updatePsuAuthentication),
(StartAuthorisationHandler) emptyAuthorisationBody ->
accountInformationService.startConsentAuthorisation(consentId, requestHeaders, requestParams));
return ResponseEntity
.status(HttpStatus.CREATED)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<Object> updateConsentsPsuData(String consentId,
String authorisationId,
Map<String, String> parameters,
Map<String, String> headers,
ObjectNode body) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<?> response = handleAuthorisationBody(body,
(UpdatePsuAuthenticationHandler) updatePsuAuthentication ->
accountInformationService.updateConsentsPsuData(consentId,
authorisationId,
requestHeaders,
requestParams,
updatePsuAuthentication),
(SelectPsuAuthenticationMethodHandler) selectPsuAuthenticationMethod ->
accountInformationService.updateConsentsPsuData(consentId,
authorisationId,
requestHeaders,
requestParams,
selectPsuAuthenticationMethod),
(TransactionAuthorisationHandler) transactionAuthorisation ->
accountInformationService.updateConsentsPsuData(consentId,
authorisationId,
requestHeaders,
requestParams,
transactionAuthorisation)
);
return ResponseEntity
.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<AccountList> getAccountList(Boolean withBalance,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.builder()
.withBalance(withBalance)
.build();
Response<AccountList> response = accountInformationService.getAccountList(requestHeaders, requestParams);
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<OK200AccountDetails> readAccountDetails(String accountId,
Boolean withBalance,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.builder()
.withBalance(withBalance)
.build();
Response<OK200AccountDetails> response = accountInformationService.readAccountDetails(
accountId, requestHeaders, requestParams);
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<Object> getTransactionList(String accountId,
LocalDate dateFrom,
LocalDate dateTo,
String entryReferenceFrom,
BookingStatusGeneric bookingStatus,
Boolean deltaList,
Boolean withBalance,
Integer pageIndex,
Integer itemsPerPage,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
if (requestHeaders.isAcceptJson()) {
Response<TransactionsResponse200Json> transactionList =
accountInformationService.getTransactionList(accountId, requestHeaders, requestParams);
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(transactionList.getHeaders()))
.body(transactionList.getBody());
}
Response<String> response = accountInformationService.getTransactionListAsString(accountId, requestHeaders, requestParams);
return ResponseEntity
.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<OK200TransactionDetails> getTransactionDetails(String accountId,
String transactionId,
Map<String, String> parameters,
Map<String, String> headers) {
Response<OK200TransactionDetails> response = accountInformationService.getTransactionDetails(accountId,
transactionId,
RequestHeaders.fromMap(headers),
RequestParams.fromMap(parameters));
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<CardAccountList> getCardAccountList(Map<String, String> parameters, Map<String, String> headers) {
Response<CardAccountList> response =
accountInformationService.getCardAccountList(RequestHeaders.fromMap(headers),
RequestParams.fromMap(parameters));
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<OK200CardAccountDetails> readCardAccountDetails(String accountId,
Map<String, String> parameters,
Map<String, String> headers) {
Response<OK200CardAccountDetails> response =
accountInformationService.getCardAccountDetails(accountId,
RequestHeaders.fromMap(headers),
RequestParams.fromMap(parameters));
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<ReadCardAccountBalanceResponse200> getCardAccountBalances(String accountId,
Map<String, String> parameters,
Map<String, String> headers) {
Response<ReadCardAccountBalanceResponse200> response =
accountInformationService.getCardAccountBalances(accountId,
RequestHeaders.fromMap(headers),
RequestParams.fromMap(parameters));
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<CardAccountsTransactionsResponse200> getCardAccountTransactionList(String accountId,
LocalDate dateFrom,
LocalDate dateTo,
String entryReferenceFrom,
BookingStatusCard bookingStatus,
Boolean deltaList,
Boolean withBalance,
Map<String, String> parameters,
Map<String, String> headers) {
Response<CardAccountsTransactionsResponse200> response =
accountInformationService.getCardAccountTransactionList(accountId,
RequestHeaders.fromMap(headers),
RequestParams.fromMap(parameters));
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<ScaStatusResponse> getConsentScaStatus(String consentId,
String authorisationId,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<ScaStatusResponse> response = accountInformationService.getConsentScaStatus(consentId,
authorisationId,
requestHeaders,
requestParams);
return ResponseEntity
.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<ReadAccountBalanceResponse200> getBalances(String accountId,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<ReadAccountBalanceResponse200> response =
accountInformationService.getBalances(accountId, requestHeaders, requestParams);
return ResponseEntity
.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
}
| 20,023 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AspspSearchController.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/controller/AspspSearchController.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import de.adorsys.xs2a.adapter.api.AspspReadOnlyRepository;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.mapper.AspspMapper;
import de.adorsys.xs2a.adapter.rest.api.AspspSearchApi;
import de.adorsys.xs2a.adapter.rest.api.model.AspspTO;
import org.mapstruct.factory.Mappers;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Optional;
@RestController
public class AspspSearchController implements AspspSearchApi {
private final AspspReadOnlyRepository aspspSearchService;
private final AspspMapper aspspMapper = Mappers.getMapper(AspspMapper.class);
public AspspSearchController(AspspReadOnlyRepository aspspSearchService) {
this.aspspSearchService = aspspSearchService;
}
@Override
public ResponseEntity<List<AspspTO>> getAspsps(@RequestParam(required = false) String name,
@RequestParam(required = false) String bic,
@RequestParam(required = false) String bankCode,
@RequestParam(required = false) String iban, // if present - other params ignored
@RequestParam(required = false) String after,
@RequestParam(required = false, defaultValue = "10") int size) {
List<Aspsp> aspsps;
if (iban != null) {
aspsps = aspspSearchService.findByIban(iban, after, size);
} else if (name == null && bic == null && bankCode == null) {
aspsps = aspspSearchService.findAll(after, size);
} else {
Aspsp aspsp = new Aspsp();
aspsp.setName(name);
aspsp.setBic(bic);
aspsp.setBankCode(bankCode);
aspsps = aspspSearchService.findLike(aspsp, after, size);
}
return ResponseEntity.ok(aspspMapper.toAspspTOs(aspsps));
}
@Override
public ResponseEntity<AspspTO> getById(String id) {
Optional<Aspsp> aspsp = aspspSearchService.findById(id);
return aspsp.map(value -> ResponseEntity.ok(aspspMapper.toAspspTO(value)))
.orElseGet(() -> ResponseEntity.notFound().build());
}
}
| 3,305 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Oauth2Controller.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/controller/Oauth2Controller.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import de.adorsys.xs2a.adapter.api.Oauth2Service;
import de.adorsys.xs2a.adapter.api.Oauth2Service.Parameters;
import de.adorsys.xs2a.adapter.api.model.HrefType;
import de.adorsys.xs2a.adapter.mapper.Oauth2Mapper;
import de.adorsys.xs2a.adapter.rest.api.Oauth2Api;
import de.adorsys.xs2a.adapter.rest.api.model.TokenResponseTO;
import org.mapstruct.factory.Mappers;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
@RestController
public class Oauth2Controller implements Oauth2Api {
private final Oauth2Service oauth2Service;
private final Oauth2Mapper mapper = Mappers.getMapper(Oauth2Mapper.class);
public Oauth2Controller(Oauth2Service oauth2Service) {
this.oauth2Service = oauth2Service;
}
@Override
public HrefType getAuthorizationUrl(Map<String, String> headers, Map<String, String> parameters) throws IOException {
URI authorizationUrl = oauth2Service.getAuthorizationRequestUri(headers, new Parameters(parameters));
HrefType hrefTypeTO = new HrefType();
hrefTypeTO.setHref(authorizationUrl.toString());
return hrefTypeTO;
}
@Override
public TokenResponseTO getToken(Map<String, String> headers, Map<String, String> parameters) throws IOException {
return mapper.map(oauth2Service.getToken(headers, new Parameters(parameters)));
}
}
| 2,305 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PaymentController.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/controller/PaymentController.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import de.adorsys.xs2a.adapter.api.PaymentInitiationService;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import de.adorsys.xs2a.adapter.rest.api.PaymentApi;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import java.lang.reflect.Field;
import java.util.EnumSet;
import java.util.Map;
@RestController
public class PaymentController extends AbstractController implements PaymentApi {
private static final EnumSet<PaymentService> SUPPORTED_PAYMENT_SERVICES
= EnumSet.of(PaymentService.PAYMENTS, PaymentService.PERIODIC_PAYMENTS);
private final PaymentInitiationService paymentService;
private final HeadersMapper headersMapper;
public PaymentController(PaymentInitiationService paymentService,
HeadersMapper headersMapper,
ObjectMapper objectMapper) {
super(objectMapper);
this.paymentService = paymentService;
this.headersMapper = headersMapper;
}
@Override
public ResponseEntity<PaymentInitationRequestResponse201> initiatePayment(
PaymentService paymentService,
PaymentProduct paymentProduct,
Map<String, String> parameters,
Map<String, String> headers,
PeriodicPaymentInitiationMultipartBody body) {
// multipart request parts passed in the @RequestParam annotated parameter
// create problems downstream when sent in the outgoing request as query parameters
for (Field field : body.getClass().getDeclaredFields()) {
parameters.remove(field.getName());
}
return initiatePaymentInternal(paymentService, paymentProduct, parameters, headers, body);
}
@Override
public ResponseEntity<PaymentInitationRequestResponse201> initiatePayment(PaymentService paymentService,
PaymentProduct paymentProduct,
Map<String, String> parameters,
Map<String, String> headers,
ObjectNode body) {
return initiatePaymentInternal(paymentService, paymentProduct, parameters, headers, body);
}
private ResponseEntity<PaymentInitationRequestResponse201> initiatePaymentInternal(PaymentService paymentService,
PaymentProduct paymentProduct,
Map<String, String> parameters,
Map<String, String> headers,
Object body) {
requireSupportedPaymentService(paymentService);
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<PaymentInitationRequestResponse201> response =
this.paymentService.initiatePayment(paymentService,
paymentProduct,
requestHeaders,
requestParams,
body);
return ResponseEntity.status(HttpStatus.CREATED)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
private void requireSupportedPaymentService(PaymentService paymentService) {
if (!SUPPORTED_PAYMENT_SERVICES.contains(paymentService)) {
throw new UnsupportedOperationException();
}
}
@Override
public ResponseEntity<PaymentInitationRequestResponse201> initiatePayment(PaymentService paymentService,
PaymentProduct paymentProduct,
Map<String, String> parameters,
Map<String, String> headers,
String body) {
return initiatePaymentInternal(paymentService, paymentProduct, parameters, headers, body);
}
@Override
public ResponseEntity<Object> getPaymentInformation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<String> response =
this.paymentService.getPaymentInformationAsString(paymentService,
paymentProduct,
paymentId,
requestHeaders,
requestParams);
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<ScaStatusResponse> getPaymentInitiationScaStatus(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<ScaStatusResponse> response =
this.paymentService.getPaymentInitiationScaStatus(paymentService,
paymentProduct,
paymentId,
authorisationId,
requestHeaders,
requestParams);
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<Object> getPaymentInitiationStatus(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
if (requestHeaders.isAcceptJson()) {
Response<PaymentInitiationStatusResponse200Json> response =
this.paymentService.getPaymentInitiationStatus(paymentService,
paymentProduct,
paymentId,
requestHeaders,
requestParams);
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
Response<String> response =
this.paymentService.getPaymentInitiationStatusAsString(paymentService,
paymentProduct,
paymentId,
requestHeaders,
requestParams);
return ResponseEntity
.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<Authorisations> getPaymentInitiationAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
Map<String, String> parameters,
Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<Authorisations> response =
this.paymentService.getPaymentInitiationAuthorisation(paymentService,
paymentProduct,
paymentId,
requestHeaders,
requestParams);
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<StartScaprocessResponse> startPaymentAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
Map<String, String> parameters,
Map<String, String> headers,
ObjectNode body) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<StartScaprocessResponse> response = handleAuthorisationBody(body,
(UpdatePsuAuthenticationHandler) updatePsuAuthentication ->
this.paymentService.startPaymentAuthorisation(paymentService,
paymentProduct,
paymentId,
requestHeaders,
requestParams,
updatePsuAuthentication),
(StartAuthorisationHandler) emptyAuthorisationBody ->
this.paymentService.startPaymentAuthorisation(paymentService,
paymentProduct,
paymentId,
requestHeaders,
requestParams)
);
return ResponseEntity
.status(HttpStatus.CREATED)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
@Override
public ResponseEntity<Object> updatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
Map<String, String> parameters,
Map<String, String> headers,
ObjectNode body) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
RequestParams requestParams = RequestParams.fromMap(parameters);
Response<?> response = handleAuthorisationBody(body,
(UpdatePsuAuthenticationHandler) updatePsuAuthentication ->
this.paymentService.updatePaymentPsuData(paymentService,
paymentProduct,
paymentId,
authorisationId,
requestHeaders,
requestParams,
updatePsuAuthentication),
(SelectPsuAuthenticationMethodHandler) selectPsuAuthenticationMethod ->
this.paymentService.updatePaymentPsuData(paymentService,
paymentProduct,
paymentId,
authorisationId,
requestHeaders,
requestParams,
selectPsuAuthenticationMethod),
(TransactionAuthorisationHandler) transactionAuthorisation ->
this.paymentService.updatePaymentPsuData(paymentService,
paymentProduct,
paymentId,
authorisationId,
requestHeaders,
requestParams,
transactionAuthorisation)
);
return ResponseEntity
.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
}
| 14,394 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
DownloadController.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/controller/DownloadController.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import de.adorsys.xs2a.adapter.api.DownloadService;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.mapper.HeadersMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class DownloadController {
private static final String V1_DOWNLOAD = "/v1/download";
private final DownloadService downloadService;
private final HeadersMapper headersMapper;
public DownloadController(DownloadService downloadService, HeadersMapper headersMapper) {
this.downloadService = downloadService;
this.headersMapper = headersMapper;
}
@GetMapping(V1_DOWNLOAD)
public ResponseEntity<byte[]> download(@RequestParam("url") String downloadUrl,
@RequestHeader Map<String, String> headers) {
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
Response<byte[]> response = downloadService.download(downloadUrl, requestHeaders);
return ResponseEntity.status(HttpStatus.OK)
.headers(headersMapper.toHttpHeaders(response.getHeaders()))
.body(response.getBody());
}
}
| 2,392 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AbstractController.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest-impl/src/main/java/de/adorsys/xs2a/adapter/rest/impl/controller/AbstractController.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.rest.impl.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.exception.BadRequestException;
import de.adorsys.xs2a.adapter.api.model.SelectPsuAuthenticationMethod;
import de.adorsys.xs2a.adapter.api.model.TransactionAuthorisation;
import de.adorsys.xs2a.adapter.api.model.UpdatePsuAuthentication;
public abstract class AbstractController {
private final ObjectMapper objectMapper;
protected AbstractController(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
Response handleAuthorisationBody(ObjectNode body, AuthorisationBodyHandler... handlers) {
for (AuthorisationBodyHandler handler : handlers) {
if (handler.isApplicable(body)) {
return handler.apply(body, objectMapper);
}
}
throw new BadRequestException("Request body doesn't match any of the supported schemas");
}
interface AuthorisationBodyHandler<T> {
boolean isApplicable(ObjectNode body);
Response apply(ObjectNode body, ObjectMapper objectMapper);
Response apply(T t);
}
@FunctionalInterface
interface UpdatePsuAuthenticationHandler extends AuthorisationBodyHandler<UpdatePsuAuthentication> {
default boolean isApplicable(ObjectNode body) {
return body.has("psuData");
}
default Response apply(ObjectNode body, ObjectMapper objectMapper) {
return apply(objectMapper.convertValue(body, UpdatePsuAuthentication.class));
}
}
@FunctionalInterface
interface SelectPsuAuthenticationMethodHandler extends AuthorisationBodyHandler<SelectPsuAuthenticationMethod> {
default boolean isApplicable(ObjectNode body) {
return body.has("authenticationMethodId");
}
default Response apply(ObjectNode body, ObjectMapper objectMapper) {
return apply(objectMapper.convertValue(body, SelectPsuAuthenticationMethod.class));
}
}
@FunctionalInterface
interface TransactionAuthorisationHandler extends AuthorisationBodyHandler<TransactionAuthorisation> {
default boolean isApplicable(ObjectNode body) {
return body.has("scaAuthenticationData");
}
default Response apply(ObjectNode body, ObjectMapper objectMapper) {
return apply(objectMapper.convertValue(body, TransactionAuthorisation.class));
}
}
@FunctionalInterface
interface StartAuthorisationHandler extends AuthorisationBodyHandler<StartAuthorisationHandler.EmptyAuthorisationBody> {
class EmptyAuthorisationBody {
}
default boolean isApplicable(ObjectNode body) {
return !body.fields().hasNext();
}
default Response apply(ObjectNode body, ObjectMapper objectMapper) {
return apply(new EmptyAuthorisationBody());
}
}
}
| 3,874 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
TestRequestResponse.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-test/src/main/java/de/adorsys/xs2a/adapter/test/TestRequestResponse.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.impl.http.JacksonObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class TestRequestResponse {
private static final ObjectMapper objectMapper = new JacksonObjectMapper().copyObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
protected static final String REQUEST = "request";
protected static final String RESPONSE = "response";
protected static final String BODY = "body";
protected static final String HEADERS = "headers";
protected static final String PARAMS = "params";
private final JsonNode jsonNode;
public TestRequestResponse(String relativePath) throws IOException {
jsonNode = objectMapper.readTree(new File("src/test/resources/" + relativePath));
}
public RequestHeaders requestHeaders() {
return RequestHeaders.fromMap(objectMapper.convertValue(jsonNode.path(REQUEST).path(HEADERS).require(),
new TypeReference<Map<String, String>>() {
}));
}
public RequestParams requestParams() {
return RequestParams.fromMap(objectMapper.convertValue(jsonNode.path(REQUEST).path(PARAMS).require(),
new TypeReference<Map<String, String>>() {
}));
}
public <T> T requestBody(Class<T> klass) {
return objectMapper.convertValue(jsonNode.path(REQUEST).path(BODY).require(), klass);
}
public String requestBody() {
return jsonNode.path(REQUEST).path(BODY).require().asText();
}
public <T> T responseBody(Class<T> klass) {
return objectMapper.convertValue(jsonNode.path(RESPONSE).path(BODY).require(), klass);
}
public String responseBody() {
return jsonNode.path(RESPONSE).path(BODY).require().asText();
}
}
| 2,997 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ServiceWireMockTestExtension.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-test/src/main/java/de/adorsys/xs2a/adapter/test/ServiceWireMockTestExtension.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.test;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;
import de.adorsys.xs2a.adapter.api.*;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.impl.http.ApacheHttpClient;
import de.adorsys.xs2a.adapter.impl.http.BaseHttpClientConfig;
import de.adorsys.xs2a.adapter.impl.http.Xs2aHttpLogSanitizer;
import de.adorsys.xs2a.adapter.impl.link.identity.IdentityLinksRewriter;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.jupiter.api.extension.*;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.platform.commons.support.AnnotationSupport;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
class ServiceWireMockTestExtension implements BeforeAllCallback, AfterAllCallback, ParameterResolver {
@Override
public void beforeAll(ExtensionContext context) throws Exception {
Class<?> testClass = context.getRequiredTestClass();
Class<? extends AdapterServiceProvider> serviceProviderClass =
AnnotationSupport.findAnnotation(testClass, ServiceWireMockTest.class)
.map(ServiceWireMockTest::value)
.orElseThrow(IllegalStateException::new);
AdapterServiceProvider serviceProvider =
serviceProviderClass.getDeclaredConstructor().newInstance();
WireMockServer wireMockServer = new WireMockServer(wireMockConfig()
.dynamicPort()
.extensions(new ResponseTemplateTransformer(true))
.usingFilesUnderClasspath(serviceProvider.getAdapterId()));
wireMockServer.start();
getStore(context).put(WireMockServer.class, wireMockServer);
Aspsp aspsp = new Aspsp();
aspsp.setUrl("http://localhost:" + wireMockServer.port());
HttpClient httpClient = new ApacheHttpClient(new Xs2aHttpLogSanitizer(), HttpClientBuilder.create().build());
Pkcs12KeyStore keyStore = new Pkcs12KeyStore(getClass().getClassLoader()
.getResourceAsStream("de/adorsys/xs2a/adapter/test/test_keystore.p12"));
HttpClientConfig httpClientConfig = new BaseHttpClientConfig(null, keyStore, null);
HttpClientFactory httpClientFactory = getHttpClientFactory(httpClient, httpClientConfig);
LinksRewriter linksRewriter = new IdentityLinksRewriter();
if (serviceProvider instanceof AccountInformationServiceProvider) {
AccountInformationService service =
((AccountInformationServiceProvider) serviceProvider).getAccountInformationService(aspsp,
httpClientFactory,
linksRewriter);
getStore(context).put(AccountInformationService.class, service);
}
if (serviceProvider instanceof PaymentInitiationServiceProvider) {
PaymentInitiationService service =
((PaymentInitiationServiceProvider) serviceProvider).getPaymentInitiationService(aspsp,
httpClientFactory,
linksRewriter);
getStore(context).put(PaymentInitiationService.class, service);
}
if (serviceProvider instanceof Oauth2ServiceProvider) {
Oauth2Service service =
((Oauth2ServiceProvider) serviceProvider).getOauth2Service(aspsp, httpClientFactory);
getStore(context).put(Oauth2Service.class, service);
}
}
private HttpClientFactory getHttpClientFactory(HttpClient httpClient, HttpClientConfig httpClientConfig) {
return new HttpClientFactory() {
@Override
public HttpClient getHttpClient(String adapterId, String qwacAlias, String[] supportedCipherSuites) {
return httpClient;
}
@Override
public HttpClientConfig getHttpClientConfig() {
return httpClientConfig;
}
};
}
private ExtensionContext.Store getStore(ExtensionContext context) {
return context.getStore(Namespace.create(getClass(), context.getRequiredTestClass()));
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
getStore(context).remove(WireMockServer.class, WireMockServer.class).stop();
getStore(context).remove(AccountInformationService.class);
getStore(context).remove(PaymentInitiationService.class);
getStore(context).remove(Oauth2Service.class);
}
@Override
public boolean supportsParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) {
return getStore(extensionContext).get(parameterContext.getParameter().getType()) != null;
}
@Override
public Object resolveParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) {
return getStore(extensionContext).get(parameterContext.getParameter().getType());
}
}
| 6,134 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ServiceWireMockTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-test/src/main/java/de/adorsys/xs2a/adapter/test/ServiceWireMockTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.test;
import de.adorsys.xs2a.adapter.api.AdapterServiceProvider;
import org.junit.jupiter.api.extension.ExtendWith;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(ServiceWireMockTestExtension.class)
public @interface ServiceWireMockTest {
Class<? extends AdapterServiceProvider> value();
}
| 1,347 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Header.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-codegen/src/main/java/de/adorsys/xs2a/adapter/codegen/Header.java | package de.adorsys.xs2a.adapter.codegen;
class Header extends Param {
public Header(String name, String description) {
super(name, description);
}
@Override
public String getParamSchema() {
return "\n" +
" \"" + name + "\": {\n" +
" \"name\": \"" + name + "\",\n" +
" \"in\": \"header\",\n" +
" \"description\": \"" + description + "\",\n" +
" \"schema\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"required\": false\n" +
" },";
}
}
| 646 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
OperationsFilter.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-codegen/src/main/java/de/adorsys/xs2a/adapter/codegen/OperationsFilter.java | package de.adorsys.xs2a.adapter.codegen;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStreamRewriter;
import java.util.HashSet;
import java.util.Set;
public class OperationsFilter extends JSONBaseListener {
private Set<String> operationIds;
private TokenStreamRewriter rewriter;
private Set<JSONParser.OperationIdContext> dead = new HashSet<>();
private Set<JSONParser.OperationIdContext> alive = new HashSet<>();
private JSONParser.PathItemContext lastPathItem; // tracking to remove trailing comma
public OperationsFilter(Set<String> operationIds, TokenStreamRewriter rewriter) {
this.rewriter = rewriter;
this.operationIds = operationIds;
}
@Override
public void enterPathItem(JSONParser.PathItemContext ctx) {
dead.clear();
alive.clear();
}
@Override
public void exitOperationId(JSONParser.OperationIdContext ctx) {
String quotedString = ctx.STRING().getText();
if (operationIds.contains(quotedString.substring(1, quotedString.length() - 1))) {
alive.add(ctx);
} else {
dead.add(ctx);
}
}
@Override
public void exitPathItem(JSONParser.PathItemContext ctx) {
if (alive.isEmpty()) {
Utils.delete(rewriter, ctx);
} else {
dead.forEach(operationIdContext -> {
JSONParser.JsonPairContext pair = (JSONParser.JsonPairContext) operationIdContext.getParent()
.getParent()
.getParent();
Utils.delete(rewriter, pair);
});
lastPathItem = ctx;
}
}
@Override
public void exitPaths(JSONParser.PathsContext ctx) {
Token nextToken = Utils.nextToken(rewriter.getTokenStream(), lastPathItem.getStop());
if (nextToken.getText().equals(",")) {
rewriter.delete(nextToken);
}
}
}
// todo if last and next to last comma separated items removed need extra cleanup for operations
| 2,034 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Main.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-codegen/src/main/java/de/adorsys/xs2a/adapter/codegen/Main.java | package de.adorsys.xs2a.adapter.codegen;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.parser.OpenAPIV3Parser;
import io.swagger.v3.parser.core.models.ParseOptions;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenStreamRewriter;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Map;
import java.util.Set;
public class Main {
private static final String CONSENT_API = "ConsentApi";
private static final String ACCOUNT_API = "AccountApi";
private static final String PAYMENT_API = "PaymentApi";
private static final String OPENAPI_SPEC_DIR = "xs2a-adapter-rest-impl/src/main/resources/static";
private static final String GENERATED_REST_API_DIR = "xs2a-adapter-generated-rest-api/src/main/java";
private static final String GENERATED_API_DIR = "xs2a-adapter-generated-api/src/main/java";
private static final Map<String, String> OPERATION_TO_INTERFACE = Map.ofEntries(
Map.entry("createConsent", CONSENT_API),
Map.entry("getConsentInformation", CONSENT_API),
Map.entry("getConsentStatus", CONSENT_API),
Map.entry("startConsentAuthorisation", CONSENT_API),
Map.entry("getConsentAuthorisation", CONSENT_API),
Map.entry("getConsentScaStatus", CONSENT_API),
Map.entry("updateConsentsPsuData", CONSENT_API),
Map.entry("deleteConsent", CONSENT_API),
Map.entry("getAccountList", ACCOUNT_API),
Map.entry("readAccountDetails", ACCOUNT_API),
Map.entry("getBalances", ACCOUNT_API),
Map.entry("getTransactionList", ACCOUNT_API),
Map.entry("getTransactionDetails", ACCOUNT_API),
// card accounts
Map.entry("getCardAccountList", ACCOUNT_API),
Map.entry("readCardAccountDetails", ACCOUNT_API),
Map.entry("getCardAccountBalances", ACCOUNT_API),
Map.entry("getCardAccountTransactionList", ACCOUNT_API),
Map.entry("initiatePayment", PAYMENT_API),
Map.entry("getPaymentInformation", PAYMENT_API),
Map.entry("getPaymentInitiationScaStatus", PAYMENT_API),
Map.entry("getPaymentInitiationStatus", PAYMENT_API),
Map.entry("getPaymentInitiationAuthorisation", PAYMENT_API),
Map.entry("startPaymentAuthorisation", PAYMENT_API),
Map.entry("updatePaymentPsuData", PAYMENT_API));
public static void main(String[] args) throws IOException {
generate("de.adorsys.xs2a.adapter","xs2a-adapter-codegen/src/main/resources/psd2-api 1.3.9 2021-05-04v1.json", "1.3.9");
}
private static void generate(String basePackage, String apiSource,String version) throws IOException {
String modifiedSpec = filterOperations(apiSource, OPERATION_TO_INTERFACE.keySet());
modifiedSpec = addCustomParams(modifiedSpec);
modifiedSpec = removeServers(modifiedSpec);
Files.writeString(Paths.get(OPENAPI_SPEC_DIR, version != null ? String.format("xs2aapi.%s.json", version): "xs2aapi.json"), modifiedSpec);
OpenAPI api = parseSpec(modifiedSpec);
FileUtils.deleteDirectory(getFile(basePackage, GENERATED_REST_API_DIR));
FileUtils.deleteDirectory(getFile(basePackage, GENERATED_API_DIR));
new CodeGenerator(api, Main::saveFile, basePackage).generate(OPERATION_TO_INTERFACE);
}
private static File getFile(String basePackage, String generatedRestApiDir) {
return new File(generatedRestApiDir.concat("/").concat(basePackage.replace(".", "/")));
}
private static OpenAPI parseSpec(String json) {
ParseOptions options = new ParseOptions();
options.setResolve(false);
return new OpenAPIV3Parser().readContents(json, null, options)
.getOpenAPI();
}
private static void saveFile(JavaFile file) {
String baseDir = file.typeSpec.kind == TypeSpec.Kind.INTERFACE ? GENERATED_REST_API_DIR : GENERATED_API_DIR;
Path path = Paths.get(baseDir, file.packageName.replace('.', '/'), file.typeSpec.name + ".java");
Path dir = path.getParent();
try {
Files.createDirectories(dir);
Files.writeString(path, file.toString(), StandardOpenOption.CREATE);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static String filterOperations(String jsonFileName, Set<String> operationIds) throws IOException {
JSONLexer lexer = new JSONLexer(CharStreams.fromFileName(jsonFileName));
CommonTokenStream tokens = new CommonTokenStream(lexer);
JSONParser parser = new JSONParser(tokens);
JSONParser.JsonContext json = parser.json();
ParseTreeWalker parseTreeWalker = new ParseTreeWalker();
TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens);
OperationsFilter listener = new OperationsFilter(operationIds, rewriter);
parseTreeWalker.walk(listener, json);
return filterComponents(rewriter.getText());
}
private static String filterComponents(String jsonString) {
JSONLexer lexer = new JSONLexer(CharStreams.fromString(jsonString));
CommonTokenStream tokens = new CommonTokenStream(lexer);
JSONParser parser = new JSONParser(tokens);
JSONParser.JsonContext json = parser.json();
ParseTreeWalker parseTreeWalker = new ParseTreeWalker();
ReferencedComponentsFinder finder = new ReferencedComponentsFinder();
parseTreeWalker.walk(finder, json);
Set<String> referencedComponents = finder.getReferencedComponents();
TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens);
ComponentsFilter filter = new ComponentsFilter(referencedComponents, rewriter);
parseTreeWalker.walk(filter, json);
return rewriter.getText();
}
private static String addCustomParams(String jsonString) {
JSONLexer lexer = new JSONLexer(CharStreams.fromString(jsonString));
CommonTokenStream tokens = new CommonTokenStream(lexer);
JSONParser parser = new JSONParser(tokens);
JSONParser.JsonContext json = parser.json();
ParseTreeWalker parseTreeWalker = new ParseTreeWalker();
TokenStreamRewriter rewriter = new TokenStreamRewriter(tokens);
ParamWriter paramWriter = new ParamWriter(rewriter,
new Header("X-GTW-ASPSP-ID", "ASPSP ID in the registry for the request routing"),
new Header("X-GTW-Bank-Code", "Bank code of bank to which the request addressed"),
new Header("X-GTW-BIC", "Business Identifier Code for the request routing"),
new Header("X-GTW-IBAN", "IBAN for the request routing"),
new AdditionalQueryParams("additionalQueryParameters", "Additional query parameters"));
parseTreeWalker.walk(paramWriter, json);
return rewriter.getText();
}
private static String removeServers(String jsonString) {
return jsonString.replaceFirst(",\\s+\"servers\"\\s*:\\s*\\[[^]]+]", "");
}
}
| 7,351 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AdditionalQueryParams.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-codegen/src/main/java/de/adorsys/xs2a/adapter/codegen/AdditionalQueryParams.java | package de.adorsys.xs2a.adapter.codegen;
public class AdditionalQueryParams extends Param {
public AdditionalQueryParams(String name, String description) {
super(name, description);
}
public String getParamSchema() {
return "\n" +
" \"" + name + "\": {\n" +
" \"name\": \"" + name + "\",\n" +
" \"in\": \"query\",\n" +
" \"description\": \"" + description + "\",\n" +
" \"schema\": {\n" +
" \"type\": \"object\",\n" +
" \"additionalProperties\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"required\": false\n" +
" },";
}
}
| 807 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ComponentsFilter.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-codegen/src/main/java/de/adorsys/xs2a/adapter/codegen/ComponentsFilter.java | package de.adorsys.xs2a.adapter.codegen;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStreamRewriter;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class ComponentsFilter extends JSONBaseListener {
private Map<String, Set<String>> referencedComponents;
private TokenStreamRewriter rewriter;
private boolean insideComponents;
private int level;
private String componentType;
private JSONParser.JsonPairContext lastComponent;
public ComponentsFilter(Set<String> references, TokenStreamRewriter rewriter) {
this.referencedComponents = references.stream()
.map(ref -> ref.split("/"))
.collect(Collectors.groupingBy(refElements -> refElements[refElements.length - 2], Collectors.mapping(refElements -> refElements[refElements.length - 1], Collectors.toSet())));
this.rewriter = rewriter;
}
@Override
public void enterJsonPair(JSONParser.JsonPairContext ctx) {
if ("\"components\"".equals(ctx.STRING().getText())) {
insideComponents = true;
return;
}
if (insideComponents) {
level++;
if (level == 1) {
componentType = stripQuotes(ctx.STRING().getText());
} else if (level == 2 && referencedComponents.containsKey(componentType)) {
Set<String> components = referencedComponents.get(componentType);
if (!components.contains(stripQuotes(ctx.STRING().getText()))) {
Utils.delete(rewriter, ctx);
} else {
lastComponent = ctx;
}
}
}
}
private String stripQuotes(String quotedString) {
return quotedString.substring(1, quotedString.length() - 1);
}
@Override
public void exitJsonPair(JSONParser.JsonPairContext ctx) {
if ("\"components\"".equals(ctx.STRING().getText())) {
insideComponents = false;
return;
}
if (insideComponents) {
if (level == 1 && lastComponent != null) {
Token nextToken = Utils.nextToken(rewriter.getTokenStream(), lastComponent.getStop());
if (nextToken.getText().equals(",")) {
rewriter.delete(nextToken);
}
lastComponent = null;
}
level--;
}
}
}
| 2,442 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Utils.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-codegen/src/main/java/de/adorsys/xs2a/adapter/codegen/Utils.java | package de.adorsys.xs2a.adapter.codegen;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.TokenStreamRewriter;
public class Utils {
public static void delete(TokenStreamRewriter rewriter, ParserRuleContext ctx) {
TokenStream tokenStream = rewriter.getTokenStream();
// handle dangling commas, trailing and leading
Token next = nextToken(tokenStream, ctx.getStop());
Token prev = prevToken(tokenStream, ctx.getStart());
if (next.getText().equals(",")) {
// remove preceding whitespace characters to avoid blank lines
rewriter.delete(prev.getTokenIndex() + 1, next.getTokenIndex());
} else if (next.getText().equals("}") && prev.getText().equals(",")) {
rewriter.delete(prev, ctx.getStop());
} else {
// should not have empty objects
throw new RuntimeException("Removing the only child:\n" + ctx.getText());
}
}
public static Token prevToken(TokenStream tokenStream, Token token) {
for (int i = token.getTokenIndex() - 1; i >= 0; i--) {
token = tokenStream.get(i);
if (token.getChannel() == Token.DEFAULT_CHANNEL) {
return token;
}
}
return token;
}
public static Token nextToken(TokenStream tokenStream, Token token) {
for (int i = token.getTokenIndex() + 1; i < tokenStream.size(); i++) {
token = tokenStream.get(i);
if (token.getChannel() == Token.DEFAULT_CHANNEL) {
return token;
}
}
return token;
}
}
| 1,711 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Param.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-codegen/src/main/java/de/adorsys/xs2a/adapter/codegen/Param.java | package de.adorsys.xs2a.adapter.codegen;
public abstract class Param {
protected final String name;
protected final String description;
public Param(String name, String description) {
this.name = name;
this.description = description;
}
public String getParamRef() {
return "{\"$ref\":\"#/components/parameters/" + name + "\"},";
}
public abstract String getParamSchema();
}
| 430 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ReferencedComponentsFinder.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-codegen/src/main/java/de/adorsys/xs2a/adapter/codegen/ReferencedComponentsFinder.java | package de.adorsys.xs2a.adapter.codegen;
import org.antlr.v4.runtime.ParserRuleContext;
import org.jgrapht.Graphs;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleDirectedGraph;
import org.jgrapht.traverse.BreadthFirstIterator;
import java.util.HashSet;
import java.util.Set;
public class ReferencedComponentsFinder extends JSONBaseListener {
private SimpleDirectedGraph<String, DefaultEdge> refs = new SimpleDirectedGraph<>(DefaultEdge.class);
private boolean insidePaths;
private Set<String> rootRefs = new HashSet<>();
private Set<String> referencedComponents;
@Override
public void enterPaths(JSONParser.PathsContext ctx) {
insidePaths = true;
}
@Override
public void exitPaths(JSONParser.PathsContext ctx) {
insidePaths = false;
}
@Override
public void exitRef(JSONParser.RefContext ctx) {
String foundReference = stripQuotes(ctx.STRING().getText());
if (insidePaths) {
rootRefs.add(foundReference);
refs.addVertex(foundReference);
} else {
StringBuilder jsonPath = new StringBuilder();
for (ParserRuleContext parent = ctx.getParent(); parent != null; parent = parent.getParent()) {
if (parent instanceof JSONParser.JsonPairContext) {
JSONParser.JsonPairContext pairContext = (JSONParser.JsonPairContext) parent;
String quotedString = pairContext.STRING().getText();
String mappingKey = stripQuotes(quotedString);
jsonPath.insert(0, "/" + mappingKey);
}
}
jsonPath.insert(0, "#");
String referencer = jsonPath.toString();
// #/components/schemas/schemaname/
referencer = referencer.substring(0, nthIndexOf(jsonPath.toString(), 4, '/'));
Graphs.addEdgeWithVertices(refs, referencer, foundReference);
}
}
private int nthIndexOf(String string, int n, int ch) {
int index = 0;
for (int i = 0; i < n; i++) {
index = string.indexOf(ch, index + 1);
if (index == -1) {
// "chosenScaMethod": {
// "$ref": "#/components/schemas/authenticationObject"
// },
return string.length();
}
}
return index;
}
private String stripQuotes(String quotedString) {
return quotedString.substring(1, quotedString.length() - 1);
}
@Override
public void exitJson(JSONParser.JsonContext ctx) {
referencedComponents = new HashSet<>();
BreadthFirstIterator iterator = new BreadthFirstIterator<>(refs, rootRefs);
while (iterator.hasNext()) {
referencedComponents.add((String) iterator.next());
}
}
public Set<String> getReferencedComponents() {
return referencedComponents;
}
}
| 2,955 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ParamWriter.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-codegen/src/main/java/de/adorsys/xs2a/adapter/codegen/ParamWriter.java | package de.adorsys.xs2a.adapter.codegen;
import org.antlr.v4.runtime.TokenStreamRewriter;
import java.util.Arrays;
import java.util.stream.Collectors;
public class ParamWriter extends JSONBaseListener {
private final TokenStreamRewriter rewriter;
private final String paramRef;
private final String paramSchema;
private boolean insidePaths;
public ParamWriter(TokenStreamRewriter rewriter, Param... param) {
this.rewriter = rewriter;
paramRef = Arrays.stream(param).map(Param::getParamRef).collect(Collectors.joining());
paramSchema = Arrays.stream(param).map(Param::getParamSchema).collect(Collectors.joining());
}
@Override
public void enterPaths(JSONParser.PathsContext ctx) {
insidePaths = true;
}
@Override
public void exitPaths(JSONParser.PathsContext ctx) {
insidePaths = false;
}
@Override
public void enterJsonPair(JSONParser.JsonPairContext ctx) {
if ("\"parameters\"".equals(ctx.STRING().toString())) {
String insertString;
if (insidePaths) {
insertString = paramRef;
} else {
insertString = paramSchema + "\n ";
}
String parameters = new StringBuilder(ctx.value().getText())
.insert(1, insertString)
.toString();
rewriter.replace(ctx.value().getStart(), ctx.value().getStop(), parameters);
}
}
}
| 1,472 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CodeGenerator.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-codegen/src/main/java/de/adorsys/xs2a/adapter/codegen/CodeGenerator.java | package de.adorsys.xs2a.adapter.codegen;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.squareup.javapoet.*;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.responses.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Generated;
import javax.lang.model.element.Modifier;
import java.lang.reflect.Type;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static com.squareup.javapoet.TypeSpec.Kind.ENUM;
public class CodeGenerator {
public static final String TOOLNAME = "xs2a-adapter-codegen";
private final OpenAPI api;
private final Consumer<JavaFile> action;
private final String apiPackage;
private final String modelPackage;
private String schemaName;
private String propertyName;
private List<TypeSpec> nestedTypes = new ArrayList<>();
private Map<String, List<MethodSpec>> interfaceToMethodSpecs;
private Map<String, TypeSpec> models;
public CodeGenerator(OpenAPI api, Consumer<JavaFile> action, String basePackage) {
this.api = api;
this.action = action;
apiPackage = basePackage + ".rest.api";
modelPackage = basePackage + ".api.model";
}
public void generate(Map<String, String> operationToInterface) {
generateModels();
generateInterfaces(operationToInterface);
}
private void generateInterfaces(Map<String, String> operationToInterface) {
interfaceToMethodSpecs = new HashMap<>();
api.getPaths().forEach((path, pathItem) -> {
pathItem.readOperationsMap().forEach((httpMethod, operation) -> {
String operationId = operation.getOperationId();
TypeName returnType = returnType(operation);
RequestBody requestBody = operation.getRequestBody();
if (requestBody == null) {
addMethod(operationToInterface.get(operationId), operationId, path, httpMethod, operation, returnType, null);
} else {
for (String mediaType : getMediaTypes(requestBody)) {
addMethod(operationToInterface.get(operationId), operationId, path, httpMethod, operation, returnType, mediaType);
}
}
});
});
interfaceToMethodSpecs.forEach((interfaceName, methodSpecs) -> {
JavaFile javaFile = JavaFile.builder(apiPackage, TypeSpec.interfaceBuilder(interfaceName)
.addModifiers(Modifier.PUBLIC)
.addAnnotation(generatedAnnotation())
.addMethods(methodSpecs)
.build())
.build();
action.accept(javaFile);
});
}
private void addMethod(String interfaceName,
String operationId, String path,
PathItem.HttpMethod httpMethod,
Operation operation, TypeName returnType, String mediaType) {
List<ParameterSpec> parameterSpecs = parameterSpecs(operation, mediaType);
AnnotationSpec.Builder requestMappingBuilder = AnnotationSpec.builder(RequestMapping.class)
.addMember("value", "$S", path)
.addMember("method", "$T.$L", RequestMethod.class, httpMethod.name());
if (mediaType != null) {
requestMappingBuilder.addMember("consumes", "$S", mediaType);
}
AnnotationSpec requestMapping = requestMappingBuilder.build();
MethodSpec methodSpec = MethodSpec.methodBuilder(operationId)
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.addAnnotation(requestMapping)
.addParameters(parameterSpecs)
.returns(returnType)
.build();
interfaceToMethodSpecs.merge(interfaceName, new ArrayList<>(List.of(methodSpec)),
(list, method) -> {
list.addAll(method);
return list;
});
}
private TypeName returnType(Operation operation) {
for (Map.Entry<String, ApiResponse> entry : operation.getResponses().entrySet()) {
String httpCode = entry.getKey();
if (httpCode.startsWith("2")) {
ApiResponse apiResponse = entry.getValue();
// remember the name for inline (anonymous) schema definitions, such as OK_200_TransactionDetails
String refName = null;
if (apiResponse.get$ref() != null) {
refName = getSimpleName(apiResponse.get$ref());
apiResponse = api.getComponents().getResponses().get(refName);
}
Content content = apiResponse.getContent();
ClassName jsonComposedSchemaType = ClassName.get(Object.class);
TypeName returnTypeName = getTypeName(content, jsonComposedSchemaType, refName);
return ParameterizedTypeName.get(ClassName.get(ResponseEntity.class), returnTypeName);
}
}
throw new RuntimeException("2xx Success response not found");
}
private Set<String> getMediaTypes(RequestBody requestBody) {
if (requestBody.getContent() == null && requestBody.get$ref() != null) {
requestBody = api.getComponents().getRequestBodies().get(getSimpleName(requestBody.get$ref()));
}
return new LinkedHashSet<>(requestBody.getContent().keySet());
}
private List<ParameterSpec> parameterSpecs(Operation operation, String mediaType) {
List<ParameterSpec> parameterSpecs = new ArrayList<>();
for (Parameter parameter : operation.getParameters()) {
if (parameter.get$ref() != null) {
parameter = api.getComponents().getParameters().get(getSimpleName(parameter.get$ref()));
}
// custom param, added manually before headers
if ("additionalQueryParameters".equals(parameter.getName())) {
continue;
}
Schema parameterSchema = parameter.getSchema();
if (parameterSchema.get$ref() != null) {
parameterSchema = api.getComponents().getSchemas().get(getSimpleName(parameterSchema.get$ref()));
}
switch (parameter.getIn()) {
case "path":
ParameterSpec pathParameter = ParameterSpec.builder(toJavaTypeName(parameterSchema, parameter.getName()), toCamelCase(parameter.getName()))
.addAnnotation(AnnotationSpec.builder(PathVariable.class)
.addMember("value", "$S", parameter.getName())
.build())
.build();
parameterSpecs.add(pathParameter);
break;
case "query":
ParameterSpec queryParameter = ParameterSpec.builder(
toJavaTypeName(parameterSchema, parameter.getName()), toCamelCase(parameter.getName()))
.addAnnotation(AnnotationSpec.builder(RequestParam.class)
.addMember("value", "$S", parameter.getName())
.addMember("required", "$L", parameter.getRequired())
.build())
.build();
parameterSpecs.add(queryParameter);
break;
case "header":
// ignore
break;
default:
throw new RuntimeException();
}
}
ParameterSpec paramsParameter = ParameterSpec.builder(
ParameterizedTypeName.get(Map.class, String.class, String.class), "parameters")
.addAnnotation(RequestParam.class)
.build();
parameterSpecs.add(paramsParameter);
ParameterSpec headersParameter = ParameterSpec.builder(ParameterizedTypeName.get(Map.class, String.class, String.class), "headers")
.addAnnotation(RequestHeader.class)
.build();
parameterSpecs.add(headersParameter);
RequestBody requestBody = operation.getRequestBody();
if (requestBody != null) {
if (requestBody.get$ref() != null) {
requestBody = api.getComponents().getRequestBodies().get(getSimpleName(requestBody.get$ref()));
}
Map<String, MediaType> content = Collections.singletonMap(mediaType, requestBody.getContent().get(mediaType));
ClassName jsonComposedSchemaType = ClassName.get(ObjectNode.class);
TypeName bodyType = getTypeName(content, jsonComposedSchemaType, null);
ParameterSpec.Builder bodyParameterBuilder = ParameterSpec.builder(bodyType, "body");
if (!mediaType.equals("multipart/form-data")) {
AnnotationSpec RequestBodyAnnotation =
AnnotationSpec.builder(org.springframework.web.bind.annotation.RequestBody.class)
.build();
bodyParameterBuilder.addAnnotation(RequestBodyAnnotation);
}
parameterSpecs.add(bodyParameterBuilder.build());
}
return parameterSpecs;
}
private TypeName getTypeName(Map<String, MediaType> content, ClassName jsonComposedSchemaType, String refName) {
if (content == null) {
return ClassName.get(Void.class);
} else if (content.size() > 1) { // multiple content media types
return ClassName.OBJECT;
} else if (content.size() == 1) {
Map.Entry<String, MediaType> entry = content.entrySet().iterator().next();
String key = entry.getKey();
if (key.equals("application/xml") || key.equals("text/plain")) {
return ClassName.get(String.class);
} else if (key.equals("application/json")) {
MediaType value = entry.getValue();
// remember one of names and put them in comments (what about many content types + oneOf ?)
Schema schema = value.getSchema();
if (schema instanceof ComposedSchema) {
return jsonComposedSchemaType;
} else if (schema.get$ref() != null) {
String schemaName = getSimpleName(schema.get$ref());
return ClassName.get(modelPackage, toClassName(schemaName));
} else if (schema instanceof ObjectSchema) {
Objects.requireNonNull(refName);
return ClassName.get(modelPackage, toClassName(refName));
} else {
throw new RuntimeException();
}
} else if (key.equals("multipart/form-data")) {
String schemaName = getSimpleName(entry.getValue().getSchema().get$ref());
return ClassName.get(modelPackage, toClassName(schemaName));
} else {
throw new RuntimeException(key);
}
} else {
throw new RuntimeException();
}
}
private String getSimpleName(String $ref) {
Objects.requireNonNull($ref);
return Paths.get($ref).getFileName().toString();
}
private TypeName toJavaTypeName(Schema schema) {
return toJavaTypeName(schema, null);
}
private TypeName toJavaTypeName(Schema schema, String name) {
if (schema.get$ref() != null) {
String simpleName = getSimpleName(schema.get$ref());
schema = api.getComponents().getSchemas().get(simpleName);
return toJavaTypeName(schema, simpleName);
}
if (name == null && schema.getEnum() != null) {
ClassName enumName = ClassName.get(modelPackage, toClassName(schemaName), toClassName(propertyName));
nestedTypes.add(enumBuilder(enumName, schema).build());
return enumName;
}
if (schema instanceof ObjectSchema || schema.getEnum() != null) {
// if (name == null) { // anonymous schemas in Error400_AIS and similar
// name = schemaName + "_" + propertyName;
// }
return ClassName.get(modelPackage, toClassName(name));
}
if (schema instanceof ByteArraySchema) {
return ArrayTypeName.of(TypeName.BYTE);
}
if (schema instanceof ArraySchema) {
Schema<?> items = ((ArraySchema) schema).getItems();
return ParameterizedTypeName.get(ClassName.get(List.class), toJavaTypeName(items));
}
if (schema instanceof MapSchema) {
return ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(String.class), toJavaTypeName((Schema) schema.getAdditionalProperties()));
}
if (schema instanceof ComposedSchema) {
// todo oneOf comment
return ClassName.get(Object.class);
}
return ClassName.get(toJavaType(schema));
}
private Type toJavaType(Schema schema) {
if (schema instanceof StringSchema) {
return String.class;
} else if (schema instanceof BooleanSchema) {
return Boolean.class;
} else if (schema instanceof DateSchema) {
return LocalDate.class;
} else if (schema instanceof DateTimeSchema) {
return OffsetDateTime.class;
} else if (schema instanceof IntegerSchema) {
return Integer.class;
} else {
throw new RuntimeException();
}
}
private String toCamelCase(String name) {
String[] words = name.split("[-_]");
StringBuilder camelCaseName = new StringBuilder(words[0]);
for (int i = 1; i < words.length; i++) {
String word = words[i];
camelCaseName.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1));
}
return camelCaseName.toString();
}
private void generateModels() {
models = new LinkedHashMap<>();
Map<String, Schema> responseSchemas = api.getComponents().getResponses().entrySet().stream()
.filter(e -> {
ApiResponse apiResponse = e.getValue();
if (apiResponse == null) return false;
Content content = apiResponse.getContent();
if (content == null) return false;
MediaType mediaType = content.get("application/json");
if (mediaType == null) return false;
return mediaType.getSchema() instanceof ObjectSchema;
}).collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getContent().get("application/json").getSchema()));
Map<String, Schema> parameterSchemas = api.getComponents().getParameters().entrySet().stream()
.filter(p -> p.getValue().getSchema() != null && (p.getValue().getIn().equals("path") || p.getValue().getIn().equals("query")))
.collect(Collectors.toMap(Map.Entry::getKey, p -> p.getValue().getSchema()));
Map<String, Schema> componentSchemas = api.getComponents().getSchemas();
Map<String, Schema> combinedSchemas = new LinkedHashMap<>(componentSchemas);
combinedSchemas.putAll(parameterSchemas);
combinedSchemas.putAll(responseSchemas);
for (Map.Entry<String, Schema> entry : combinedSchemas.entrySet()) {
String name = entry.getKey();
Schema schema = entry.getValue();
if (!shouldBeSkipped(name)) {
schemaName = name;
TypeSpec.Builder typeSpecBuilder;
if (schema instanceof ObjectSchema) {
ObjectSchema objectSchema = (ObjectSchema) schema;
List<FieldSpec> fieldSpecs = fieldSpecs(objectSchema.getProperties());
String className = toClassName(name);
typeSpecBuilder = TypeSpec.classBuilder(className)
.addModifiers(Modifier.PUBLIC)
.addFields(fieldSpecs)
.addMethods(methods(fieldSpecs, className));
if (!nestedTypes.isEmpty()) {
nestedTypes.forEach(typeSpecBuilder::addType);
nestedTypes.clear();
}
} else if (schema.getEnum() != null) {
typeSpecBuilder = enumBuilder(ClassName.get(modelPackage, toClassName(name)), schema);
} else {
continue;
}
TypeSpec typeSpec = typeSpecBuilder.addAnnotation(generatedAnnotation())
.build();
TypeSpec typeSpecCreatedEarlier = models.get(typeSpec.name);
if (typeSpecCreatedEarlier == null) {
models.put(typeSpec.name, typeSpec);
} else if (!typeSpecCreatedEarlier.equals(typeSpec)) {
if (typeSpec.kind == ENUM && typeSpecCreatedEarlier.kind == ENUM) {
System.out.println("Merging enum " + name + " into " + typeSpecCreatedEarlier.name);
TypeSpec.Builder builder = typeSpecCreatedEarlier.toBuilder();
typeSpec.enumConstants.forEach(builder::addEnumConstant);
models.put(typeSpec.name, builder.build());
} else {
System.out.println("Merging " + name + " into " + typeSpecCreatedEarlier.name);
TypeSpec.Builder builder = typeSpecCreatedEarlier.toBuilder();
typeSpec.fieldSpecs.forEach(f -> {
if (!typeSpecCreatedEarlier.fieldSpecs.contains(f)) {
builder.addField(f);
}
});
typeSpec.methodSpecs.forEach(m -> {
if (!typeSpecCreatedEarlier.methodSpecs.contains(m)) {
builder.addMethod(m);
}
});
models.put(typeSpec.name, builder.build());
}
}
}
}
for (TypeSpec typeSpec : models.values()) {
JavaFile file = JavaFile.builder(modelPackage, typeSpec)
.build();
action.accept(file);
}
}
private TypeSpec.Builder enumBuilder(ClassName enumName, Schema schema) {
TypeSpec.Builder typeSpecBuilder;
typeSpecBuilder = TypeSpec.enumBuilder(enumName)
.addModifiers(Modifier.PUBLIC)
.addField(String.class, "value", Modifier.PRIVATE)
.addMethod(MethodSpec.constructorBuilder()
.addParameter(String.class, "value")
.addStatement("this.$N = $N", "value", "value")
.build())
.addMethod(MethodSpec.methodBuilder("fromValue")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addAnnotation(JsonCreator.class)
.addParameter(String.class, "value")
.returns(enumName)
.beginControlFlow("for ($N e : $N.values())", enumName.simpleName(), enumName.simpleName())
.beginControlFlow("if (e.value.equals(value))")
.addStatement("return e")
.endControlFlow()
.endControlFlow()
.addStatement("return null")
.build())
.addMethod(MethodSpec.methodBuilder("toString")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.addAnnotation(JsonValue.class)
.returns(String.class)
.addStatement("return value")
.build());
StringSchema stringSchema = (StringSchema) schema;
for (String enumValue : stringSchema.getEnum()) {
TypeSpec enumValueWithParam = TypeSpec.anonymousClassBuilder("$S", enumValue)
.build();
if (!Character.isJavaIdentifierStart(enumValue.charAt(0))) {
enumValue = "_" + enumValue;
}
typeSpecBuilder.addEnumConstant(enumValue.toUpperCase().replace('-', '_').replace('.', '_'), enumValueWithParam);
}
return typeSpecBuilder;
}
private AnnotationSpec generatedAnnotation() {
return AnnotationSpec.builder(Generated.class)
.addMember("value", "$S", TOOLNAME)
.build();
}
private boolean shouldBeSkipped(String name) {
return name.matches("Error\\d{3}_[A-Z]{3,}");
}
private String toClassName(String name) {
String className;
if (name.matches("tppMessage\\d{3}_[A-Z]{3,}")) {
className = "TppMessage";
} else if (name.matches("MessageCode\\d{3}_[A-Z]{3,}")) {
className = "MessageCode";
} else if (name.matches("Error\\d{3}_NG_[A-Z]{3,}")) {
className = "ErrorResponse";
} else {
className = StringUtils.capitalize(toCamelCase(name));
}
return className;
}
private List<FieldSpec> fieldSpecs(Map<String, Schema> properties) {
List<FieldSpec> fieldSpecs = new ArrayList<>(properties.size());
properties.forEach((name, schema) -> {
propertyName = name.startsWith("_") ? name.substring(1) : name;
TypeName typeName = toJavaTypeName(schema);
FieldSpec.Builder builder = FieldSpec.builder(typeName, propertyName, Modifier.PRIVATE);
if (name.startsWith("_")) {
builder.addAnnotation(AnnotationSpec.builder(JsonProperty.class)
.addMember("value", "$S", name)
.build());
}
FieldSpec fieldSpec = builder
.build();
fieldSpecs.add(fieldSpec);
});
return fieldSpecs;
}
private List<MethodSpec> methods(List<FieldSpec> fieldSpecs, String className) {
List<MethodSpec> methodSpecs = gettersAndSetters(fieldSpecs);
MethodSpec equals = MethodSpec.methodBuilder("equals")
.addModifiers(Modifier.PUBLIC)
.returns(boolean.class)
.addAnnotation(Override.class)
.addParameter(Object.class, "o")
.addStatement("if (this == o) return true")
.addStatement("if (o == null || getClass() != o.getClass()) return false")
.addStatement("$N that = ($N) o", className, className)
.addStatement(fieldSpecs.stream()
.map(f -> String.format("Objects.equals(%s, that.%s)", f.name, f.name))
.collect(Collectors.joining(" &&\n", "return ", "")))
.build();
MethodSpec hashCode = MethodSpec.methodBuilder("hashCode")
.addModifiers(Modifier.PUBLIC)
.returns(int.class)
.addAnnotation(Override.class)
.addStatement(fieldSpecs.stream()
.map(f -> f.name)
.collect(Collectors.joining(",\n", "return $T.hash(", ")")), Objects.class)
.build();
methodSpecs.add(equals);
methodSpecs.add(hashCode);
return methodSpecs;
}
private List<MethodSpec> gettersAndSetters(List<FieldSpec> fieldSpecs) {
ArrayList<MethodSpec> methodSpecs = new ArrayList<>(fieldSpecs.size());
for (FieldSpec fieldSpec : fieldSpecs) {
MethodSpec getter = MethodSpec.methodBuilder("get" + StringUtils.capitalize(fieldSpec.name))
.addModifiers(Modifier.PUBLIC)
.returns(fieldSpec.type)
.addStatement("return $N", fieldSpec)
.build();
MethodSpec setter = MethodSpec.methodBuilder("set" + StringUtils.capitalize(fieldSpec.name))
.addModifiers(Modifier.PUBLIC)
.addParameter(fieldSpec.type, fieldSpec.name)
.addStatement("this.$N = $N", fieldSpec, fieldSpec)
.build();
methodSpecs.add(getter);
methodSpecs.add(setter);
}
return methodSpecs;
}
}
| 24,736 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixRequestResponseHandlersTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/test/java/de/adorsys/xs2a/adapter/crealogix/CrealogixRequestResponseHandlersTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.exception.ErrorResponseException;
import de.adorsys.xs2a.adapter.api.exception.RequestAuthorizationValidationException;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.exception.AccessTokenException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.assertj.core.api.Assertions.*;
class CrealogixRequestResponseHandlersTest extends CrealogixTestHelper {
private static final CrealogixRequestResponseHandlers requestResponseHandlers = new CrealogixRequestResponseHandlers(null);
@ParameterizedTest
@ValueSource(ints = {401, 403})
void crealogixResponseHandler(int status) {
HttpClient.ResponseHandler<Object> responseHandler
= requestResponseHandlers.crealogixResponseHandler(Object.class);
assertThatThrownBy(() ->
responseHandler.apply(status, null, null))
.isInstanceOf(ErrorResponseException.class)
.hasMessage(CrealogixRequestResponseHandlers.RESPONSE_ERROR_MESSAGE)
.matches(er -> ((ErrorResponseException) er)
.getErrorResponse()
.orElseGet(() -> fail("There should be ErrorResponse"))
.getLinks()
.get("embeddedPreAuth")
.getHref()
.equals("/v1/embedded-pre-auth/token"));
}
@Test
void crealogixRequestHandler_throwsPreAuthorisationException() {
RequestHeaders emptyHeaders = RequestHeaders.empty();
assertThatThrownBy(() ->
requestResponseHandlers.crealogixRequestHandler(emptyHeaders))
.isInstanceOf(RequestAuthorizationValidationException.class)
.hasMessageContaining(CrealogixRequestResponseHandlers.REQUEST_ERROR_MESSAGE)
.matches(er -> ((RequestAuthorizationValidationException) er)
.getErrorResponse()
.getLinks()
.get("embeddedPreAuth")
.getHref()
.equals("/v1/embedded-pre-auth/token"));
}
@Test
void crealogixRequestHandler_throwsAccessTokenException_wrongAuthorizationType() {
RequestHeaders flawedHeaders = getHeadersWithAuthorization("foo");
assertThatThrownBy(() ->
requestResponseHandlers.crealogixRequestHandler(flawedHeaders))
.isInstanceOf(AccessTokenException.class)
.hasMessage(CrealogixRequestResponseHandlers.INVALID_CREDENTIALS_TYPE_MESSAGE);
}
@Test
void crealogixRequestHandler() {
RequestHeaders actualHeaders = requestResponseHandlers.crealogixRequestHandler(getHeadersWithAuthorization());
assertThat(actualHeaders.toMap())
.hasSize(1)
.contains(entry(RequestHeaders.PSD2_AUTHORIZATION, "Bearer " + TOKEN));
}
}
| 3,905 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixTestHelper.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/test/java/de/adorsys/xs2a/adapter/crealogix/CrealogixTestHelper.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.http.Request;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.impl.http.RequestBuilderImpl;
import static java.util.Collections.singletonMap;
import static org.mockito.Mockito.mock;
public class CrealogixTestHelper {
protected static final String AUTHORIZATION = "Authorization";
protected static final String TOKEN = "token";
protected static final String AUTHORIZATION_VALUE = "Bearer " + TOKEN;
protected final HttpClient httpClient = mock(HttpClient.class);
protected final HttpClientFactory httpClientFactory = mock(HttpClientFactory.class);
protected final HttpClientConfig httpClientConfig = mock(HttpClientConfig.class);
protected final LinksRewriter linksRewriter = mock(LinksRewriter.class);
protected final Aspsp aspsp = getAspsp();
protected <T> Response<T> getResponse(T body) {
return new Response<>(-1, body, ResponseHeaders.emptyResponseHeaders());
}
protected Request.Builder getRequestBuilder(String method) {
return new RequestBuilderImpl(httpClient, method, "");
}
private Aspsp getAspsp() {
Aspsp aspsp = new Aspsp();
aspsp.setUrl("https://url.com");
return aspsp;
}
protected RequestHeaders getHeadersWithAuthorization() {
return getHeadersWithAuthorization(AUTHORIZATION_VALUE);
}
protected RequestHeaders getHeadersWithAuthorization(String value) {
return RequestHeaders.fromMap(singletonMap(AUTHORIZATION, value));
}
}
| 2,793 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
DkbServiceProviderTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/test/java/de/adorsys/xs2a/adapter/crealogix/DkbServiceProviderTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import de.adorsys.xs2a.adapter.api.AccountInformationService;
import de.adorsys.xs2a.adapter.api.EmbeddedPreAuthorisationService;
import de.adorsys.xs2a.adapter.api.PaymentInitiationService;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class DkbServiceProviderTest {
private final DkbServiceProvider provider = new DkbServiceProvider();
private final HttpClientFactory httpClientFactory = mock(HttpClientFactory.class);
private final HttpClientConfig httpClientConfig = mock(HttpClientConfig.class);
private final Aspsp aspsp = new Aspsp();
@BeforeEach
void setUp() {
when(httpClientFactory.getHttpClientConfig()).thenReturn(httpClientConfig);
}
@Test
void getAccountInformationService() {
AccountInformationService service = provider.getAccountInformationService(aspsp, httpClientFactory, null);
assertThat(service)
.isNotNull()
.isExactlyInstanceOf(CrealogixAccountInformationService.class);
}
@Test
void getPaymentInitiationService() {
PaymentInitiationService service = provider.getPaymentInitiationService(aspsp, httpClientFactory, null);
assertThat(service)
.isNotNull()
.isExactlyInstanceOf(CrealogixPaymentInitiationService.class);
}
@Test
void getAdapterId() {
String actual = provider.getAdapterId();
assertThat(actual).isEqualTo("dkb-adapter");
}
@Test
void getEmbeddedPreAuthorisationService() {
EmbeddedPreAuthorisationService service = provider.getEmbeddedPreAuthorisationService(aspsp, httpClientFactory);
assertThat(service)
.isNotNull()
.isExactlyInstanceOf(CrealogixEmbeddedPreAuthorisationService.class);
}
}
| 2,967 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixPaymentInitiationServiceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/test/java/de/adorsys/xs2a/adapter/crealogix/CrealogixPaymentInitiationServiceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import de.adorsys.xs2a.adapter.api.PaymentInitiationService;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.crealogix.model.CrealogixPaymentInitiationWithStatusResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static de.adorsys.xs2a.adapter.api.model.PaymentProduct.SEPA_CREDIT_TRANSFERS;
import static de.adorsys.xs2a.adapter.api.model.PaymentService.PAYMENTS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
class CrealogixPaymentInitiationServiceTest extends CrealogixTestHelper {
private static final String PAYMENT_ID = "paymentId";
private static final String AUTHORIZATION_ID = "authorizationId";
private PaymentInitiationService service;
@BeforeEach
void setUp() {
when(httpClientFactory.getHttpClient(any())).thenReturn(httpClient);
when(httpClientFactory.getHttpClientConfig()).thenReturn(httpClientConfig);
service = new CrealogixPaymentInitiationService(aspsp, httpClientFactory, linksRewriter);
}
@Test
void getSinglePaymentInformation() {
when(httpClient.get(any())).thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new CrealogixPaymentInitiationWithStatusResponse()));
Response<?> actualResponse = service.getSinglePaymentInformation(SEPA_CREDIT_TRANSFERS,
"paymentId",
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull()
.extracting(Response::getBody)
.isInstanceOf(PaymentInitiationWithStatusResponse.class);
}
@Test
void initiatePayment() {
when(httpClient.post(anyString())).thenReturn(getRequestBuilder("POST"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new PaymentInitationRequestResponse201()));
Response<PaymentInitationRequestResponse201> actualResponse
= service.initiatePayment(
PAYMENTS,
SEPA_CREDIT_TRANSFERS,
getHeadersWithAuthorization(),
RequestParams.empty(),
new PaymentInitiationJson()
);
verify(httpClient, times(1)).post(anyString());
verify(httpClient, times(1)).send(any(), any());
assertThat(actualResponse)
.isNotNull()
.extracting(Response::getBody)
.isInstanceOf(PaymentInitationRequestResponse201.class);
}
@Test
void getPeriodicPaymentInformation() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new PeriodicPaymentInitiationWithStatusResponse()));
Response<PeriodicPaymentInitiationWithStatusResponse> actualResponse
= service.getPeriodicPaymentInformation(SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getPeriodicPain001PaymentInformation() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new PeriodicPaymentInitiationMultipartBody()));
Response<PeriodicPaymentInitiationMultipartBody> actualResponse
= service.getPeriodicPain001PaymentInformation(SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getPaymentInformationAsString() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse("body"));
Response<String> actualResponse = service.getPaymentInformationAsString(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getPaymentInitiationScaStatus() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new ScaStatusResponse()));
Response<ScaStatusResponse> actualResponse = service.getPaymentInitiationScaStatus(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
AUTHORIZATION_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getPaymentInitiationStatus() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new PaymentInitiationStatusResponse200Json()));
Response<PaymentInitiationStatusResponse200Json> actualResponse = service.getPaymentInitiationStatus(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getPaymentInitiationStatusAsString() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse("body"));
Response<String> actualResponse = service.getPaymentInitiationStatusAsString(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getPaymentInitiationAuthorisation() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new Authorisations()));
Response<Authorisations> actualResponse = service.getPaymentInitiationAuthorisation(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void startPaymentAuthorisation() {
when(httpClient.post(anyString()))
.thenReturn(getRequestBuilder("POST"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new StartScaprocessResponse()));
Response<StartScaprocessResponse> actualResponse = service.startPaymentAuthorisation(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void startPaymentAuthorisation_withPsuAuthentication() {
when(httpClient.post(anyString()))
.thenReturn(getRequestBuilder("POST"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new StartScaprocessResponse()));
Response<StartScaprocessResponse> actualResponse = service.startPaymentAuthorisation(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty(),
new UpdatePsuAuthentication());
assertThat(actualResponse)
.isNotNull();
}
@Test
void updatePaymentPsuData_psuAuthentication() {
when(httpClient.put(anyString()))
.thenReturn(getRequestBuilder("PUT"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new UpdatePsuAuthenticationResponse()));
Response<UpdatePsuAuthenticationResponse> actualResponse = service.updatePaymentPsuData(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
AUTHORIZATION_ID,
getHeadersWithAuthorization(),
RequestParams.empty(),
new UpdatePsuAuthentication());
assertThat(actualResponse)
.isNotNull();
}
@Test
void updatePaymentPsuData_selectScaMethod() {
when(httpClient.put(anyString()))
.thenReturn(getRequestBuilder("PUT"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new SelectPsuAuthenticationMethodResponse()));
Response<SelectPsuAuthenticationMethodResponse> actualResponse = service.updatePaymentPsuData(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
AUTHORIZATION_ID,
getHeadersWithAuthorization(),
RequestParams.empty(),
new SelectPsuAuthenticationMethod());
assertThat(actualResponse)
.isNotNull();
}
@Test
void updatePaymentPsuData_authorizeTransaction() {
when(httpClient.put(anyString()))
.thenReturn(getRequestBuilder("PUT"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new ScaStatusResponse()));
Response<ScaStatusResponse> actualResponse = service.updatePaymentPsuData(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
AUTHORIZATION_ID,
getHeadersWithAuthorization(),
RequestParams.empty(),
new TransactionAuthorisation());
assertThat(actualResponse)
.isNotNull();
}
}
| 10,902 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixEmbeddedPreAuthorisationServiceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/test/java/de/adorsys/xs2a/adapter/crealogix/CrealogixEmbeddedPreAuthorisationServiceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.http.Request;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.api.model.EmbeddedPreAuthorisationRequest;
import de.adorsys.xs2a.adapter.api.model.TokenResponse;
import de.adorsys.xs2a.adapter.crealogix.model.CrealogixValidationResponse;
import de.adorsys.xs2a.adapter.impl.http.BaseHttpClientConfig;
import de.adorsys.xs2a.adapter.impl.http.Xs2aHttpLogSanitizer;
import de.adorsys.xs2a.adapter.api.exception.AccessTokenException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.*;
class CrealogixEmbeddedPreAuthorisationServiceTest {
private final HttpClient httpClient = mock(HttpClient.class);
private final HttpClientFactory clientFactory = mock(HttpClientFactory.class);
private final Aspsp aspsp = getAspsp();
private CrealogixEmbeddedPreAuthorisationService authorisationService;
private final HttpClientConfig clientConfig = new BaseHttpClientConfig(new Xs2aHttpLogSanitizer(), null, null);
@BeforeEach
void setUp() {
when(clientFactory.getHttpClient(any())).thenReturn(httpClient);
when(clientFactory.getHttpClientConfig()).thenReturn(clientConfig);
authorisationService
= new CrealogixEmbeddedPreAuthorisationService(CrealogixClient.DKB, aspsp, clientFactory);
}
@Test
void getToken() {
Response<CrealogixValidationResponse> psd2Response = mock(Response.class);
TokenResponse psd2TokenResponse = new TokenResponse();
psd2TokenResponse.setAccessToken("psd2");
Request.Builder psd2Builder = mock(Request.Builder.class);
doReturn(psd2Builder).when(httpClient).post("https://localhost:8443/foo/boo/token");
doReturn(psd2Builder).when(psd2Builder).jsonBody(anyString());
doReturn(psd2Builder).when(psd2Builder).headers(anyMap());
doReturn(psd2Response).when(psd2Builder).send(any());
doReturn(psd2Response).when(psd2Response).map(any());
doReturn(psd2TokenResponse).when(psd2Response).getBody();
TokenResponse token = authorisationService.getToken(new EmbeddedPreAuthorisationRequest(), RequestHeaders.fromMap(Collections.emptyMap()));
assertThat(token.getAccessToken()).isNotBlank();
}
@ParameterizedTest
@ValueSource(ints = {200, 201, 202})
void responseHandler_successfulStatuses(int statusCode) throws JsonProcessingException {
String stringBody = new ObjectMapper().writeValueAsString(new TokenResponse());
InputStream inputStream = new ByteArrayInputStream(stringBody.getBytes());
TokenResponse actualResponse
= authorisationService.responseHandler(TokenResponse.class).apply(statusCode, inputStream, ResponseHeaders.emptyResponseHeaders());
assertThat(actualResponse)
.isNotNull()
.isInstanceOf(TokenResponse.class);
}
@ParameterizedTest
@ValueSource(ints = {302, 403, 500})
void responseHandler_notSuccessfulStatuses(int statusCode) {
HttpClient.ResponseHandler<TokenResponse> responseHandler = authorisationService.responseHandler(TokenResponse.class);
ResponseHeaders responseHeaders = ResponseHeaders.emptyResponseHeaders();
InputStream body = new ByteArrayInputStream("body".getBytes());
assertThatThrownBy(() -> responseHandler.apply(statusCode, body, responseHeaders))
.isInstanceOf(AccessTokenException.class);
}
private Aspsp getAspsp() {
String url = "https://localhost:8443/";
Aspsp aspsp = new Aspsp();
aspsp.setIdpUrl(url);
return aspsp;
}
}
| 5,298 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixAccountInformationServiceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/test/java/de/adorsys/xs2a/adapter/crealogix/CrealogixAccountInformationServiceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import de.adorsys.xs2a.adapter.api.AccountInformationService;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.model.*;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
class CrealogixAccountInformationServiceTest extends CrealogixTestHelper {
public static final String ACCOUNT_ID = "accountId";
public static final String CONSENT_ID = "consentId";
public static final String AUTHORISATION_ID = "authorisationId";
private static final String REMITTANCE_INFORMATION_STRUCTURED = "remittanceInformationStructuredStringValue";
private AccountInformationService service;
@BeforeEach
void setUp() {
when(httpClientFactory.getHttpClient(any())).thenReturn(httpClient);
when(httpClientFactory.getHttpClientConfig()).thenReturn(httpClientConfig);
service = new CrealogixAccountInformationService(aspsp, httpClientFactory, linksRewriter);
}
@Test
void createConsent() {
when(httpClient.post(anyString())).thenReturn(getRequestBuilder("POST"));
when(httpClient.send(any(), any()))
.thenReturn(new Response<>(-1,
new ConsentsResponse201(),
ResponseHeaders.emptyResponseHeaders()));
Response<ConsentsResponse201> actualResponse
= service.createConsent(getHeadersWithAuthorization(),
RequestParams.empty(),
new Consents());
verify(httpClient, times(1)).post(anyString());
verify(httpClient, times(1)).send(any(), any());
assertThat(actualResponse)
.isNotNull()
.extracting(Response::getBody)
.isInstanceOf(ConsentsResponse201.class);
}
@Test
void getTransactionList() {
String rawResponse = "{\n" +
" \"transactions\": {\n" +
" \"booked\": [\n" +
" {\n" +
" \"remittanceInformationStructured\": {" +
" \"reference\": \"" + REMITTANCE_INFORMATION_STRUCTURED + "\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenAnswer(invocationOnMock -> {
HttpClient.ResponseHandler responseHandler = invocationOnMock.getArgument(1, HttpClient.ResponseHandler.class);
return new Response<>(-1,
responseHandler.apply(200,
new ByteArrayInputStream(rawResponse.getBytes()),
ResponseHeaders.emptyResponseHeaders()),
null);
});
Response<?> actualResponse
= service.getTransactionList(ACCOUNT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
verify(httpClient, times(1)).get(anyString());
verify(httpClient, times(1)).send(any(), any());
assertThat(actualResponse)
.isNotNull()
.extracting(Response::getBody)
.asInstanceOf(InstanceOfAssertFactories.type(TransactionsResponse200Json.class))
.matches(body ->
body.getTransactions()
.getBooked()
.get(0)
.getRemittanceInformationStructured()
.equals(REMITTANCE_INFORMATION_STRUCTURED));
}
@Test
void getTransactionDetails() {
String rawResponse = "{\n" +
" \"transactionsDetails\": {\n" +
" \"remittanceInformationStructured\": {" +
" \"reference\": \"" + REMITTANCE_INFORMATION_STRUCTURED + "\"\n" +
" }\n" +
" }\n" +
"}";
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenAnswer(invocationOnMock -> {
HttpClient.ResponseHandler responseHandler = invocationOnMock.getArgument(1, HttpClient.ResponseHandler.class);
return new Response<>(-1,
responseHandler.apply(200,
new ByteArrayInputStream(rawResponse.getBytes()),
ResponseHeaders.emptyResponseHeaders()),
null);
});
Response<?> actualResponse = service.getTransactionDetails(ACCOUNT_ID,
"transactionId",
getHeadersWithAuthorization(),
RequestParams.empty());
verify(httpClient, times(1)).get(anyString());
verify(httpClient, times(1)).send(any(), any());
assertThat(actualResponse)
.isNotNull()
.extracting(Response::getBody)
.asInstanceOf(InstanceOfAssertFactories.type(OK200TransactionDetails.class))
.matches(body ->
body.getTransactionsDetails()
.getRemittanceInformationStructured()
.equals(REMITTANCE_INFORMATION_STRUCTURED));
}
@Test
void getConsentInformation() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new ConsentInformationResponse200Json()));
Response<ConsentInformationResponse200Json> actualResponse = service.getConsentInformation(CONSENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void deleteConsent() {
when(httpClient.delete(anyString()))
.thenReturn(getRequestBuilder("DELETE"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(Void.TYPE));
Response<Void> actualResponse = service.deleteConsent(CONSENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getConsentStatus() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new ConsentStatusResponse200()));
Response<ConsentStatusResponse200> actualResponse = service.getConsentStatus(CONSENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void startConsentAuthorisation() {
when(httpClient.post(anyString()))
.thenReturn(getRequestBuilder("POST"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new StartScaprocessResponse()));
Response<StartScaprocessResponse> actualResponse = service.startConsentAuthorisation(CONSENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void startConsentAuthorisationWithPsuAuthentication() {
when(httpClient.post(anyString()))
.thenReturn(getRequestBuilder("POST"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new StartScaprocessResponse()));
Response<StartScaprocessResponse> actualResponse = service.startConsentAuthorisation(CONSENT_ID,
getHeadersWithAuthorization(),
RequestParams.empty(),
new UpdatePsuAuthentication());
assertThat(actualResponse)
.isNotNull();
}
@Test
void updateConsentsPsuData_authenticatePsu() {
when(httpClient.put(anyString()))
.thenReturn(getRequestBuilder("PUT"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new UpdatePsuAuthenticationResponse()));
Response<UpdatePsuAuthenticationResponse> actualResponse = service.updateConsentsPsuData(CONSENT_ID,
AUTHORISATION_ID,
getHeadersWithAuthorization(),
RequestParams.empty(),
new UpdatePsuAuthentication());
assertThat(actualResponse)
.isNotNull();
}
@Test
void updateConsentsPsuData_selectScaMethod() {
when(httpClient.put(anyString()))
.thenReturn(getRequestBuilder("PUT"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new SelectPsuAuthenticationMethodResponse()));
Response<SelectPsuAuthenticationMethodResponse> actualResponse = service.updateConsentsPsuData(CONSENT_ID,
AUTHORISATION_ID,
getHeadersWithAuthorization(),
RequestParams.empty(),
new SelectPsuAuthenticationMethod());
assertThat(actualResponse)
.isNotNull();
}
@Test
void updateConsentsPsuData_authorizeTransaction() {
when(httpClient.put(anyString()))
.thenReturn(getRequestBuilder("PUT"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new ScaStatusResponse()));
Response<ScaStatusResponse> actualResponse = service.updateConsentsPsuData(CONSENT_ID,
AUTHORISATION_ID,
getHeadersWithAuthorization(),
RequestParams.empty(),
new TransactionAuthorisation());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getAccountList() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new AccountList()));
Response<AccountList> actualResponse = service.getAccountList(
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void readAccountDetails() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new OK200AccountDetails()));
Response<OK200AccountDetails> actualResponse = service.readAccountDetails(
"accountId",
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getTransactionListAsString() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse("transactions"));
Response<String> actualResponse = service.getTransactionListAsString(ACCOUNT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getConsentScaStatus() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new ScaStatusResponse()));
Response<String> actualResponse = service.getTransactionListAsString(ACCOUNT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getBalances() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new ReadAccountBalanceResponse200()));
Response<ReadAccountBalanceResponse200> actualResponse = service.getBalances(ACCOUNT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getCardAccountList() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new CardAccountList()));
Response<CardAccountList> actualResponse = service.getCardAccountList(
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getCardAccountDetails() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new OK200CardAccountDetails()));
Response<OK200CardAccountDetails> actualResponse = service.getCardAccountDetails(ACCOUNT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getCardAccountBalances() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new ReadCardAccountBalanceResponse200()));
Response<ReadCardAccountBalanceResponse200> actualResponse = service.getCardAccountBalances(ACCOUNT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
@Test
void getCardAccountTransactionList() {
when(httpClient.get(anyString()))
.thenReturn(getRequestBuilder("GET"));
when(httpClient.send(any(), any()))
.thenReturn(getResponse(new CardAccountsTransactionsResponse200()));
Response<CardAccountsTransactionsResponse200> actualResponse = service.getCardAccountTransactionList(ACCOUNT_ID,
getHeadersWithAuthorization(),
RequestParams.empty());
assertThat(actualResponse)
.isNotNull();
}
}
| 15,631 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixAccountInformationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/CrealogixAccountInformationService.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.crealogix.model.CrealogixOK200TransactionDetails;
import de.adorsys.xs2a.adapter.crealogix.model.CrealogixTransactionResponse200Json;
import de.adorsys.xs2a.adapter.impl.BaseAccountInformationService;
import org.mapstruct.factory.Mappers;
import static java.util.function.Function.identity;
public class CrealogixAccountInformationService extends BaseAccountInformationService {
private final CrealogixMapper crealogixMapper = Mappers.getMapper(CrealogixMapper.class);
private final CrealogixRequestResponseHandlers requestResponseHandlers;
public CrealogixAccountInformationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter) {
super(aspsp,
httpClientFactory.getHttpClient(aspsp.getAdapterId()),
linksRewriter,
httpClientFactory.getHttpClientConfig().getLogSanitizer());
this.requestResponseHandlers = new CrealogixRequestResponseHandlers(httpClientFactory.getHttpClientConfig().getLogSanitizer());
}
@Override
public Response<ConsentsResponse201> createConsent(RequestHeaders requestHeaders,
RequestParams requestParams,
Consents body) {
return super.createConsent(requestHandler(requestHeaders),
requestParams,
body,
identity(),
requestResponseHandlers.crealogixResponseHandler(ConsentsResponse201.class));
}
private RequestHeaders requestHandler(RequestHeaders requestHeaders) {
return requestResponseHandlers.crealogixRequestHandler(requestHeaders);
}
@Override
public Response<ConsentInformationResponse200Json> getConsentInformation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getConsentInformation(consentId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<Void> deleteConsent(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.deleteConsent(consentId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<ConsentStatusResponse200> getConsentStatus(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getConsentStatus(consentId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<StartScaprocessResponse> startConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.startConsentAuthorisation(consentId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<StartScaprocessResponse> startConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
return super.startConsentAuthorisation(consentId,
requestHandler(requestHeaders),
requestParams,
updatePsuAuthentication);
}
@Override
public Response<UpdatePsuAuthenticationResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
return super.updateConsentsPsuData(consentId,
authorisationId,
requestHandler(requestHeaders),
requestParams,
updatePsuAuthentication);
}
@Override
public Response<SelectPsuAuthenticationMethodResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
SelectPsuAuthenticationMethod selectPsuAuthenticationMethod) {
return super.updateConsentsPsuData(consentId,
authorisationId,
requestHandler(requestHeaders),
requestParams,
selectPsuAuthenticationMethod);
}
@Override
public Response<ScaStatusResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
TransactionAuthorisation transactionAuthorisation) {
return super.updateConsentsPsuData(consentId,
authorisationId,
requestHandler(requestHeaders),
requestParams,
transactionAuthorisation);
}
@Override
public Response<AccountList> getAccountList(RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getAccountList(requestHandler(requestHeaders), requestParams);
}
@Override
public Response<OK200AccountDetails> readAccountDetails(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.readAccountDetails(accountId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<TransactionsResponse200Json> getTransactionList(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getTransactionList(accountId,
requestHandler(requestHeaders),
requestParams,
CrealogixTransactionResponse200Json.class,
crealogixMapper::toTransactionsResponse200Json);
}
@Override
public Response<OK200TransactionDetails> getTransactionDetails(String accountId,
String transactionId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getTransactionDetails(accountId,
transactionId,
requestHandler(requestHeaders),
requestParams,
CrealogixOK200TransactionDetails.class,
crealogixMapper::toOK200TransactionDetails);
}
@Override
public Response<String> getTransactionListAsString(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getTransactionListAsString(accountId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<ScaStatusResponse> getConsentScaStatus(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getConsentScaStatus(consentId, authorisationId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<ReadAccountBalanceResponse200> getBalances(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getBalances(accountId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<CardAccountList> getCardAccountList(RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getCardAccountList(requestHandler(requestHeaders), requestParams);
}
@Override
public Response<OK200CardAccountDetails> getCardAccountDetails(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getCardAccountDetails(accountId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<ReadCardAccountBalanceResponse200> getCardAccountBalances(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getCardAccountBalances(accountId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<CardAccountsTransactionsResponse200> getCardAccountTransactionList(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getCardAccountTransactionList(accountId, requestHandler(requestHeaders), requestParams);
}
}
| 11,990 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixClient.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/CrealogixClient.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
public enum CrealogixClient {
DKB("dkb");
private final String prefix;
CrealogixClient(String prefix) {
this.prefix = prefix;
}
public String getPrefix() {
return prefix;
}
}
| 1,092 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixMapper.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/CrealogixMapper.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.crealogix.model.*;
import org.mapstruct.Mapper;
@Mapper
public interface CrealogixMapper {
PaymentInitiationWithStatusResponse toPaymentInitiationWithStatusResponse(CrealogixPaymentInitiationWithStatusResponse value);
TransactionsResponse200Json toTransactionsResponse200Json(CrealogixTransactionResponse200Json value);
OK200TransactionDetails toOK200TransactionDetails(CrealogixOK200TransactionDetails value);
Transactions toTransactions(CrealogixTransactionDetails value);
TokenResponse toTokenResponse(CrealogixValidationResponse value);
default String map(RemittanceInformationStructured value) {
return value == null ? null : value.getReference();
}
}
| 1,645 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
DkbServiceProvider.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/DkbServiceProvider.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import de.adorsys.xs2a.adapter.api.*;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.impl.AbstractAdapterServiceProvider;
public class DkbServiceProvider extends AbstractAdapterServiceProvider implements EmbeddedPreAuthorisationServiceProvider {
@Override
public AccountInformationService getAccountInformationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter) {
return new CrealogixAccountInformationService(aspsp,
httpClientFactory,
linksRewriter);
}
@Override
public PaymentInitiationService getPaymentInitiationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter) {
return new CrealogixPaymentInitiationService(aspsp,
httpClientFactory,
linksRewriter);
}
@Override
public String getAdapterId() {
return "dkb-adapter";
}
@Override
public EmbeddedPreAuthorisationService getEmbeddedPreAuthorisationService(Aspsp aspsp, HttpClientFactory httpClientFactory) {
return new CrealogixEmbeddedPreAuthorisationService(CrealogixClient.DKB, aspsp, httpClientFactory);
}
}
| 2,447 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixPaymentInitiationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/CrealogixPaymentInitiationService.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.crealogix.model.CrealogixPaymentInitiationWithStatusResponse;
import de.adorsys.xs2a.adapter.impl.BasePaymentInitiationService;
import org.mapstruct.factory.Mappers;
import static java.util.function.Function.identity;
public class CrealogixPaymentInitiationService extends BasePaymentInitiationService {
private final CrealogixMapper mapper = Mappers.getMapper(CrealogixMapper.class);
private final CrealogixRequestResponseHandlers requestResponseHandlers;
public CrealogixPaymentInitiationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter) {
super(aspsp,
httpClientFactory.getHttpClient(aspsp.getAdapterId()),
linksRewriter,
httpClientFactory.getHttpClientConfig().getLogSanitizer());
HttpClientConfig config = httpClientFactory.getHttpClientConfig();
this.requestResponseHandlers = new CrealogixRequestResponseHandlers(config.getLogSanitizer());
}
@Override
public Response<PaymentInitationRequestResponse201> initiatePayment(PaymentService paymentService,
PaymentProduct paymentProduct,
RequestHeaders requestHeaders,
RequestParams requestParams,
Object body) {
return super.initiatePayment(paymentService,
paymentProduct,
body,
requestHandler(requestHeaders),
requestParams,
identity(),
requestResponseHandlers.crealogixResponseHandler(PaymentInitationRequestResponse201.class));
}
@Override
public Response<PaymentInitiationWithStatusResponse> getSinglePaymentInformation(PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getPaymentInformation(PaymentService.PAYMENTS,
paymentProduct,
paymentId,
requestHandler(requestHeaders),
requestParams,
requestResponseHandlers.jsonResponseHandler(CrealogixPaymentInitiationWithStatusResponse.class))
.map(mapper::toPaymentInitiationWithStatusResponse);
}
@Override
public Response<PeriodicPaymentInitiationWithStatusResponse> getPeriodicPaymentInformation(PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getPeriodicPaymentInformation(paymentProduct, paymentId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<PeriodicPaymentInitiationMultipartBody> getPeriodicPain001PaymentInformation(PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getPeriodicPain001PaymentInformation(paymentProduct, paymentId, requestHandler(requestHeaders), requestParams);
}
@Override
public Response<String> getPaymentInformationAsString(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getPaymentInformationAsString(paymentService,
paymentProduct,
paymentId,
requestHandler(requestHeaders),
requestParams);
}
@Override
public Response<ScaStatusResponse> getPaymentInitiationScaStatus(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getPaymentInitiationScaStatus(paymentService,
paymentProduct,
paymentId,
authorisationId,
requestHandler(requestHeaders),
requestParams);
}
@Override
public Response<PaymentInitiationStatusResponse200Json> getPaymentInitiationStatus(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getPaymentInitiationStatus(paymentService,
paymentProduct,
paymentId,
requestHandler(requestHeaders),
requestParams);
}
@Override
public Response<String> getPaymentInitiationStatusAsString(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getPaymentInitiationStatusAsString(paymentService,
paymentProduct,
paymentId,
requestHandler(requestHeaders),
requestParams);
}
@Override
public Response<Authorisations> getPaymentInitiationAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getPaymentInitiationAuthorisation(paymentService,
paymentProduct,
paymentId,
requestHandler(requestHeaders),
requestParams);
}
@Override
public Response<StartScaprocessResponse> startPaymentAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.startPaymentAuthorisation(paymentService,
paymentProduct,
paymentId,
requestHandler(requestHeaders),
requestParams);
}
@Override
public Response<StartScaprocessResponse> startPaymentAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
return super.startPaymentAuthorisation(paymentService,
paymentProduct,
paymentId,
requestHandler(requestHeaders),
requestParams,
updatePsuAuthentication);
}
@Override
public Response<UpdatePsuAuthenticationResponse> updatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
return super.updatePaymentPsuData(paymentService,
paymentProduct,
paymentId,
authorisationId,
requestHandler(requestHeaders),
requestParams,
updatePsuAuthentication);
}
@Override
public Response<SelectPsuAuthenticationMethodResponse> updatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
SelectPsuAuthenticationMethod selectPsuAuthenticationMethod) {
return super.updatePaymentPsuData(paymentService,
paymentProduct,
paymentId,
authorisationId,
requestHandler(requestHeaders),
requestParams,
selectPsuAuthenticationMethod);
}
@Override
public Response<ScaStatusResponse> updatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
TransactionAuthorisation transactionAuthorisation) {
return super.updatePaymentPsuData(paymentService,
paymentProduct,
paymentId,
authorisationId,
requestHandler(requestHeaders),
requestParams,
transactionAuthorisation);
}
private RequestHeaders requestHandler(RequestHeaders requestHeaders) {
return requestResponseHandlers.crealogixRequestHandler(requestHeaders);
}
}
| 13,608 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixEmbeddedPreAuthorisationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/CrealogixEmbeddedPreAuthorisationService.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import de.adorsys.xs2a.adapter.api.EmbeddedPreAuthorisationService;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.api.model.EmbeddedPreAuthorisationRequest;
import de.adorsys.xs2a.adapter.api.model.TokenResponse;
import de.adorsys.xs2a.adapter.crealogix.model.CrealogixValidationResponse;
import de.adorsys.xs2a.adapter.impl.http.JacksonObjectMapper;
import de.adorsys.xs2a.adapter.impl.http.JsonMapper;
import de.adorsys.xs2a.adapter.api.exception.AccessTokenException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.mapstruct.factory.Mappers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.Response.Status;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import static de.adorsys.xs2a.adapter.api.config.AdapterConfig.readProperty;
public class CrealogixEmbeddedPreAuthorisationService implements EmbeddedPreAuthorisationService {
private final Logger logger = LoggerFactory.getLogger(CrealogixEmbeddedPreAuthorisationService.class);
private final CrealogixMapper mapper = Mappers.getMapper(CrealogixMapper.class);
public static final String PSD2_TOKEN_URL = ".psd2_token.url";
private static final String CREDENTIALS_JSON_BODY = "{\"username\":\"%s\",\"password\":\"%s\"}";
private final Aspsp aspsp;
private final HttpClient httpClient;
private final HttpLogSanitizer logSanitizer;
private final JsonMapper jsonMapper;
private final String psd2TokenUrl;
public CrealogixEmbeddedPreAuthorisationService(CrealogixClient crealogixClient,
Aspsp aspsp,
HttpClientFactory httpClientFactory) {
this.aspsp = aspsp;
this.httpClient = httpClientFactory.getHttpClient(aspsp.getAdapterId());
this.logSanitizer = httpClientFactory.getHttpClientConfig().getLogSanitizer();
jsonMapper = new JacksonObjectMapper();
String prefix = crealogixClient.getPrefix();
psd2TokenUrl = readProperty(prefix + PSD2_TOKEN_URL, "");
if (StringUtils.isEmpty(psd2TokenUrl)) {
throw new AccessTokenException("PSD2 Token URL is not provided");
}
}
@Override
public TokenResponse getToken(EmbeddedPreAuthorisationRequest request, RequestHeaders requestHeaders) {
String psd2AuthorisationToken = retrievePsd2AuthorisationToken(request.getUsername(), request.getPassword());
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setAccessToken(psd2AuthorisationToken);
return tokenResponse;
}
private String retrievePsd2AuthorisationToken(String username, String password) {
Map<String, String> headers = new HashMap<>(2);
headers.put(RequestHeaders.CONTENT_TYPE, "application/json");
Response<TokenResponse> response = httpClient.post(adjustIdpUrl(aspsp.getIdpUrl()) + psd2TokenUrl)
.jsonBody(String.format(CREDENTIALS_JSON_BODY, username, password))
.headers(headers)
.send(responseHandler(CrealogixValidationResponse.class))
.map(mapper::toTokenResponse);
return response.getBody().getAccessToken();
}
<T> HttpClient.ResponseHandler<T> responseHandler(Class<T> tClass) {
return (statusCode, responseBody, responseHeaders) -> {
if (isSuccess(statusCode)) {
return jsonMapper.readValue(responseBody, tClass);
}
String sanitizedResponse = logSanitizer.sanitize(toString(responseBody));
logger.error("Failed to retrieve Token. Status code: {}\nBank response: {}", statusCode, sanitizedResponse);
throw new AccessTokenException("Can't retrieve access token by provided credentials", statusCode, sanitizedResponse, true);
};
}
private String toString(InputStream inputStream) {
try {
return IOUtils.toString(inputStream, Charset.defaultCharset());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private boolean isSuccess(int statusCode) {
return Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(statusCode));
}
private static String adjustIdpUrl(String idpUrl) {
return idpUrl.endsWith("/") ? idpUrl.substring(0, idpUrl.length() - 1) : idpUrl;
}
}
| 5,685 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixRequestResponseHandlers.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/CrealogixRequestResponseHandlers.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.exception.ErrorResponseException;
import de.adorsys.xs2a.adapter.api.exception.RequestAuthorizationValidationException;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.impl.http.ResponseHandlers;
import de.adorsys.xs2a.adapter.api.exception.AccessTokenException;
import java.util.Map;
import java.util.stream.Stream;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
public class CrealogixRequestResponseHandlers {
public static final String REQUEST_ERROR_MESSAGE = "authorization header is missing, embedded pre-authorization may be needed";
public static final String RESPONSE_ERROR_MESSAGE = "embedded pre-authorisation needed";
public static final String INVALID_CREDENTIALS_TYPE_MESSAGE = "Authorization header credentials type is invalid. 'Bearer' type is expected";
private static final String BEARER = "Bearer ";
private final ResponseHandlers responseHandlers;
public CrealogixRequestResponseHandlers(HttpLogSanitizer logSanitizer) {
this.responseHandlers = new ResponseHandlers(logSanitizer);
}
public RequestHeaders crealogixRequestHandler(RequestHeaders requestHeaders) {
return Stream.of(requestHeaders)
.map(RequestHeaders::toMap)
.map(this::checkAuthorizationHeader)
.map(this::validateCredentialsType)
.map(this::mapToPsd2Authorisation)
.map(RequestHeaders::fromMap)
.findFirst() // always should be one object, if empty
.orElse(requestHeaders); // return original headers, which shouldn't be the case
}
private Map<String, String> mapToPsd2Authorisation(Map<String, String> requestHeaders) {
String token = requestHeaders.remove(RequestHeaders.AUTHORIZATION);
requestHeaders.put(RequestHeaders.PSD2_AUTHORIZATION, token);
return requestHeaders;
}
private Map<String, String> validateCredentialsType(Map<String, String> requestHeaders) {
String token = requestHeaders.get(RequestHeaders.AUTHORIZATION);
if (!token.startsWith(BEARER)) {
throw new AccessTokenException(INVALID_CREDENTIALS_TYPE_MESSAGE);
}
return requestHeaders;
}
private Map<String, String> checkAuthorizationHeader(Map<String, String> requestHeaders) {
if (!requestHeaders.containsKey(RequestHeaders.AUTHORIZATION)) {
throw new RequestAuthorizationValidationException(
getErrorResponse(REQUEST_ERROR_MESSAGE),
REQUEST_ERROR_MESSAGE);
}
return requestHeaders;
}
public <T> HttpClient.ResponseHandler<T> crealogixResponseHandler(Class<T> tClass) {
return (statusCode, responseBody, responseHeaders) -> {
if (statusCode == 401 || statusCode == 403) {
throw new ErrorResponseException(
401,
ResponseHeaders.emptyResponseHeaders(),
getErrorResponse(),
RESPONSE_ERROR_MESSAGE);
}
return responseHandlers.jsonResponseHandler(tClass).apply(statusCode, responseBody, responseHeaders);
};
}
public <T> HttpClient.ResponseHandler<T> jsonResponseHandler(Class<T> tClass) {
return responseHandlers.jsonResponseHandler(tClass);
}
private static ErrorResponse getErrorResponse(String message) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setLinks(singletonMap("embeddedPreAuth", getHrefType()));
errorResponse.setTppMessages(singletonList(getTppMessage(message)));
return errorResponse;
}
private static ErrorResponse getErrorResponse() {
return getErrorResponse(RESPONSE_ERROR_MESSAGE);
}
private static HrefType getHrefType() {
HrefType hrefType = new HrefType();
hrefType.setHref("/v1/embedded-pre-auth/token");
return hrefType;
}
private static TppMessage getTppMessage(String message) {
TppMessage tppMessage = new TppMessage();
tppMessage.setCategory(TppMessageCategory.ERROR);
tppMessage.setCode(MessageCode.TOKEN_UNKNOWN.toString());
tppMessage.setText(message);
return tppMessage;
}
}
| 5,408 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixAccountReport.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/model/CrealogixAccountReport.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.adorsys.xs2a.adapter.api.model.HrefType;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class CrealogixAccountReport {
private List<CrealogixTransactionDetails> booked;
private List<CrealogixTransactionDetails> pending;
@JsonProperty("_links")
private Map<String, HrefType> links;
public List<CrealogixTransactionDetails> getBooked() {
return booked;
}
public void setBooked(List<CrealogixTransactionDetails> booked) {
this.booked = booked;
}
public List<CrealogixTransactionDetails> getPending() {
return pending;
}
public void setPending(List<CrealogixTransactionDetails> pending) {
this.pending = pending;
}
public Map<String, HrefType> getLinks() {
return links;
}
public void setLinks(Map<String, HrefType> links) {
this.links = links;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CrealogixAccountReport that = (CrealogixAccountReport) o;
return Objects.equals(booked, that.booked) &&
Objects.equals(pending, that.pending) &&
Objects.equals(links, that.links);
}
@Override
public int hashCode() {
return Objects.hash(booked,
pending,
links);
}
}
| 2,348 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixAuthItem.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/model/CrealogixAuthItem.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix.model;
import java.util.Objects;
public class CrealogixAuthItem {
private String authOptionId;
private CrealogixAuthType authType;
private String authInfo;
public String getAuthOptionId() {
return authOptionId;
}
public void setAuthOptionId(String authOptionId) {
this.authOptionId = authOptionId;
}
public CrealogixAuthType getAuthType() {
return authType;
}
public void setAuthType(CrealogixAuthType authType) {
this.authType = authType;
}
public String getAuthInfo() {
return authInfo;
}
public void setAuthInfo(String authInfo) {
this.authInfo = authInfo;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CrealogixAuthItem that = (CrealogixAuthItem) o;
return Objects.equals(authOptionId, that.authOptionId) &&
authType == that.authType &&
Objects.equals(authInfo, that.authInfo);
}
@Override
public int hashCode() {
return Objects.hash(authOptionId, authType, authInfo);
}
}
| 2,044 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixActionCode.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/model/CrealogixActionCode.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix.model;
import java.util.stream.Stream;
public enum CrealogixActionCode {
PROMPT_FOR_LOGIN_NAME_PASSWORD,
PROMPT_FOR_AUTH_METHOD_SELECTION,
PROMPT_FOR_TAN,
POLL_FOR_TAN,
STOP_POLL_FOR_TAN,
PROMPT_FOR_PASSWORD_CHANGE,
PROMPT_FOR_SCOPE_ACCEPTANCE,
SEND_REQUEST;
public static CrealogixActionCode fromValue(String text) {
return Stream.of(CrealogixActionCode.values())
.filter(c -> c.name().equalsIgnoreCase(text))
.findFirst().orElse(null);
}
}
| 1,389 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixTransactionDetails.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/model/CrealogixTransactionDetails.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.adorsys.xs2a.adapter.api.model.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class CrealogixTransactionDetails {
private String transactionId;
private String entryReference;
private String endToEndId;
private String mandateId;
private String checkId;
private String creditorId;
private LocalDate bookingDate;
private LocalDate valueDate;
private Amount transactionAmount;
private List<ReportExchangeRate> currencyExchange;
private String creditorName;
private AccountReference creditorAccount;
private String creditorAgent;
private String ultimateCreditor;
private String debtorName;
private AccountReference debtorAccount;
private String debtorAgent;
private String ultimateDebtor;
private String remittanceInformationUnstructured;
private List<String> remittanceInformationUnstructuredArray;
private RemittanceInformationStructured remittanceInformationStructured;
private List<RemittanceInformationStructured> remittanceInformationStructuredArray;
private String additionalInformation;
private AdditionalInformationStructured additionalInformationStructured;
private PurposeCode purposeCode;
private String bankTransactionCode;
private String proprietaryBankTransactionCode;
private Balance balanceAfterTransaction;
@JsonProperty("_links")
private Map<String, HrefType> links;
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getEntryReference() {
return entryReference;
}
public void setEntryReference(String entryReference) {
this.entryReference = entryReference;
}
public String getEndToEndId() {
return endToEndId;
}
public void setEndToEndId(String endToEndId) {
this.endToEndId = endToEndId;
}
public String getMandateId() {
return mandateId;
}
public void setMandateId(String mandateId) {
this.mandateId = mandateId;
}
public String getCheckId() {
return checkId;
}
public void setCheckId(String checkId) {
this.checkId = checkId;
}
public String getCreditorId() {
return creditorId;
}
public void setCreditorId(String creditorId) {
this.creditorId = creditorId;
}
public LocalDate getBookingDate() {
return bookingDate;
}
public void setBookingDate(LocalDate bookingDate) {
this.bookingDate = bookingDate;
}
public LocalDate getValueDate() {
return valueDate;
}
public void setValueDate(LocalDate valueDate) {
this.valueDate = valueDate;
}
public Amount getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(Amount transactionAmount) {
this.transactionAmount = transactionAmount;
}
public List<ReportExchangeRate> getCurrencyExchange() {
return currencyExchange;
}
public void setCurrencyExchange(List<ReportExchangeRate> currencyExchange) {
this.currencyExchange = currencyExchange;
}
public String getCreditorName() {
return creditorName;
}
public void setCreditorName(String creditorName) {
this.creditorName = creditorName;
}
public AccountReference getCreditorAccount() {
return creditorAccount;
}
public void setCreditorAccount(AccountReference creditorAccount) {
this.creditorAccount = creditorAccount;
}
public String getCreditorAgent() {
return creditorAgent;
}
public void setCreditorAgent(String creditorAgent) {
this.creditorAgent = creditorAgent;
}
public String getUltimateCreditor() {
return ultimateCreditor;
}
public void setUltimateCreditor(String ultimateCreditor) {
this.ultimateCreditor = ultimateCreditor;
}
public String getDebtorName() {
return debtorName;
}
public void setDebtorName(String debtorName) {
this.debtorName = debtorName;
}
public AccountReference getDebtorAccount() {
return debtorAccount;
}
public void setDebtorAccount(AccountReference debtorAccount) {
this.debtorAccount = debtorAccount;
}
public String getDebtorAgent() {
return debtorAgent;
}
public void setDebtorAgent(String debtorAgent) {
this.debtorAgent = debtorAgent;
}
public String getUltimateDebtor() {
return ultimateDebtor;
}
public void setUltimateDebtor(String ultimateDebtor) {
this.ultimateDebtor = ultimateDebtor;
}
public String getRemittanceInformationUnstructured() {
return remittanceInformationUnstructured;
}
public void setRemittanceInformationUnstructured(String remittanceInformationUnstructured) {
this.remittanceInformationUnstructured = remittanceInformationUnstructured;
}
public List<String> getRemittanceInformationUnstructuredArray() {
return remittanceInformationUnstructuredArray;
}
public void setRemittanceInformationUnstructuredArray(
List<String> remittanceInformationUnstructuredArray) {
this.remittanceInformationUnstructuredArray = remittanceInformationUnstructuredArray;
}
public RemittanceInformationStructured getRemittanceInformationStructured() {
return remittanceInformationStructured;
}
public void setRemittanceInformationStructured(RemittanceInformationStructured remittanceInformationStructured) {
this.remittanceInformationStructured = remittanceInformationStructured;
}
public List<RemittanceInformationStructured> getRemittanceInformationStructuredArray() {
return remittanceInformationStructuredArray;
}
public void setRemittanceInformationStructuredArray(
List<RemittanceInformationStructured> remittanceInformationStructuredArray) {
this.remittanceInformationStructuredArray = remittanceInformationStructuredArray;
}
public String getAdditionalInformation() {
return additionalInformation;
}
public void setAdditionalInformation(String additionalInformation) {
this.additionalInformation = additionalInformation;
}
public AdditionalInformationStructured getAdditionalInformationStructured() {
return additionalInformationStructured;
}
public void setAdditionalInformationStructured(
AdditionalInformationStructured additionalInformationStructured) {
this.additionalInformationStructured = additionalInformationStructured;
}
public PurposeCode getPurposeCode() {
return purposeCode;
}
public void setPurposeCode(PurposeCode purposeCode) {
this.purposeCode = purposeCode;
}
public String getBankTransactionCode() {
return bankTransactionCode;
}
public void setBankTransactionCode(String bankTransactionCode) {
this.bankTransactionCode = bankTransactionCode;
}
public String getProprietaryBankTransactionCode() {
return proprietaryBankTransactionCode;
}
public void setProprietaryBankTransactionCode(String proprietaryBankTransactionCode) {
this.proprietaryBankTransactionCode = proprietaryBankTransactionCode;
}
public Balance getBalanceAfterTransaction() {
return balanceAfterTransaction;
}
public void setBalanceAfterTransaction(Balance balanceAfterTransaction) {
this.balanceAfterTransaction = balanceAfterTransaction;
}
public Map<String, HrefType> getLinks() {
return links;
}
public void setLinks(Map<String, HrefType> links) {
this.links = links;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CrealogixTransactionDetails that = (CrealogixTransactionDetails) o;
return Objects.equals(transactionId, that.transactionId) &&
Objects.equals(entryReference, that.entryReference) &&
Objects.equals(endToEndId, that.endToEndId) &&
Objects.equals(mandateId, that.mandateId) &&
Objects.equals(checkId, that.checkId) &&
Objects.equals(creditorId, that.creditorId) &&
Objects.equals(bookingDate, that.bookingDate) &&
Objects.equals(valueDate, that.valueDate) &&
Objects.equals(transactionAmount, that.transactionAmount) &&
Objects.equals(currencyExchange, that.currencyExchange) &&
Objects.equals(creditorName, that.creditorName) &&
Objects.equals(creditorAccount, that.creditorAccount) &&
Objects.equals(creditorAgent, that.creditorAgent) &&
Objects.equals(ultimateCreditor, that.ultimateCreditor) &&
Objects.equals(debtorName, that.debtorName) &&
Objects.equals(debtorAccount, that.debtorAccount) &&
Objects.equals(debtorAgent, that.debtorAgent) &&
Objects.equals(ultimateDebtor, that.ultimateDebtor) &&
Objects.equals(remittanceInformationUnstructured, that.remittanceInformationUnstructured) &&
Objects.equals(remittanceInformationUnstructuredArray, that.remittanceInformationUnstructuredArray) &&
Objects.equals(remittanceInformationStructured, that.remittanceInformationStructured) &&
Objects.equals(remittanceInformationStructuredArray, that.remittanceInformationStructuredArray) &&
Objects.equals(additionalInformation, that.additionalInformation) &&
Objects.equals(additionalInformationStructured, that.additionalInformationStructured) &&
Objects.equals(purposeCode, that.purposeCode) &&
Objects.equals(bankTransactionCode, that.bankTransactionCode) &&
Objects.equals(proprietaryBankTransactionCode, that.proprietaryBankTransactionCode) &&
Objects.equals(balanceAfterTransaction, that.balanceAfterTransaction) &&
Objects.equals(links, that.links);
}
@Override
public int hashCode() {
return Objects.hash(transactionId,
entryReference,
endToEndId,
mandateId,
checkId,
creditorId,
bookingDate,
valueDate,
transactionAmount,
currencyExchange,
creditorName,
creditorAccount,
creditorAgent,
ultimateCreditor,
debtorName,
debtorAccount,
debtorAgent,
ultimateDebtor,
remittanceInformationUnstructured,
remittanceInformationUnstructuredArray,
remittanceInformationStructured,
remittanceInformationStructuredArray,
additionalInformation,
additionalInformationStructured,
purposeCode,
bankTransactionCode,
proprietaryBankTransactionCode,
balanceAfterTransaction,
links);
}
}
| 12,140 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixPaymentInitiationWithStatusResponse.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/model/CrealogixPaymentInitiationWithStatusResponse.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix.model;
import de.adorsys.xs2a.adapter.api.model.AccountReference;
import de.adorsys.xs2a.adapter.api.model.Address;
import de.adorsys.xs2a.adapter.api.model.Amount;
import de.adorsys.xs2a.adapter.api.model.TransactionStatus;
import java.time.LocalDate;
import java.util.Objects;
public class CrealogixPaymentInitiationWithStatusResponse {
private String endToEndIdentification;
private AccountReference debtorAccount;
private Amount instructedAmount;
private AccountReference creditorAccount;
private String creditorAgent;
private String creditorName;
private Address creditorAddress;
private String remittanceInformationUnstructured;
private LocalDate requestedExecutionDate;
private TransactionStatus transactionStatus;
public String getEndToEndIdentification() {
return endToEndIdentification;
}
public void setEndToEndIdentification(String endToEndIdentification) {
this.endToEndIdentification = endToEndIdentification;
}
public AccountReference getDebtorAccount() {
return debtorAccount;
}
public void setDebtorAccount(AccountReference debtorAccount) {
this.debtorAccount = debtorAccount;
}
public Amount getInstructedAmount() {
return instructedAmount;
}
public void setInstructedAmount(Amount instructedAmount) {
this.instructedAmount = instructedAmount;
}
public AccountReference getCreditorAccount() {
return creditorAccount;
}
public void setCreditorAccount(AccountReference creditorAccount) {
this.creditorAccount = creditorAccount;
}
public String getCreditorAgent() {
return creditorAgent;
}
public void setCreditorAgent(String creditorAgent) {
this.creditorAgent = creditorAgent;
}
public String getCreditorName() {
return creditorName;
}
public void setCreditorName(String creditorName) {
this.creditorName = creditorName;
}
public Address getCreditorAddress() {
return creditorAddress;
}
public void setCreditorAddress(Address creditorAddress) {
this.creditorAddress = creditorAddress;
}
public String getRemittanceInformationUnstructured() {
return remittanceInformationUnstructured;
}
public void setRemittanceInformationUnstructured(String remittanceInformationUnstructured) {
this.remittanceInformationUnstructured = remittanceInformationUnstructured;
}
public LocalDate getRequestedExecutionDate() {
return requestedExecutionDate;
}
public void setRequestedExecutionDate(LocalDate requestedExecutionDate) {
this.requestedExecutionDate = requestedExecutionDate;
}
public TransactionStatus getTransactionStatus() {
return transactionStatus;
}
public void setTransactionStatus(TransactionStatus transactionStatus) {
this.transactionStatus = transactionStatus;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CrealogixPaymentInitiationWithStatusResponse that = (CrealogixPaymentInitiationWithStatusResponse) o;
return Objects.equals(endToEndIdentification, that.endToEndIdentification) &&
Objects.equals(debtorAccount, that.debtorAccount) &&
Objects.equals(instructedAmount, that.instructedAmount) &&
Objects.equals(creditorAccount, that.creditorAccount) &&
Objects.equals(creditorAgent, that.creditorAgent) &&
Objects.equals(creditorName, that.creditorName) &&
Objects.equals(creditorAddress, that.creditorAddress) &&
Objects.equals(remittanceInformationUnstructured, that.remittanceInformationUnstructured) &&
Objects.equals(requestedExecutionDate, that.requestedExecutionDate) &&
transactionStatus == that.transactionStatus;
}
@Override
public int hashCode() {
return Objects.hash(endToEndIdentification,
debtorAccount,
instructedAmount,
creditorAccount,
creditorAgent,
creditorName,
creditorAddress,
remittanceInformationUnstructured,
requestedExecutionDate,
transactionStatus);
}
}
| 5,226 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixValidationResponse.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/model/CrealogixValidationResponse.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix.model;
import java.util.List;
import java.util.Objects;
/**
* custom DKB model, that the bank returns for 'Login / Credentials validation' request
* i.e. POST /psd2-auth/v1/auth/token
*/
public class CrealogixValidationResponse {
private CrealogixReturnCode returnCode;
private CrealogixActionCode actionCode;
private String returnMsg;
private String lastSuccessfulLoginTimestamp;
private String authOptionIdLastUsed;
private CrealogixAuthType authTypeSelected;
private String authOptionIdSelected;
private String challenge;
private Integer timeout;
private List<CrealogixAuthItem> authSelectionList;
private String accessToken;
public CrealogixReturnCode getReturnCode() {
return returnCode;
}
public void setReturnCode(CrealogixReturnCode returnCode) {
this.returnCode = returnCode;
}
public CrealogixActionCode getActionCode() {
return actionCode;
}
public void setActionCode(CrealogixActionCode actionCode) {
this.actionCode = actionCode;
}
public String getReturnMsg() {
return returnMsg;
}
public void setReturnMsg(String returnMsg) {
this.returnMsg = returnMsg;
}
public String getLastSuccessfulLoginTimestamp() {
return lastSuccessfulLoginTimestamp;
}
public void setLastSuccessfulLoginTimestamp(String lastSuccessfulLoginTimestamp) {
this.lastSuccessfulLoginTimestamp = lastSuccessfulLoginTimestamp;
}
public String getAuthOptionIdLastUsed() {
return authOptionIdLastUsed;
}
public void setAuthOptionIdLastUsed(String authOptionIdLastUsed) {
this.authOptionIdLastUsed = authOptionIdLastUsed;
}
public CrealogixAuthType getAuthTypeSelected() {
return authTypeSelected;
}
public void setAuthTypeSelected(CrealogixAuthType authTypeSelected) {
this.authTypeSelected = authTypeSelected;
}
public String getAuthOptionIdSelected() {
return authOptionIdSelected;
}
public void setAuthOptionIdSelected(String authOptionIdSelected) {
this.authOptionIdSelected = authOptionIdSelected;
}
public String getChallenge() {
return challenge;
}
public void setChallenge(String challenge) {
this.challenge = challenge;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
public List<CrealogixAuthItem> getAuthSelectionList() {
return authSelectionList;
}
public void setAuthSelectionList(List<CrealogixAuthItem> authSelectionList) {
this.authSelectionList = authSelectionList;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CrealogixValidationResponse that = (CrealogixValidationResponse) o;
return Objects.equals(returnCode, that.returnCode) &&
Objects.equals(actionCode, that.actionCode) &&
Objects.equals(returnMsg, that.returnMsg) &&
Objects.equals(lastSuccessfulLoginTimestamp, that.lastSuccessfulLoginTimestamp) &&
Objects.equals(authOptionIdLastUsed, that.authOptionIdLastUsed) &&
Objects.equals(authTypeSelected, that.authTypeSelected) &&
Objects.equals(authOptionIdSelected, that.authOptionIdSelected) &&
Objects.equals(challenge, that.challenge) &&
Objects.equals(timeout, that.timeout) &&
Objects.equals(authSelectionList, that.authSelectionList) &&
Objects.equals(accessToken, that.accessToken);
}
@Override
public int hashCode() {
return Objects.hash(returnCode, actionCode, returnMsg, lastSuccessfulLoginTimestamp, authOptionIdLastUsed, authTypeSelected, authOptionIdSelected, challenge, timeout, authSelectionList, accessToken);
}
}
| 5,019 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixOK200TransactionDetails.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/model/CrealogixOK200TransactionDetails.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix.model;
import java.util.Objects;
public class CrealogixOK200TransactionDetails {
private CrealogixTransactionDetails transactionsDetails;
public CrealogixTransactionDetails getTransactionsDetails() {
return transactionsDetails;
}
public void setTransactionsDetails(CrealogixTransactionDetails transactionsDetails) {
this.transactionsDetails = transactionsDetails;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CrealogixOK200TransactionDetails that = (CrealogixOK200TransactionDetails) o;
return Objects.equals(transactionsDetails, that.transactionsDetails);
}
@Override
public int hashCode() {
return Objects.hash(transactionsDetails);
}
}
| 1,705 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixReturnCode.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/model/CrealogixReturnCode.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix.model;
import java.util.stream.Stream;
public enum CrealogixReturnCode {
NONE,
CORRECT,
CORRECT_PASSWORD_CHANGE,
FAILED,
LOCKED,
TEMPORARY_LOCKED,
PASSWORD_EXPIRED,
OFFLINE_TOOL_ONLY,
NO_SUITABLE_AUTHENTICATION_TYPE,
TAN_WRONG,
TAN_INVALIDATED,
TAN_EXPIRED,
TAN_NOT_ACTIVE,
NOTIFICATION_UNDELIVERABLE,
NOTIFICATION_CONFIRMATION_REJECTED,
NOTIFICATION_EXPIRED,
AWAITING_USER_RESPONSE;
public static CrealogixReturnCode fromValue(String text) {
return Stream.of(CrealogixReturnCode.values())
.filter(c -> c.name().equalsIgnoreCase(text))
.findFirst().orElse(null);
}
}
| 1,550 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixTransactionResponse200Json.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/model/CrealogixTransactionResponse200Json.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.adorsys.xs2a.adapter.api.model.AccountReference;
import de.adorsys.xs2a.adapter.api.model.Balance;
import de.adorsys.xs2a.adapter.api.model.HrefType;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class CrealogixTransactionResponse200Json {
private AccountReference account;
private CrealogixAccountReport transactions;
private List<Balance> balances;
@JsonProperty("_links")
private Map<String, HrefType> links;
public AccountReference getAccount() {
return account;
}
public void setAccount(AccountReference account) {
this.account = account;
}
public CrealogixAccountReport getTransactions() {
return transactions;
}
public void setTransactions(CrealogixAccountReport transactions) {
this.transactions = transactions;
}
public List<Balance> getBalances() {
return balances;
}
public void setBalances(List<Balance> balances) {
this.balances = balances;
}
public Map<String, HrefType> getLinks() {
return links;
}
public void setLinks(Map<String, HrefType> links) {
this.links = links;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CrealogixTransactionResponse200Json that = (CrealogixTransactionResponse200Json) o;
return Objects.equals(account, that.account) &&
Objects.equals(transactions, that.transactions) &&
Objects.equals(balances, that.balances) &&
Objects.equals(links, that.links);
}
@Override
public int hashCode() {
return Objects.hash(account,
transactions,
balances,
links);
}
}
| 2,754 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
CrealogixAuthType.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/crealogix-adapter/src/main/java/de/adorsys/xs2a/adapter/crealogix/model/CrealogixAuthType.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.crealogix.model;
import java.util.stream.Stream;
public enum CrealogixAuthType {
PASSWORD,
SMSTAN,
MATRIX,
FOTOTAN,
PUSHTAN,
DIGIPASS,
CHIPTAN;
public static CrealogixAuthType fromValue(String text) {
return Stream.of(CrealogixAuthType.values())
.filter(t -> t.name().equalsIgnoreCase(text))
.findFirst().orElse(null);
}
}
| 1,256 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderServiceProviderTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/test/java/de/adorsys/xs2a/adapter/santander/SantanderServiceProviderTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.AccountInformationService;
import de.adorsys.xs2a.adapter.api.Oauth2Service;
import de.adorsys.xs2a.adapter.api.PaymentInitiationService;
import de.adorsys.xs2a.adapter.api.Pkcs12KeyStore;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class SantanderServiceProviderTest {
private SantanderServiceProvider serviceProvider;
private final HttpClientConfig httpClientConfig = mock(HttpClientConfig.class);
private final HttpClientFactory httpClientFactory = mock(HttpClientFactory.class);
private final Pkcs12KeyStore keyStore = mock(Pkcs12KeyStore.class);
private final Aspsp aspsp = new Aspsp();
@BeforeEach
void setUp() {
serviceProvider = new SantanderServiceProvider();
when(httpClientFactory.getHttpClientConfig()).thenReturn(httpClientConfig);
when(httpClientConfig.getKeyStore()).thenReturn(keyStore);
}
@Test
void getAccountInformationService() {
AccountInformationService actualService
= serviceProvider.getAccountInformationService(aspsp, httpClientFactory, null);
assertThat(actualService)
.isExactlyInstanceOf(SantanderAccountInformationService.class);
}
@Test
void getPaymentInitiationService() {
PaymentInitiationService actualService
= serviceProvider.getPaymentInitiationService(aspsp, httpClientFactory, null);
assertThat(actualService)
.isExactlyInstanceOf(SantanderPaymentInitiationService.class);
}
@Test
void getOauth2Service() {
Oauth2Service actualService
= serviceProvider.getOauth2Service(aspsp, httpClientFactory);
assertThat(actualService)
.isExactlyInstanceOf(SantanderOauth2Service.class);
}
}
| 2,984 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderRequestHandlerTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/test/java/de/adorsys/xs2a/adapter/santander/SantanderRequestHandlerTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.exception.RequestAuthorizationValidationException;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Map;
class SantanderRequestHandlerTest {
private final SantanderRequestHandler requestHandler = new SantanderRequestHandler();
@Test
void validateRequest_throwException() {
RequestHeaders requestHeaders = RequestHeaders.empty();
Assertions.assertThatThrownBy(() -> requestHandler.validateRequest(requestHeaders))
.hasMessageContaining(SantanderRequestHandler.REQUEST_ERROR_MESSAGE)
.isExactlyInstanceOf(RequestAuthorizationValidationException.class);
}
@Test
void validateRequest_noException() {
Map<String, String> headers = Map.of(RequestHeaders.AUTHORIZATION, "Bearer foo");
RequestHeaders requestHeaders = RequestHeaders.fromMap(headers);
Assertions.assertThatCode(() -> requestHandler.validateRequest(requestHeaders))
.doesNotThrowAnyException();
}
}
| 1,970 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderPaymentInitiationServiceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/test/java/de/adorsys/xs2a/adapter/santander/SantanderPaymentInitiationServiceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.*;
import de.adorsys.xs2a.adapter.api.exception.RequestAuthorizationValidationException;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.http.Request;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.api.validation.ValidationError;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Map;
import static de.adorsys.xs2a.adapter.api.model.PaymentProduct.SEPA_CREDIT_TRANSFERS;
import static de.adorsys.xs2a.adapter.api.model.PaymentService.PAYMENTS;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class SantanderPaymentInitiationServiceTest {
private static final RequestHeaders HEADERS_WITH_AUTHORISATION
= RequestHeaders.fromMap(Map.of(RequestHeaders.AUTHORIZATION, "Bearer foo"));
private static final RequestParams EMPTY_PARAMS = RequestParams.empty();
private static final RequestHeaders EMPTY_HEADERS = RequestHeaders.empty();
private static Request.Builder requestBuilder;
private SantanderPaymentInitiationService paymentInitiationService;
@Mock
private HttpClientFactory httpClientFactory;
@Mock
private HttpClientConfig httpClientConfig;
@Mock
private SantanderOauth2Service oauth2Service;
@Mock
private Aspsp aspsp;
@Mock
private Pkcs12KeyStore keyStore;
@Mock
private HttpClient httpClient;
@Mock
private LinksRewriter linksRewriter;
@BeforeEach
void setUp() {
requestBuilder = mock(Request.Builder.class);
when(httpClientFactory.getHttpClient(any(), any())).thenReturn(httpClient);
when(httpClientFactory.getHttpClientConfig()).thenReturn(httpClientConfig);
when(httpClientConfig.getKeyStore()).thenReturn(keyStore);
paymentInitiationService = new SantanderPaymentInitiationService(aspsp, httpClientFactory, linksRewriter, oauth2Service);
}
@Test
@SuppressWarnings("unchecked")
void initiatePayment() {
ArgumentCaptor<Map<String, String>> headersCaptor = ArgumentCaptor.forClass(Map.class);
when(httpClient.post(anyString())).thenReturn(requestBuilder);
when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder);
when(requestBuilder.send(any(), any()))
.thenReturn(new Response<>(-1, new PaymentInitationRequestResponse201(), ResponseHeaders.emptyResponseHeaders()));
paymentInitiationService.initiatePayment(PAYMENTS, SEPA_CREDIT_TRANSFERS, EMPTY_HEADERS, EMPTY_PARAMS, null);
verify(requestBuilder, times(1)).headers(headersCaptor.capture());
Map<String, String> actualHeaders = headersCaptor.getValue();
assertThat(actualHeaders)
.isNotEmpty()
.containsEntry(RequestHeaders.AUTHORIZATION, "Bearer null");
}
@Test
void getPaymentInitiationStatus() {
Map<String, String> headerWithIpAddressAndAuthorisation = Map.of(RequestHeaders.PSU_IP_ADDRESS, "0.0.0.0",
RequestHeaders.AUTHORIZATION, "Bearer foo");
when(httpClient.get(anyString())).thenReturn(requestBuilder);
when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder);
assertThatCode(() -> paymentInitiationService.getPaymentInitiationStatus(PAYMENTS, SEPA_CREDIT_TRANSFERS, "", RequestHeaders.fromMap(headerWithIpAddressAndAuthorisation), EMPTY_PARAMS))
.doesNotThrowAnyException();
assertThatThrownBy(() -> paymentInitiationService.getPaymentInitiationStatus(PAYMENTS, SEPA_CREDIT_TRANSFERS, "", EMPTY_HEADERS, EMPTY_PARAMS))
.isExactlyInstanceOf(RequestAuthorizationValidationException.class);
}
@Test
void validateGetPaymentInitiationStatus() {
Map<String, String> headerWithPsuIpAddress = Map.of(RequestHeaders.PSU_IP_ADDRESS, "0.0.0.0");
List<ValidationError> shouldBeEmpty
= paymentInitiationService.validateGetPaymentInitiationStatus(null, null, null, RequestHeaders.fromMap(headerWithPsuIpAddress), null);
List<ValidationError> shouldHaveError
= paymentInitiationService.validateGetPaymentInitiationStatus(null, null, null, EMPTY_HEADERS, null);
assertThat(shouldBeEmpty)
.isEmpty();
assertThat(shouldHaveError)
.isNotEmpty()
.contains(ValidationError.required(RequestHeaders.PSU_IP_ADDRESS));
}
@Test
void getSinglePaymentInformation() {
when(httpClient.get(anyString())).thenReturn(requestBuilder);
when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder);
assertThatCode(() -> paymentInitiationService.getSinglePaymentInformation(SEPA_CREDIT_TRANSFERS, "", HEADERS_WITH_AUTHORISATION, EMPTY_PARAMS))
.doesNotThrowAnyException();
assertThatThrownBy(() -> paymentInitiationService.getSinglePaymentInformation(SEPA_CREDIT_TRANSFERS, "", EMPTY_HEADERS, EMPTY_PARAMS))
.isExactlyInstanceOf(RequestAuthorizationValidationException.class);
}
@Test
void throwUnsupportedOperationException() {
assertThatThrownBy(() -> paymentInitiationService.getPaymentInitiationAuthorisation(null, null, null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> paymentInitiationService.startPaymentAuthorisation(null, null, null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> paymentInitiationService.startPaymentAuthorisation(null, null, null, null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> paymentInitiationService.updatePaymentPsuData(null, null, null, null, null, null, (UpdatePsuAuthentication) null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> paymentInitiationService.updatePaymentPsuData(null, null, null, null, null, null, (SelectPsuAuthenticationMethod) null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> paymentInitiationService.updatePaymentPsuData(null, null, null, null, null, null, (TransactionAuthorisation) null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> paymentInitiationService.getPaymentInitiationScaStatus(null, null, null, null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
}
@Test
void getPeriodicPaymentInformation() {
when(httpClient.get(anyString())).thenReturn(requestBuilder);
when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder);
when(requestBuilder.send(any(), any()))
.thenReturn(new Response<>(-1, new PeriodicPaymentInitiationWithStatusResponse(), ResponseHeaders.emptyResponseHeaders()));
assertThatCode(() -> paymentInitiationService.getPeriodicPaymentInformation(SEPA_CREDIT_TRANSFERS, "", HEADERS_WITH_AUTHORISATION, EMPTY_PARAMS))
.doesNotThrowAnyException();
assertThatThrownBy(() -> paymentInitiationService.getPeriodicPaymentInformation(SEPA_CREDIT_TRANSFERS, "", EMPTY_HEADERS, EMPTY_PARAMS))
.isExactlyInstanceOf(RequestAuthorizationValidationException.class);
}
}
| 8,686 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderPaymentInitiationServiceWireMockTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/test/java/de/adorsys/xs2a/adapter/santander/SantanderPaymentInitiationServiceWireMockTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.PaymentInitiationService;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.test.ServiceWireMockTest;
import de.adorsys.xs2a.adapter.test.TestRequestResponse;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
@ServiceWireMockTest(SantanderServiceProvider.class)
class SantanderPaymentInitiationServiceWireMockTest {
private static final String PAYMENT_ID = "73c52dc3-bd44-42b3-bc86-6b61c3167b63";
private final PaymentInitiationService paymentInitiationService;
SantanderPaymentInitiationServiceWireMockTest(PaymentInitiationService paymentInitiationService) {
this.paymentInitiationService = paymentInitiationService;
}
@Test
void initiatePayment() throws IOException {
TestRequestResponse requestResponse = new TestRequestResponse("pis/payments/sepa-credit-transfers/initiate-payment.json");
Response<PaymentInitationRequestResponse201> response = paymentInitiationService.initiatePayment(PaymentService.PAYMENTS,
PaymentProduct.SEPA_CREDIT_TRANSFERS,
requestResponse.requestHeaders(),
RequestParams.empty(),
requestResponse.requestBody(PaymentInitiationJson.class));
assertThat(response.getBody())
.isEqualTo(requestResponse.responseBody(PaymentInitationRequestResponse201.class));
}
@Test
void getPaymentStatus() throws IOException {
TestRequestResponse requestResponse = new TestRequestResponse("pis/payments/sepa-credit-transfers/get-payment-status.json");
Response<PaymentInitiationStatusResponse200Json> response = paymentInitiationService.getPaymentInitiationStatus(PaymentService.PAYMENTS,
PaymentProduct.SEPA_CREDIT_TRANSFERS,
PAYMENT_ID,
requestResponse.requestHeaders(),
RequestParams.empty());
assertThat(response.getBody())
.isEqualTo(requestResponse.responseBody(PaymentInitiationStatusResponse200Json.class));
}
}
| 3,059 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderAccountInformationServiceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/test/java/de/adorsys/xs2a/adapter/santander/SantanderAccountInformationServiceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.*;
import de.adorsys.xs2a.adapter.api.exception.RequestAuthorizationValidationException;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.http.Request;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.impl.http.RequestBuilderImpl;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.ByteArrayInputStream;
import java.util.Map;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class SantanderAccountInformationServiceTest {
private static final String URI = "https://foo.boo";
private static final String ACCOUNT_ID = "accountId";
private static final String REMITTANCE_INFORMATION_STRUCTURED = "remittanceInformationStructuredStringValue";
private static final String CONSENT_ID = "consentId";
private static final RequestHeaders HEADERS_WITH_AUTHORISATION
= RequestHeaders.fromMap(Map.of(RequestHeaders.AUTHORIZATION, "Bearer foo"));
private static Request.Builder requestBuilder;
private static final RequestHeaders EMPTY_REQUEST_HEADERS = RequestHeaders.empty();
private static final RequestParams EMPTY_REQUEST_PARAMS = RequestParams.empty();
private SantanderAccountInformationService accountInformationService;
@Mock
private HttpClient httpClient;
@Mock
private Aspsp aspsp;
@Mock
private LinksRewriter linksRewriter;
@Mock
private SantanderOauth2Service oauth2Service;
@Mock
private HttpClientFactory httpClientFactory;
@Mock
private HttpClientConfig httpClientConfig;
@Mock
private Pkcs12KeyStore keyStore;
@BeforeEach
void setUp() {
requestBuilder = mock(Request.Builder.class);
when(httpClientFactory.getHttpClient(any(), any())).thenReturn(httpClient);
when(httpClientFactory.getHttpClientConfig()).thenReturn(httpClientConfig);
when(httpClientConfig.getKeyStore()).thenReturn(keyStore);
accountInformationService = new SantanderAccountInformationService(aspsp, oauth2Service, httpClientFactory, linksRewriter);
}
@Test
void getTransactionList() {
String rawResponse = "{\n" +
" \"transactions\": {\n" +
" \"booked\": [\n" +
" {\n" +
" \"remittanceInformationStructured\": {" +
" \"reference\": \"" + REMITTANCE_INFORMATION_STRUCTURED + "\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
when(httpClient.get(anyString()))
.thenReturn(new RequestBuilderImpl(httpClient, "GET", URI));
when(httpClient.send(any(), any()))
.thenAnswer(invocationOnMock -> {
HttpClient.ResponseHandler responseHandler = invocationOnMock.getArgument(1, HttpClient.ResponseHandler.class);
return new Response<>(-1,
responseHandler.apply(200,
new ByteArrayInputStream(rawResponse.getBytes()),
ResponseHeaders.emptyResponseHeaders()),
null);
});
Response<?> actualResponse
= accountInformationService.getTransactionList(ACCOUNT_ID, HEADERS_WITH_AUTHORISATION, EMPTY_REQUEST_PARAMS);
verify(httpClient, times(1)).get(anyString());
verify(httpClient, times(1)).send(any(), any());
assertThat(actualResponse)
.isNotNull()
.extracting(Response::getBody)
.asInstanceOf(InstanceOfAssertFactories.type(TransactionsResponse200Json.class))
.matches(body ->
body.getTransactions()
.getBooked()
.get(0)
.getRemittanceInformationStructured()
.equals(REMITTANCE_INFORMATION_STRUCTURED));
}
@Test
@SuppressWarnings("unchecked")
void createConsent() {
var requestBuilder = mock(Request.Builder.class);
ArgumentCaptor<Map<String, String>> headersCaptor = ArgumentCaptor.forClass(Map.class);
when(httpClient.post(anyString())).thenReturn(requestBuilder);
when(requestBuilder.jsonBody(anyString())).thenReturn(requestBuilder);
when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder);
when(requestBuilder.send(any(), any()))
.thenReturn(getResponse(new ConsentsResponse201()));
accountInformationService.createConsent(EMPTY_REQUEST_HEADERS, EMPTY_REQUEST_PARAMS, new Consents());
verify(requestBuilder, times(1)).headers(headersCaptor.capture());
Map<String, String> actualHeaders = headersCaptor.getValue();
assertThat(actualHeaders)
.isNotEmpty()
.containsEntry(RequestHeaders.AUTHORIZATION, "Bearer null");
}
@Test
void getConsentInformation() {
when(httpClient.get(anyString())).thenReturn(requestBuilder);
when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder);
when(requestBuilder.send(any(), any()))
.thenReturn(getResponse(new ConsentInformationResponse200Json()));
assertThatCode(() -> accountInformationService.getConsentInformation(CONSENT_ID, HEADERS_WITH_AUTHORISATION, EMPTY_REQUEST_PARAMS))
.doesNotThrowAnyException();
assertThatThrownBy(() -> accountInformationService.getConsentInformation(CONSENT_ID, EMPTY_REQUEST_HEADERS, EMPTY_REQUEST_PARAMS))
.isExactlyInstanceOf(RequestAuthorizationValidationException.class);
}
@Test
void getConsentStatus() {
when(httpClient.get(anyString())).thenReturn(requestBuilder);
when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder);
when(requestBuilder.send(any(), any()))
.thenReturn(getResponse(new ConsentStatusResponse200()));
assertThatCode(() -> accountInformationService.getConsentStatus(CONSENT_ID, HEADERS_WITH_AUTHORISATION, EMPTY_REQUEST_PARAMS))
.doesNotThrowAnyException();
assertThatThrownBy(() -> accountInformationService.getConsentInformation(CONSENT_ID, EMPTY_REQUEST_HEADERS, EMPTY_REQUEST_PARAMS))
.isExactlyInstanceOf(RequestAuthorizationValidationException.class);
}
@Test
void deleteConsent() {
when(httpClient.delete(anyString())).thenReturn(requestBuilder);
when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder);
when(requestBuilder.send(any(), any()))
.thenReturn(getResponse(null));
assertThatCode(() -> accountInformationService.deleteConsent(CONSENT_ID, HEADERS_WITH_AUTHORISATION, EMPTY_REQUEST_PARAMS))
.doesNotThrowAnyException();
assertThatThrownBy(() -> accountInformationService.deleteConsent(CONSENT_ID, EMPTY_REQUEST_HEADERS, EMPTY_REQUEST_PARAMS))
.isExactlyInstanceOf(RequestAuthorizationValidationException.class);
}
@Test
void getAccountList() {
when(httpClient.get(anyString())).thenReturn(requestBuilder);
when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder);
when(requestBuilder.send(any(), any()))
.thenReturn(getResponse(new AccountList()));
assertThatCode(() -> accountInformationService.getAccountList(HEADERS_WITH_AUTHORISATION, EMPTY_REQUEST_PARAMS))
.doesNotThrowAnyException();
assertThatThrownBy(() -> accountInformationService.getAccountList(EMPTY_REQUEST_HEADERS, EMPTY_REQUEST_PARAMS))
.isExactlyInstanceOf(RequestAuthorizationValidationException.class);
}
@Test
void readAccountDetails() {
when(httpClient.get(anyString())).thenReturn(requestBuilder);
when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder);
when(requestBuilder.send(any(), any()))
.thenReturn(getResponse(new OK200AccountDetails()));
assertThatCode(() -> accountInformationService.readAccountDetails(ACCOUNT_ID, HEADERS_WITH_AUTHORISATION, EMPTY_REQUEST_PARAMS))
.doesNotThrowAnyException();
assertThatThrownBy(() -> accountInformationService.readAccountDetails(ACCOUNT_ID, EMPTY_REQUEST_HEADERS, EMPTY_REQUEST_PARAMS))
.isExactlyInstanceOf(RequestAuthorizationValidationException.class);
}
private <T> Response<T> getResponse(T body) {
return new Response<>(-1, body, ResponseHeaders.emptyResponseHeaders());
}
@Test
void getBalances() {
when(httpClient.get(anyString())).thenReturn(requestBuilder);
when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder);
when(requestBuilder.send(any(), any()))
.thenReturn(getResponse(new ReadAccountBalanceResponse200()));
assertThatCode(() -> accountInformationService.getBalances(ACCOUNT_ID, HEADERS_WITH_AUTHORISATION, EMPTY_REQUEST_PARAMS))
.doesNotThrowAnyException();
assertThatThrownBy(() -> accountInformationService.getBalances(ACCOUNT_ID, EMPTY_REQUEST_HEADERS, EMPTY_REQUEST_PARAMS))
.isExactlyInstanceOf(RequestAuthorizationValidationException.class);
}
@Test
void getTransactionList_throwError() {
assertThatThrownBy(() -> accountInformationService.getTransactionList(ACCOUNT_ID, EMPTY_REQUEST_HEADERS, EMPTY_REQUEST_PARAMS))
.isExactlyInstanceOf(RequestAuthorizationValidationException.class);
}
@Test
void throwUnsupportedOperationException() {
assertThatThrownBy(() -> accountInformationService.startConsentAuthorisation(null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.startConsentAuthorisation(null, null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.updateConsentsPsuData(null, null, null, null, (UpdatePsuAuthentication) null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.updateConsentsPsuData(null, null, null, null, (SelectPsuAuthenticationMethod) null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.updateConsentsPsuData(null, null, null, null, (TransactionAuthorisation) null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.getTransactionDetails(null, null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.getConsentAuthorisation(null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.getConsentAuthorisation(null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.getCardAccountList(null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.getCardAccountDetails(null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.getCardAccountBalances(null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.getCardAccountTransactionList(null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> accountInformationService.getConsentScaStatus(null, null, null, null))
.isExactlyInstanceOf(UnsupportedOperationException.class);
}
}
| 13,324 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderAccountInformationServiceWireMockTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/test/java/de/adorsys/xs2a/adapter/santander/SantanderAccountInformationServiceWireMockTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.AccountInformationService;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.test.ServiceWireMockTest;
import de.adorsys.xs2a.adapter.test.TestRequestResponse;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
@ServiceWireMockTest(SantanderServiceProvider.class)
class SantanderAccountInformationServiceWireMockTest {
private static final String ACCOUNT_ID = "3b5a3b70-ceec-4518-b23e-ee5d1302f532";
private static final String CONSENT_ID = "3087d8e2-2eb0-4e54-9af9-32ea8c6eef02";
private final AccountInformationService accountInformationService;
SantanderAccountInformationServiceWireMockTest(AccountInformationService accountInformationService) {
this.accountInformationService = accountInformationService;
}
@Test
void createConsent() throws IOException {
TestRequestResponse requestResponse = new TestRequestResponse("ais/create-consent.json");
Response<ConsentsResponse201> response = accountInformationService.createConsent(requestResponse.requestHeaders(),
RequestParams.empty(),
requestResponse.requestBody(Consents.class));
assertThat(response.getBody())
.isEqualTo(requestResponse.responseBody(ConsentsResponse201.class));
}
@Test
void getAccounts() throws IOException {
TestRequestResponse requestResponse = new TestRequestResponse("ais/get-accounts.json");
Response<AccountList> response = accountInformationService.getAccountList(requestResponse.requestHeaders(),
requestResponse.requestParams());
assertThat(response.getBody())
.isEqualTo(requestResponse.responseBody(AccountList.class));
}
@Test
void getTransactions() throws IOException {
TestRequestResponse requestResponse = new TestRequestResponse("ais/get-transactions.json");
Response<TransactionsResponse200Json> response = accountInformationService.getTransactionList(ACCOUNT_ID,
requestResponse.requestHeaders(),
requestResponse.requestParams());
assertThat(response.getBody())
.isEqualTo(requestResponse.responseBody(TransactionsResponse200Json.class));
}
@Test
void getBalances() throws IOException {
TestRequestResponse requestResponse = new TestRequestResponse("ais/get-balances.json");
Response<ReadAccountBalanceResponse200> response = accountInformationService.getBalances(ACCOUNT_ID,
requestResponse.requestHeaders(),
RequestParams.empty());
assertThat(response.getBody())
.isEqualTo(requestResponse.responseBody(ReadAccountBalanceResponse200.class));
}
@Test
void getConsentStatus() throws IOException {
TestRequestResponse requestResponse = new TestRequestResponse("ais/get-consent-status.json");
Response<ConsentStatusResponse200> response = accountInformationService.getConsentStatus(CONSENT_ID,
requestResponse.requestHeaders(),
RequestParams.empty());
assertThat(response.getBody())
.isEqualTo(requestResponse.responseBody(ConsentStatusResponse200.class));
}
@Test
void deleteConsent() throws IOException {
TestRequestResponse requestResponse = new TestRequestResponse("ais/delete-consent.json");
Response<Void> response = accountInformationService.deleteConsent(CONSENT_ID,
requestResponse.requestHeaders(),
RequestParams.empty());
assertThat(response.getStatusCode())
.isEqualTo(204);
}
}
| 4,650 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderOauth2ServiceWireMockTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/test/java/de/adorsys/xs2a/adapter/santander/SantanderOauth2ServiceWireMockTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.Oauth2Service;
import de.adorsys.xs2a.adapter.api.model.TokenResponse;
import de.adorsys.xs2a.adapter.test.ServiceWireMockTest;
import de.adorsys.xs2a.adapter.test.TestRequestResponse;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@ServiceWireMockTest(SantanderServiceProvider.class)
class SantanderOauth2ServiceWireMockTest {
private final Oauth2Service oauth2Service;
SantanderOauth2ServiceWireMockTest(Oauth2Service oauth2Service) {
this.oauth2Service = oauth2Service;
}
@Test
void getAuthorizationEndpoint() throws IOException {
TestRequestResponse requestResponse = new TestRequestResponse("oauth2/get-authorization-endpoint.json");
// Needed a mutable map to put into Parameters, otherwise requestParams().toMap() will return unmodifiable collection
// which will throw UnsupportedOperationException downstream.
Map<String, String> modifiableParams = new LinkedHashMap<>(requestResponse.requestParams().toMap());
URI actualUri = oauth2Service.getAuthorizationRequestUri(requestResponse.requestHeaders().toMap(),
new Oauth2Service.Parameters(modifiableParams));
// It's onerous to get a WireMock port in running test environment, thus checking determined parts of URL only
assertThat(actualUri)
.isNotNull()
.asString()
.contains("http://localhost", "response_type=code", "scope=AIS%3A3087d8e2-2eb0-4e54-9af9-32ea8c6eef02");
}
@Test
void getClientCredentialsToken() throws IOException {
TestRequestResponse requestResponse = new TestRequestResponse("oauth2/get-client-credentials-token.json");
Map<String, String> modifiableParams = new LinkedHashMap<>(requestResponse.requestParams().toMap());
TokenResponse actualToken = oauth2Service.getToken(requestResponse.requestHeaders().toMap(),
new Oauth2Service.Parameters(modifiableParams));
assertThat(actualToken)
.isNotNull()
.isEqualTo(requestResponse.responseBody(TokenResponse.class));
}
@Test
void getAccessToken() throws IOException {
TestRequestResponse requestResponse = new TestRequestResponse("oauth2/get-access-token.json");
Map<String, String> modifiableParams = new LinkedHashMap<>(requestResponse.requestParams().toMap());
TokenResponse actualToken = oauth2Service.getToken(requestResponse.requestHeaders().toMap(),
new Oauth2Service.Parameters(modifiableParams));
assertThat(actualToken)
.isNotNull()
.isEqualTo(requestResponse.responseBody(TokenResponse.class));
}
}
| 3,707 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderOauth2ServiceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/test/java/de/adorsys/xs2a/adapter/santander/SantanderOauth2ServiceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.Oauth2Service;
import de.adorsys.xs2a.adapter.api.Oauth2Service.Parameters;
import de.adorsys.xs2a.adapter.api.Pkcs12KeyStore;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.api.validation.ValidationError;
import de.adorsys.xs2a.adapter.impl.http.ApacheHttpClient;
import de.adorsys.xs2a.adapter.impl.oauth2.api.model.AuthorisationServerMetaData;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.*;
class SantanderOauth2ServiceTest {
private static final String SCA_OAUTH_LINK = "https://santander.de/.well-known/oauth-authorization-server";
private static final String AUTHORIZATION_ENDPOINT = "https://api.santander.de/oauthsos/password/authorize";
private static final String TOKEN_ENDPOINT = "https://api.santander.de/v1/oauth_matls/token";
private static final String CLIENT_ID = "PSDDE-BAFIN-123456";
private static final String REDIRECT_URI = "https://tpp-redirect.com/cb";
private static final String STATE = "S8NJ7uqk5fY4EjNvP_G_FtyJu6pUsvH9jsYni9dMAJw";
private static final String PAYMENT_ID = "6ee7548f-3fd7-45c1-a6e8-a378e31d8726";
private static final String CONSENT_ID = "consent_id";
private static final String AUTHORIZATION_CODE = "authorization_code";
private static final String REFRESH_TOKEN = "refresh_token";
private SantanderOauth2Service oauth2Service;
private final HttpClient httpClient = spy(new ApacheHttpClient(null, null));
private final HttpClientFactory httpClientFactory = mock(HttpClientFactory.class);
private final HttpClientConfig httpClientConfig = mock(HttpClientConfig.class);
private final Pkcs12KeyStore keyStore = mock(Pkcs12KeyStore.class);
private final Aspsp aspsp = getAspsp();
private Aspsp getAspsp() {
Aspsp aspsp = new Aspsp();
aspsp.setUrl("https://api.santander.de");
return aspsp;
}
@BeforeEach
void setUp() throws Exception {
doReturn(authorizationServerMetadata())
.when(httpClient).send(argThat(req -> req.uri().equals(SCA_OAUTH_LINK)), any());
doReturn(new Response<>(200, null, null))
.when(httpClient).send(argThat(req -> req.uri().equals(TOKEN_ENDPOINT)), any());
when(keyStore.getOrganizationIdentifier(any()))
.thenReturn(CLIENT_ID);
when(httpClientFactory.getHttpClient(any(), any())).thenReturn(httpClient);
when(httpClientFactory.getHttpClientConfig()).thenReturn(httpClientConfig);
when(httpClientConfig.getKeyStore()).thenReturn(keyStore);
oauth2Service = SantanderOauth2Service.create(aspsp, httpClientFactory);
}
private Response<AuthorisationServerMetaData> authorizationServerMetadata() {
AuthorisationServerMetaData metadata = new AuthorisationServerMetaData();
metadata.setAuthorisationEndpoint(AUTHORIZATION_ENDPOINT);
metadata.setTokenEndpoint(TOKEN_ENDPOINT);
return new Response<>(200, metadata, ResponseHeaders.emptyResponseHeaders());
}
@Test
void validateGetAuthorizationRequestUri() {
List<ValidationError> validationErrors =
oauth2Service.validateGetAuthorizationRequestUri(Collections.emptyMap(), new Parameters());
assertThat(validationErrors).containsExactly(ValidationError.required(Parameters.SCA_OAUTH_LINK),
ValidationError.required(Parameters.CONSENT_ID + " or " + Parameters.PAYMENT_ID));
}
@Test
void getAuthorizationRequestUriForPayment() throws Exception {
Parameters parameters = new Parameters();
parameters.setScaOAuthLink(SCA_OAUTH_LINK);
parameters.setRedirectUri(REDIRECT_URI);
parameters.setState(STATE);
parameters.setPaymentId(PAYMENT_ID);
URI authorizationRequestUri = oauth2Service.getAuthorizationRequestUri(null, parameters);
assertThat(authorizationRequestUri)
.hasToString("https://api.santander.de/oauthsos/password/authorize?" +
"response_type=code" +
"&state=" + STATE +
"&redirect_uri=" + URLEncoder.encode(REDIRECT_URI, StandardCharsets.UTF_8.name()) +
"&code_challenge_method=S256" +
"&code_challenge=" + oauth2Service.codeChallenge() +
"&client_id=" + CLIENT_ID +
"&scope=PIS%3A" + PAYMENT_ID);
}
@Test
void getAuthorizationRequestUriForConsent() throws Exception {
Parameters parameters = new Parameters();
parameters.setScaOAuthLink(SCA_OAUTH_LINK);
parameters.setRedirectUri(REDIRECT_URI);
parameters.setState(STATE);
parameters.setConsentId(CONSENT_ID);
URI authorizationRequestUri = oauth2Service.getAuthorizationRequestUri(null, parameters);
assertThat(authorizationRequestUri)
.hasToString("https://api.santander.de/oauthsos/password/authorize?" +
"response_type=code" +
"&state=" + STATE +
"&redirect_uri=" + URLEncoder.encode(REDIRECT_URI, StandardCharsets.UTF_8.name()) +
"&code_challenge_method=S256" +
"&code_challenge=" + oauth2Service.codeChallenge() +
"&client_id=" + CLIENT_ID +
"&scope=AIS%3A" + CONSENT_ID);
}
@Test
void getToken() throws Exception {
Parameters parameters = new Parameters();
parameters.setGrantType(Oauth2Service.GrantType.AUTHORIZATION_CODE.toString());
parameters.setAuthorizationCode(AUTHORIZATION_CODE);
parameters.setRedirectUri(REDIRECT_URI);
oauth2Service.getToken(null, parameters);
Map<String, String> expectedBody = new HashMap<>();
expectedBody.put(Parameters.GRANT_TYPE, Oauth2Service.GrantType.AUTHORIZATION_CODE.toString());
expectedBody.put(Parameters.CODE, AUTHORIZATION_CODE);
expectedBody.put(Parameters.CLIENT_ID, CLIENT_ID);
expectedBody.put(Parameters.CODE_VERIFIER, oauth2Service.codeVerifier());
expectedBody.put(Parameters.REDIRECT_URI, REDIRECT_URI);
Mockito.verify(httpClient, Mockito.times(1)).send(argThat(req -> {
boolean tokenExchange = req.uri().equals(TOKEN_ENDPOINT);
if (tokenExchange) {
assertEquals(expectedBody, req.urlEncodedBody());
}
return tokenExchange;
}), any());
}
@Test
void getTokenRefresh() throws Exception {
Parameters parameters = new Parameters();
parameters.setGrantType(Oauth2Service.GrantType.REFRESH_TOKEN.toString());
parameters.setRefreshToken(REFRESH_TOKEN);
oauth2Service.getToken(null, parameters);
Map<String, String> expectedBody = new HashMap<>();
expectedBody.put(Parameters.GRANT_TYPE, Oauth2Service.GrantType.REFRESH_TOKEN.toString());
expectedBody.put(Parameters.REFRESH_TOKEN, REFRESH_TOKEN);
expectedBody.put(Parameters.CLIENT_ID, CLIENT_ID);
Mockito.verify(httpClient, Mockito.times(1)).send(argThat(req -> {
boolean tokenExchange = req.uri().equals(TOKEN_ENDPOINT);
if (tokenExchange) {
assertEquals(expectedBody, req.urlEncodedBody());
}
return tokenExchange;
}), any());
}
}
| 8,950 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderCertificateSubjectClientIdOauth2ServiceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/test/java/de/adorsys/xs2a/adapter/santander/SantanderCertificateSubjectClientIdOauth2ServiceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.Oauth2Service;
import de.adorsys.xs2a.adapter.api.Pkcs12KeyStore;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.net.URI;
import java.security.KeyStoreException;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class SantanderCertificateSubjectClientIdOauth2ServiceTest {
private static final String BOGUS_URI = "http://foo.boo";
private static final String CLIENT_ID = "PSDDE-BAFIN-123456";
@InjectMocks
SantanderCertificateSubjectClientIdOauth2Service clientIdOauth2Service;
@Mock
Oauth2Service oauth2Service;
@Mock
Pkcs12KeyStore keyStore;
@BeforeEach
void setUp() throws KeyStoreException {
when(keyStore.getOrganizationIdentifier(any())).thenReturn(CLIENT_ID);
}
@Test
void getAuthorizationRequestUri() throws IOException, KeyStoreException {
when(oauth2Service.getAuthorizationRequestUri(anyMap(), any()))
.thenReturn(URI.create(BOGUS_URI));
URI actualUri = clientIdOauth2Service.getAuthorizationRequestUri(Map.of(), new Oauth2Service.Parameters());
verify(oauth2Service, times(1)).getAuthorizationRequestUri(anyMap(), any());
verify(keyStore, times(1)).getQsealCertificate(any());
assertThat(actualUri)
.isEqualTo(URI.create(BOGUS_URI + "?client_id=" + CLIENT_ID));
}
@Test
void getToken() throws IOException, KeyStoreException {
ArgumentCaptor<Oauth2Service.Parameters> paramsCaptor = ArgumentCaptor.forClass(Oauth2Service.Parameters.class);
clientIdOauth2Service.getToken(Map.of(), new Oauth2Service.Parameters());
verify(oauth2Service, times(1)).getToken(anyMap(), paramsCaptor.capture());
verify(keyStore, times(1)).getQsealCertificate(any());
verify(keyStore, times(1)).getOrganizationIdentifier(any());
Oauth2Service.Parameters actualParams = paramsCaptor.getValue();
assertThat(actualParams)
.isNotNull()
.extracting(Oauth2Service.Parameters::getClientId)
.isEqualTo(CLIENT_ID);
}
}
| 3,418 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderCertificateSubjectClientIdOauth2Service.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/SantanderCertificateSubjectClientIdOauth2Service.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.Oauth2Service;
import de.adorsys.xs2a.adapter.api.Pkcs12KeyStore;
import de.adorsys.xs2a.adapter.api.exception.Xs2aAdapterException;
import de.adorsys.xs2a.adapter.api.model.TokenResponse;
import de.adorsys.xs2a.adapter.impl.http.UriBuilder;
import java.io.IOException;
import java.net.URI;
import java.security.KeyStoreException;
import java.util.Map;
public class SantanderCertificateSubjectClientIdOauth2Service implements Oauth2Service {
private final Oauth2Service oauth2Service;
private final Pkcs12KeyStore keyStore;
public SantanderCertificateSubjectClientIdOauth2Service(Oauth2Service oauth2Service, Pkcs12KeyStore keyStore) {
this.oauth2Service = oauth2Service;
this.keyStore = keyStore;
}
@Override
public URI getAuthorizationRequestUri(Map<String, String> headers, Parameters parameters) throws IOException {
return UriBuilder.fromUri(oauth2Service.getAuthorizationRequestUri(headers, parameters))
.queryParam(Parameters.CLIENT_ID, clientId(parameters))
.build();
}
private String clientId(Parameters parameters) {
String clientId = parameters.getClientId();
if (clientId != null) {
return clientId;
}
try {
String certificateAlias = SantanderCertificateAliasResolver.getCertificateAlias(keyStore);
return keyStore.getOrganizationIdentifier(certificateAlias);
} catch (KeyStoreException e) {
throw new Xs2aAdapterException(e);
}
}
@Override
public TokenResponse getToken(Map<String, String> headers, Parameters parameters) throws IOException {
parameters.setClientId(clientId(parameters));
return oauth2Service.getToken(headers, parameters);
}
}
| 2,682 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderServiceProvider.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/SantanderServiceProvider.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.AccountInformationService;
import de.adorsys.xs2a.adapter.api.Oauth2ServiceProvider;
import de.adorsys.xs2a.adapter.api.PaymentInitiationService;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.impl.AbstractAdapterServiceProvider;
public class SantanderServiceProvider extends AbstractAdapterServiceProvider implements Oauth2ServiceProvider {
@Override
public AccountInformationService getAccountInformationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter) {
return new SantanderAccountInformationService(aspsp,
getOauth2Service(aspsp, httpClientFactory),
httpClientFactory,
linksRewriter);
}
@Override
public PaymentInitiationService getPaymentInitiationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter) {
return new SantanderPaymentInitiationService(aspsp,
httpClientFactory,
linksRewriter,
getOauth2Service(aspsp, httpClientFactory));
}
@Override
public String getAdapterId() {
return "santander-adapter";
}
@Override
public SantanderOauth2Service getOauth2Service(Aspsp aspsp, HttpClientFactory httpClientFactory) {
return SantanderOauth2Service.create(aspsp, httpClientFactory);
}
}
| 2,633 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderHttpClientFactory.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/SantanderHttpClientFactory.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.Pkcs12KeyStore;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
public class SantanderHttpClientFactory {
private SantanderHttpClientFactory() {
}
public static HttpClient getHttpClient(String adapterId, HttpClientFactory httpClientFactory) {
HttpClientConfig config = httpClientFactory.getHttpClientConfig();
Pkcs12KeyStore keyStore = config.getKeyStore();
String qwacAlias = SantanderCertificateAliasResolver.getCertificateAlias(keyStore); // null allowed, will load default certificate
return httpClientFactory.getHttpClient(adapterId, qwacAlias);
}
}
| 1,637 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderPaymentInitiationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/SantanderPaymentInitiationService.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.api.validation.ValidationError;
import de.adorsys.xs2a.adapter.impl.BasePaymentInitiationService;
import java.util.List;
import java.util.Map;
public class SantanderPaymentInitiationService extends BasePaymentInitiationService {
private final SantanderOauth2Service oauth2Service;
private final SantanderRequestHandler requestHandler = new SantanderRequestHandler();
public SantanderPaymentInitiationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter,
SantanderOauth2Service oauth2Service) {
super(aspsp,
SantanderHttpClientFactory.getHttpClient(aspsp.getAdapterId(), httpClientFactory),
linksRewriter,
httpClientFactory.getHttpClientConfig().getLogSanitizer());
this.oauth2Service = oauth2Service;
}
@Override
public Response<PaymentInitationRequestResponse201> initiatePayment(PaymentService paymentService,
PaymentProduct paymentProduct,
RequestHeaders requestHeaders,
RequestParams requestParams,
Object body) {
Map<String, String> updatedHeaders = addBearerHeader(requestHeaders.toMap());
return super.initiatePayment(paymentService, paymentProduct, RequestHeaders.fromMap(updatedHeaders), requestParams, body);
}
@Override
public Response<PaymentInitiationStatusResponse200Json> getPaymentInitiationStatus(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requestHandler.validateRequest(requestHeaders);
return super.getPaymentInitiationStatus(paymentService, paymentProduct, paymentId, requestHeaders, requestParams);
}
@Override
public List<ValidationError> validateGetPaymentInitiationStatus(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
Map<String, String> headers = requestHeaders.toMap();
if (!headers.containsKey(RequestHeaders.PSU_IP_ADDRESS)) {
return List.of(ValidationError.required(RequestHeaders.PSU_IP_ADDRESS));
}
return List.of();
}
@Override
public Response<PaymentInitiationWithStatusResponse> getSinglePaymentInformation(PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requestHandler.validateRequest(requestHeaders);
return super.getSinglePaymentInformation(paymentProduct, paymentId, requestHeaders, requestParams);
}
@Override
public Response<PeriodicPaymentInitiationWithStatusResponse> getPeriodicPaymentInformation(PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requestHandler.validateRequest(requestHeaders);
return super.getPeriodicPaymentInformation(paymentProduct, paymentId, requestHeaders, requestParams);
}
@Override
public Response<Authorisations> getPaymentInitiationAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
throw new UnsupportedOperationException();
}
@Override
public Response<StartScaprocessResponse> startPaymentAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
throw new UnsupportedOperationException();
}
@Override
public Response<StartScaprocessResponse> startPaymentAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
throw new UnsupportedOperationException();
}
@Override
public Response<UpdatePsuAuthenticationResponse> updatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
throw new UnsupportedOperationException();
}
@Override
public Response<SelectPsuAuthenticationMethodResponse> updatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
SelectPsuAuthenticationMethod selectPsuAuthenticationMethod) {
throw new UnsupportedOperationException();
}
@Override
public Response<ScaStatusResponse> updatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
TransactionAuthorisation transactionAuthorisation) {
throw new UnsupportedOperationException();
}
@Override
public Response<ScaStatusResponse> getPaymentInitiationScaStatus(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
throw new UnsupportedOperationException();
}
private Map<String, String> addBearerHeader(Map<String, String> headers) {
headers.put("Authorization", "Bearer " + oauth2Service.getClientCredentialsAccessToken());
return headers;
}
}
| 10,796 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderAccountInformationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/SantanderAccountInformationService.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.impl.BaseAccountInformationService;
import de.adorsys.xs2a.adapter.santander.model.SantanderTransactionResponse200Json;
import org.mapstruct.factory.Mappers;
import java.util.Map;
public class SantanderAccountInformationService extends BaseAccountInformationService {
private final SantanderMapper santanderMapper = Mappers.getMapper(SantanderMapper.class);
private final SantanderOauth2Service oauth2Service;
private final SantanderRequestHandler requestHandler = new SantanderRequestHandler();
public SantanderAccountInformationService(Aspsp aspsp,
SantanderOauth2Service oauth2Service,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter) {
super(aspsp,
SantanderHttpClientFactory.getHttpClient(aspsp.getAdapterId(), httpClientFactory),
linksRewriter,
httpClientFactory.getHttpClientConfig().getLogSanitizer());
this.oauth2Service = oauth2Service;
}
@Override
public Response<ConsentsResponse201> createConsent(RequestHeaders requestHeaders,
RequestParams requestParams,
Consents body) {
Map<String, String> updatedHeaders = addBearerHeader(requestHeaders.toMap());
return super.createConsent(RequestHeaders.fromMap(updatedHeaders), requestParams, body);
}
@Override
public Response<StartScaprocessResponse> startConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
throw new UnsupportedOperationException();
}
@Override
public Response<StartScaprocessResponse> startConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
throw new UnsupportedOperationException();
}
@Override
public Response<UpdatePsuAuthenticationResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
throw new UnsupportedOperationException();
}
@Override
public Response<SelectPsuAuthenticationMethodResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
SelectPsuAuthenticationMethod selectPsuAuthenticationMethod) {
throw new UnsupportedOperationException();
}
@Override
public Response<ScaStatusResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
TransactionAuthorisation transactionAuthorisation) {
throw new UnsupportedOperationException();
}
@Override
public Response<ConsentInformationResponse200Json> getConsentInformation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requestHandler.validateRequest(requestHeaders);
return super.getConsentInformation(consentId, requestHeaders, requestParams);
}
@Override
public Response<ConsentStatusResponse200> getConsentStatus(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requestHandler.validateRequest(requestHeaders);
return super.getConsentStatus(consentId, requestHeaders, requestParams);
}
@Override
public Response<Void> deleteConsent(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requestHandler.validateRequest(requestHeaders);
return super.deleteConsent(consentId, requestHeaders, requestParams);
}
@Override
public Response<AccountList> getAccountList(RequestHeaders requestHeaders,
RequestParams requestParams) {
requestHandler.validateRequest(requestHeaders);
return super.getAccountList(requestHeaders, requestParams);
}
@Override
public Response<OK200AccountDetails> readAccountDetails(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requestHandler.validateRequest(requestHeaders);
return super.readAccountDetails(accountId, requestHeaders, requestParams);
}
@Override
public Response<ReadAccountBalanceResponse200> getBalances(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requestHandler.validateRequest(requestHeaders);
return super.getBalances(accountId, requestHeaders, requestParams);
}
@Override
public Response<TransactionsResponse200Json> getTransactionList(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requestHandler.validateRequest(requestHeaders);
return super.getTransactionList(accountId,
requestHeaders,
requestParams,
SantanderTransactionResponse200Json.class,
santanderMapper::toTransactionsResponse200Json);
}
@Override
public Response<OK200TransactionDetails> getTransactionDetails(String accountId,
String transactionId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
throw new UnsupportedOperationException();
}
@Override
public Response<Authorisations> getConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
throw new UnsupportedOperationException();
}
@Override
public Response<CardAccountList> getCardAccountList(RequestHeaders requestHeaders,
RequestParams requestParams) {
throw new UnsupportedOperationException();
}
@Override
public Response<OK200CardAccountDetails> getCardAccountDetails(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
throw new UnsupportedOperationException();
}
@Override
public Response<ReadCardAccountBalanceResponse200> getCardAccountBalances(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
throw new UnsupportedOperationException();
}
@Override
public Response<CardAccountsTransactionsResponse200> getCardAccountTransactionList(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
throw new UnsupportedOperationException();
}
@Override
public Response<ScaStatusResponse> getConsentScaStatus(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
throw new UnsupportedOperationException();
}
private Map<String, String> addBearerHeader(Map<String, String> headers) {
headers.put("Authorization", "Bearer " + oauth2Service.getClientCredentialsAccessToken());
return headers;
}
@Override
protected Map<String, String> resolvePsuIdHeader(Map<String, String> headers) {
headers.remove(RequestHeaders.PSU_ID); // will actually fail if PSU-ID is provided
return headers;
}
}
| 11,479 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderOauth2Service.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/SantanderOauth2Service.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.Oauth2Service;
import de.adorsys.xs2a.adapter.api.PkceOauth2Extension;
import de.adorsys.xs2a.adapter.api.Pkcs12KeyStore;
import de.adorsys.xs2a.adapter.api.config.AdapterConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.api.model.TokenResponse;
import de.adorsys.xs2a.adapter.api.validation.ValidationError;
import de.adorsys.xs2a.adapter.impl.BaseOauth2Service;
import de.adorsys.xs2a.adapter.impl.PkceOauth2Service;
import de.adorsys.xs2a.adapter.impl.http.ResponseHandlers;
import de.adorsys.xs2a.adapter.impl.http.UriBuilder;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static de.adorsys.xs2a.adapter.api.validation.Validation.requireValid;
class SantanderOauth2Service implements Oauth2Service, PkceOauth2Extension {
private static final String SANTANDER_TOKEN_URL_PROPERTY = "santander.token.url";
private static final String TOKEN_URL = AdapterConfig.readProperty(SANTANDER_TOKEN_URL_PROPERTY, "/v1/oauth_matls/token");
private static final String GRANT_TYPE_VALUE = "client_credentials";
private static String baseUrl;
private final Oauth2Service oauth2Service;
private static HttpClient httpClient;
private static ResponseHandlers responseHandlers;
SantanderOauth2Service(Oauth2Service oauth2Service) {
this.oauth2Service = oauth2Service;
}
public static SantanderOauth2Service create(Aspsp aspsp, HttpClientFactory httpClientFactory) {
baseUrl = aspsp.getUrl();
httpClient = SantanderHttpClientFactory.getHttpClient(aspsp.getAdapterId(), httpClientFactory);
HttpLogSanitizer logSanitizer = httpClientFactory.getHttpClientConfig().getLogSanitizer();
Pkcs12KeyStore keyStore = httpClientFactory.getHttpClientConfig().getKeyStore();
responseHandlers = new ResponseHandlers(logSanitizer);
return new SantanderOauth2Service(
new SantanderCertificateSubjectClientIdOauth2Service(
new PkceOauth2Service(new BaseOauth2Service(aspsp, httpClient, logSanitizer)),
keyStore));
}
@Override
public URI getAuthorizationRequestUri(Map<String, String> headers, Parameters parameters) throws IOException {
requireValid(validateGetAuthorizationRequestUri(headers, parameters));
fixScaOAuthLink(parameters);
return UriBuilder.fromUri(oauth2Service.getAuthorizationRequestUri(headers, parameters))
.queryParam("scope", scope(parameters))
.build();
}
private void fixScaOAuthLink(Parameters parameters) {
String scaOAuthLink = parameters.getScaOAuthLink();
scaOAuthLink = scaOAuthLink.toLowerCase();
if (scaOAuthLink.startsWith("https://")) {
return; // link in an expected format
}
parameters.setScaOAuthLink(baseUrl + scaOAuthLink);
}
private String scope(Parameters parameters) {
if (parameters.getPaymentId() != null) {
return "PIS:" + parameters.getPaymentId();
}
if (parameters.getConsentId() != null) {
return "AIS:" + parameters.getConsentId();
}
throw new IllegalStateException(); // request validation doesn't permit this case to occur
}
@Override
public List<ValidationError> validateGetAuthorizationRequestUri(Map<String, String> headers, Parameters parameters) {
List<ValidationError> validationErrors = new ArrayList<>();
if (parameters.getScaOAuthLink() == null) {
validationErrors.add(ValidationError.required(Parameters.SCA_OAUTH_LINK));
}
if (parameters.getPaymentId() == null && parameters.getConsentId() == null) {
validationErrors.add(ValidationError.required(Parameters.CONSENT_ID + " or " + Parameters.PAYMENT_ID));
}
return validationErrors;
}
@Override
public TokenResponse getToken(Map<String, String> headers, Parameters parameters) throws IOException {
parameters.setTokenEndpoint(baseUrl + TOKEN_URL);
return oauth2Service.getToken(headers, parameters);
}
public String getClientCredentialsAccessToken() {
return httpClient.post(baseUrl + TOKEN_URL)
.urlEncodedBody(Map.of(Parameters.GRANT_TYPE, GRANT_TYPE_VALUE))
.send(responseHandlers.jsonResponseHandler(TokenResponse.class))
.getBody()
.getAccessToken();
}
}
| 5,562 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderCertificateAliasResolver.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/SantanderCertificateAliasResolver.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.Pkcs12KeyStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.KeyStoreException;
import java.security.cert.X509Certificate;
public class SantanderCertificateAliasResolver {
private static final Logger logger = LoggerFactory.getLogger(SantanderCertificateAliasResolver.class);
private static final String SANTANDER_QWAC_ALIAS = "santander_qwac";
private SantanderCertificateAliasResolver() { }
// For Sandbox environment, Adapter will try to get Santander certificates.
public static String getCertificateAlias(Pkcs12KeyStore keyStore) {
try {
X509Certificate certificate = keyStore.getQsealCertificate(SANTANDER_QWAC_ALIAS); // works for QWAC
if (certificate != null) {
logger.info("Santander Sandbox certificate will be used");
return SANTANDER_QWAC_ALIAS;
}
} catch (KeyStoreException e) {
logger.error("Failed to get a certificate from the KeyStore", e);
}
// Indicating using default certificate
logger.info("Using default QWAC certificate");
return null;
}
}
| 2,064 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderRequestHandler.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/SantanderRequestHandler.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.exception.RequestAuthorizationValidationException;
import de.adorsys.xs2a.adapter.api.model.ErrorResponse;
import de.adorsys.xs2a.adapter.api.model.MessageCode;
import de.adorsys.xs2a.adapter.api.model.TppMessage;
import de.adorsys.xs2a.adapter.api.model.TppMessageCategory;
import java.util.Map;
import static java.util.Collections.singletonList;
public class SantanderRequestHandler {
public static final String REQUEST_ERROR_MESSAGE = "AUTHORIZATION header is missing";
public void validateRequest(RequestHeaders requestHeaders) {
Map<String, String> headers = requestHeaders.toMap();
if (!headers.containsKey(RequestHeaders.AUTHORIZATION)) {
throw new RequestAuthorizationValidationException(
getErrorResponse(),
REQUEST_ERROR_MESSAGE);
}
}
private static ErrorResponse getErrorResponse() {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setTppMessages(singletonList(getTppMessage()));
return errorResponse;
}
private static TppMessage getTppMessage() {
TppMessage tppMessage = new TppMessage();
tppMessage.setCategory(TppMessageCategory.ERROR);
tppMessage.setCode(MessageCode.TOKEN_UNKNOWN.toString());
tppMessage.setText(REQUEST_ERROR_MESSAGE);
return tppMessage;
}
}
| 2,318 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderMapper.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/SantanderMapper.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander;
import de.adorsys.xs2a.adapter.api.model.RemittanceInformationStructured;
import de.adorsys.xs2a.adapter.api.model.Transactions;
import de.adorsys.xs2a.adapter.api.model.TransactionsResponse200Json;
import de.adorsys.xs2a.adapter.santander.model.SantanderTransactionDetails;
import de.adorsys.xs2a.adapter.santander.model.SantanderTransactionResponse200Json;
import org.mapstruct.Mapper;
@Mapper
public interface SantanderMapper {
TransactionsResponse200Json toTransactionsResponse200Json(SantanderTransactionResponse200Json value);
Transactions toTransactions(SantanderTransactionDetails value);
default String map(RemittanceInformationStructured value) {
return value == null ? null : value.getReference();
}
}
| 1,613 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderTransactionResponse200Json.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/model/SantanderTransactionResponse200Json.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.adorsys.xs2a.adapter.api.model.AccountReference;
import de.adorsys.xs2a.adapter.api.model.Balance;
import de.adorsys.xs2a.adapter.api.model.HrefType;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class SantanderTransactionResponse200Json {
private AccountReference account;
private SantanderAccountReport transactions;
private List<Balance> balances;
@JsonProperty("_links")
private Map<String, HrefType> links;
public AccountReference getAccount() {
return account;
}
public void setAccount(AccountReference account) {
this.account = account;
}
public SantanderAccountReport getTransactions() {
return transactions;
}
public void setTransactions(SantanderAccountReport transactions) {
this.transactions = transactions;
}
public List<Balance> getBalances() {
return balances;
}
public void setBalances(List<Balance> balances) {
this.balances = balances;
}
public Map<String, HrefType> getLinks() {
return links;
}
public void setLinks(Map<String, HrefType> links) {
this.links = links;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SantanderTransactionResponse200Json that = (SantanderTransactionResponse200Json) o;
return Objects.equals(account, that.account) &&
Objects.equals(transactions, that.transactions) &&
Objects.equals(balances, that.balances) &&
Objects.equals(links, that.links);
}
@Override
public int hashCode() {
return Objects.hash(account,
transactions,
balances,
links);
}
}
| 2,754 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderTransactionDetails.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/model/SantanderTransactionDetails.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.adorsys.xs2a.adapter.api.model.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class SantanderTransactionDetails {
private String transactionId;
private String entryReference;
private String endToEndId;
private String mandateId;
private String checkId;
private String creditorId;
private LocalDate bookingDate;
private LocalDate valueDate;
private Amount transactionAmount;
private List<ReportExchangeRate> currencyExchange;
private String creditorName;
private AccountReference creditorAccount;
private String creditorAgent;
private String ultimateCreditor;
private String debtorName;
private AccountReference debtorAccount;
private String debtorAgent;
private String ultimateDebtor;
private String remittanceInformationUnstructured;
private List<String> remittanceInformationUnstructuredArray;
private RemittanceInformationStructured remittanceInformationStructured;
private List<RemittanceInformationStructured> remittanceInformationStructuredArray;
private String additionalInformation;
private AdditionalInformationStructured additionalInformationStructured;
private PurposeCode purposeCode;
private String bankTransactionCode;
private String proprietaryBankTransactionCode;
private Balance balanceAfterTransaction;
@JsonProperty("_links")
private Map<String, HrefType> links;
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getEntryReference() {
return entryReference;
}
public void setEntryReference(String entryReference) {
this.entryReference = entryReference;
}
public String getEndToEndId() {
return endToEndId;
}
public void setEndToEndId(String endToEndId) {
this.endToEndId = endToEndId;
}
public String getMandateId() {
return mandateId;
}
public void setMandateId(String mandateId) {
this.mandateId = mandateId;
}
public String getCheckId() {
return checkId;
}
public void setCheckId(String checkId) {
this.checkId = checkId;
}
public String getCreditorId() {
return creditorId;
}
public void setCreditorId(String creditorId) {
this.creditorId = creditorId;
}
public LocalDate getBookingDate() {
return bookingDate;
}
public void setBookingDate(LocalDate bookingDate) {
this.bookingDate = bookingDate;
}
public LocalDate getValueDate() {
return valueDate;
}
public void setValueDate(LocalDate valueDate) {
this.valueDate = valueDate;
}
public Amount getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(Amount transactionAmount) {
this.transactionAmount = transactionAmount;
}
public List<ReportExchangeRate> getCurrencyExchange() {
return currencyExchange;
}
public void setCurrencyExchange(List<ReportExchangeRate> currencyExchange) {
this.currencyExchange = currencyExchange;
}
public String getCreditorName() {
return creditorName;
}
public void setCreditorName(String creditorName) {
this.creditorName = creditorName;
}
public AccountReference getCreditorAccount() {
return creditorAccount;
}
public void setCreditorAccount(AccountReference creditorAccount) {
this.creditorAccount = creditorAccount;
}
public String getCreditorAgent() {
return creditorAgent;
}
public void setCreditorAgent(String creditorAgent) {
this.creditorAgent = creditorAgent;
}
public String getUltimateCreditor() {
return ultimateCreditor;
}
public void setUltimateCreditor(String ultimateCreditor) {
this.ultimateCreditor = ultimateCreditor;
}
public String getDebtorName() {
return debtorName;
}
public void setDebtorName(String debtorName) {
this.debtorName = debtorName;
}
public AccountReference getDebtorAccount() {
return debtorAccount;
}
public void setDebtorAccount(AccountReference debtorAccount) {
this.debtorAccount = debtorAccount;
}
public String getDebtorAgent() {
return debtorAgent;
}
public void setDebtorAgent(String debtorAgent) {
this.debtorAgent = debtorAgent;
}
public String getUltimateDebtor() {
return ultimateDebtor;
}
public void setUltimateDebtor(String ultimateDebtor) {
this.ultimateDebtor = ultimateDebtor;
}
public String getRemittanceInformationUnstructured() {
return remittanceInformationUnstructured;
}
public void setRemittanceInformationUnstructured(String remittanceInformationUnstructured) {
this.remittanceInformationUnstructured = remittanceInformationUnstructured;
}
public List<String> getRemittanceInformationUnstructuredArray() {
return remittanceInformationUnstructuredArray;
}
public void setRemittanceInformationUnstructuredArray(
List<String> remittanceInformationUnstructuredArray) {
this.remittanceInformationUnstructuredArray = remittanceInformationUnstructuredArray;
}
public RemittanceInformationStructured getRemittanceInformationStructured() {
return remittanceInformationStructured;
}
public void setRemittanceInformationStructured(RemittanceInformationStructured remittanceInformationStructured) {
this.remittanceInformationStructured = remittanceInformationStructured;
}
public List<RemittanceInformationStructured> getRemittanceInformationStructuredArray() {
return remittanceInformationStructuredArray;
}
public void setRemittanceInformationStructuredArray(
List<RemittanceInformationStructured> remittanceInformationStructuredArray) {
this.remittanceInformationStructuredArray = remittanceInformationStructuredArray;
}
public String getAdditionalInformation() {
return additionalInformation;
}
public void setAdditionalInformation(String additionalInformation) {
this.additionalInformation = additionalInformation;
}
public AdditionalInformationStructured getAdditionalInformationStructured() {
return additionalInformationStructured;
}
public void setAdditionalInformationStructured(
AdditionalInformationStructured additionalInformationStructured) {
this.additionalInformationStructured = additionalInformationStructured;
}
public PurposeCode getPurposeCode() {
return purposeCode;
}
public void setPurposeCode(PurposeCode purposeCode) {
this.purposeCode = purposeCode;
}
public String getBankTransactionCode() {
return bankTransactionCode;
}
public void setBankTransactionCode(String bankTransactionCode) {
this.bankTransactionCode = bankTransactionCode;
}
public String getProprietaryBankTransactionCode() {
return proprietaryBankTransactionCode;
}
public void setProprietaryBankTransactionCode(String proprietaryBankTransactionCode) {
this.proprietaryBankTransactionCode = proprietaryBankTransactionCode;
}
public Balance getBalanceAfterTransaction() {
return balanceAfterTransaction;
}
public void setBalanceAfterTransaction(Balance balanceAfterTransaction) {
this.balanceAfterTransaction = balanceAfterTransaction;
}
public Map<String, HrefType> getLinks() {
return links;
}
public void setLinks(Map<String, HrefType> links) {
this.links = links;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SantanderTransactionDetails that = (SantanderTransactionDetails) o;
return Objects.equals(transactionId, that.transactionId) &&
Objects.equals(entryReference, that.entryReference) &&
Objects.equals(endToEndId, that.endToEndId) &&
Objects.equals(mandateId, that.mandateId) &&
Objects.equals(checkId, that.checkId) &&
Objects.equals(creditorId, that.creditorId) &&
Objects.equals(bookingDate, that.bookingDate) &&
Objects.equals(valueDate, that.valueDate) &&
Objects.equals(transactionAmount, that.transactionAmount) &&
Objects.equals(currencyExchange, that.currencyExchange) &&
Objects.equals(creditorName, that.creditorName) &&
Objects.equals(creditorAccount, that.creditorAccount) &&
Objects.equals(creditorAgent, that.creditorAgent) &&
Objects.equals(ultimateCreditor, that.ultimateCreditor) &&
Objects.equals(debtorName, that.debtorName) &&
Objects.equals(debtorAccount, that.debtorAccount) &&
Objects.equals(debtorAgent, that.debtorAgent) &&
Objects.equals(ultimateDebtor, that.ultimateDebtor) &&
Objects.equals(remittanceInformationUnstructured, that.remittanceInformationUnstructured) &&
Objects.equals(remittanceInformationUnstructuredArray, that.remittanceInformationUnstructuredArray) &&
Objects.equals(remittanceInformationStructured, that.remittanceInformationStructured) &&
Objects.equals(remittanceInformationStructuredArray, that.remittanceInformationStructuredArray) &&
Objects.equals(additionalInformation, that.additionalInformation) &&
Objects.equals(additionalInformationStructured, that.additionalInformationStructured) &&
Objects.equals(purposeCode, that.purposeCode) &&
Objects.equals(bankTransactionCode, that.bankTransactionCode) &&
Objects.equals(proprietaryBankTransactionCode, that.proprietaryBankTransactionCode) &&
Objects.equals(balanceAfterTransaction, that.balanceAfterTransaction) &&
Objects.equals(links, that.links);
}
@Override
public int hashCode() {
return Objects.hash(transactionId,
entryReference,
endToEndId,
mandateId,
checkId,
creditorId,
bookingDate,
valueDate,
transactionAmount,
currencyExchange,
creditorName,
creditorAccount,
creditorAgent,
ultimateCreditor,
debtorName,
debtorAccount,
debtorAgent,
ultimateDebtor,
remittanceInformationUnstructured,
remittanceInformationUnstructuredArray,
remittanceInformationStructured,
remittanceInformationStructuredArray,
additionalInformation,
additionalInformationStructured,
purposeCode,
bankTransactionCode,
proprietaryBankTransactionCode,
balanceAfterTransaction,
links);
}
}
| 12,140 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SantanderAccountReport.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/santander-adapter/src/main/java/de/adorsys/xs2a/adapter/santander/model/SantanderAccountReport.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.santander.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.adorsys.xs2a.adapter.api.model.HrefType;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class SantanderAccountReport {
private List<SantanderTransactionDetails> booked;
private List<SantanderTransactionDetails> pending;
@JsonProperty("_links")
private Map<String, HrefType> links;
public List<SantanderTransactionDetails> getBooked() {
return booked;
}
public void setBooked(List<SantanderTransactionDetails> booked) {
this.booked = booked;
}
public List<SantanderTransactionDetails> getPending() {
return pending;
}
public void setPending(List<SantanderTransactionDetails> pending) {
this.pending = pending;
}
public Map<String, HrefType> getLinks() {
return links;
}
public void setLinks(Map<String, HrefType> links) {
this.links = links;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SantanderAccountReport that = (SantanderAccountReport) o;
return Objects.equals(booked, that.booked) &&
Objects.equals(pending, that.pending) &&
Objects.equals(links, that.links);
}
@Override
public int hashCode() {
return Objects.hash(booked,
pending,
links);
}
}
| 2,348 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ConsorsPaymentInitiationServiceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/consors-bank-adapter/src/test/java/de/adorsys/xs2a/adapter/consors/ConsorsPaymentInitiationServiceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.consors;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.http.Request;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.impl.http.RequestBuilderImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.HashMap;
import java.util.Map;
import static de.adorsys.xs2a.adapter.api.RequestHeaders.PSU_ID;
import static de.adorsys.xs2a.adapter.api.model.PaymentProduct.SEPA_CREDIT_TRANSFERS;
import static de.adorsys.xs2a.adapter.api.model.PaymentService.PAYMENTS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class ConsorsPaymentInitiationServiceTest {
private ConsorsPaymentInitiationService service;
@Mock
private HttpClient client;
@Mock
private HttpClientFactory httpClientFactory;
@Mock
private HttpClientConfig httpClientConfig;
@Mock
private LinksRewriter rewriter;
@Spy
private final Aspsp aspsp = buildAspsp();
@Captor
private ArgumentCaptor<Request.Builder> builderCaptor;
@BeforeEach
void setUp() {
when(httpClientFactory.getHttpClient(any())).thenReturn(client);
when(httpClientFactory.getHttpClientConfig()).thenReturn(httpClientConfig);
service = new ConsorsPaymentInitiationService(aspsp, httpClientFactory, rewriter);
}
@Test
void initiatePayment_noPsuId() {
when(client.post(any())).thenReturn(new RequestBuilderImpl(client, null, null));
when(client.send(any(), any()))
.thenReturn(new Response<>(-1,
new PaymentInitationRequestResponse201(),
ResponseHeaders.emptyResponseHeaders()));
service.initiatePayment(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
RequestHeaders.empty(),
RequestParams.empty(),
new PaymentInitiationJson());
verify(client, times(1)).send(builderCaptor.capture(), any());
Map<String, String> actualHeaders = builderCaptor.getValue().headers();
assertThat(actualHeaders)
.isEmpty();
}
@Test
void initiatePayment_psuIdAvailable() {
Map<String, String> headers = new HashMap<>();
headers.put(PSU_ID, "foo");
when(client.post(any())).thenReturn(new RequestBuilderImpl(client, null, null));
when(client.send(any(), any()))
.thenReturn(new Response<>(-1,
new PaymentInitationRequestResponse201(),
ResponseHeaders.emptyResponseHeaders()));
service.initiatePayment(PAYMENTS,
SEPA_CREDIT_TRANSFERS,
RequestHeaders.fromMap(headers),
RequestParams.empty(),
new PaymentInitiationJson());
verify(client, times(1)).send(builderCaptor.capture(), any());
Map<String, String> actualHeaders = builderCaptor.getValue().headers();
assertThat(actualHeaders)
.isEmpty();
}
private Aspsp buildAspsp() {
Aspsp aspsp = new Aspsp();
aspsp.setUrl("https://example.com");
return aspsp;
}
}
| 4,561 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ConsorsAccountInformationServiceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/consors-bank-adapter/src/test/java/de/adorsys/xs2a/adapter/consors/ConsorsAccountInformationServiceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.consors;
import de.adorsys.xs2a.adapter.api.*;
import de.adorsys.xs2a.adapter.api.http.*;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.impl.http.AbstractHttpClient;
import de.adorsys.xs2a.adapter.impl.http.RequestBuilderImpl;
import de.adorsys.xs2a.adapter.impl.link.identity.IdentityLinksRewriter;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;
import static de.adorsys.xs2a.adapter.api.RequestHeaders.PSU_ID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
class ConsorsAccountInformationServiceTest {
private final HttpClient httpClient = Mockito.spy(AbstractHttpClient.class);
private final HttpClientConfig httpClientConfig = Mockito.mock(HttpClientConfig.class);
private final AccountInformationService service = new ConsorsServiceProvider()
.getAccountInformationService(new Aspsp(), getHttpClientFactory(), new IdentityLinksRewriter());
private ArgumentCaptor<Request.Builder> builderCaptor;
private HttpClientFactory getHttpClientFactory() {
return new HttpClientFactory() {
@Override
public HttpClient getHttpClient(String adapterId, String qwacAlias, String[] supportedCipherSuites) {
return httpClient;
}
@Override
public HttpClientConfig getHttpClientConfig() {
return httpClientConfig;
}
};
}
@BeforeEach
void setUp() {
builderCaptor = ArgumentCaptor.forClass(Request.Builder.class);
}
@Test
void createConsent_noPsuId() {
Mockito.when(httpClient.send(Mockito.any(), Mockito.any()))
.thenReturn(new Response<>(-1, new ConsentsResponse201(), ResponseHeaders.emptyResponseHeaders()));
service.createConsent(RequestHeaders.empty(), RequestParams.empty(), new Consents());
Mockito.verify(httpClient, Mockito.times(1))
.send(builderCaptor.capture(), Mockito.any());
Map<String, String> actualHeaders = builderCaptor.getValue().headers();
assertThat(actualHeaders)
.isNotEmpty()
.containsEntry(PSU_ID, "");
}
@Test
void createConsent_blankPsuId() {
Map<String, String> headers = new HashMap<>();
headers.put(PSU_ID, " ");
Mockito.when(httpClient.send(Mockito.any(), Mockito.any()))
.thenReturn(new Response<>(-1, new ConsentsResponse201(), ResponseHeaders.emptyResponseHeaders()));
service.createConsent(RequestHeaders.fromMap(headers), RequestParams.empty(), new Consents());
Mockito.verify(httpClient, Mockito.times(1))
.send(builderCaptor.capture(), Mockito.any());
Map<String, String> actualHeaders = builderCaptor.getValue().headers();
assertThat(actualHeaders)
.isNotEmpty()
.containsEntry(PSU_ID, "");
}
@Test
void createConsent_notEmptyPsuId() {
Map<String, String> headers = new HashMap<>();
headers.put(PSU_ID, "foo");
Mockito.when(httpClient.send(Mockito.any(), Mockito.any()))
.thenReturn(new Response<>(-1, new ConsentsResponse201(), ResponseHeaders.emptyResponseHeaders()));
service.createConsent(RequestHeaders.fromMap(headers), RequestParams.empty(), new Consents());
Mockito.verify(httpClient, Mockito.times(1))
.send(builderCaptor.capture(), Mockito.any());
Map<String, String> actualHeaders = builderCaptor.getValue().headers();
assertThat(actualHeaders)
.isNotEmpty()
.containsEntry(PSU_ID, "");
}
@Test
void getTransactionSetsAcceptApplicationJson() {
Mockito.when(httpClient.send(Mockito.any(), Mockito.any()))
.thenReturn(new Response<>(200, new TransactionsResponse200Json(), ResponseHeaders.emptyResponseHeaders()));
service.getTransactionListAsString(null, RequestHeaders.empty(), RequestParams.empty());
Mockito.verify(httpClient, Mockito.times(1))
.send(builderCaptor.capture(), Mockito.any());
assertThat(builderCaptor.getValue().headers())
.containsEntry(RequestHeaders.ACCEPT, ContentType.APPLICATION_JSON);
}
@Test
void getTransactionDetails() {
String rawResponse = "{\n" +
" \"transactionsDetails\": {\n" +
" \"transactionId\": \"test\"\n" +
" }\n" +
"}";
when(httpClient.get(anyString()))
.thenReturn(new RequestBuilderImpl(httpClient, "GET", "https://uri.com"));
when(httpClient.send(any(), any()))
.thenAnswer(invocationOnMock -> {
HttpClient.ResponseHandler responseHandler = invocationOnMock.getArgument(1, HttpClient.ResponseHandler.class);
return new Response<>(-1,
responseHandler.apply(200,
new ByteArrayInputStream(rawResponse.getBytes()),
ResponseHeaders.emptyResponseHeaders()),
null);
});
Response<?> actualResponse
= service.getTransactionDetails("accountId", "transactionId", RequestHeaders.empty(), RequestParams.empty());
verify(httpClient, times(1)).get(anyString());
verify(httpClient, times(1)).send(any(), any());
assertThat(actualResponse)
.isNotNull()
.extracting(Response::getBody)
.asInstanceOf(InstanceOfAssertFactories.type(OK200TransactionDetails.class))
.matches(body ->
body.getTransactionsDetails()
.getTransactionId()
.equals("test"));
}
}
| 6,894 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PsuIdHeaderInterceptorTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/consors-bank-adapter/src/test/java/de/adorsys/xs2a/adapter/consors/PsuIdHeaderInterceptorTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.consors;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.http.Request;
import de.adorsys.xs2a.adapter.impl.http.RequestBuilderImpl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
class PsuIdHeaderInterceptorTest {
private static final String PSU_ID = "psu id";
private static final String QUOTES = "\"\"";
private static final String RANDOM_HEADER = "random header";
private PsuIdHeaderInterceptor interceptor;
private Request.Builder builder;
@BeforeEach
public void setUp() {
interceptor = new PsuIdHeaderInterceptor();
builder = new RequestBuilderImpl(null, null, null);
}
@Test
void apply_withValidPsuId() {
builder.header(RequestHeaders.PSU_ID, PSU_ID);
interceptor.preHandle(builder);
assertEquals(PSU_ID, builder.headers().get(RequestHeaders.PSU_ID));
}
@Test
void apply_psuIdQuotes() {
builder.header(RequestHeaders.PSU_ID, QUOTES);
interceptor.preHandle(builder);
assertNull(builder.headers().get(RequestHeaders.PSU_ID));
}
@Test
void apply_noPsuIdHeader() {
builder.header(RANDOM_HEADER, RANDOM_HEADER);
interceptor.preHandle(builder);
assertFalse(builder.headers().containsKey(RequestHeaders.PSU_ID));
assertEquals(builder.headers(), builder.headers());
}
}
| 2,459 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ConsorsServiceProviderTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/consors-bank-adapter/src/test/java/de/adorsys/xs2a/adapter/consors/ConsorsServiceProviderTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.consors;
import de.adorsys.xs2a.adapter.api.AccountInformationService;
import de.adorsys.xs2a.adapter.api.PaymentInitiationService;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ConsorsServiceProviderTest {
private ConsorsServiceProvider serviceProvider;
private final HttpClientConfig httpClientConfig = mock(HttpClientConfig.class);
private final HttpClientFactory httpClientFactory = mock(HttpClientFactory.class);
private final Aspsp aspsp = new Aspsp();
@BeforeEach
void setUp() {
serviceProvider = new ConsorsServiceProvider();
when(httpClientFactory.getHttpClientConfig()).thenReturn(httpClientConfig);
}
@Test
void getAccountInformationService() {
AccountInformationService actualService
= serviceProvider.getAccountInformationService(aspsp, httpClientFactory, null);
assertThat(actualService)
.isExactlyInstanceOf(ConsorsAccountInformationService.class);
}
@Test
void getPaymentInitiationService() {
PaymentInitiationService actualService
= serviceProvider.getPaymentInitiationService(aspsp, httpClientFactory, null);
assertThat(actualService)
.isExactlyInstanceOf(ConsorsPaymentInitiationService.class);
}
}
| 2,476 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PsuIdHeaderInterceptor.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/consors-bank-adapter/src/main/java/de/adorsys/xs2a/adapter/consors/PsuIdHeaderInterceptor.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.consors;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.http.Interceptor;
import de.adorsys.xs2a.adapter.api.http.Request;
public class PsuIdHeaderInterceptor implements Interceptor {
private static final String QUOTES = "\"\"";
@Override
public Request.Builder preHandle(Request.Builder builder) {
if (QUOTES.equals(builder.headers().get(RequestHeaders.PSU_ID))) {
builder.headers().replace(RequestHeaders.PSU_ID, null);
}
return builder;
}
}
| 1,400 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ConsorsServiceProvider.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/consors-bank-adapter/src/main/java/de/adorsys/xs2a/adapter/consors/ConsorsServiceProvider.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.consors;
import de.adorsys.xs2a.adapter.api.*;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.impl.AbstractAdapterServiceProvider;
public class ConsorsServiceProvider extends AbstractAdapterServiceProvider {
private final PsuIdHeaderInterceptor psuIdHeaderInterceptor = new PsuIdHeaderInterceptor();
@Override
public AccountInformationService getAccountInformationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter) {
return new ConsorsAccountInformationService(aspsp,
httpClientFactory,
getInterceptors(aspsp, psuIdHeaderInterceptor),
linksRewriter);
}
@Override
public PaymentInitiationService getPaymentInitiationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter) {
return new ConsorsPaymentInitiationService(aspsp,
httpClientFactory,
linksRewriter);
}
@Override
public String getAdapterId() {
return "consors-bank-adapter";
}
}
| 2,300 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ConsorsAccountInformationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/consors-bank-adapter/src/main/java/de/adorsys/xs2a/adapter/consors/ConsorsAccountInformationService.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.consors;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.http.Interceptor;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.api.model.Consents;
import de.adorsys.xs2a.adapter.api.model.ConsentsResponse201;
import de.adorsys.xs2a.adapter.api.model.OK200TransactionDetails;
import de.adorsys.xs2a.adapter.consors.model.ConsorsOK200TransactionDetails;
import de.adorsys.xs2a.adapter.impl.BaseAccountInformationService;
import org.mapstruct.factory.Mappers;
import java.util.List;
import java.util.Map;
import static de.adorsys.xs2a.adapter.api.RequestHeaders.PSU_ID;
public class ConsorsAccountInformationService extends BaseAccountInformationService {
private final ConsorsMapper mapper = Mappers.getMapper(ConsorsMapper.class);
public ConsorsAccountInformationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
List<Interceptor> interceptors,
LinksRewriter linksRewriter) {
super(aspsp,
httpClientFactory.getHttpClient(aspsp.getAdapterId()),
interceptors,
linksRewriter,
httpClientFactory.getHttpClientConfig().getLogSanitizer());
}
@Override
public Response<String> getTransactionListAsString(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return getTransactionList(accountId, requestHeaders, requestParams)
.map(jsonMapper::writeValueAsString);
}
@Override
public Response<ConsentsResponse201> createConsent(RequestHeaders requestHeaders,
RequestParams requestParams,
Consents body) {
Map<String, String> checkedHeader = removePsuIdHeader(requestHeaders.toMap());
return super.createConsent(RequestHeaders.fromMap(checkedHeader), requestParams, body);
}
@Override
public Response<OK200TransactionDetails> getTransactionDetails(String accountId,
String transactionId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return super.getTransactionDetails(accountId,
transactionId,
requestHeaders,
requestParams,
ConsorsOK200TransactionDetails.class,
mapper::toOK200TransactionDetails);
}
private Map<String, String> removePsuIdHeader(Map<String, String> headers) {
headers.remove(PSU_ID);
return headers;
}
}
| 3,994 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ConsorsPaymentInitiationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/consors-bank-adapter/src/main/java/de/adorsys/xs2a/adapter/consors/ConsorsPaymentInitiationService.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.consors;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.api.model.PaymentInitationRequestResponse201;
import de.adorsys.xs2a.adapter.api.model.PaymentProduct;
import de.adorsys.xs2a.adapter.api.model.PaymentService;
import de.adorsys.xs2a.adapter.impl.BasePaymentInitiationService;
import java.util.Map;
import static de.adorsys.xs2a.adapter.api.RequestHeaders.PSU_ID;
public class ConsorsPaymentInitiationService extends BasePaymentInitiationService {
public ConsorsPaymentInitiationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter) {
super(aspsp,
httpClientFactory.getHttpClient(aspsp.getAdapterId()),
linksRewriter,
httpClientFactory.getHttpClientConfig().getLogSanitizer());
}
@Override
public Response<PaymentInitationRequestResponse201> initiatePayment(PaymentService paymentService,
PaymentProduct paymentProduct,
RequestHeaders requestHeaders,
RequestParams requestParams,
Object body) {
Map<String, String> checkedHeader = removePsuIdHeader(requestHeaders.toMap());
return super.initiatePayment(paymentService, paymentProduct, RequestHeaders.fromMap(checkedHeader), requestParams, body);
}
private Map<String, String> removePsuIdHeader(Map<String, String> headers) {
headers.remove(PSU_ID);
return headers;
}
}
| 2,897 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ConsorsMapper.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/consors-bank-adapter/src/main/java/de/adorsys/xs2a/adapter/consors/ConsorsMapper.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.consors;
import de.adorsys.xs2a.adapter.api.model.OK200TransactionDetails;
import de.adorsys.xs2a.adapter.consors.model.ConsorsOK200TransactionDetails;
import org.mapstruct.Mapper;
@Mapper
public interface ConsorsMapper {
OK200TransactionDetails toOK200TransactionDetails(ConsorsOK200TransactionDetails value);
}
| 1,182 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ConsorsOK200TransactionDetails.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/consors-bank-adapter/src/main/java/de/adorsys/xs2a/adapter/consors/model/ConsorsOK200TransactionDetails.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.consors.model;
import de.adorsys.xs2a.adapter.api.model.Transactions;
import java.util.Objects;
public class ConsorsOK200TransactionDetails {
private Transactions transactionsDetails;
public Transactions getTransactionsDetails() {
return transactionsDetails;
}
public void setTransactionsDetails(Transactions transactionsDetails) {
this.transactionsDetails = transactionsDetails;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConsorsOK200TransactionDetails that = (ConsorsOK200TransactionDetails) o;
return Objects.equals(transactionsDetails, that.transactionsDetails);
}
@Override
public int hashCode() {
return Objects.hash(transactionsDetails);
}
}
| 1,708 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SpardaAccountInformationServiceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/sparda-bank-adapter/src/test/java/de/adorsys/xs2a/adapter/sparda/SpardaAccountInformationServiceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.sparda;
import de.adorsys.xs2a.adapter.api.*;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.api.model.OK200TransactionDetails;
import de.adorsys.xs2a.adapter.api.model.TransactionsResponse200Json;
import de.adorsys.xs2a.adapter.impl.http.RequestBuilderImpl;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.ByteArrayInputStream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class SpardaAccountInformationServiceTest {
private static final String URI = "https://foo.boo";
private static final String ACCOUNT_ID = "accountId";
private static final String REMITTANCE_INFORMATION_STRUCTURED = "remittanceInformationStructuredStringValue";
private AccountInformationService accountInformationService;
@Mock
private HttpClient httpClient;
@Mock
private Aspsp aspsp;
@Mock
private LinksRewriter linksRewriter;
@Mock
private HttpClientFactory httpClientFactory;
@Mock
private HttpClientConfig httpClientConfig;
@BeforeEach
void setUp() {
when(httpClientFactory.getHttpClient(any())).thenReturn(httpClient);
when(httpClientFactory.getHttpClientConfig()).thenReturn(httpClientConfig);
accountInformationService = new SpardaServiceProvider().getAccountInformationService(aspsp, httpClientFactory, linksRewriter);
}
@Test
void getTransactionList() {
String rawResponse = "{\n" +
" \"transactions\": {\n" +
" \"booked\": [\n" +
" {\n" +
" \"remittanceInformationStructured\": {" +
" \"reference\": \"" + REMITTANCE_INFORMATION_STRUCTURED + "\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
when(httpClient.get(anyString()))
.thenReturn(new RequestBuilderImpl(httpClient, "GET", URI));
when(httpClient.send(any(), any()))
.thenAnswer(invocationOnMock -> {
HttpClient.ResponseHandler responseHandler = invocationOnMock.getArgument(1, HttpClient.ResponseHandler.class);
return new Response<>(-1,
responseHandler.apply(200,
new ByteArrayInputStream(rawResponse.getBytes()),
ResponseHeaders.emptyResponseHeaders()),
null);
});
Response<?> actualResponse
= accountInformationService.getTransactionList(ACCOUNT_ID, RequestHeaders.empty(), RequestParams.empty());
verify(httpClient, times(1)).get(anyString());
verify(httpClient, times(1)).send(any(), any());
assertThat(actualResponse)
.isNotNull()
.extracting(Response::getBody)
.asInstanceOf(InstanceOfAssertFactories.type(TransactionsResponse200Json.class))
.matches(body ->
body.getTransactions()
.getBooked()
.get(0)
.getRemittanceInformationStructured()
.equals(REMITTANCE_INFORMATION_STRUCTURED));
}
@Test
void getTransactionDetails() {
String rawResponse = "{\n" +
" \"transactionsDetails\": {\n" +
" \"remittanceInformationStructured\": {" +
" \"reference\": \"" + REMITTANCE_INFORMATION_STRUCTURED + "\"\n" +
" }\n" +
" }\n" +
"}";
when(httpClient.get(anyString()))
.thenReturn(new RequestBuilderImpl(httpClient, "GET", URI));
when(httpClient.send(any(), any()))
.thenAnswer(invocationOnMock -> {
HttpClient.ResponseHandler responseHandler = invocationOnMock.getArgument(1, HttpClient.ResponseHandler.class);
return new Response<>(-1,
responseHandler.apply(200,
new ByteArrayInputStream(rawResponse.getBytes()),
ResponseHeaders.emptyResponseHeaders()),
null);
});
Response<?> actualResponse
= accountInformationService.getTransactionDetails(ACCOUNT_ID, "transactionId", RequestHeaders.empty(), RequestParams.empty());
verify(httpClient, times(1)).get(anyString());
verify(httpClient, times(1)).send(any(), any());
assertThat(actualResponse)
.isNotNull()
.extracting(Response::getBody)
.asInstanceOf(InstanceOfAssertFactories.type(OK200TransactionDetails.class))
.matches(body ->
body.getTransactionsDetails()
.getRemittanceInformationStructured()
.equals(REMITTANCE_INFORMATION_STRUCTURED));
}
}
| 6,249 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SpardaJwtServiceTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/adapters/sparda-bank-adapter/src/test/java/de/adorsys/xs2a/adapter/sparda/SpardaJwtServiceTest.java | /*
* Copyright 2018-2022 adorsys GmbH & Co KG
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version. This program is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* This project is also available under a separate commercial license. You can
* contact us at [email protected].
*/
package de.adorsys.xs2a.adapter.sparda;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class SpardaJwtServiceTest {
/*
* Token content:
*
* 1. Headers:
* {
* "alg": "HS256",
* "typ": "JWT"
* }
*
* 2. Payload:
* {
* "sub": "1234567890",
* "name": "John Doe",
* "iat": 1516239022
* }
*/
private static final String CORRECT_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" +
".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ" +
".SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
private static final String WRONG_TOKEN = "wrongToken";
private static final String EXPECTED_PSU_ID = "1234567890";
private final SpardaJwtService spardaJwtService = new SpardaJwtService();
@Test
void getPsuId_failure_ParseExceptionIsThrown() {
assertThrows(RuntimeException.class, () -> spardaJwtService.getPsuId(WRONG_TOKEN));
}
@Test
void getPsuId_success() {
String actualPsuId = spardaJwtService.getPsuId(CORRECT_TOKEN);
assertEquals(EXPECTED_PSU_ID, actualPsuId);
}
}
| 2,204 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |