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 |
---|---|---|---|---|---|---|---|---|---|---|---|
BaseDownloadService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/BaseDownloadService.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.impl;
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.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer;
import de.adorsys.xs2a.adapter.api.http.Interceptor;
import de.adorsys.xs2a.adapter.impl.http.ResponseHandlers;
import de.adorsys.xs2a.adapter.impl.http.StringUri;
import java.util.Collections;
import java.util.Map;
import static de.adorsys.xs2a.adapter.api.validation.Validation.requireValid;
public class BaseDownloadService extends AbstractService implements DownloadService {
private static final String HTTPS_PROTOCOL = "https://";
protected final String baseUri;
private final Interceptor requestBuilderInterceptor;
private final ResponseHandlers responseHandlers;
public BaseDownloadService(String baseUri, HttpClient httpClient) {
this(baseUri, httpClient, null);
}
public BaseDownloadService(String baseUri, HttpClient httpClient, HttpLogSanitizer logSanitizer) {
this(baseUri, httpClient, null, logSanitizer);
}
public BaseDownloadService(String baseUri,
HttpClient httpClient,
Interceptor requestBuilderInterceptor,
HttpLogSanitizer logSanitizer) {
super(httpClient);
this.baseUri = baseUri;
this.requestBuilderInterceptor = requestBuilderInterceptor;
this.responseHandlers = new ResponseHandlers(logSanitizer);
}
@Override
public Response<byte[]> download(String downloadUrl, RequestHeaders requestHeaders) {
requireValid(validateDownload(downloadUrl, requestHeaders));
Map<String, String> headersMap = populateGetHeaders(requestHeaders.toMap());
Response<byte[]> response = httpClient.get(modifyDownloadUrl(downloadUrl))
.headers(headersMap)
.send(responseHandlers.byteArrayResponseHandler(), Collections.singletonList(requestBuilderInterceptor));
return new Response<>(
response.getStatusCode(),
response.getBody(),
modifyResponseHeaders(response.getHeaders())
);
}
protected String modifyDownloadUrl(String downloadUrl) {
if (StringUri.isUri(downloadUrl)) {
return StringUri.fromElements(baseUri, downloadUrl);
}
if (!StringUri.containsProtocol(downloadUrl)) {
return StringUri.fromElements(HTTPS_PROTOCOL, downloadUrl);
}
return downloadUrl;
}
protected ResponseHeaders modifyResponseHeaders(ResponseHeaders responseHeaders) {
Map<String, String> headersMap = responseHeaders.getHeadersMap();
headersMap.put(ResponseHeaders.CONTENT_TYPE, "application/octet-stream");
return ResponseHeaders.fromMap(headersMap);
}
}
| 3,878 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AbstractAdapterServiceProvider.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/AbstractAdapterServiceProvider.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.impl;
import de.adorsys.xs2a.adapter.api.AccountInformationServiceProvider;
import de.adorsys.xs2a.adapter.api.PaymentInitiationServiceProvider;
import de.adorsys.xs2a.adapter.api.http.Interceptor;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.impl.http.wiremock.WiremockStubDifferenceDetectingInterceptor;
import java.util.*;
public abstract class AbstractAdapterServiceProvider implements AccountInformationServiceProvider, PaymentInitiationServiceProvider {
private boolean wiremockValidationEnabled;
@Override
public void wiremockValidationEnabled(boolean value) {
this.wiremockValidationEnabled = value;
}
public List<Interceptor> getInterceptors(Aspsp aspsp, Interceptor... interceptors) {
List<Interceptor> list = new ArrayList<>(Optional.ofNullable(interceptors)
.map(Arrays::asList)
.orElseGet(Collections::emptyList));
if (wiremockValidationEnabled && WiremockStubDifferenceDetectingInterceptor.isWiremockSupported(aspsp.getAdapterId())) {
list.add(new WiremockStubDifferenceDetectingInterceptor(aspsp));
return Collections.unmodifiableList(list);
}
return list;
}
}
| 2,172 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
BaseAccountInformationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/BaseAccountInformationService.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.impl;
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.http.ContentType;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer;
import de.adorsys.xs2a.adapter.api.http.Interceptor;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.impl.http.ResponseHandlers;
import de.adorsys.xs2a.adapter.impl.http.StringUri;
import de.adorsys.xs2a.adapter.impl.link.identity.IdentityLinksRewriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import static de.adorsys.xs2a.adapter.api.validation.Validation.requireValid;
import static java.util.function.Function.identity;
public class BaseAccountInformationService extends AbstractService implements AccountInformationService {
private static final LinksRewriter DEFAULT_LINKS_REWRITER = new IdentityLinksRewriter();
protected static final Logger logger = LoggerFactory.getLogger(BaseAccountInformationService.class);
protected static final String V1 = "v1";
protected static final String CONSENTS = "consents";
protected static final String ACCOUNTS = "accounts";
protected static final String TRANSACTIONS = "transactions";
protected static final String BALANCES = "balances";
protected static final String CARD_ACCOUNTS = "card-accounts";
protected final Aspsp aspsp;
private final LinksRewriter linksRewriter;
private final List<Interceptor> interceptors;
private final ResponseHandlers responseHandlers;
public BaseAccountInformationService(Aspsp aspsp,
HttpClient httpClient,
List<Interceptor> interceptors) {
this(aspsp, httpClient, interceptors, DEFAULT_LINKS_REWRITER, null);
}
public BaseAccountInformationService(Aspsp aspsp,
HttpClient httpClient,
LinksRewriter linksRewriter) {
this(aspsp, httpClient, Collections.emptyList(), linksRewriter, null);
}
public BaseAccountInformationService(Aspsp aspsp,
HttpClient httpClient,
LinksRewriter linksRewriter,
HttpLogSanitizer logSanitizer) {
this(aspsp, httpClient, Collections.emptyList(), linksRewriter, logSanitizer);
}
public BaseAccountInformationService(Aspsp aspsp,
HttpClient httpClient,
List<Interceptor> interceptors,
LinksRewriter linksRewriter,
HttpLogSanitizer logSanitizer) {
super(httpClient);
this.aspsp = aspsp;
this.interceptors = Optional.ofNullable(interceptors).orElseGet(Collections::emptyList);
this.linksRewriter = linksRewriter;
this.responseHandlers = new ResponseHandlers(logSanitizer);
}
@Override
public Response<ConsentsResponse201> createConsent(RequestHeaders requestHeaders,
RequestParams requestParams,
Consents body) {
return createConsent(requestHeaders,
requestParams,
body,
identity(),
responseHandlers.jsonResponseHandler(ConsentsResponse201.class));
}
protected <T> Response<ConsentsResponse201> createConsent(RequestHeaders requestHeaders,
RequestParams requestParams,
Consents body,
Class<T> klass,
Function<T, ConsentsResponse201> mapper) {
return createConsent(requestHeaders, requestParams, body, mapper, responseHandlers.jsonResponseHandler(klass));
}
protected <T> Response<ConsentsResponse201> createConsent(RequestHeaders requestHeaders,
RequestParams requestParams,
Consents body,
Function<T, ConsentsResponse201> mapper,
HttpClient.ResponseHandler<T> responseHandler) {
requireValid(validateCreateConsent(requestHeaders, requestParams, body));
Map<String, String> headersMap = populatePostHeaders(requestHeaders.toMap());
headersMap = resolvePsuIdHeader(headersMap);
headersMap = addPsuIdTypeHeader(headersMap);
String bodyString = jsonMapper.writeValueAsString(jsonMapper.convertValue(body, Consents.class));
String uri = buildUri(getConsentBaseUri(), requestParams);
Response<T> response = httpClient.post(uri)
.jsonBody(bodyString)
.headers(headersMap)
.send(responseHandler, interceptors);
ConsentsResponse201 creationResponse = mapper.apply(response.getBody());
creationResponse.setLinks(linksRewriter.rewrite(creationResponse.getLinks()));
return new Response<>(response.getStatusCode(), creationResponse, response.getHeaders());
}
@Override
public Response<ConsentInformationResponse200Json> getConsentInformation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return getConsentInformation(consentId,
requestHeaders,
requestParams,
ConsentInformationResponse200Json.class,
identity());
}
protected <T> Response<ConsentInformationResponse200Json> getConsentInformation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
Class<T> klass,
Function<T, ConsentInformationResponse200Json> mapper) {
requireValid(validateGetConsentInformation(consentId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getConsentBaseUri(), consentId);
uri = buildUri(uri, requestParams);
Map<String, String> headersMap = populateGetHeaders(requestHeaders.toMap());
Response<T> response = httpClient.get(uri)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(klass), interceptors);
ConsentInformationResponse200Json consentInformation = mapper.apply(response.getBody());
consentInformation.setLinks(linksRewriter.rewrite(consentInformation.getLinks()));
return new Response<>(response.getStatusCode(), consentInformation, response.getHeaders());
}
@Override
public Response<Void> deleteConsent(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requireValid(validateDeleteConsent(consentId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getConsentBaseUri(), consentId);
uri = buildUri(uri, requestParams);
Map<String, String> headersMap = populateDeleteHeaders(requestHeaders.toMap());
return httpClient.delete(uri)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(Void.class), interceptors);
}
@Override
public Response<ConsentStatusResponse200> getConsentStatus(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requireValid(validateGetConsentStatus(consentId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getConsentBaseUri(), consentId, STATUS);
uri = buildUri(uri, requestParams);
Map<String, String> headersMap = populateGetHeaders(requestHeaders.toMap());
return httpClient.get(uri)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(ConsentStatusResponse200.class), interceptors);
}
@Override
public Response<Authorisations> getConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requireValid(validateGetConsentAuthorisation(consentId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getConsentBaseUri(), consentId, AUTHORISATIONS);
uri = buildUri(uri, requestParams);
Map<String, String> headersMap = populateGetHeaders(requestHeaders.toMap());
return httpClient.get(uri)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(Authorisations.class), interceptors);
}
@Override
public Response<StartScaprocessResponse> startConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requireValid(validateStartConsentAuthorisation(consentId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getConsentBaseUri(), consentId, AUTHORISATIONS);
uri = buildUri(uri, requestParams);
Map<String, String> headersMap = populatePostHeaders(requestHeaders.toMap());
Response<StartScaprocessResponse> response = httpClient.post(uri)
.headers(headersMap)
.emptyBody(true)
.send(responseHandlers.jsonResponseHandler(StartScaprocessResponse.class),
interceptors);
Optional.ofNullable(response.getBody())
.ifPresent(body -> body.setLinks(linksRewriter.rewrite(body.getLinks())));
return response;
}
protected <T> Response<StartScaprocessResponse> startConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
Class<T> klass,
Function<T, StartScaprocessResponse> mapper) {
requireValid(validateStartConsentAuthorisation(consentId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getConsentBaseUri(), consentId, AUTHORISATIONS);
uri = buildUri(uri, requestParams);
Map<String, String> headersMap = populatePostHeaders(requestHeaders.toMap());
Response<T> response = httpClient.post(uri)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(klass), interceptors);
StartScaprocessResponse startScaProcessResponse = mapper.apply(response.getBody());
startScaProcessResponse.setLinks(linksRewriter.rewrite(startScaProcessResponse.getLinks()));
return new Response<>(response.getStatusCode(), startScaProcessResponse, response.getHeaders());
}
@Override
public Response<StartScaprocessResponse> startConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
return startConsentAuthorisation(consentId,
requestHeaders,
requestParams,
updatePsuAuthentication,
StartScaprocessResponse.class,
identity());
}
protected <T> Response<StartScaprocessResponse> startConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication,
Class<T> klass,
Function<T, StartScaprocessResponse> mapper) {
requireValid(validateStartConsentAuthorisation(consentId, requestHeaders, requestParams, updatePsuAuthentication));
String uri = StringUri.fromElements(getConsentBaseUri(), consentId, AUTHORISATIONS);
uri = buildUri(uri, requestParams);
Map<String, String> headersMap = populatePostHeaders(requestHeaders.toMap());
String body = jsonMapper.writeValueAsString(updatePsuAuthentication);
Response<T> response = httpClient.post(uri)
.jsonBody(body)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(klass), interceptors);
StartScaprocessResponse startScaProcessResponse = mapper.apply(response.getBody());
startScaProcessResponse.setLinks(linksRewriter.rewrite(startScaProcessResponse.getLinks()));
return new Response<>(response.getStatusCode(), startScaProcessResponse, response.getHeaders());
}
@Override
public Response<UpdatePsuAuthenticationResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
return updateConsentsPsuData(consentId,
authorisationId,
requestHeaders,
requestParams,
updatePsuAuthentication,
UpdatePsuAuthenticationResponse.class,
identity());
}
protected <T> Response<UpdatePsuAuthenticationResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication,
Class<T> klass,
Function<T, UpdatePsuAuthenticationResponse> mapper) {
requireValid(validateUpdateConsentsPsuData(consentId, authorisationId, requestHeaders, requestParams, updatePsuAuthentication));
String uri = StringUri.fromElements(getConsentBaseUri(), consentId, AUTHORISATIONS, authorisationId);
uri = buildUri(uri, requestParams);
Map<String, String> headersMap = populatePutHeaders(requestHeaders.toMap());
headersMap = addPsuIdTypeHeader(headersMap);
String body = jsonMapper.writeValueAsString(updatePsuAuthentication);
Response<T> response = httpClient.put(uri)
.jsonBody(body)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(klass), interceptors);
UpdatePsuAuthenticationResponse updatePsuAuthenticationResponse = mapper.apply(response.getBody());
updatePsuAuthenticationResponse.setLinks(linksRewriter.rewrite(updatePsuAuthenticationResponse.getLinks()));
return new Response<>(response.getStatusCode(), updatePsuAuthenticationResponse, response.getHeaders());
}
@Override
public Response<SelectPsuAuthenticationMethodResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
SelectPsuAuthenticationMethod selectPsuAuthenticationMethod) {
return updateConsentsPsuData(consentId,
authorisationId,
requestHeaders,
requestParams,
selectPsuAuthenticationMethod,
SelectPsuAuthenticationMethodResponse.class,
identity());
}
protected <T> Response<SelectPsuAuthenticationMethodResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
SelectPsuAuthenticationMethod selectPsuAuthenticationMethod,
Class<T> klass,
Function<T, SelectPsuAuthenticationMethodResponse> mapper) {
requireValid(validateUpdateConsentsPsuData(consentId, authorisationId, requestHeaders, requestParams, selectPsuAuthenticationMethod));
String uri = StringUri.fromElements(getConsentBaseUri(), consentId, AUTHORISATIONS, authorisationId);
uri = buildUri(uri, requestParams);
Map<String, String> headersMap = populatePutHeaders(requestHeaders.toMap());
headersMap = addPsuIdTypeHeader(headersMap);
String body = jsonMapper.writeValueAsString(selectPsuAuthenticationMethod);
Response<T> response = httpClient.put(uri)
.jsonBody(body)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(klass), interceptors);
SelectPsuAuthenticationMethodResponse selectPsuAuthenticationMethodResponse = mapper.apply(response.getBody());
selectPsuAuthenticationMethodResponse.setLinks(linksRewriter.rewrite(selectPsuAuthenticationMethodResponse.getLinks()));
return new Response<>(response.getStatusCode(), selectPsuAuthenticationMethodResponse, response.getHeaders());
}
@Override
public Response<ScaStatusResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
TransactionAuthorisation transactionAuthorisation) {
return updateConsentsPsuData(consentId,
authorisationId,
requestHeaders,
requestParams,
transactionAuthorisation,
ScaStatusResponse.class,
identity());
}
protected <T> Response<ScaStatusResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
TransactionAuthorisation transactionAuthorisation,
Class<T> klass,
Function<T, ScaStatusResponse> mapper) {
requireValid(validateUpdateConsentsPsuData(consentId,
authorisationId,
requestHeaders,
requestParams,
transactionAuthorisation));
String uri = getUpdateConsentPsuDataUri(consentId, authorisationId);
uri = buildUri(uri, requestParams);
Map<String, String> headersMap = populatePutHeaders(requestHeaders.toMap());
headersMap = addPsuIdTypeHeader(headersMap);
String body = jsonMapper.writeValueAsString(transactionAuthorisation);
Response<T> response = httpClient.put(uri)
.jsonBody(body)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(klass), interceptors);
ScaStatusResponse scaStatusResponse = mapper.apply(response.getBody());
return new Response<>(response.getStatusCode(), scaStatusResponse, response.getHeaders());
}
protected String getUpdateConsentPsuDataUri(String consentId, String authorisationId) {
return StringUri.fromElements(getConsentBaseUri(), consentId, AUTHORISATIONS, authorisationId);
}
@Override
public Response<AccountList> getAccountList(RequestHeaders requestHeaders, RequestParams requestParams) {
requireValid(validateGetAccountList(requestHeaders, requestParams));
Map<String, String> headersMap = populateGetHeaders(requestHeaders.toMap());
headersMap = addConsentIdHeader(headersMap);
String uri = buildUri(getAccountsBaseUri(), requestParams);
Response<AccountList> response = httpClient.get(uri)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(AccountList.class), interceptors);
Optional.ofNullable(response.getBody())
.map(AccountList::getAccounts)
.ifPresent(accounts ->
accounts.forEach(account -> account.setLinks(linksRewriter.rewrite(account.getLinks()))));
return response;
}
@Override
public Response<OK200AccountDetails> readAccountDetails(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requireValid(validateReadAccountDetails(requestHeaders, requestParams));
Map<String, String> headersMap = populateGetHeaders(requestHeaders.toMap());
headersMap = addConsentIdHeader(headersMap);
String uri = buildUri(StringUri.fromElements(getAccountsBaseUri(), accountId), requestParams);
Response<OK200AccountDetails> response = httpClient.get(uri)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(OK200AccountDetails.class), interceptors);
Optional.ofNullable(response.getBody())
.map(OK200AccountDetails::getAccount)
.ifPresent(account -> account.setLinks(linksRewriter.rewrite(account.getLinks())));
return response;
}
@Override
public Response<TransactionsResponse200Json> getTransactionList(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return getTransactionList(accountId, requestHeaders, requestParams, TransactionsResponse200Json.class, identity());
}
private String getTransactionListUri(String accountId, RequestParams requestParams) {
String uri = StringUri.fromElements(getAccountsBaseUri(), accountId, TRANSACTIONS);
uri = buildUri(uri, requestParams);
return uri;
}
protected <T> Response<TransactionsResponse200Json> getTransactionList(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams,
Class<T> klass,
Function<T, TransactionsResponse200Json> mapper) {
requireValid(validateGetTransactionList(accountId, requestHeaders, requestParams));
Map<String, String> headersMap = populateGetHeaders(requestHeaders.toMap());
headersMap.put(ACCEPT_HEADER, ContentType.APPLICATION_JSON);
String uri = getTransactionListUri(accountId, requestParams);
Response<T> response = httpClient.get(uri)
.headers(headersMap)
.send(responseHandlers.jsonResponseHandler(klass), interceptors);
TransactionsResponse200Json transactionsReport = mapper.apply(response.getBody());
logTransactionsSize(transactionsReport);
transactionsReport.setLinks(linksRewriter.rewrite(transactionsReport.getLinks()));
Optional.ofNullable(transactionsReport.getTransactions())
.ifPresent(report -> {
report.setLinks(linksRewriter.rewrite(report.getLinks()));
rewriteTransactionsLinks(report.getBooked());
rewriteTransactionsLinks(report.getPending());
});
return new Response<>(response.getStatusCode(), transactionsReport, response.getHeaders());
}
private void rewriteTransactionsLinks(List<Transactions> transactions) {
Optional.ofNullable(transactions)
.ifPresent(ts ->
ts.forEach(transaction -> transaction.setLinks(linksRewriter.rewrite(transaction.getLinks())))
);
}
private void logTransactionsSize(TransactionsResponse200Json transactionsReport) {
int size = 0;
if (transactionsReport != null && transactionsReport.getTransactions() != null) {
AccountReport transactions = transactionsReport.getTransactions();
if (transactions.getPending() != null) {
size += transactions.getPending().size();
}
if (transactions.getBooked() != null) {
size += transactions.getBooked().size();
}
}
logger.info("<-- There are {} transactions in the response", size);
}
@Override
public Response<OK200TransactionDetails> getTransactionDetails(String accountId,
String transactionId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return getTransactionDetails(accountId,
transactionId,
requestHeaders,
requestParams,
OK200TransactionDetails.class,
identity());
}
protected <T> Response<OK200TransactionDetails> getTransactionDetails(String accountId,
String transactionId,
RequestHeaders requestHeaders,
RequestParams requestParams,
Class<T> klass,
Function<T, OK200TransactionDetails> mapper) {
requireValid(validateGetTransactionDetails(accountId, transactionId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getAccountsBaseUri(), accountId, TRANSACTIONS, transactionId);
uri = buildUri(uri, requestParams);
Response<OK200TransactionDetails> response = httpClient.get(uri)
.headers(populateGetHeaders(requestHeaders.toMap()))
.send(responseHandlers.jsonResponseHandler(klass), interceptors)
.map(mapper);
Optional.ofNullable(response.getBody())
.map(OK200TransactionDetails::getTransactionsDetails)
.ifPresent(t -> t.setLinks(linksRewriter.rewrite(t.getLinks())));
return new Response<>(response.getStatusCode(), response.getBody(), response.getHeaders());
}
@Override
public Response<String> getTransactionListAsString(String accountId, RequestHeaders requestHeaders, RequestParams requestParams) {
requireValid(validateGetTransactionListAsString(accountId, requestHeaders, requestParams));
String uri = getTransactionListUri(accountId, requestParams);
Map<String, String> headers = populateGetHeaders(requestHeaders.toMap());
Response<String> response = httpClient.get(uri)
.headers(headers)
.send(responseHandlers.stringResponseHandler(), interceptors);
logger.info("<-- There is no information about transactions");
return response;
}
@Override
public Response<ScaStatusResponse> getConsentScaStatus(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requireValid(validateGetConsentScaStatus(consentId, authorisationId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getConsentBaseUri(), consentId, AUTHORISATIONS, authorisationId);
uri = buildUri(uri, requestParams);
Map<String, String> headers = populateGetHeaders(requestHeaders.toMap());
return httpClient.get(uri)
.headers(headers)
.send(responseHandlers.jsonResponseHandler(ScaStatusResponse.class), interceptors);
}
@Override
public Response<ReadAccountBalanceResponse200> getBalances(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return getBalances(accountId, requestHeaders, requestParams, ReadAccountBalanceResponse200.class, identity());
}
@Override
public Response<CardAccountList> getCardAccountList(RequestHeaders requestHeaders, RequestParams requestParams) {
requireValid(validateGetCardAccountList(requestHeaders, requestParams));
String uri = StringUri.fromElements(getBaseUri(), V1, CARD_ACCOUNTS);
uri = buildUri(uri, requestParams);
Map<String, String> headers = populateGetHeaders(requestHeaders.toMap());
Response<CardAccountList> response = httpClient.get(uri)
.headers(headers)
.send(responseHandlers.jsonResponseHandler(CardAccountList.class), interceptors);
Optional.ofNullable(response.getBody())
.map(CardAccountList::getCardAccounts)
.ifPresent(accounts ->
accounts.forEach(account ->
account.setLinks(linksRewriter.rewrite(account.getLinks()))));
return response;
}
@Override
public Response<OK200CardAccountDetails> getCardAccountDetails(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requireValid(validateGetCardAccountDetails(accountId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getBaseUri(), V1, CARD_ACCOUNTS, accountId);
uri = buildUri(uri, requestParams);
Map<String, String> headers = populateGetHeaders(requestHeaders.toMap());
Response<OK200CardAccountDetails> response = httpClient.get(uri)
.headers(headers)
.send(responseHandlers.jsonResponseHandler(OK200CardAccountDetails.class),
interceptors);
Optional.ofNullable(response.getBody())
.map(OK200CardAccountDetails::getCardAccount)
.ifPresent(account -> account.setLinks(linksRewriter.rewrite(account.getLinks())));
return response;
}
@Override
public Response<ReadCardAccountBalanceResponse200> getCardAccountBalances(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requireValid(validateGetCardAccountBalances(accountId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getBaseUri(), V1, CARD_ACCOUNTS, accountId, BALANCES);
uri = buildUri(uri, requestParams);
Map<String, String> headers = populateGetHeaders(requestHeaders.toMap());
return httpClient.get(uri)
.headers(headers)
.send(responseHandlers.jsonResponseHandler(ReadCardAccountBalanceResponse200.class), interceptors);
}
@Override
public Response<CardAccountsTransactionsResponse200> getCardAccountTransactionList(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
requireValid(validateGetCardAccountTransactionList(accountId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getBaseUri(), V1, CARD_ACCOUNTS, accountId, TRANSACTIONS);
uri = buildUri(uri, requestParams);
Map<String, String> headers = populateGetHeaders(requestHeaders.toMap());
Response<CardAccountsTransactionsResponse200> response = httpClient.get(uri)
.headers(headers)
.send(responseHandlers.jsonResponseHandler(CardAccountsTransactionsResponse200.class),
interceptors);
CardAccountsTransactionsResponse200 body = response.getBody();
if (body != null) {
body.setLinks(linksRewriter.rewrite(body.getLinks()));
CardAccountReport cardTransactions = body.getCardTransactions();
if (cardTransactions != null) {
cardTransactions.setLinks(linksRewriter.rewrite(cardTransactions.getLinks()));
}
}
return response;
}
protected <T> Response<ReadAccountBalanceResponse200> getBalances(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams,
Class<T> klass,
Function<T, ReadAccountBalanceResponse200> mapper) {
requireValid(validateGetBalances(accountId, requestHeaders, requestParams));
String uri = StringUri.fromElements(getAccountsBaseUri(), accountId, BALANCES);
uri = buildUri(uri, requestParams);
Map<String, String> headers = populateGetHeaders(requestHeaders.toMap());
Response<T> response = httpClient.get(uri)
.headers(headers)
.send(responseHandlers.jsonResponseHandler(klass), interceptors);
ReadAccountBalanceResponse200 balanceReport = mapper.apply(response.getBody());
return new Response<>(response.getStatusCode(), balanceReport, response.getHeaders());
}
protected String getBaseUri() {
return aspsp.getUrl();
}
protected String getIdpUri() {
return aspsp.getIdpUrl();
}
protected String getConsentBaseUri() {
return StringUri.fromElements(getBaseUri(), V1, CONSENTS);
}
protected String getAccountsBaseUri() {
return StringUri.fromElements(getBaseUri(), V1, ACCOUNTS);
}
}
| 40,518 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ScopeWithResourceIdOauth2Service.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/ScopeWithResourceIdOauth2Service.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.impl;
import de.adorsys.xs2a.adapter.api.Oauth2Service;
import de.adorsys.xs2a.adapter.api.exception.BadRequestException;
import de.adorsys.xs2a.adapter.api.model.Scope;
import de.adorsys.xs2a.adapter.api.validation.ValidationError;
import de.adorsys.xs2a.adapter.impl.http.UriBuilder;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class ScopeWithResourceIdOauth2Service extends Oauth2ServiceDecorator {
private static final String UNSUPPORTED_SCOPE_VALUE_ERROR_MESSAGE = "Scope value [%s] is not supported";
private static final String PAYMENT_ID_MISSING_ERROR_MESSAGE = "Payment id should be provided for pis scope";
private static final String CONSENT_ID_MISSING_ERROR_MESSAGE = "Consent id should be provided for ais scope";
private static final String UNKNOWN_SCOPE_VALUE_ERROR_MESSAGE = "Unknown scope value";
private static final String CONSENT_OR_PAYMENT_ID_MISSING_ERROR_MESSAGE = "Either consent id or payment id should be provided";
private final String aisScopePrefix;
private final String pisScopePrefix;
public ScopeWithResourceIdOauth2Service(Oauth2Service oauth2Service,
String aisScopePrefix,
String pisScopePrefix) {
super(oauth2Service);
this.aisScopePrefix = aisScopePrefix;
this.pisScopePrefix = pisScopePrefix;
}
@Override
public List<ValidationError> validateGetAuthorizationRequestUri(Map<String, String> headers,
Parameters parameters) {
List<ValidationError> validationErrors = new ArrayList<>();
String scope = parameters.getScope();
if (StringUtils.isNotEmpty(scope)) {
if (!Scope.contains(scope)) {
validationErrors.add(new ValidationError(ValidationError.Code.NOT_SUPPORTED,
Parameters.SCOPE,
String.format(UNSUPPORTED_SCOPE_VALUE_ERROR_MESSAGE, scope)));
} else if (Scope.isAis(Scope.fromValue(scope))) {
if (StringUtils.isBlank(parameters.getConsentId())) {
validationErrors.add(new ValidationError(ValidationError.Code.REQUIRED,
Parameters.CONSENT_ID,
CONSENT_ID_MISSING_ERROR_MESSAGE));
}
} else if (Scope.isPis(Scope.fromValue(scope)) && StringUtils.isBlank(parameters.getPaymentId())) {
validationErrors.add(new ValidationError(ValidationError.Code.REQUIRED,
Parameters.PAYMENT_ID,
PAYMENT_ID_MISSING_ERROR_MESSAGE));
}
}
return Collections.unmodifiableList(validationErrors);
}
@Override
public URI getAuthorizationRequestUri(Map<String, String> headers, Parameters parameters) throws IOException {
return UriBuilder.fromUri(oauth2Service.getAuthorizationRequestUri(headers, parameters))
.queryParam("scope", scope(parameters))
.build();
}
private String scope(Parameters parameters) {
if (StringUtils.isEmpty(parameters.getScope())) {
return computeScope(parameters);
} else {
return mapScope(parameters);
}
}
private String computeScope(Parameters parameters) {
if (StringUtils.isNotBlank(parameters.getConsentId())) {
return aisScopePrefix + parameters.getConsentId();
}
if (StringUtils.isNotBlank(parameters.getPaymentId())) {
return pisScopePrefix + parameters.getPaymentId();
}
throw new BadRequestException(CONSENT_OR_PAYMENT_ID_MISSING_ERROR_MESSAGE);
}
private String mapScope(Parameters parameters) {
Scope scope = Scope.fromValue(parameters.getScope());
if (Scope.isAis(scope)) {
return aisScopePrefix + parameters.getConsentId();
} else if (Scope.isPis(scope)) {
return pisScopePrefix + parameters.getPaymentId();
}
throw new BadRequestException(UNKNOWN_SCOPE_VALUE_ERROR_MESSAGE);
}
}
| 5,140 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
BaseOauth2Service.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/BaseOauth2Service.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.impl;
import de.adorsys.xs2a.adapter.api.Oauth2Service;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
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.impl.http.ResponseHandlers;
import de.adorsys.xs2a.adapter.impl.http.UriBuilder;
import de.adorsys.xs2a.adapter.impl.oauth2.api.model.AuthorisationServerMetaData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
public class BaseOauth2Service implements Oauth2Service {
private static final Logger logger = LoggerFactory.getLogger(BaseOauth2Service.class);
private final HttpClient httpClient;
private final Aspsp aspsp;
private final ResponseHandlers responseHandlers;
public BaseOauth2Service(Aspsp aspsp, HttpClient httpClient) {
this(aspsp, httpClient, null);
}
public BaseOauth2Service(Aspsp aspsp, HttpClient httpClient, HttpLogSanitizer logSanitizer) {
this.httpClient = httpClient;
this.aspsp = aspsp;
this.responseHandlers = new ResponseHandlers(logSanitizer);
}
@Override
public URI getAuthorizationRequestUri(Map<String, String> headers, Parameters parameters) throws IOException {
return UriBuilder.fromUri(getAuthorizationEndpoint(parameters))
.queryParam(Parameters.RESPONSE_TYPE, ResponseType.CODE.toString())
.queryParam(Parameters.STATE, parameters.getState())
.queryParam(Parameters.REDIRECT_URI, parameters.getRedirectUri())
.queryParam(Parameters.SCOPE, parameters.getScope())
.build();
}
private String getAuthorizationEndpoint(Parameters parameters) {
String authorizationEndpoint = parameters.getAuthorizationEndpoint();
if (authorizationEndpoint != null) {
logger.debug("Get Authorisation Request URI: resolved on the adapter side");
return authorizationEndpoint;
}
AuthorisationServerMetaData metadata = getAuthorizationServerMetadata(parameters);
return metadata.getAuthorisationEndpoint();
}
private AuthorisationServerMetaData getAuthorizationServerMetadata(Parameters parameters) {
String scaOAuthLink = parameters.removeScaOAuthLink();
String metadataUri = scaOAuthLink != null ? scaOAuthLink : aspsp.getIdpUrl();
return httpClient.get(metadataUri)
.send(responseHandlers.jsonResponseHandler(AuthorisationServerMetaData.class))
.getBody();
}
@Override
public TokenResponse getToken(Map<String, String> headers, Parameters parameters) throws IOException {
Response<TokenResponse> response = httpClient.post(getTokenEndpoint(parameters))
.urlEncodedBody(parameters.asMap())
.send(responseHandlers.jsonResponseHandler(TokenResponse.class));
return response.getBody();
}
private String getTokenEndpoint(Parameters parameters) {
String tokenEndpoint = parameters.removeTokenEndpoint();
if (tokenEndpoint != null) {
return tokenEndpoint;
}
return getAuthorizationServerMetadata(parameters).getTokenEndpoint();
}
}
| 4,214 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
RequestSigningService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/signing/RequestSigningService.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.impl.signing;
import de.adorsys.xs2a.adapter.api.Pkcs12KeyStore;
import de.adorsys.xs2a.adapter.api.exception.HttpRequestSigningException;
import de.adorsys.xs2a.adapter.impl.signing.header.Digest;
import de.adorsys.xs2a.adapter.impl.signing.header.Signature;
import de.adorsys.xs2a.adapter.impl.signing.header.TppSignatureCertificate;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Map;
import static de.adorsys.xs2a.adapter.impl.signing.util.Constants.*;
public class RequestSigningService {
private final Pkcs12KeyStore keyStore;
public RequestSigningService(Pkcs12KeyStore keyStore) {
this.keyStore = keyStore;
}
public Digest buildDigest(String requestBody) {
return Digest.builder()
.requestBody(requestBody)
.build();
}
public Signature buildSignature(Map<String, String> headersMap) {
return Signature.builder()
.keyId(getKeyId())
.headers(headersMap)
.privateKey(getPrivateKey())
.build();
}
private String getKeyId() {
X509Certificate certificate = getCertificate();
return CERTIFICATE_SERIAL_NUMBER_ATTRIBUTE
+ EQUALS_SIGN_SEPARATOR
+ certificate.getSerialNumber().toString(16) // toString(16) is used to provide hexadecimal coding as mentioned in specification
+ COMMA_SEPARATOR
+ CERTIFICATION_AUTHORITY_ATTRIBUTE
+ EQUALS_SIGN_SEPARATOR
+ certificate.getIssuerX500Principal()
.getName()
.replaceAll(SPACE_SEPARATOR, HEXADECIMAL_SPACE_SEPARATOR);
}
private X509Certificate getCertificate() {
X509Certificate certificate = null;
try {
certificate = keyStore.getQsealCertificate();
} catch (KeyStoreException e) {
throw new HttpRequestSigningException(e);
}
return certificate;
}
private PrivateKey getPrivateKey() {
try {
return keyStore.getQsealPrivateKey();
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
throw new HttpRequestSigningException(e);
}
}
public TppSignatureCertificate buildTppSignatureCertificate() {
return TppSignatureCertificate.builder()
.publicKeyAsString(getPublicKeyAsString())
.build();
}
private String getPublicKeyAsString() {
X509Certificate certificate = getCertificate();
try {
return Base64.getEncoder().encodeToString(certificate.getEncoded());
} catch (CertificateEncodingException e) {
throw new HttpRequestSigningException(e);
}
}
}
| 3,921 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
TppSignatureCertificate.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/signing/header/TppSignatureCertificate.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.impl.signing.header;
import de.adorsys.xs2a.adapter.impl.signing.util.Constants;
public class TppSignatureCertificate {
private String headerValue;
private TppSignatureCertificate(String headerValue) {
this.headerValue = headerValue;
}
public static TppSignatureCertificateBuilder builder() {
return new TppSignatureCertificateBuilder();
}
public String getHeaderName() {
return Constants.TPP_SIGNATURE_CERTIFICATE_HEADER_NAME;
}
public String getHeaderValue() {
return headerValue;
}
public static final class TppSignatureCertificateBuilder {
private String publicKeyAsString;
private TppSignatureCertificateBuilder() {
}
public TppSignatureCertificateBuilder publicKeyAsString(String publicKeyAsString) {
this.publicKeyAsString = publicKeyAsString;
return this;
}
public TppSignatureCertificate build() {
return new TppSignatureCertificate(publicKeyAsString);
}
}
}
| 1,908 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Signature.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/signing/header/Signature.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.impl.signing.header;
import de.adorsys.xs2a.adapter.api.exception.HttpRequestSigningException;
import de.adorsys.xs2a.adapter.impl.signing.algorithm.EncodingAlgorithm;
import de.adorsys.xs2a.adapter.impl.signing.algorithm.SigningAlgorithm;
import de.adorsys.xs2a.adapter.impl.signing.util.Constants;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class Signature {
private final String headerValue;
private Signature(String headerValue) {
this.headerValue = headerValue;
}
public static Builder builder() {
return new Builder();
}
public String getHeaderName() {
return Constants.SIGNATURE_HEADER_NAME;
}
public String getHeaderValue() {
return headerValue;
}
public static final class Builder {
private String keyId;
private SigningAlgorithm signingAlgorithm = SigningAlgorithm.SHA256_WITH_RSA;
private EncodingAlgorithm encodingAlgorithm = EncodingAlgorithm.BASE64;
private Charset charset = StandardCharsets.UTF_8;
private Map<String, String> headersMap;
private PrivateKey privateKey;
private Builder() {
}
public Builder keyId(String keyId) {
this.keyId = keyId;
return this;
}
public Builder signingAlgorithm(SigningAlgorithm signingAlgorithm) {
this.signingAlgorithm = signingAlgorithm;
return this;
}
public Builder encodingAlgorithm(EncodingAlgorithm encodingAlgorithm) {
this.encodingAlgorithm = encodingAlgorithm;
return this;
}
public Builder charset(Charset charset) {
this.charset = charset;
return this;
}
public Builder headers(Map<String, String> headers) {
this.headersMap = new HashMap<>(headers);
return this;
}
public Builder privateKey(PrivateKey privateKey) {
this.privateKey = privateKey;
return this;
}
public Signature build() {
if (privateKeyNotExist()) {
throw new HttpRequestSigningException("Private key is missing: it is impossible to create a signature without such a key");
}
if (requiredAttributesNotExist()) {
throw new HttpRequestSigningException(
String.format("Required Signature header attributes must be present. Current values [%s] = %s, [%s] = %s, [%s] = %s)",
Constants.KEY_ID_ATTRIBUTE_NAME, keyId,
Constants.ALGORITHM_ATTRIBUTE_NAME, signingAlgorithm,
Constants.HEADERS_ATTRIBUTE_NAME, headersMap
)
);
}
List<Entry<String, String>> headersEntries = getSortedHeaderEntries(headersMap);
String headersAttributeValue = buildHeaderAttributeValue(headersEntries);
String signingString = buildSigningString(headersEntries);
byte[] signedData = signingAlgorithm.getSigningService().sign(privateKey, signingString, charset);
String signatureAttributeValue = encodingAlgorithm.getEncodingService().encode(signedData);
return new Signature(
buildSignatureHeader(keyId, signingAlgorithm.getAlgorithmName(), headersAttributeValue, signatureAttributeValue)
);
}
private boolean privateKeyNotExist() {
return privateKey == null;
}
private boolean requiredAttributesNotExist() {
return keyId == null || keyId.isEmpty()
|| signingAlgorithm == null
|| headersMap == null || headersMap.isEmpty();
}
private List<Entry<String, String>> getSortedHeaderEntries(Map<String, String> headersMap) {
// important, as the order must be strict
return headersMap.entrySet().stream()
.sorted(Comparator.comparing(Entry::getKey))
.collect(Collectors.toList());
}
private String buildHeaderAttributeValue(List<Entry<String, String>> headersEntries) {
return headersEntries.stream()
.map(Entry::getKey)
.map(String::toLowerCase)
.collect(Collectors.joining(Constants.SPACE_SEPARATOR));
}
private String buildSigningString(List<Entry<String, String>> headersEntries) {
return headersEntries.stream()
.map(entry -> this.buildSigningLine(entry.getKey(), entry.getValue()))
.collect(Collectors.joining(Constants.LINE_BREAK_SEPARATOR));
}
private String buildSigningLine(String headerName, String headerValue) {
return headerName.toLowerCase() + Constants.COLON_SEPARATOR + Constants.SPACE_SEPARATOR + headerValue;
}
private String buildSignatureHeader(String keyIdAttributeValue,
String algorithmAttributeValue,
String headersAttributeValue,
String signatureAttributeValue) {
return buildAttribute(Constants.KEY_ID_ATTRIBUTE_NAME, keyIdAttributeValue)
+ Constants.COMMA_SEPARATOR
+ buildAttribute(Constants.ALGORITHM_ATTRIBUTE_NAME, algorithmAttributeValue)
+ Constants.COMMA_SEPARATOR
+ buildAttribute(Constants.HEADERS_ATTRIBUTE_NAME, headersAttributeValue)
+ Constants.COMMA_SEPARATOR
+ buildAttribute(Constants.SIGNATURE_ATTRIBUTE_NAME, signatureAttributeValue);
}
private String buildAttribute(String attributeName, String attributeValue) {
return attributeName
+ Constants.EQUALS_SIGN_SEPARATOR
+ Constants.QUOTE_SEPARATOR
+ attributeValue
+ Constants.QUOTE_SEPARATOR;
}
}
}
| 7,351 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Digest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/signing/header/Digest.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.impl.signing.header;
import de.adorsys.xs2a.adapter.impl.signing.algorithm.EncodingAlgorithm;
import de.adorsys.xs2a.adapter.impl.signing.algorithm.HashingAlgorithm;
import de.adorsys.xs2a.adapter.impl.signing.util.Constants;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class Digest {
private String headerValue;
private Digest(String headerValue) {
this.headerValue = headerValue;
}
public static DigestBuilder builder() {
return new DigestBuilder();
}
public String getHeaderName() {
return Constants.DIGEST_HEADER_NAME;
}
public String getHeaderValue() {
return headerValue;
}
public static final class DigestBuilder {
private String requestBody;
private HashingAlgorithm hashingAlgorithm = HashingAlgorithm.SHA256;
private EncodingAlgorithm encodingAlgorithm = EncodingAlgorithm.BASE64;
private Charset charset = StandardCharsets.UTF_8;
private DigestBuilder() {
}
public DigestBuilder requestBody(String requestBody) {
this.requestBody = requestBody;
return this;
}
public DigestBuilder hashingAlgorithm(HashingAlgorithm hashingAlgorithm) {
this.hashingAlgorithm = hashingAlgorithm;
return this;
}
public DigestBuilder encodingAlgorithm(EncodingAlgorithm encodingAlgorithm) {
this.encodingAlgorithm = encodingAlgorithm;
return this;
}
public DigestBuilder charset(Charset charset) {
this.charset = charset;
return this;
}
public Digest build() {
byte[] digestBytes = hashingAlgorithm.getHashingService()
.hash(requestBody, charset);
String digestEncoded = encodingAlgorithm.getEncodingService()
.encode(digestBytes);
return new Digest(buildDigestHeader(hashingAlgorithm.getAlgorithmName(), digestEncoded));
}
private String buildDigestHeader(String algorithmName, String digestEncoded) {
return algorithmName + Constants.EQUALS_SIGN_SEPARATOR + digestEncoded;
}
}
}
| 3,136 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Constants.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/signing/util/Constants.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.impl.signing.util;
public final class Constants {
// header names:
public static final String DIGEST_HEADER_NAME = "Digest";
public static final String SIGNATURE_HEADER_NAME = "Signature";
public static final String TPP_SIGNATURE_CERTIFICATE_HEADER_NAME = "TPP-Signature-Certificate";
// signature header attributes names:
public static final String KEY_ID_ATTRIBUTE_NAME = "keyId";
public static final String ALGORITHM_ATTRIBUTE_NAME = "algorithm";
public static final String HEADERS_ATTRIBUTE_NAME = "headers";
public static final String SIGNATURE_ATTRIBUTE_NAME = "signature";
// separators:
public static final String EQUALS_SIGN_SEPARATOR = "=";
public static final String COLON_SEPARATOR = ":";
public static final String COMMA_SEPARATOR = ",";
public static final String QUOTE_SEPARATOR = "\"";
public static final String SPACE_SEPARATOR = " ";
public static final String HEXADECIMAL_SPACE_SEPARATOR = "%20";
public static final String LINE_BREAK_SEPARATOR = "\n";
// certificates:
public static final String CERTIFICATE_SERIAL_NUMBER_ATTRIBUTE = "SN";
public static final String CERTIFICATION_AUTHORITY_ATTRIBUTE = "CA";
private Constants() {
}
}
| 2,110 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
HashingAlgorithm.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/signing/algorithm/HashingAlgorithm.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.impl.signing.algorithm;
import de.adorsys.xs2a.adapter.api.exception.HttpRequestSigningException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public enum HashingAlgorithm {
SHA256("SHA-256", new Sha256HashingService()),
SHA512("SHA-512", new Sha512HashingService());
private final String algorithmName;
private final HashingService hashingService;
HashingAlgorithm(String algorithmName, HashingService hashingService) {
this.algorithmName = algorithmName;
this.hashingService = hashingService;
}
public String getAlgorithmName() {
return algorithmName;
}
public HashingService getHashingService() {
return hashingService;
}
public interface HashingService {
byte[] hash(String data, Charset charset);
}
private abstract static class AbstractShaHashingService implements HashingService {
@SuppressWarnings("java:S4790")
@Override
public byte[] hash(String data, Charset charset) {
try {
return MessageDigest.getInstance(getAlgorithm().getAlgorithmName())
.digest(data.getBytes(charset));
} catch (NoSuchAlgorithmException e) {
throw new HttpRequestSigningException("No such hashing algorithm: "
+ getAlgorithm().getAlgorithmName());
}
}
protected abstract HashingAlgorithm getAlgorithm();
}
private static class Sha256HashingService extends AbstractShaHashingService {
@Override
protected HashingAlgorithm getAlgorithm() {
return HashingAlgorithm.SHA256;
}
}
private static class Sha512HashingService extends AbstractShaHashingService {
@Override
protected HashingAlgorithm getAlgorithm() {
return HashingAlgorithm.SHA512;
}
}
}
| 2,810 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
EncodingAlgorithm.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/signing/algorithm/EncodingAlgorithm.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.impl.signing.algorithm;
import java.util.Base64;
public enum EncodingAlgorithm {
BASE64("BASE64", new Base64EncodingService());
private final String algorithmName;
private final EncodingService encodingService;
EncodingAlgorithm(String algorithmName, EncodingService encodingService) {
this.algorithmName = algorithmName;
this.encodingService = encodingService;
}
public String getAlgorithmName() {
return algorithmName;
}
public EncodingService getEncodingService() {
return encodingService;
}
public interface EncodingService {
String encode(byte[] data);
}
private static class Base64EncodingService implements EncodingService {
@Override
public String encode(byte[] data) {
return Base64.getEncoder().encodeToString(data);
}
}
}
| 1,733 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
SigningAlgorithm.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/signing/algorithm/SigningAlgorithm.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.impl.signing.algorithm;
import de.adorsys.xs2a.adapter.api.exception.HttpRequestSigningException;
import java.nio.charset.Charset;
import java.security.*;
public enum SigningAlgorithm {
SHA256_WITH_RSA("SHA256withRSA", new Sha256WithRsaSigningService());
private final String algorithmName;
private final SigningService signingService;
SigningAlgorithm(String algorithmName, SigningService signingService) {
this.algorithmName = algorithmName;
this.signingService = signingService;
}
public String getAlgorithmName() {
return algorithmName;
}
public SigningService getSigningService() {
return signingService;
}
public interface SigningService {
byte[] sign(PrivateKey privateKey, String data, Charset charset);
}
private static class Sha256WithRsaSigningService implements SigningService {
@Override
public byte[] sign(PrivateKey privateKey, String data, Charset charset) {
try {
Signature rsaSha256Signature = Signature.getInstance(getAlgorithm().getAlgorithmName());
rsaSha256Signature.initSign(privateKey);
rsaSha256Signature.update(data.getBytes(charset));
return rsaSha256Signature.sign();
} catch (SignatureException | InvalidKeyException | NoSuchAlgorithmException e) {
throw new HttpRequestSigningException("Exception during the signing algorithm"
+ getAlgorithm().getAlgorithmName() + " usage: " + e);
}
}
private SigningAlgorithm getAlgorithm() {
return SigningAlgorithm.SHA256_WITH_RSA;
}
}
}
| 2,559 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
JsonMapper.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/JsonMapper.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.impl.http;
import java.io.InputStream;
public interface JsonMapper {
String writeValueAsString(Object value);
<T> T readValue(InputStream inputStream, Class<T> klass);
<T> T readValue(String s, Class<T> klass);
<T> T convertValue(Object value, Class<T> klass);
}
| 1,146 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
UriBuilder.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/UriBuilder.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.impl.http;
import java.net.URI;
public abstract class UriBuilder {
public static UriBuilder fromUri(URI baseUri) {
return new ApacheUriBuilder(baseUri);
}
public static UriBuilder fromUri(String baseUri) {
return new ApacheUriBuilder(URI.create(baseUri));
}
public abstract UriBuilder queryParam(String name, String value);
public abstract UriBuilder renameQueryParam(String currentName, String newName);
public abstract URI build();
}
| 1,349 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
JacksonObjectMapper.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/JacksonObjectMapper.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.impl.http;
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 java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
public class JacksonObjectMapper implements JsonMapper {
private final ObjectMapper objectMapper;
public JacksonObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public JacksonObjectMapper() {
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.registerModule(new Psd2DateTimeModule());
}
@Override
public String writeValueAsString(Object value) {
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new UncheckedIOException(e);
}
}
@Override
public <T> T readValue(InputStream inputStream, Class<T> klass) {
try {
return objectMapper.readValue(inputStream, klass);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public <T> T readValue(String s, Class<T> klass) {
try {
return objectMapper.readValue(s, klass);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public <T> T convertValue(Object value, Class<T> klass) {
return objectMapper.convertValue(value, klass);
}
public ObjectMapper copyObjectMapper() {
return objectMapper.copy();
}
}
| 2,952 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
HttpHeaders.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/HttpHeaders.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.impl.http;
import org.apache.commons.lang3.StringEscapeUtils;
import java.util.*;
import static java.lang.String.CASE_INSENSITIVE_ORDER;
/**
* @see <a href="https://tools.ietf.org/html/rfc7230>rfc7230</a>
*/
final class HttpHeaders {
private static final String LF = "\n";
private final Map<String, List<String>> headers;
private HttpHeaders(Map<String, List<String>> headers) {
this.headers = headers;
}
static HttpHeaders parse(String headers) {
if (headers == null || headers.isEmpty()) {
return new HttpHeaders(Collections.emptyMap());
}
TreeMap<String, List<String>> headersMap = new TreeMap<>(CASE_INSENSITIVE_ORDER);
// HTTP-message = start-line *( header-field CRLF ) CRLF [ message-body ]
// The line terminator for message-header fields is the sequence CRLF.
// However, we recommend that applications, when parsing such headers,
// recognize a single LF as a line terminator and ignore the leading CR.
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.3
for (String header : headers.split(LF)) {
if (header.trim().isEmpty()) {
continue;
}
// header-field = field-name ":" OWS field-value OWS
// OWS - optional whitespace
String[] headerComponents = header.split(":");
if (headerComponents.length != 2) {
throw new IllegalArgumentException("Cannot parse \"" + escape(header) + "\" as a header");
}
String headerName = headerComponents[0];
String headerValue = headerComponents[1].trim();
headersMap.computeIfAbsent(headerName, k -> new ArrayList<>())
.add(headerValue);
}
return new HttpHeaders(Collections.unmodifiableMap(headersMap));
}
@SuppressWarnings("deprecated")
private static String escape(String s) {
return StringEscapeUtils.escapeJava(s);
}
public int size() {
return headers.size();
}
public Optional<String> getContentType() {
// https://tools.ietf.org/html/rfc7231#section-3.1.1.5
return getFirstValue("Content-Type");
}
private Optional<String> getFirstValue(String headerName) {
return headers.get(headerName).stream().findFirst();
}
public Optional<String> getContentDisposition() {
return getFirstValue("Content-Disposition");
}
}
| 3,350 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Psd2DateTimeModule.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/Psd2DateTimeModule.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.impl.http;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.time.OffsetDateTime;
public class Psd2DateTimeModule extends SimpleModule {
public Psd2DateTimeModule() {
addDeserializer(OffsetDateTime.class, new Psd2DateTimeDeserializer());
}
}
| 1,144 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
HttpClientException.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/HttpClientException.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.impl.http;
public class HttpClientException extends RuntimeException {
public HttpClientException() {
}
public HttpClientException(String message) {
super(message);
}
public HttpClientException(Throwable cause) {
super(cause);
}
}
| 1,136 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AbstractHttpClient.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/AbstractHttpClient.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.impl.http;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.Request;
public abstract class AbstractHttpClient implements HttpClient {
protected static final String GET = "GET";
protected static final String POST = "POST";
protected static final String PUT = "PUT";
protected static final String DELETE = "DELETE";
@Override
public Request.Builder get(String uri) {
return new RequestBuilderImpl(this, GET, uri);
}
@Override
public Request.Builder post(String uri) {
return new RequestBuilderImpl(this, POST, uri);
}
@Override
public Request.Builder put(String uri) {
return new RequestBuilderImpl(this, PUT, uri);
}
@Override
public Request.Builder delete(String uri) {
return new RequestBuilderImpl(this, DELETE, uri);
}
}
| 1,731 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
RequestBuilderImpl.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/RequestBuilderImpl.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.impl.http;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.Interceptor;
import de.adorsys.xs2a.adapter.api.http.Request;
import java.util.*;
import static java.lang.String.CASE_INSENSITIVE_ORDER;
public class RequestBuilderImpl implements Request.Builder {
private final HttpClient httpClient;
private String method;
private String uri;
private Map<String, String> headers = new TreeMap<>(CASE_INSENSITIVE_ORDER);
private String body;
private BodyType bodyType;
private Map<String, String> formData;
private Map<String, String> xmlParts;
private Map<String, String> jsonParts;
private Map<String, String> plainTextParts;
private enum BodyType {
JSON, EMPTY_JSON, XML, MULTIPART
}
public RequestBuilderImpl(HttpClient httpClient, String method, String uri) {
this.httpClient = httpClient;
this.method = method;
this.uri = uri;
}
@Override
public String method() {
return method;
}
@Override
public String uri() {
return uri;
}
public Request.Builder uri(String uri) {
this.uri = uri;
return this;
}
@Override
public Request.Builder headers(Map<String, String> headers) {
this.headers = headers;
return this;
}
@Override
public Map<String, String> headers() {
return headers;
}
@Override
public Request.Builder header(String name, String value) {
if (name != null && value != null) {
headers.put(name, value);
}
return this;
}
@Override
public Request.Builder jsonBody(String body) {
this.body = body;
bodyType = BodyType.JSON;
return this;
}
@Override
public boolean jsonBody() {
return bodyType == BodyType.JSON;
}
@Override
public Request.Builder xmlBody(String body) {
this.body = body;
bodyType = BodyType.XML;
return this;
}
@Override
public boolean xmlBody() {
return bodyType == BodyType.XML;
}
@Override
public Request.Builder addXmlPart(String name, String xmlPart) {
if (xmlParts == null) {
xmlParts = new LinkedHashMap<>();
}
xmlParts.put(name, xmlPart);
bodyType = BodyType.MULTIPART;
return this;
}
@Override
public Map<String, String> xmlParts() {
if (xmlParts == null) {
return Collections.emptyMap();
}
return xmlParts;
}
@Override
public Request.Builder addJsonPart(String name, String jsonPart) {
if (jsonParts == null) {
jsonParts = new LinkedHashMap<>();
}
jsonParts.put(name, jsonPart);
bodyType = BodyType.MULTIPART;
return this;
}
@Override
public Map<String, String> jsonParts() {
if (jsonParts == null) {
return Collections.emptyMap();
}
return jsonParts;
}
@Override
public Request.Builder addPlainTextPart(String name, Object part) {
if (plainTextParts == null) {
plainTextParts = new LinkedHashMap<>();
}
if (part != null) {
plainTextParts.put(name, part.toString());
bodyType = BodyType.MULTIPART;
}
return this;
}
@Override
public Map<String, String> plainTextParts() {
if (plainTextParts == null) {
return Collections.emptyMap();
}
return plainTextParts;
}
@Override
public boolean multipartBody() {
return bodyType == BodyType.MULTIPART;
}
@Override
public String body() {
return body;
}
@Override
public Request.Builder emptyBody(boolean emptyBody) {
if (emptyBody) {
bodyType = BodyType.EMPTY_JSON;
} else {
bodyType = null;
}
return this;
}
@Override
public boolean emptyBody() {
return bodyType == BodyType.EMPTY_JSON;
}
@Override
public Request.Builder urlEncodedBody(Map<String, String> formData) {
this.formData = formData;
return this;
}
@Override
public Map<String, String> urlEncodedBody() {
return formData;
}
@Override
public <T> Response<T> send(HttpClient.ResponseHandler<T> responseHandler, List<Interceptor> interceptors) {
for (Interceptor interceptor : interceptors) {
if (interceptor != null) {
interceptor.preHandle(this);
}
}
Response<T> response = httpClient.send(this, responseHandler);
for (Interceptor interceptor : interceptors) {
if (interceptor != null) {
response = interceptor.postHandle(this, response);
}
}
return response;
}
@Override
public String content() {
return httpClient.content(this);
}
}
| 5,902 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ApacheHttpClientFactory.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/ApacheHttpClientFactory.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.impl.http;
import de.adorsys.xs2a.adapter.api.exception.Xs2aAdapterException;
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 org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.security.GeneralSecurityException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class ApacheHttpClientFactory implements HttpClientFactory {
private final HttpClientBuilder httpClientBuilder;
private final ConcurrentMap<String, HttpClient> cache = new ConcurrentHashMap<>();
private final HttpClientConfig clientConfig;
public ApacheHttpClientFactory(HttpClientBuilder httpClientBuilder, HttpClientConfig clientConfig) {
this.httpClientBuilder = httpClientBuilder;
this.clientConfig = clientConfig;
}
@Override
public HttpClient getHttpClient(String adapterId, String qwacAlias, String[] supportedCipherSuites) {
return cache.computeIfAbsent(adapterId, key -> createHttpClient(qwacAlias, supportedCipherSuites));
}
@Override
public HttpClientConfig getHttpClientConfig() {
return clientConfig;
}
private HttpClient createHttpClient(String qwacAlias, String[] supportedCipherSuites) {
synchronized (this) {
CloseableHttpClient httpClient;
SSLContext sslContext = getSslContext(qwacAlias);
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
SSLConnectionSocketFactory sslSocketFactory =
new SSLConnectionSocketFactory(socketFactory, null, supportedCipherSuites, (HostnameVerifier) null);
httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
httpClient = httpClientBuilder.build();
return new ApacheHttpClient(clientConfig.getLogSanitizer(), httpClient);
}
}
private SSLContext getSslContext(String qwacAlias) {
try {
return clientConfig.getKeyStore().getSslContext(qwacAlias);
} catch (GeneralSecurityException e) {
throw new Xs2aAdapterException(e);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
| 3,437 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ResponseHandlers.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/ResponseHandlers.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.impl.http;
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.NotAcceptableException;
import de.adorsys.xs2a.adapter.api.exception.OAuthException;
import de.adorsys.xs2a.adapter.api.exception.Xs2aAdapterException;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer;
import de.adorsys.xs2a.adapter.api.model.ErrorResponse;
import de.adorsys.xs2a.adapter.api.model.HrefType;
import de.adorsys.xs2a.adapter.api.model.TppMessage;
import de.adorsys.xs2a.adapter.api.model.TppMessageCategory;
import org.apache.commons.fileupload.MultipartStream;
import org.apache.commons.fileupload.ParameterParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static de.adorsys.xs2a.adapter.api.http.ContentType.*;
public class ResponseHandlers {
private static final Pattern CHARSET_PATTERN = Pattern.compile("charset=([^;]+)");
private static final ErrorResponse EMPTY_ERROR_RESPONSE = new ErrorResponse();
private static final HttpLogSanitizer DEFAULT_LOG_SANITIZER = new Xs2aHttpLogSanitizer();
private static final JsonMapper jsonMapper = new JacksonObjectMapper();
private static final Logger log = LoggerFactory.getLogger(ResponseHandlers.class);
private final HttpLogSanitizer logSanitizer;
public ResponseHandlers(HttpLogSanitizer logSanitizer) {
this.logSanitizer = getOrDefaultLogSanitizer(logSanitizer);
}
public ResponseHandlers() {
this(null);
}
private HttpLogSanitizer getOrDefaultLogSanitizer(HttpLogSanitizer logSanitizer) {
return Optional.ofNullable(logSanitizer).orElse(DEFAULT_LOG_SANITIZER);
}
public <T> HttpClient.ResponseHandler<T> jsonResponseHandler(Class<T> klass) {
return (statusCode, responseBody, responseHeaders) -> {
if (statusCode == 204) {
return null;
}
PushbackInputStream pushbackResponseBody = new PushbackInputStream(responseBody);
String contentType = responseHeaders.getHeader(RequestHeaders.CONTENT_TYPE);
if (statusCode >= 400) {
// this statement is needed as error response handling is different from the successful response
if ((contentType == null || !contentType.startsWith(APPLICATION_JSON)) && isNotJson(pushbackResponseBody)) {
throw responseException(statusCode, pushbackResponseBody, responseHeaders,
ResponseHandlers::buildEmptyErrorResponse);
}
throw responseException(statusCode, pushbackResponseBody, responseHeaders,
ResponseHandlers::buildErrorResponseFromString);
}
if (contentType != null && !contentType.startsWith(APPLICATION_JSON)) {
throw new NotAcceptableException(String.format(
"Content type %s is not acceptable, has to start with %s", contentType, APPLICATION_JSON));
}
switch (statusCode) {
case 200:
case 201:
case 202:
return jsonMapper.readValue(responseBody, klass);
default:
throw responseException(statusCode, pushbackResponseBody, responseHeaders,
ResponseHandlers::buildErrorResponseFromString);
}
};
}
public <T> HttpClient.ResponseHandler<T> paymentInitiationResponseHandler(String scaOAuthUrl, Class<T> klass) {
return consentCreationResponseHandler(scaOAuthUrl, klass);
}
public <T> HttpClient.ResponseHandler<T> consentCreationResponseHandler(String scaOAuthUrl, Class<T> klass) {
return (statusCode, responseBody, responseHeaders) -> {
if (statusCode == 401 || statusCode == 403) {
String contentType = responseHeaders.getHeader(RequestHeaders.CONTENT_TYPE);
PushbackInputStream pushbackResponseBody = new PushbackInputStream(responseBody);
// this statement is needed as error response handling is different from the successful response
if ((contentType == null || !contentType.startsWith(APPLICATION_JSON)) && isNotJson(pushbackResponseBody)) {
// needed to avoid org.springframework.http.converter.HttpMessageNotWritableException:
// No converter for [class de.adorsys.xs2a.adapter.api.model.ErrorResponse]
// with preset Content-Type 'application/xml;charset=UTF-8'
Map<String, String> headersMap = responseHeaders.getHeadersMap();
headersMap.put(ResponseHeaders.CONTENT_TYPE, APPLICATION_JSON);
throw oAuthException(pushbackResponseBody, ResponseHeaders.fromMap(headersMap), scaOAuthUrl,
ResponseHandlers::buildErrorResponseForOAuthNonJsonCase);
}
throw oAuthException(pushbackResponseBody, responseHeaders, scaOAuthUrl,
ResponseHandlers::buildErrorResponseFromString);
}
return jsonResponseHandler(klass)
.apply(statusCode, responseBody, responseHeaders);
};
}
private OAuthException oAuthException(PushbackInputStream responseBody,
ResponseHeaders responseHeaders,
String scaOAuthUrl,
Function<String, ErrorResponse> errorResponseBuilder) {
ErrorResponse errorResponse;
String originalResponse = null;
if (isEmpty(responseBody)) {
errorResponse = new ErrorResponse();
} else {
originalResponse = toString(responseBody, responseHeaders);
originalResponse = logSanitizer.sanitize(originalResponse);
errorResponse = errorResponseBuilder.apply(originalResponse);
}
if (scaOAuthUrl != null) {
HrefType scaOAuth = new HrefType();
scaOAuth.setHref(scaOAuthUrl);
Map<String, HrefType> links = Collections.singletonMap("scaOAuth", scaOAuth);
errorResponse.setLinks(links);
}
return new OAuthException(responseHeaders, errorResponse, originalResponse);
}
private boolean isNotJson(PushbackInputStream responseBody) {
try {
int data = responseBody.read();
responseBody.unread(data);
if (data != -1) {
char firstChar = (char) data;
// There are only 2 possible char options here: '{' (JSON) and '<' (XML and HTML).
// ASCII code of '{' is 123 and ASCII code of '<' is 66,
// so the scope of the byte is enough for this purpose.
return firstChar != '{';
}
return true;
} catch (IOException e) {
return true;
}
}
private ErrorResponseException responseException(int statusCode,
PushbackInputStream responseBody,
ResponseHeaders responseHeaders,
Function<String, ErrorResponse> errorResponseBuilder) {
if (isEmpty(responseBody)) {
return new ErrorResponseException(statusCode, responseHeaders);
}
String originalResponse = toString(responseBody, responseHeaders);
originalResponse = logSanitizer.sanitize(originalResponse);
ErrorResponse errorResponse = errorResponseBuilder.apply(originalResponse);
return new ErrorResponseException(statusCode, responseHeaders, errorResponse, originalResponse);
}
private static ErrorResponse buildErrorResponseFromString(String originalResponse) {
return jsonMapper.readValue(originalResponse, ErrorResponse.class);
}
private static ErrorResponse buildEmptyErrorResponse(String originalResponse) {
return EMPTY_ERROR_RESPONSE;
}
private static ErrorResponse buildErrorResponseForOAuthNonJsonCase(String originalResponse) {
ErrorResponse errorResponse = new ErrorResponse();
TppMessage tppMessage = new TppMessage();
tppMessage.setCategory(TppMessageCategory.ERROR);
tppMessage.setText(originalResponse);
errorResponse.setTppMessages(Collections.singletonList(tppMessage));
return errorResponse;
}
private boolean isEmpty(PushbackInputStream responseBody) {
try {
int nextByte = responseBody.read();
if (nextByte == -1) {
return true;
}
responseBody.unread(nextByte);
return false;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public HttpClient.ResponseHandler<String> stringResponseHandler() {
return (statusCode, responseBody, responseHeaders) -> {
if (statusCode == 200) {
return toString(responseBody, responseHeaders);
}
throw responseException(statusCode, new PushbackInputStream(responseBody), responseHeaders,
ResponseHandlers::buildEmptyErrorResponse);
};
}
public HttpClient.ResponseHandler<byte[]> byteArrayResponseHandler() {
return (statusCode, responseBody, responseHeaders) -> {
switch (statusCode) {
case 200:
case 201:
case 202:
case 204:
return toByteArray(responseBody);
default:
throw responseException(statusCode, new PushbackInputStream(responseBody), responseHeaders,
ResponseHandlers::buildEmptyErrorResponse);
}
};
}
private String toString(InputStream responseBody, ResponseHeaders responseHeaders) {
String charset = StandardCharsets.UTF_8.name();
String contentType = responseHeaders.getHeader(RequestHeaders.CONTENT_TYPE);
if (contentType != null) {
Matcher matcher = CHARSET_PATTERN.matcher(contentType);
if (matcher.find()) {
charset = matcher.group(1);
}
}
log.debug("{} charset will be used for response body parsing", charset);
try {
return readResponseBodyAsByteArrayOutputStream(responseBody)
.toString(charset);
} catch (UnsupportedEncodingException e) {
throw new UncheckedIOException(e);
}
}
private byte[] toByteArray(InputStream responseBody) {
return readResponseBodyAsByteArrayOutputStream(responseBody)
.toByteArray();
}
private ByteArrayOutputStream readResponseBodyAsByteArrayOutputStream(InputStream responseBody) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int length;
while ((length = responseBody.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public <T> HttpClient.ResponseHandler<T> multipartFormDataResponseHandler(Class<T> bodyClass) {
return (statusCode, responseBody, responseHeaders) -> {
if (statusCode != 200) {
throw responseException(statusCode,
new PushbackInputStream(responseBody),
responseHeaders,
ResponseHandlers::buildErrorResponseFromString);
}
try {
return parseResponseIntoObject(bodyClass, responseBody, responseHeaders);
} catch (ReflectiveOperationException | IntrospectionException e) {
throw new Xs2aAdapterException(e);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
protected <T> T parseResponseIntoObject(Class<T> bodyClass,
InputStream responseBody,
ResponseHeaders responseHeaders)
throws ReflectiveOperationException, IOException, IntrospectionException {
T bodyInstance = bodyClass.getDeclaredConstructor().newInstance();
String contentType = responseHeaders.getHeader(RequestHeaders.CONTENT_TYPE);
if (contentType == null || !contentType.startsWith(MULTIPART_FORM_DATA)) {
throw new HttpClientException("Unexpected content type: " + contentType);
}
ParameterParser parser = new ParameterParser();
Map<String, String> params = parser.parse(contentType, new char[] {';', ','});
String boundary = params.get("boundary");
if (boundary == null) {
throw new HttpClientException("Failed to parse boundary from the Content-Type header");
}
MultipartStream multipartStream = new MultipartStream(responseBody, boundary.getBytes());
boolean nextPart = multipartStream.skipPreamble();
while (nextPart) {
HttpHeaders headers = HttpHeaders.parse(multipartStream.readHeaders());
String partContentType = headers.getContentType()
.orElseThrow(() -> new HttpClientException("Body part has unspecified content type"));
String partContentDisposition = headers.getContentDisposition()
.orElseThrow(() -> new HttpClientException("Body part has unspecified content disposition"));
String partName = parser.parse(partContentDisposition, ';').get("name");
if (partName == null) {
throw new HttpClientException("Body part has unspecified name");
}
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(partName, bodyClass);
ByteArrayOutputStream out = new ByteArrayOutputStream();
multipartStream.readBodyData(out);
if (partContentType.startsWith(APPLICATION_XML)) {
propertyDescriptor.getWriteMethod().invoke(bodyInstance, out.toString());
} else if (partContentType.startsWith(APPLICATION_JSON)) {
Class<?> propertyType = propertyDescriptor.getPropertyType();
Object json = jsonMapper.readValue(new ByteArrayInputStream(out.toByteArray()), propertyType);
propertyDescriptor.getWriteMethod().invoke(bodyInstance, json);
} else {
Class<?> propertyType = propertyDescriptor.getPropertyType();
Object json = jsonMapper.convertValue(out.toString(), propertyType);
propertyDescriptor.getWriteMethod().invoke(bodyInstance, json);
}
nextPart = multipartStream.readBoundary();
}
return bodyInstance;
}
}
| 16,406 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ApacheHttpClient.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/ApacheHttpClient.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.impl.http;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer;
import de.adorsys.xs2a.adapter.api.http.Request;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.io.EmptyInputStream;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;
public class ApacheHttpClient extends AbstractHttpClient {
private static final Logger logger = LoggerFactory.getLogger(ApacheHttpClient.class);
private static final HttpLogSanitizer DEFAULT_LOG_SANITIZER = new Xs2aHttpLogSanitizer();
private final HttpLogSanitizer logSanitizer;
private final CloseableHttpClient httpClient;
public ApacheHttpClient(HttpLogSanitizer logSanitizer, CloseableHttpClient httpClient) {
this.logSanitizer = getOrDefaultLogSanitizer(logSanitizer);
this.httpClient = httpClient;
}
private HttpLogSanitizer getOrDefaultLogSanitizer(HttpLogSanitizer logSanitizer) {
return Optional.ofNullable(logSanitizer).orElse(DEFAULT_LOG_SANITIZER);
}
@Override
public <T> Response<T> send(Request.Builder requestBuilder, ResponseHandler<T> responseHandler) {
return execute(createRequest(requestBuilder), requestBuilder.headers(), responseHandler);
}
private HttpUriRequest createRequest(Request.Builder requestBuilder) {
switch (requestBuilder.method()) {
case GET:
return new HttpGet(requestBuilder.uri());
case POST:
HttpPost post = new HttpPost(requestBuilder.uri());
if (requestBuilder.jsonBody()) {
post.setEntity(new StringEntity(requestBuilder.body(), ContentType.APPLICATION_JSON));
} else if (requestBuilder.xmlBody()) {
post.setEntity(new StringEntity(requestBuilder.body(), ContentType.APPLICATION_XML));
} else if (requestBuilder.emptyBody()) {
post.setEntity(new StringEntity("{}", ContentType.APPLICATION_JSON));
} else if (requestBuilder.urlEncodedBody() != null) {
List<NameValuePair> list = requestBuilder.urlEncodedBody().entrySet().stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
try {
post.setEntity(new UrlEncodedFormEntity(list));
} catch (UnsupportedEncodingException e) {
throw new UncheckedIOException(e);
}
} else if (requestBuilder.multipartBody()) {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
// static boundary for equal requests in send and content methods
.setBoundary("KfIPVSuloXL9RBOp_4z784vc73PWKzOrr6Ps");
requestBuilder.xmlParts().forEach((name, value) ->
multipartEntityBuilder.addPart(name, new StringBody(value, ContentType.APPLICATION_XML)));
requestBuilder.jsonParts().forEach((name, value) ->
multipartEntityBuilder.addPart(name, new StringBody(value, ContentType.APPLICATION_JSON)));
requestBuilder.plainTextParts().forEach((name, value) ->
multipartEntityBuilder.addPart(name, new StringBody(value, ContentType.TEXT_PLAIN)));
post.setEntity(multipartEntityBuilder.build());
}
return post;
case PUT:
HttpPut put = new HttpPut(requestBuilder.uri());
if (requestBuilder.jsonBody()) {
put.setEntity(new StringEntity(requestBuilder.body(), ContentType.APPLICATION_JSON));
}
return put;
case DELETE:
return new HttpDelete(requestBuilder.uri());
default:
throw new UnsupportedOperationException(requestBuilder.method());
}
}
@Override
public String content(Request.Builder requestBuilder) {
return getContent(createRequest(requestBuilder));
}
private String getContent(HttpUriRequest request) {
Optional<HttpEntity> requestEntity = getRequestEntity(request);
try {
return requestEntity.isPresent() ? EntityUtils.toString(requestEntity.get()) : "";
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private Optional<HttpEntity> getRequestEntity(HttpUriRequest request) {
HttpEntity entity = null;
if (request instanceof HttpEntityEnclosingRequest) {
entity = ((HttpEntityEnclosingRequest) request).getEntity();
}
return Optional.ofNullable(entity);
}
private <T> Response<T> execute(
HttpUriRequest request,
Map<String, String> headers,
ResponseHandler<T> responseHandler
) {
headers.forEach(request::addHeader);
logRequest(request, headers);
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
Map<String, String> responseHeadersMap = toHeadersMap(response.getAllHeaders());
ResponseHeaders responseHeaders = ResponseHeaders.fromMap(responseHeadersMap);
InputStream content = entity != null ? entity.getContent() : EmptyInputStream.INSTANCE;
T responseBody = responseHandler.apply(statusCode, content, responseHeaders);
logResponse(responseBody, response, responseHeadersMap);
return new Response<>(statusCode, responseBody, responseHeaders);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private <T> void logResponse(T responseBody, CloseableHttpResponse response, Map<String, String> headers) {
StringBuilder responseLogs = new StringBuilder("\n");
String direction = "\t<--";
responseLogs.append(logHttpEvent(headers, response.getStatusLine().toString(), direction));
HttpEntity entity = response.getEntity();
String contentType = entity != null && entity.getContentType() != null ? entity.getContentType().getValue() : "";
String sanitizedResponseBody = logSanitizer.sanitizeResponseBody(responseBody, contentType);
responseLogs.append(String.format("%s Response body [%s]: %s%n", direction, contentType, sanitizedResponseBody));
responseLogs.append(direction);
logger.debug("{}", responseLogs);
}
private void logRequest(HttpUriRequest request, Map<String, String> headers) {
StringBuilder requestLogs = new StringBuilder("\n");
String direction = "\t-->";
requestLogs.append(logHttpEvent(headers, request.getRequestLine().toString(), direction));
Optional<HttpEntity> requestEntityOptional = getRequestEntity(request);
if (requestEntityOptional.isPresent()) {
HttpEntity entity = requestEntityOptional.get();
String contentType = entity.getContentType() != null ? entity.getContentType().getValue() : "";
String sanitizedResponseBody = logSanitizer.sanitizeRequestBody(entity, contentType);
requestLogs.append(String.format("%s Request body [%s]: %s%n", direction, contentType, sanitizedResponseBody));
requestLogs.append(direction);
}
logger.debug("{}", requestLogs);
}
private StringBuilder logHttpEvent(Map<String, String> headers, String httpLine, String direction) {
StringBuilder logs = new StringBuilder();
logs.append(String.format("%s %s%n", direction, logSanitizer.sanitize(httpLine)));
headers.forEach((key, value) -> logs.append(String.format("%s %s: %s%n", direction, key, logSanitizer.sanitizeHeader(key, value))));
logs.append(direction).append("\n");
return logs;
}
private Map<String, String> toHeadersMap(Header[] headers) {
if (Objects.isNull(headers)) {
return new HashMap<>();
}
// Don't override this to Stream API until staying on JDK 8, as JDK 8 has an issue for such a case
// https://stackoverflow.com/questions/40039649/why-does-collectors-tomap-report-value-instead-of-key-on-duplicate-key-error
Map<String, String> headersMap = new HashMap<>();
for (Header header : headers) {
headersMap.put(header.getName(), header.getValue());
}
return headersMap;
}
}
| 10,344 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
RequestSigningInterceptor.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/RequestSigningInterceptor.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.impl.http;
import de.adorsys.xs2a.adapter.api.Pkcs12KeyStore;
import de.adorsys.xs2a.adapter.api.http.Interceptor;
import de.adorsys.xs2a.adapter.api.http.Request;
import de.adorsys.xs2a.adapter.impl.signing.RequestSigningService;
import de.adorsys.xs2a.adapter.impl.signing.header.Digest;
import de.adorsys.xs2a.adapter.impl.signing.header.Signature;
import de.adorsys.xs2a.adapter.impl.signing.header.TppSignatureCertificate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static de.adorsys.xs2a.adapter.api.RequestHeaders.*;
public class RequestSigningInterceptor implements Interceptor {
// according to BG spec 1.3 (chapter 12.2)
// since BG spec 1.3.4 Date is not a mandatory field. A place for refactoring.
private static final List<String> SIGNATURE_HEADERS
= Arrays.asList(DIGEST, X_REQUEST_ID, PSU_ID, PSU_CORPORATE_ID, DATE, TPP_REDIRECT_URI);
private final RequestSigningService requestSigningService;
public RequestSigningInterceptor(Pkcs12KeyStore keyStore) {
requestSigningService = new RequestSigningService(keyStore);
}
@Override
public Request.Builder preHandle(Request.Builder requestBuilder) {
// Digest header computing and adding MUST BE BEFORE the Signature header, as Digest is used in Signature header computation
populateDigest(requestBuilder);
populateSignature(requestBuilder);
populateTppSignatureCertificate(requestBuilder);
return requestBuilder;
}
private void populateDigest(Request.Builder requestBuilder) {
String requestBody = requestBuilder.content();
if (requestBody == null) {
requestBody = "";
}
Digest digest = requestSigningService.buildDigest(requestBody);
requestBuilder.header(digest.getHeaderName(), digest.getHeaderValue());
}
private void populateSignature(Request.Builder requestBuilder) {
Map<String, String> headersMap = requestBuilder.headers().entrySet().stream()
.filter(e -> SIGNATURE_HEADERS.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Signature signature = requestSigningService.buildSignature(headersMap);
requestBuilder.header(signature.getHeaderName(), signature.getHeaderValue());
}
private void populateTppSignatureCertificate(Request.Builder requestBuilder) {
TppSignatureCertificate tppSignatureCertificate = requestSigningService.buildTppSignatureCertificate();
requestBuilder.header(tppSignatureCertificate.getHeaderName(), tppSignatureCertificate.getHeaderValue());
}
}
| 3,623 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ApacheUriBuilder.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/ApacheUriBuilder.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.impl.http;
import de.adorsys.xs2a.adapter.api.exception.Xs2aAdapterException;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
// intentionally package private
class ApacheUriBuilder extends UriBuilder {
private final URIBuilder uriBuilder;
ApacheUriBuilder(URI baseUri) {
uriBuilder = new URIBuilder(baseUri);
}
@Override
public UriBuilder queryParam(String name, String value) {
if (name != null && value != null) {
uriBuilder.setParameter(name, value);
}
return this;
}
@Override
public UriBuilder renameQueryParam(String currentName, String newName) {
List<NameValuePair> queryParams = uriBuilder.getQueryParams();
uriBuilder.removeQuery();
for (NameValuePair queryParam : queryParams) {
if (queryParam.getName().equals(currentName)) {
uriBuilder.addParameter(newName, queryParam.getValue());
} else {
uriBuilder.addParameter(queryParam.getName(), queryParam.getValue());
}
}
return this;
}
@Override
public URI build() {
try {
return uriBuilder.build();
} catch (URISyntaxException e) {
throw new Xs2aAdapterException(e);
}
}
}
| 2,268 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
BaseHttpClientConfig.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/BaseHttpClientConfig.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.impl.http;
import de.adorsys.xs2a.adapter.api.Pkcs12KeyStore;
import de.adorsys.xs2a.adapter.api.http.HttpClientConfig;
import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer;
public class BaseHttpClientConfig implements HttpClientConfig {
private final HttpLogSanitizer logSanitizer;
private final Pkcs12KeyStore keyStore;
private final String wiremockStandaloneUrl;
public BaseHttpClientConfig(HttpLogSanitizer logSanitizer, Pkcs12KeyStore keyStore,
String wiremockStandaloneUrl) {
this.logSanitizer = logSanitizer;
this.keyStore = keyStore;
this.wiremockStandaloneUrl = wiremockStandaloneUrl;
}
@Override
public HttpLogSanitizer getLogSanitizer() {
return logSanitizer;
}
@Override
public Pkcs12KeyStore getKeyStore() {
return keyStore;
}
public String getWiremockStandaloneUrl() {
return wiremockStandaloneUrl;
}
}
| 1,822 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
StringUri.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/StringUri.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.impl.http;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class StringUri {
private static final Pattern VERSION_PATTERN = Pattern.compile("\\bv\\d+");
private static final String SPACE = " ";
private static final String ENCODED_SPACE = "%20";
private StringUri() {
}
public static String fromElements(Object... elements) {
return Arrays.stream(elements)
.map(String::valueOf)
.map(StringUri::trimUri)
.map(StringUri::formatUri)
.collect(Collectors.joining("/"));
}
private static String trimUri(String str) {
if (str == null || str.isEmpty()) {
return "";
}
str = str.startsWith("/") ? str.substring(1) : str;
return str.endsWith("/") ? str.substring(0, str.length() - 1) : str;
}
public static String withQuery(String uri, Map<String, ?> requestParams) {
if (requestParams.isEmpty()) {
return uri;
}
String requestParamsString = requestParams.entrySet().stream()
.filter(entry -> entry.getKey() != null && entry.getValue() != null)
.map(entry -> entry.getKey() + "=" + encode(entry.getValue().toString()))
.collect(Collectors.joining("&"));
if (requestParamsString.isEmpty()) {
return uri;
}
return uri + "?" + requestParamsString;
}
public static String withQuery(String uri, String paramName, String paramValue) {
if (paramName == null || paramName.isEmpty()
|| paramValue == null || paramValue.isEmpty()) {
return uri;
}
return uri + "?" + paramName + "=" + encode(paramValue);
}
public static Map<String, String> getQueryParamsFromUri(String uri) {
Map<String, String> queryParams = new HashMap<>();
if (!uri.contains("?")) {
return queryParams;
}
String paramsString = uri.split("\\?")[1];
String[] paramsWithValues = paramsString.split("&");
for (String paramWithValueString : paramsWithValues) {
String[] paramAndValue = paramWithValueString.split("=", 2);
queryParams.put(paramAndValue[0], paramAndValue.length > 1 ? decode(paramAndValue[1]) : null);
}
return queryParams;
}
public static String decode(String url) {
try {
return URLDecoder.decode(url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("The Character Encoding is not supported", e);
}
}
private static String encode(String param) {
try {
return URLEncoder.encode(param, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("The Character Encoding is not supported", e);
}
}
private static String formatUri(String uri) {
return uri.replace(SPACE, ENCODED_SPACE);
}
public static boolean isUri(String stringToCheck) {
return stringToCheck.startsWith("/") || startsWithVersion(stringToCheck);
}
private static boolean startsWithVersion(String stringToCheck) {
return VERSION_PATTERN.matcher(stringToCheck.split("/")[0]).find();
}
public static boolean containsProtocol(String urlToCheck) {
return urlToCheck.contains("://");
}
public static boolean containsQueryParam(String uri, String paramName) {
return getQueryParamsFromUri(uri)
.containsKey(paramName);
}
public static String appendQueryParam(String uri, String paramName, String paramValue) {
Map<String, String> params = getQueryParamsFromUri(uri);
params.put(paramName, paramValue);
return withQuery(removeAllQueryParams(uri), params);
}
public static String removeAllQueryParams(String uri) {
return uri.split("\\?")[0];
}
public static Optional<String> getVersion(String uri) {
Matcher matcher = VERSION_PATTERN.matcher(uri);
if (matcher.find()) {
return Optional.of(matcher.group(0));
}
return Optional.empty();
}
public static String copyQueryParams(String sourceUri, String targetUri) {
if (!containsQueryParams(sourceUri)) {
return targetUri;
}
return targetUri + (containsQueryParams(targetUri) ? "&" : "?") + sourceUri.split("\\?")[1];
}
private static boolean containsQueryParams(String uri) {
return uri.split("\\?").length > 1;
}
}
| 5,788 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Psd2DateTimeDeserializer.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/Psd2DateTimeDeserializer.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.impl.http;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
public class Psd2DateTimeDeserializer extends JsonDeserializer<OffsetDateTime> {
private DateTimeFormatter psd2Formatter = new DateTimeFormatterBuilder()
// date/time
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
// offset (hh:mm - "+00:00" when it's zero)
.optionalStart().appendOffset("+HH:MM", "+00:00").optionalEnd()
// offset (hhmm - "+0000" when it's zero)
.optionalStart().appendOffset("+HHMM", "+0000").optionalEnd()
// offset (hh - "Z" when it's zero)
.optionalStart().appendOffset("+HH", "Z").optionalEnd()
// create formatter
.toFormatter();
@Override
public OffsetDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
String text = parser.getText();
if (text == null || text.isEmpty()) {
return null;
}
return OffsetDateTime.parse(text, psd2Formatter);
}
}
| 2,627 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Xs2aHttpLogSanitizer.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/Xs2aHttpLogSanitizer.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.impl.http;
import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Xs2aHttpLogSanitizer implements HttpLogSanitizer {
private static final Logger logger = LoggerFactory.getLogger(Xs2aHttpLogSanitizer.class);
private static final String APPLICATION_JSON = "application/json";
static final String REPLACEMENT = "******";
private final Set<String> sanitizeHeaders = new HashSet<>();
private final Set<String> nonSanitizedBodyProperties = new HashSet<>();
private final List<Pattern> patterns = new ArrayList<>();
private final JsonMapper objectMapper = new JacksonObjectMapper();
/**
* @param whitelist is a list of request/response body fields that a client wants to be unveiled in logs.
* Empty list may be passed. Field names must conform Berlin Group specification and written
* in camelCase, otherwise it will have no effect and Xs2aHttpLogSanitizer will still mask values.
*/
public Xs2aHttpLogSanitizer(List<String> whitelist) {
this();
if (whitelist != null) {
nonSanitizedBodyProperties.addAll(whitelist);
}
}
public Xs2aHttpLogSanitizer() {
patterns.add(Pattern.compile("(consents|accounts|authorisations|credit-transfers|target-2-payments)/[^/?\\s\\[\"]+(.*?)"));
// To tackle DKB errors and Commerzbank Authorization URIs
patterns.add(Pattern.compile("([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})"));
List<String> headers = toLowerCase(Arrays.asList(
"Authorization",
"PSU-ID",
"PSU-Corporate-ID",
"Consent-ID",
"X-GTW-IBAN",
"Location",
"Signature",
"TPP-Signature-Certificate",
"Digest",
"X-dynatrace-Origin-URL", // Unicredit header
"PSD2-AUTHORIZATION"));
sanitizeHeaders.addAll(headers);
}
private List<String> toLowerCase(List<String> list) {
return list.stream()
.map(String::toLowerCase)
.collect(Collectors.toList());
}
public String sanitizeHeader(String name, String value) {
if (sanitizeHeaders.contains(name.toLowerCase())) {
return REPLACEMENT;
}
return value;
}
public String sanitize(String data) {
String replacedData = data;
for (Pattern pattern : patterns) {
Matcher matcher = pattern.matcher(replacedData);
var groupCount = matcher.groupCount();
if (matcher.find()) {
if (2 == groupCount) {
replacedData = matcher.replaceAll("$1/" + REPLACEMENT + "$2");
} else if (1 == groupCount) {
replacedData = matcher.replaceAll(REPLACEMENT);
}
}
}
return replacedData;
}
public String sanitizeRequestBody(Object httpEntity, String contentType) {
if (contentType.startsWith(APPLICATION_JSON)) {
try {
return sanitizeStringifiedJsonBody(EntityUtils.toString((HttpEntity) httpEntity));
} catch (Exception e) {
logger.error("Can't parse request as json. It will be replaced with {}", REPLACEMENT);
}
}
return REPLACEMENT;
}
public String sanitizeResponseBody(Object responseBody, String contentType) {
if (contentType.startsWith(APPLICATION_JSON)) {
try {
String json;
if (responseBody instanceof String) {
json = (String) responseBody;
} else {
json = objectMapper.writeValueAsString(responseBody);
}
return sanitizeStringifiedJsonBody(json);
} catch (Exception e) {
logger.error("Can't parse response as json. It will be replaced with {}", REPLACEMENT);
}
}
return REPLACEMENT;
}
private String sanitizeStringifiedJsonBody(String body) {
Object responseMap = objectMapper.readValue(body, Object.class);
sanitizeObject(responseMap);
return objectMapper.writeValueAsString(responseMap);
}
private Map<String, Object> sanitizeMap(Map<String, Object> responseMap) {
for (Map.Entry<String, Object> entry : responseMap.entrySet()) {
if (!nonSanitizedBodyProperties.contains(entry.getKey())) {
responseMap.replace(entry.getKey(), sanitizeObject(entry.getValue()));
}
}
return responseMap;
}
@SuppressWarnings({"rawtypes", "unchecked"})
private List sanitizeList(List list) {
for (int i = 0; i < list.size(); i++) {
list.set(i, sanitizeObject(list.get(i)));
}
return list;
}
@SuppressWarnings({"rawtypes", "unchecked"})
private Object sanitizeObject(Object item) {
if (item instanceof Map) {
return sanitizeMap((Map<String, Object>) item);
}
if (item instanceof List) {
return sanitizeList((List) item);
}
return REPLACEMENT;
}
}
| 6,323 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
WiremockHttpClient.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/WiremockHttpClient.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.impl.http.wiremock;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;
import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer;
import de.adorsys.xs2a.adapter.api.http.Request;
import de.adorsys.xs2a.adapter.impl.http.ApacheHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.SecureRandom;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
public class WiremockHttpClient extends ApacheHttpClient {
private static final Logger logger = LoggerFactory.getLogger(WiremockHttpClient.class);
private static final String URL_REGEX = "https?://[^/]+";
private WireMockServer wireMockServer;
private final String wireMockUrl;
public WiremockHttpClient(String adapterId, CloseableHttpClient httpClient) {
this(adapterId, httpClient, randomPort(), null, null);
}
public WiremockHttpClient(String adapterId, CloseableHttpClient httpClient, HttpLogSanitizer logSanitizer) {
this(adapterId, httpClient, randomPort(), logSanitizer, null);
}
public WiremockHttpClient(String adapterId, CloseableHttpClient httpClient,
HttpLogSanitizer logSanitizer, String wiremockStandaloneUrl) {
this(adapterId, httpClient, randomPort(), logSanitizer, wiremockStandaloneUrl);
}
public WiremockHttpClient(String adapterId, CloseableHttpClient httpClient, int wireMockPort,
HttpLogSanitizer logSanitizer, String wiremockStandaloneUrl) {
super(logSanitizer, httpClient);
if (StringUtils.isNotEmpty(wiremockStandaloneUrl)) {
wireMockUrl = wiremockStandaloneUrl;
logger.info("Wiremock [standalone] server is connected: {}", wireMockUrl);
} else {
WireMockConfiguration options = options()
.port(wireMockPort)
.extensions(new ResponseTemplateTransformer(true))
.fileSource(new JarReadingClasspathFileSource(adapterId));
wireMockServer = new WireMockServer(options);
wireMockServer.start();
wireMockUrl = "http://localhost:" + wireMockServer.port();
logger.info("Wiremock [local] server is up and running: {}", wireMockUrl);
}
}
@Override
public Request.Builder get(String uri) {
return super.get(rewriteUrl(uri));
}
@Override
public Request.Builder post(String uri) {
return super.post(rewriteUrl(uri));
}
@Override
public Request.Builder put(String uri) {
return super.put(rewriteUrl(uri));
}
@Override
public Request.Builder delete(String uri) {
return super.delete(rewriteUrl(uri));
}
public static int randomPort() {
return new SecureRandom().nextInt((2 << 15) - 9000) + 9000;
}
private String rewriteUrl(String sourceUrl) {
return sourceUrl.replaceFirst(URL_REGEX, wireMockUrl);
}
}
| 4,175 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
WiremockFileType.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/WiremockFileType.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.impl.http.wiremock;
import org.apache.http.client.utils.URIBuilder;
import java.net.URISyntaxException;
import java.util.Arrays;
public enum WiremockFileType {
AIS_CREATE_CONSENT("ais-create-consent.json") {
@Override
public boolean check(String url, String method, String body) {
return POST_METHOD.equalsIgnoreCase(method) && CONSENTS_URI.equals(url);
}
},
AIS_START_PSU_AUTHENTICATION("ais-start-psu-authentication.json") {
@Override
public boolean check(String url, String method, String body) {
return POST_METHOD.equalsIgnoreCase(method)
&& url.startsWith(CONSENTS_URI)
&& url.endsWith(AUTHORISATIONS_URI);
}
},
AIS_UPDATE_PSU_AUTHENTICATION("ais-update-psu-authentication.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(CONSENTS_URI)
&& body.contains(PSU_DATA);
}
},
AIS_SELECT_SCA_METHOD("ais-select-sca-method.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(CONSENTS_URI)
&& body.contains(AUTHENTICATION_METHOD_ID);
}
},
AIS_SEND_OTP("ais-send-otp.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(CONSENTS_URI)
&& body.contains(SCA_AUTHENTICATION_DATA);
}
},
AIS_GET_ACCOUNTS("ais-get-accounts.json") {
@Override
public boolean check(String url, String method, String body) {
try {
URIBuilder uriBuilder = new URIBuilder(url);
return GET_METHOD.equalsIgnoreCase(method)
&& uriBuilder.getPath().endsWith(ACCOUNTS_URI);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return false;
}
},
AIS_GET_BALANCES("ais-get-balances.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(ACCOUNTS_URI)
&& url.endsWith("/balances");
}
},
AIS_GET_TRANSACTIONS("ais-get-transactions.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(ACCOUNTS_URI)
&& url.contains("/transactions");
}
},
AIS_DELETE_CONSENT("ais-delete-consent.json") {
@Override
public boolean check(String url, String method, String body) {
return DELETE_METHOD.equalsIgnoreCase(method)
&& url.startsWith(CONSENTS_URI);
}
},
AIS_GET_SCA_STATUS("ais-get-sca-status.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(CONSENTS_URI)
&& url.contains(AUTHORISATIONS_URI);
}
},
AIS_GET_CONSENT_STATUS("ais-get-consent-status.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(CONSENTS_URI)
&& url.endsWith(STATUS_URI);
}
},
// Payment Initiation
PIS_PAYMENTS_SCT_INITIATE_PAYMENT("pis-payments-sct-initiate-payment.json") {
@Override
public boolean check(String url, String method, String body) {
return POST_METHOD.equalsIgnoreCase(method)
&& url.equals(PAYMENTS_SCT_URI);
}
},
PIS_PAYMENTS_PAIN001_SCT_INITIATE_PAYMENT("pis-payments-pain001-sct-initiate-payment.json") {
@Override
public boolean check(String url, String method, String body) {
return POST_METHOD.equalsIgnoreCase(method)
&& url.equals(PAYMENTS_PAIN001_SCT_URI);
}
},
PIS_PERIODIC_SCT_INITIATE_PAYMENT("pis-periodic-sct-initiate-payment.json") {
@Override
public boolean check(String url, String method, String body) {
return POST_METHOD.equalsIgnoreCase(method)
&& url.equals(PERIODIC_SCT_URI);
}
},
PIS_PERIODIC_PAIN001_SCT_INITIATE_PAYMENT("pis-periodic-pain001-sct-initiate-payment.json") {
@Override
public boolean check(String url, String method, String body) {
return POST_METHOD.equalsIgnoreCase(method)
&& url.equals(PERIODIC_PAIN001_CST_URI);
}
},
// Start PSU Authentication
PIS_PAYMENTS_SCT_START_PSU_AUTHENTICATION("pis-payments-sct-start-psu-authentication.json") {
@Override
public boolean check(String url, String method, String body) {
return POST_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_SCT_URI)
&& url.endsWith(AUTHORISATIONS_URI);
}
},
PIS_PAYMENTS_PAIN001_SCT_START_PSU_AUTHENTICATION("pis-payments-pain001-sct-start-psu-authentication.json") {
@Override
public boolean check(String url, String method, String body) {
return POST_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_PAIN001_SCT_URI)
&& url.endsWith(AUTHORISATIONS_URI);
}
},
PIS_PERIODIC_SCT_START_PSU_AUTHENTICATION("pis-periodic-sct-start-psu-authentication.json") {
@Override
public boolean check(String url, String method, String body) {
return POST_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_SCT_URI)
&& url.endsWith(AUTHORISATIONS_URI);
}
},
PIS_PERIODIC_PAIN001_SCT_START_PSU_AUTHENTICATION("pis-periodic-pain001-sct-start-psu-authentication.json") {
@Override
public boolean check(String url, String method, String body) {
return POST_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_PAIN001_CST_URI)
&& url.endsWith(AUTHORISATIONS_URI);
}
},
// Update PSU Authentication
PIS_PAYMENTS_SCT_UPDATE_PSU_AUTHENTICATION("pis-payments-sct-update-psu-authentication.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_SCT_URI)
&& body.contains(PSU_DATA);
}
},
PIS_PAYMENTS_PAIN001_SCT_UPDATE_PSU_AUTHENTICATION("pis-payments-pain001-sct-update-psu-authentication.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_PAIN001_SCT_URI)
&& body.contains(PSU_DATA);
}
},
PIS_PERIODIC_SCT_UPDATE_PSU_AUTHENTICATION("pis-periodic-sct-update-psu-authentication.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_SCT_URI)
&& body.contains(PSU_DATA);
}
},
PIS_PERIODIC_PAIN001_SCT_UPDATE_PSU_AUTHENTICATION("pis-periodic-pain001-sct-update-psu-authentication.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_PAIN001_CST_URI)
&& body.contains(PSU_DATA);
}
},
// Select SCA Method
PIS_PAYMENTS_SCT_SELECT_SCA_METHOD("pis-payments-sct-select-sca-method.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_SCT_URI)
&& body.contains(AUTHENTICATION_METHOD_ID);
}
},
PIS_PAYMENTS_PAIN001_SCT_SELECT_SCA_METHOD("pis-payments-pain001-sct-select-sca-method.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_PAIN001_SCT_URI)
&& body.contains(AUTHENTICATION_METHOD_ID);
}
},
PIS_PERIODIC_SCT_SELECT_SCA_METHOD("pis-periodic-sct-select-sca-method.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_SCT_URI)
&& body.contains(AUTHENTICATION_METHOD_ID);
}
},
PIS_PERIODIC_PAIN001_SCT_SELECT_SCA_METHOD("pis-periodic-pain001-sct-select-sca-method.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_PAIN001_CST_URI)
&& body.contains(AUTHENTICATION_METHOD_ID);
}
},
// Send OTP
PIS_PAYMENTS_SCT_SEND_OTP("pis-payments-sct-send-otp.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_SCT_URI)
&& body.contains(SCA_AUTHENTICATION_DATA);
}
},
PIS_PAYMENTS_PAIN001_SCT_SEND_OTP("pis-payments-pain001-sct-send-otp.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_PAIN001_SCT_URI)
&& body.contains(SCA_AUTHENTICATION_DATA);
}
},
PIS_PERIODIC_SCT_SEND_OTP("pis-periodic-sct-send-otp.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_SCT_URI)
&& body.contains(SCA_AUTHENTICATION_DATA);
}
},
PIS_PERIODIC_PAIN001_SCT_SEND_OTP("pis-periodic-pain001-sct-send-otp.json") {
@Override
public boolean check(String url, String method, String body) {
return PUT_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_PAIN001_CST_URI)
&& body.contains(SCA_AUTHENTICATION_DATA);
}
},
// Get Transaction Status
PIS_PAYMENTS_SCT_GET_TRANSACTION_STATUS("pis-payments-sct-get-payment-status.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_SCT_URI)
&& url.endsWith(STATUS_URI);
}
},
PIS_PAYMENTS_PAIN001_SCT_GET_TRANSACTION_STATUS("pis-payments-pain001-sct-get-payment-status.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_PAIN001_SCT_URI)
&& url.endsWith(STATUS_URI);
}
},
PIS_PERIODIC_SCT_GET_TRANSACTION_STATUS("pis-periodic-sct-get-payment-status.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_SCT_URI)
&& url.endsWith(STATUS_URI);
}
},
PIS_PERIODIC_PAIN001_SCT_GET_TRANSACTION_STATUS("pis-periodic-pain001-sct-get-payment-status.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_PAIN001_CST_URI)
&& url.endsWith(STATUS_URI);
}
},
// Get SCA Status
PIS_PAYMENTS_SCT_GET_SCA_STATUS("pis-payments-sct-get-sca-status.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_SCT_URI)
&& url.contains(AUTHORISATIONS_URI);
}
},
PIS_PAYMENTS_PAIN001_SCT_GET_SCA_STATUS("pis-payments-pain001-sct-get-sca-status.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PAYMENTS_PAIN001_SCT_URI)
&& url.contains(AUTHORISATIONS_URI);
}
},
PIS_PERIODIC_SCT_GET_SCA_STATUS("pis-periodic-sct-get-sca-status.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_SCT_URI)
&& url.contains(AUTHORISATIONS_URI);
}
},
PIS_PERIODIC_PAIN001_SCT_GET_SCA_STATUS("pis-periodic-pain001-sct-get-sca-status.json") {
@Override
public boolean check(String url, String method, String body) {
return GET_METHOD.equalsIgnoreCase(method)
&& url.startsWith(PERIODIC_PAIN001_CST_URI)
&& url.contains(AUTHORISATIONS_URI);
}
};
private static final String SCA_AUTHENTICATION_DATA = "scaAuthenticationData";
private static final String AUTHENTICATION_METHOD_ID = "authenticationMethodId";
private static final String PSU_DATA = "psuData";
private static final String DELETE_METHOD = "DELETE";
private static final String POST_METHOD = "POST";
private static final String PUT_METHOD = "PUT";
private static final String GET_METHOD = "GET";
private static final String CONSENTS_URI = "/v1/consents";
private static final String ACCOUNTS_URI = "/v1/accounts";
private static final String AUTHORISATIONS_URI = "/authorisations";
private static final String STATUS_URI = "/status";
private static final String PAYMENTS_SCT_URI = "/v1/payments/sepa-credit-transfers";
private static final String PAYMENTS_PAIN001_SCT_URI = "/v1/payments/pain.001-sepa-credit-transfers";
private static final String PERIODIC_SCT_URI = "/v1/periodic-payments/sepa-credit-transfers";
private static final String PERIODIC_PAIN001_CST_URI = "/v1/periodic-payments/pain.001-sepa-credit-transfers";
private final String filename;
WiremockFileType(String filename) {
this.filename = filename;
}
public abstract boolean check(String url, String method, String body);
public String getFileName() {
return filename;
}
public static WiremockFileType resolve(String url, String method, String body) {
return Arrays.stream(values())
.filter(r -> r.check(url, method, body))
.findFirst()
.orElseThrow(() -> new IllegalStateException("Can't resolve wiremock stub"));
}
}
| 16,495 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
WiremockHttpClientFactory.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/WiremockHttpClientFactory.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.impl.http.wiremock;
import de.adorsys.xs2a.adapter.api.exception.Xs2aAdapterException;
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 org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.security.GeneralSecurityException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class WiremockHttpClientFactory implements HttpClientFactory {
private final HttpClientBuilder httpClientBuilder;
private final HttpClientConfig httpClientConfig;
private final ConcurrentMap<String, HttpClient> cache = new ConcurrentHashMap<>();
public WiremockHttpClientFactory(HttpClientBuilder httpClientBuilder, HttpClientConfig httpClientConfig) {
this.httpClientBuilder = httpClientBuilder;
this.httpClientConfig = httpClientConfig;
}
@Override
public HttpClient getHttpClient(String adapterId, String qwacAlias, String[] supportedCipherSuites) {
return cache.computeIfAbsent(adapterId, key -> createHttpClient(qwacAlias, supportedCipherSuites, adapterId));
}
@Override
public HttpClientConfig getHttpClientConfig() {
return httpClientConfig;
}
private HttpClient createHttpClient(String qwacAlias, String[] supportedCipherSuites, String adapterId) {
synchronized (this) {
CloseableHttpClient httpClient;
SSLContext sslContext = getSslContext(qwacAlias);
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
SSLConnectionSocketFactory sslSocketFactory =
new SSLConnectionSocketFactory(socketFactory, null, supportedCipherSuites, (HostnameVerifier) null);
httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
httpClient = httpClientBuilder.build();
return new WiremockHttpClient(adapterId, httpClient, httpClientConfig.getLogSanitizer(),
httpClientConfig.getWiremockStandaloneUrl());
}
}
private SSLContext getSslContext(String qwacAlias) {
try {
return httpClientConfig.getKeyStore().getSslContext(qwacAlias);
} catch (GeneralSecurityException e) {
throw new Xs2aAdapterException(e);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
| 3,607 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ClassUtils.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/ClassUtils.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.impl.http.wiremock;
import java.beans.Introspector;
import java.io.Closeable;
import java.io.Externalizable;
import java.io.Serializable;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* @deprecated Will be deleted with https://jira.adorsys.de/browse/XS2AAD-624.
*
* Miscellaneous {@code java.lang.Class} utility methods.
* Mainly for internal use within the framework.
*
* <p>Removed usage of Nullable annotation and Assert class
*
* @author Juergen Hoeller
* @author Keith Donald
* @author Rob Harrop
* @author Sam Brannen
* @since 1.1
* @see TypeUtils
* @see ReflectionUtils
*/
@Deprecated
final class ClassUtils {
private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0];
private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new IdentityHashMap(8);
private static final Map<Class<?>, Class<?>> primitiveTypeToWrapperMap = new IdentityHashMap(8);
private static final Map<String, Class<?>> primitiveTypeNameMap = new HashMap(32);
private static final Map<String, Class<?>> commonClassCache = new HashMap(64);
private static final Set<Class<?>> javaLanguageInterfaces;
private static final Map<Method, Method> interfaceMethodCache = new ConcurrentHashMap<>(256);
private ClassUtils() {
}
private static void registerCommonClasses(Class<?>... commonClasses) {
Class[] var1 = commonClasses;
int var2 = commonClasses.length;
for (int var3 = 0; var3 < var2; ++var3) {
Class<?> clazz = var1[var3];
commonClassCache.put(clazz.getName(), clazz);
}
}
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
} catch (Throwable var3) {
}
if (cl == null) {
cl = ClassUtils.class.getClassLoader();
if (cl == null) {
try {
cl = ClassLoader.getSystemClassLoader();
} catch (Throwable var2) {
}
}
}
return cl;
}
public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {
Thread currentThread = Thread.currentThread();
ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
if (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {
currentThread.setContextClassLoader(classLoaderToUse);
return threadContextClassLoader;
} else {
return null;
}
}
public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError {
Class<?> clazz = resolvePrimitiveClassName(name);
if (clazz == null) {
clazz = (Class) commonClassCache.get(name);
}
if (clazz != null) {
return clazz;
} else {
Class elementClass;
String elementName;
if (name.endsWith("[]")) {
elementName = name.substring(0, name.length() - "[]".length());
elementClass = forName(elementName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
} else if (name.startsWith("[L") && name.endsWith(";")) {
elementName = name.substring("[L".length(), name.length() - 1);
elementClass = forName(elementName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
} else if (name.startsWith("[")) {
elementName = name.substring("[".length());
elementClass = forName(elementName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
} else {
ClassLoader clToUse = classLoader;
if (classLoader == null) {
clToUse = getDefaultClassLoader();
}
try {
return Class.forName(name, false, clToUse);
} catch (ClassNotFoundException var9) {
int lastDotIndex = name.lastIndexOf(46);
if (lastDotIndex != -1) {
String innerClassName =
name.substring(0, lastDotIndex) + '$' + name.substring(lastDotIndex + 1);
try {
return Class.forName(innerClassName, false, clToUse);
} catch (ClassNotFoundException var8) {
}
}
throw var9;
}
}
}
}
public static Class<?> resolveClassName(String className, ClassLoader classLoader) throws IllegalArgumentException {
try {
return forName(className, classLoader);
} catch (IllegalAccessError var3) {
throw new IllegalStateException("Readability mismatch in inheritance hierarchy of class ["
+ className + "]: "
+ var3.getMessage(), var3);
} catch (LinkageError var4) {
throw new IllegalArgumentException("Unresolvable class definition for class [" + className + "]", var4);
} catch (ClassNotFoundException var5) {
throw new IllegalArgumentException("Could not find class [" + className + "]", var5);
}
}
public static boolean isPresent(String className, ClassLoader classLoader) {
try {
forName(className, classLoader);
return true;
} catch (IllegalAccessError var3) {
throw new IllegalStateException("Readability mismatch in inheritance hierarchy of class ["
+ className + "]: "
+ var3.getMessage(), var3);
} catch (Throwable var4) {
return false;
}
}
public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
if (classLoader == null) {
return true;
} else {
try {
if (clazz.getClassLoader() == classLoader) {
return true;
}
} catch (SecurityException var3) {
}
return isLoadable(clazz, classLoader);
}
}
public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {
try {
ClassLoader target = clazz.getClassLoader();
if (target == classLoader || target == null) {
return true;
}
if (classLoader == null) {
return false;
}
ClassLoader current = classLoader;
while (current != null) {
current = current.getParent();
if (current == target) {
return true;
}
}
while (target != null) {
target = target.getParent();
if (target == classLoader) {
return false;
}
}
} catch (SecurityException var4) {
}
return classLoader != null && isLoadable(clazz, classLoader);
}
private static boolean isLoadable(Class<?> clazz, ClassLoader classLoader) {
try {
return clazz == classLoader.loadClass(clazz.getName());
} catch (ClassNotFoundException var3) {
return false;
}
}
public static Class<?> resolvePrimitiveClassName(String name) {
Class<?> result = null;
if (name != null && name.length() <= 7) {
result = (Class) primitiveTypeNameMap.get(name);
}
return result;
}
public static boolean isPrimitiveWrapper(Class<?> clazz) {
return primitiveWrapperTypeMap.containsKey(clazz);
}
public static boolean isPrimitiveOrWrapper(Class<?> clazz) {
return clazz.isPrimitive() || isPrimitiveWrapper(clazz);
}
public static boolean isPrimitiveArray(Class<?> clazz) {
return clazz.isArray() && clazz.getComponentType().isPrimitive();
}
public static boolean isPrimitiveWrapperArray(Class<?> clazz) {
return clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType());
}
public static Class<?> resolvePrimitiveIfNecessary(Class<?> clazz) {
return clazz.isPrimitive() && clazz != Void.TYPE ? (Class) primitiveTypeToWrapperMap.get(clazz) : clazz;
}
public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
if (lhsType.isAssignableFrom(rhsType)) {
return true;
} else {
Class resolvedWrapper;
if (lhsType.isPrimitive()) {
resolvedWrapper = (Class) primitiveWrapperTypeMap.get(rhsType);
return lhsType == resolvedWrapper;
} else {
resolvedWrapper = (Class) primitiveTypeToWrapperMap.get(rhsType);
return resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper);
}
}
}
public static boolean isAssignableValue(Class<?> type, Object value) {
return value != null ? isAssignable(type, value.getClass()) : !type.isPrimitive();
}
public static String convertResourcePathToClassName(String resourcePath) {
return resourcePath.replace('/', '.');
}
public static String convertClassNameToResourcePath(String className) {
return className.replace('.', '/');
}
public static String addResourcePathToPackagePath(Class<?> clazz, String resourceName) {
return !resourceName.startsWith("/")
? classPackageAsResourcePath(clazz) + '/' + resourceName
: classPackageAsResourcePath(clazz) + resourceName;
}
public static String classPackageAsResourcePath(Class<?> clazz) {
if (clazz == null) {
return "";
} else {
String className = clazz.getName();
int packageEndIndex = className.lastIndexOf(46);
if (packageEndIndex == -1) {
return "";
} else {
String packageName = className.substring(0, packageEndIndex);
return packageName.replace('.', '/');
}
}
}
public static String classNamesToString(Class<?>... classes) {
return classNamesToString((Collection) Arrays.asList(classes));
}
public static String classNamesToString(Collection<Class<?>> classes) {
if (isEmpty(classes)) {
return "[]";
} else {
StringJoiner stringJoiner = new StringJoiner(", ", "[", "]");
Iterator var2 = classes.iterator();
while (var2.hasNext()) {
Class<?> clazz = (Class) var2.next();
stringJoiner.add(clazz.getName());
}
return stringJoiner.toString();
}
}
public static Class<?>[] toClassArray(Collection<Class<?>> collection) {
return !isEmpty(collection)
? (Class[]) collection.toArray(EMPTY_CLASS_ARRAY)
: EMPTY_CLASS_ARRAY;
}
public static Class<?>[] getAllInterfaces(Object instance) {
return getAllInterfacesForClass(instance.getClass());
}
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz) {
return getAllInterfacesForClass(clazz, (ClassLoader) null);
}
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz, ClassLoader classLoader) {
return toClassArray(getAllInterfacesForClassAsSet(clazz, classLoader));
}
public static Set<Class<?>> getAllInterfacesAsSet(Object instance) {
return getAllInterfacesForClassAsSet(instance.getClass());
}
public static Set<Class<?>> getAllInterfacesForClassAsSet(Class<?> clazz) {
return getAllInterfacesForClassAsSet(clazz, (ClassLoader) null);
}
public static Set<Class<?>> getAllInterfacesForClassAsSet(Class<?> clazz, ClassLoader classLoader) {
if (clazz.isInterface() && isVisible(clazz, classLoader)) {
return Collections.singleton(clazz);
} else {
Set<Class<?>> interfaces = new LinkedHashSet();
for (Class current = clazz; current != null; current = current.getSuperclass()) {
Class<?>[] ifcs = current.getInterfaces();
Class[] var5 = ifcs;
int var6 = ifcs.length;
for (int var7 = 0; var7 < var6; ++var7) {
Class<?> ifc = var5[var7];
if (isVisible(ifc, classLoader)) {
interfaces.add(ifc);
}
}
}
return interfaces;
}
}
public static Class<?> createCompositeInterface(Class<?>[] interfaces, ClassLoader classLoader) {
return Proxy.getProxyClass(classLoader, interfaces);
}
public static Class<?> determineCommonAncestor(Class<?> clazz1, Class<?> clazz2) {
if (clazz1 == null) {
return clazz2;
} else if (clazz2 == null) {
return clazz1;
} else if (clazz1.isAssignableFrom(clazz2)) {
return clazz1;
} else if (clazz2.isAssignableFrom(clazz1)) {
return clazz2;
} else {
Class ancestor = clazz1;
do {
ancestor = ancestor.getSuperclass();
if (ancestor == null || Object.class == ancestor) {
return null;
}
} while (!ancestor.isAssignableFrom(clazz2));
return ancestor;
}
}
public static boolean isJavaLanguageInterface(Class<?> ifc) {
return javaLanguageInterfaces.contains(ifc);
}
public static boolean isInnerClass(Class<?> clazz) {
return clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers());
}
/**
* @deprecated
*/
@Deprecated
public static boolean isCglibProxy(Object object) {
return isCglibProxyClass(object.getClass());
}
/**
* @deprecated
*/
@Deprecated
public static boolean isCglibProxyClass(Class<?> clazz) {
return clazz != null && isCglibProxyClassName(clazz.getName());
}
/**
* @deprecated
*/
@Deprecated
public static boolean isCglibProxyClassName(String className) {
return className != null && className.contains("$$");
}
public static Class<?> getUserClass(Object instance) {
return getUserClass(instance.getClass());
}
public static Class<?> getUserClass(Class<?> clazz) {
if (clazz.getName().contains("$$")) {
Class<?> superclass = clazz.getSuperclass();
if (superclass != null && superclass != Object.class) {
return superclass;
}
}
return clazz;
}
public static String getDescriptiveType(Object value) {
if (value == null) {
return null;
} else {
Class<?> clazz = value.getClass();
if (!Proxy.isProxyClass(clazz)) {
return clazz.getTypeName();
} else {
String prefix = clazz.getName() + " implementing ";
StringJoiner result = new StringJoiner(",", prefix, "");
Class[] var4 = clazz.getInterfaces();
int var5 = var4.length;
for (int var6 = 0; var6 < var5; ++var6) {
Class<?> ifc = var4[var6];
result.add(ifc.getName());
}
return result.toString();
}
}
}
public static boolean matchesTypeName(Class<?> clazz, String typeName) {
return typeName != null && (typeName.equals(clazz.getTypeName()) || typeName.equals(clazz.getSimpleName()));
}
public static String getShortName(String className) {
int lastDotIndex = className.lastIndexOf(46);
int nameEndIndex = className.indexOf("$$");
if (nameEndIndex == -1) {
nameEndIndex = className.length();
}
String shortName = className.substring(lastDotIndex + 1, nameEndIndex);
shortName = shortName.replace('$', '.');
return shortName;
}
public static String getShortName(Class<?> clazz) {
return getShortName(getQualifiedName(clazz));
}
public static String getShortNameAsProperty(Class<?> clazz) {
String shortName = getShortName(clazz);
int dotIndex = shortName.lastIndexOf(46);
shortName = dotIndex != -1 ? shortName.substring(dotIndex + 1) : shortName;
return Introspector.decapitalize(shortName);
}
public static String getClassFileName(Class<?> clazz) {
String className = clazz.getName();
int lastDotIndex = className.lastIndexOf(46);
return className.substring(lastDotIndex + 1) + ".class";
}
public static String getPackageName(Class<?> clazz) {
return getPackageName(clazz.getName());
}
public static String getPackageName(String fqClassName) {
int lastDotIndex = fqClassName.lastIndexOf(46);
return lastDotIndex != -1 ? fqClassName.substring(0, lastDotIndex) : "";
}
public static String getQualifiedName(Class<?> clazz) {
return clazz.getTypeName();
}
public static String getQualifiedMethodName(Method method) {
return getQualifiedMethodName(method, (Class) null);
}
public static String getQualifiedMethodName(Method method, Class<?> clazz) {
return (clazz != null ? clazz : method.getDeclaringClass()).getName() + '.' + method.getName();
}
public static boolean hasConstructor(Class<?> clazz, Class<?>... paramTypes) {
return getConstructorIfAvailable(clazz, paramTypes) != null;
}
public static <T> Constructor<T> getConstructorIfAvailable(Class<T> clazz, Class<?>... paramTypes) {
try {
return clazz.getConstructor(paramTypes);
} catch (NoSuchMethodException var3) {
return null;
}
}
public static boolean hasMethod(Class<?> clazz, Method method) {
if (clazz == method.getDeclaringClass()) {
return true;
} else {
String methodName = method.getName();
Class<?>[] paramTypes = method.getParameterTypes();
return getMethodOrNull(clazz, methodName, paramTypes) != null;
}
}
public static boolean hasMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
return getMethodIfAvailable(clazz, methodName, paramTypes) != null;
}
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
if (paramTypes != null) {
try {
return clazz.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException var4) {
throw new IllegalStateException("Expected method not found: " + var4);
}
} else {
Set<Method> candidates = findMethodCandidatesByName(clazz, methodName);
if (candidates.size() == 1) {
return (Method) candidates.iterator().next();
} else if (candidates.isEmpty()) {
throw new IllegalStateException("Expected method not found: " + clazz.getName() + '.' + methodName);
} else {
throw new IllegalStateException("No unique method found: " + clazz.getName() + '.' + methodName);
}
}
}
public static Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>... paramTypes) {
if (paramTypes != null) {
return getMethodOrNull(clazz, methodName, paramTypes);
} else {
Set<Method> candidates = findMethodCandidatesByName(clazz, methodName);
return candidates.size() == 1 ? (Method) candidates.iterator().next() : null;
}
}
public static int getMethodCountForName(Class<?> clazz, String methodName) {
int count = 0;
Method[] declaredMethods = clazz.getDeclaredMethods();
Method[] var4 = declaredMethods;
int var5 = declaredMethods.length;
int var6;
for (var6 = 0; var6 < var5; ++var6) {
Method method = var4[var6];
if (methodName.equals(method.getName())) {
++count;
}
}
Class<?>[] ifcs = clazz.getInterfaces();
Class[] var10 = ifcs;
var6 = ifcs.length;
for (int var11 = 0; var11 < var6; ++var11) {
Class<?> ifc = var10[var11];
count += getMethodCountForName(ifc, methodName);
}
if (clazz.getSuperclass() != null) {
count += getMethodCountForName(clazz.getSuperclass(), methodName);
}
return count;
}
public static boolean hasAtLeastOneMethodWithName(Class<?> clazz, String methodName) {
Method[] declaredMethods = clazz.getDeclaredMethods();
Method[] var3 = declaredMethods;
int var4 = declaredMethods.length;
int var5;
for (var5 = 0; var5 < var4; ++var5) {
Method method = var3[var5];
if (method.getName().equals(methodName)) {
return true;
}
}
Class<?>[] ifcs = clazz.getInterfaces();
Class[] var9 = ifcs;
var5 = ifcs.length;
for (int var10 = 0; var10 < var5; ++var10) {
Class<?> ifc = var9[var10];
if (hasAtLeastOneMethodWithName(ifc, methodName)) {
return true;
}
}
return clazz.getSuperclass() != null && hasAtLeastOneMethodWithName(clazz.getSuperclass(), methodName);
}
public static Method getMostSpecificMethod(Method method, Class<?> targetClass) {
if (targetClass != null && targetClass != method.getDeclaringClass() && isOverridable(method, targetClass)) {
try {
if (Modifier.isPublic(method.getModifiers())) {
try {
return targetClass.getMethod(method.getName(), method.getParameterTypes());
} catch (NoSuchMethodException var3) {
return method;
}
}
Method specificMethod = ReflectionUtils.findMethod(targetClass,
method.getName(),
method.getParameterTypes());
return specificMethod != null ? specificMethod : method;
} catch (SecurityException var4) {
}
}
return method;
}
public static Method getInterfaceMethodIfPossible(Method method) {
return Modifier.isPublic(method.getModifiers()) && !method.getDeclaringClass().isInterface()
? (Method) interfaceMethodCache.computeIfAbsent(method, (key) -> {
for (Class current = key.getDeclaringClass();
current != null && current != Object.class;
current = current.getSuperclass()) {
Class<?>[] ifcs = current.getInterfaces();
Class[] var3 = ifcs;
int var4 = ifcs.length;
int var5 = 0;
while (var5 < var4) {
Class ifc = var3[var5];
try {
return ifc.getMethod(key.getName(), key.getParameterTypes());
} catch (NoSuchMethodException var8) {
++var5;
}
}
}
return key;
}) : method;
}
public static boolean isUserLevelMethod(Method method) {
return method.isBridge() || !method.isSynthetic() && !isGroovyObjectMethod(method);
}
private static boolean isGroovyObjectMethod(Method method) {
return method.getDeclaringClass().getName().equals("groovy.lang.GroovyObject");
}
private static boolean isOverridable(Method method, Class<?> targetClass) {
if (Modifier.isPrivate(method.getModifiers())) {
return false;
} else if (!Modifier.isPublic(method.getModifiers()) && !Modifier.isProtected(method.getModifiers())) {
return targetClass == null || getPackageName(method.getDeclaringClass())
.equals(getPackageName(targetClass));
} else {
return true;
}
}
public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {
try {
Method method = clazz.getMethod(methodName, args);
return Modifier.isStatic(method.getModifiers()) ? method : null;
} catch (NoSuchMethodException var4) {
return null;
}
}
private static Method getMethodOrNull(Class<?> clazz, String methodName, Class<?>[] paramTypes) {
try {
return clazz.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException var4) {
return null;
}
}
private static Set<Method> findMethodCandidatesByName(Class<?> clazz, String methodName) {
Set<Method> candidates = new HashSet(1);
Method[] methods = clazz.getMethods();
Method[] var4 = methods;
int var5 = methods.length;
for (int var6 = 0; var6 < var5; ++var6) {
Method method = var4[var6];
if (methodName.equals(method.getName())) {
candidates.add(method);
}
}
return candidates;
}
static {
primitiveWrapperTypeMap.put(Boolean.class, Boolean.TYPE);
primitiveWrapperTypeMap.put(Byte.class, Byte.TYPE);
primitiveWrapperTypeMap.put(Character.class, Character.TYPE);
primitiveWrapperTypeMap.put(Double.class, Double.TYPE);
primitiveWrapperTypeMap.put(Float.class, Float.TYPE);
primitiveWrapperTypeMap.put(Integer.class, Integer.TYPE);
primitiveWrapperTypeMap.put(Long.class, Long.TYPE);
primitiveWrapperTypeMap.put(Short.class, Short.TYPE);
primitiveWrapperTypeMap.put(Void.class, Void.TYPE);
Iterator var0 = primitiveWrapperTypeMap.entrySet().iterator();
while (var0.hasNext()) {
Map.Entry<Class<?>, Class<?>> entry = (Map.Entry) var0.next();
primitiveTypeToWrapperMap.put(entry.getValue(), entry.getKey());
registerCommonClasses((Class) entry.getKey());
}
Set<Class<?>> primitiveTypes = new HashSet(32);
primitiveTypes.addAll(primitiveWrapperTypeMap.values());
Collections.addAll(primitiveTypes,
boolean[].class,
byte[].class,
char[].class,
double[].class,
float[].class,
int[].class,
long[].class,
short[].class);
primitiveTypes.add(Void.TYPE);
Iterator var4 = primitiveTypes.iterator();
while (var4.hasNext()) {
Class<?> primitiveType = (Class) var4.next();
primitiveTypeNameMap.put(primitiveType.getName(), primitiveType);
}
registerCommonClasses(Boolean[].class,
Byte[].class,
Character[].class,
Double[].class,
Float[].class,
Integer[].class,
Long[].class,
Short[].class);
registerCommonClasses(Number.class,
Number[].class,
String.class,
String[].class,
Class.class,
Class[].class,
Object.class,
Object[].class);
registerCommonClasses(Throwable.class,
Exception.class,
RuntimeException.class,
Error.class,
StackTraceElement.class,
StackTraceElement[].class);
registerCommonClasses(Enum.class,
Iterable.class,
Iterator.class,
Enumeration.class,
Collection.class,
List.class,
Set.class,
Map.class,
Map.Entry.class,
Optional.class);
Class<?>[] javaLanguageInterfaceArray = new Class[]{
Serializable.class,
Externalizable.class,
Closeable.class,
AutoCloseable.class,
Cloneable.class,
Comparable.class};
registerCommonClasses(javaLanguageInterfaceArray);
javaLanguageInterfaces = new HashSet(Arrays.asList(javaLanguageInterfaceArray));
}
public static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
}
| 30,439 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
WiremockSupportedHeader.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/WiremockSupportedHeader.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.impl.http.wiremock;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.isEmpty;
enum WiremockSupportedHeader {
X_REQUEST_ID("X-Request-ID"),
CONSENT_ID("Consent-ID"),
DIGEST("Digest"),
PSU_ID("PSU-ID"),
PSU_CORPORATE_ID("PSU-Corporate-ID"),
TPP_REDIRECT_URI("TPP-Redirect-URI"),
DATE("Date"),
SIGNATURE("Signature"),
TPP_SIGNATURE_CERTIFICATE("TPP-Signature-Certificate"),
PSU_IP_ADDRESS("PSU-IP-Address"),
PSU_ID_TYPE("PSU-ID-Type"),
PSU_CORPORATE_ID_TYPE("PSU-Corporate-ID-Type"),
TPP_REDIRECT_PREFERRED("TPP-Redirect-Preferred"),
TPP_NOK_REDIRECT_URI("TPP-Nok-Redirect-URI"),
TPP_EXPLICIT_AUTHORISATION_PREFERRED("TPP-Explicit-Authorisation-Preferred"),
PSU_IP_PORT("PSU-IP-Port"),
PSU_ACCEPT("PSU-Accept"),
PSU_ACCEPT_CHARSET("PSU-Accept-Charset"),
PSU_ACCEPT_ENCODING("PSU-Accept-Encoding"),
PSU_ACCEPT_LANGUAGE("PSU-Accept-Language"),
PSU_USER_AGENT("PSU-User-Agent"),
PSU_HTTP_METHOD("PSU-Http-Method"),
PSU_DEVICE_ID("PSU-Device-ID"),
PSU_GEO_LOCATION("PS-Geo-Location"),
CONTENT_TYPE("Content-Type") {
@Override
boolean isEqual(String stubValue, String currentValue) {
if (isEmpty(stubValue) || isEmpty(currentValue)) {
return false;
}
return currentValue.matches(stubValue);
}
},
AUTHORIZATION("Authorization");
private final String name;
WiremockSupportedHeader(String name) {
this.name = name;
}
public String getName() {
return name;
}
@SuppressWarnings("S1172")
boolean isEqual(String stubValue, String currentValue) {
return true;
}
static Set<String> set() {
return Arrays.stream(values())
.map(WiremockSupportedHeader::getName)
.collect(Collectors.toSet());
}
static Optional<WiremockSupportedHeader> resolve(String header) {
return Arrays.stream(values())
.filter(h -> h.getName().equalsIgnoreCase(header))
.findFirst();
}
}
| 3,072 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
JarClassPathResource.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/JarClassPathResource.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.impl.http.wiremock;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
/**
* @deprecated Will be deleted with https://jira.adorsys.de/browse/XS2AAD-624.
*/
@Deprecated
class JarClassPathResource {
private final String path;
private ClassLoader classLoader;
private Class<?> clazz;
JarClassPathResource(String path) {
this(path, (ClassLoader) null);
}
JarClassPathResource(String path, ClassLoader classLoader) {
String pathToUse = StringUtils.cleanPath(path);
if (pathToUse.startsWith("/")) {
pathToUse = pathToUse.substring(1);
}
this.path = pathToUse;
this.classLoader = classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader();
}
JarClassPathResource(String path, Class<?> clazz) {
this.path = StringUtils.cleanPath(path);
this.clazz = clazz;
}
public String getDescription() {
StringBuilder builder = new StringBuilder("class path resource [");
String pathToUse = this.path;
if (this.clazz != null && !pathToUse.startsWith("/")) {
builder.append(ClassUtils.classPackageAsResourcePath(this.clazz));
builder.append('/');
}
if (pathToUse.startsWith("/")) {
pathToUse = pathToUse.substring(1);
}
builder.append(pathToUse);
builder.append(']');
return builder.toString();
}
protected URL resolveURL() {
if (this.clazz != null) {
return this.clazz.getResource(this.path);
} else {
return this.classLoader != null ? this.classLoader.getResource(this.path) : ClassLoader.getSystemResource(this.path);
}
}
public URL getURL() throws IOException {
URL url = this.resolveURL();
if (url == null) {
throw new FileNotFoundException(this.getDescription() + " cannot be resolved to URL because it does not exist");
} else {
return url;
}
}
public URI getURI() throws IOException {
URL url = this.getURL();
try {
return ResourceUtils.toURI(url);
} catch (URISyntaxException var3) {
throw new IOException("Invalid URI [" + url + "]", var3);
}
}
}
| 3,231 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
WiremockStubDifferenceDetectingInterceptor.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/WiremockStubDifferenceDetectingInterceptor.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.impl.http.wiremock;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.http.Interceptor;
import de.adorsys.xs2a.adapter.api.http.Request;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import org.apache.commons.io.IOUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmlunit.builder.DiffBuilder;
import org.xmlunit.diff.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;
import static java.lang.Thread.currentThread;
import static org.apache.commons.lang3.StringUtils.isEmpty;
public class WiremockStubDifferenceDetectingInterceptor implements Interceptor {
private static final Logger log = LoggerFactory.getLogger(WiremockStubDifferenceDetectingInterceptor.class);
private static final CustomTextDifferenceEvaluator customTextDifferenceEvaluator
= new CustomTextDifferenceEvaluator();
private static final String HEADERS = "headers";
private static final String BODY = "body";
private static final String BODY_FILE_NAME = "bodyFileName";
private static final String BODY_PATTERNS = "bodyPatterns";
private static final String MULTIPART_PATTERNS = "multipartPatterns";
private static final String CONTENT_TYPE = WiremockSupportedHeader.CONTENT_TYPE.getName();
private static final String MAPPINGS_DIR = File.separator + "mappings" + File.separator;
private static final String MAPPINGS_DIR_PATH = "%s" + MAPPINGS_DIR;
private static final String APPLICATION_JSON = "application/json";
private static final String MULTIPART_FORMDATA = "multipart/form-data";
public static final String EQUAL_TO_XML = "equalToXml";
public static final String EQUAL_TO_JSON = "equalToJson";
private static final String PAYLOAD = "-payload";
private static final String DIFFERENCES_STR = "\nDifferences:";
private final Aspsp aspsp;
private final ObjectMapper objectMapper;
public WiremockStubDifferenceDetectingInterceptor(Aspsp aspsp) {
this.aspsp = aspsp;
objectMapper = new ObjectMapper();
}
@Override
public Request.Builder preHandle(Request.Builder builder) {
return builder;
}
@Override
public <T> Response<T> postHandle(Request.Builder builder, Response<T> response) {
try {
WiremockFileType wiremockFileType = WiremockFileType.resolve(URI.create(builder.uri()).getPath(), builder.method(), builder.body());
String fileName = buildStubFilePath(aspsp.getAdapterId(), wiremockFileType.getFileName());
Map<String, Object> jsonFile = readStubFile(fileName);
List<String> changes = new ArrayList<>();
getUrl(jsonFile).flatMap(url -> analyzeUrl(builder, url))
.ifPresent(changes::add);
getHeaders(jsonFile, PayloadType.REQUEST)
.flatMap(headers -> analyzeRequestHeaders(builder, headers))
.ifPresent(changes::add);
getRequestBody(jsonFile)
.flatMap(body -> analyzeRequestBody(builder, body))
.ifPresent(changes::add);
getResponseBody(jsonFile, aspsp.getAdapterId())
.flatMap(body -> analyzeResponseBody(response, body))
.ifPresent(changes::add);
Map<String, String> headersMap = response.getHeaders().getHeadersMap();
if (!changes.isEmpty()) {
String headerValue = String.join(",", changes);
headerValue = aspsp.getAdapterId() + ":" + wiremockFileType.name() + ":" + headerValue;
headersMap.put(ResponseHeaders.X_GTW_ASPSP_CHANGES_DETECTED, headerValue);
}
return new Response<>(response.getStatusCode(), response.getBody(), ResponseHeaders.fromMap(headersMap));
} catch (IllegalStateException e) {
log.error(e.getMessage());
} catch (Exception e) {
log.error("Can't find the difference with wiremock stub", e);
}
return response;
}
private Optional<String> analyzeUrl(Request.Builder builder, String stubUrl) {
try {
URIBuilder reqUriBuilder = new URIBuilder(builder.uri());
URIBuilder stubUriBuilder = new URIBuilder(stubUrl.replace("\\?", "?"));
Map<String, String> reqParams = getParamsMap(reqUriBuilder.getQueryParams());
Map<String, String> stubParams = getParamsMap(stubUriBuilder.getQueryParams());
StringBuilder differences = new StringBuilder();
if (!reqUriBuilder.getPath().matches(stubUriBuilder.getPath())) {
differences
.append("\n")
.append("Request URL is different");
}
reqParams.forEach((key, value) -> {
if (stubParams.containsKey(key)) {
String stubParamValue = getEncodedParamValue(stubParams, key);
if (!value.matches(stubParamValue)) {
differences
.append("\n")
.append("URL parameter ")
.append(key)
.append(" is different. Req/Stub ")
.append(value)
.append(" / ")
.append(stubParamValue);
}
} else {
differences
.append("\n")
.append("URL parameter ")
.append(key)
.append(" is absent");
}
});
if (differences.length() != 0) {
log.warn("Differences: {}", differences);
return Optional.of("url");
}
} catch (URISyntaxException e) {
log.error(e.getMessage());
}
return Optional.empty();
}
private String getEncodedParamValue(Map<String, String> params, String key) {
String paramValue = params.get(key);
try {
return URLEncoder.encode(paramValue, Charset.defaultCharset().name());
} catch (UnsupportedEncodingException e) {
log.error("Can't encode param value={}", paramValue, e);
}
return paramValue;
}
private Map<String, String> getParamsMap(List<NameValuePair> queryParams) {
return queryParams
.stream()
.map(p -> new AbstractMap.SimpleEntry<>(p.getName(), p.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
@SuppressWarnings("unchecked")
private Optional<String> getUrl(Map<String, Object> jsonFile) {
Map<String, Object> request = (Map<String, Object>) jsonFile.get(PayloadType.REQUEST.value);
Optional<String> url = Optional.ofNullable((String) request.get("url"));
if (url.isPresent()) {
return url;
}
return Optional.ofNullable((String) request.get("urlPattern"));
}
private <T> Optional<String> analyzeResponseBody(Response<T> response,
String responseBody) {
try {
String body = getResponseBody(response);
if (response.getHeaders().getHeader(CONTENT_TYPE).startsWith(APPLICATION_JSON)) {
return analyzeJsonPayloadStructure(responseBody, body, PayloadType.RESPONSE);
}
return analyzeXmlPayloadStructure(body, responseBody, PayloadType.RESPONSE);
} catch (JsonProcessingException e) {
log.error("Can't retrieve response body", e);
}
return Optional.empty();
}
private Optional<String> analyzeXmlPayloadStructure(String payloadBody, String stubBody, PayloadType payloadType) {
Diff diffs = DiffBuilder
.compare(isEmpty(payloadBody) ? "<Document></Document>" : payloadBody)
.withTest(stubBody)
.ignoreWhitespace()
.withDifferenceEvaluator(customTextDifferenceEvaluator)
.checkForSimilar()
.build();
Iterator<Difference> iterator = diffs.getDifferences().iterator();
if (iterator.hasNext()) {
StringBuilder differences = new StringBuilder(DIFFERENCES_STR);
iterator.forEachRemaining(diff -> differences.append("\n").append(diff.toString()));
log.warn("{} stub xml {} body is different from the aspsp {}.\n{}", aspsp.getAdapterId(), payloadType.value, payloadType.value, differences);
return Optional.of(payloadType.value + PAYLOAD);
}
return Optional.empty();
}
private static class CustomTextDifferenceEvaluator implements DifferenceEvaluator {
@Override
public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) {
if (outcome == ComparisonResult.EQUAL) {
return outcome;
}
if (comparison.getTestDetails().getValue() != null
&& comparison.getTestDetails().getValue().equals("${xmlunit.ignore}")) {
return ComparisonResult.SIMILAR;
}
return DifferenceEvaluators.Default.evaluate(comparison, outcome);
}
}
@SuppressWarnings("unchecked")
private Optional<String> analyzeJsonPayloadStructure(String payloadBody, String body, PayloadType payloadType) {
try {
Map<String, Object> stubBody = objectMapper.readValue(payloadBody, Map.class);
Map<String, Object> currentBody
= isEmpty(body) ? Collections.emptyMap() : objectMapper.readValue(body, Map.class);
Map<String, Object> stubMap = FlatMapUtils.flatten(stubBody);
Map<String, Object> currentBodyMap = FlatMapUtils.flatten(currentBody);
return checkForDifferences(payloadType, stubMap, currentBodyMap);
} catch (JsonProcessingException e) {
log.error("Can't get differences for the {} or wiremock stub body", payloadType.value, e);
}
return Optional.empty();
}
private Optional<String> checkForDifferences(PayloadType payloadType, Map<String, Object> stubMap, Map<String, Object> currentBodyMap) {
Set<Map.Entry<String, Object>> entries = stubMap.entrySet();
StringBuilder differences = new StringBuilder(DIFFERENCES_STR);
if (!currentBodyMap.keySet().containsAll(stubMap.keySet())) {
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
if (!currentBodyMap.containsKey(key)) {
differences.append("\n").append(key).append(" field is absent");
} else {
checkFieldValues(currentBodyMap, differences, entry, key);
}
}
} else {
// check values if all fields are present
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
checkFieldValues(currentBodyMap, differences, entry, key);
}
}
// print and return value only if differences encountered
if (differences.length() > DIFFERENCES_STR.length()) {
log.warn("{} stub json {} body is different from the aspsp {}.\n{}", aspsp.getAdapterId(), payloadType.value, payloadType.value, differences);
return Optional.of(payloadType.value + PAYLOAD);
}
return Optional.empty();
}
private void checkFieldValues(Map<String, Object> currentBodyMap, StringBuilder differences, Map.Entry<String, Object> entry, String key) {
Object currentValue = currentBodyMap.get(key);
Object stubbedValue = entry.getValue();
if (!sameValues(currentValue, stubbedValue)) {
// intentionally not printing field value - may contain sensitive data
differences.append("\n").append(key).append(" field value is not matching");
}
}
private boolean sameValues(Object currentValue, Object stubbedValue) {
if (Objects.isNull(currentValue) || Objects.isNull(stubbedValue)) {
// the case only for test scenarios, should not occur in production
return false;
}
if (stubbedValue instanceof String && ((String) stubbedValue).contains("${json-unit.regex}")) {
// dynamic value, no need for checking
return true;
}
return currentValue.equals(stubbedValue);
}
private enum PayloadType {
REQUEST("request"),
RESPONSE("response");
public final String value;
PayloadType(String value) {
this.value = value;
}
}
private <T> String getResponseBody(Response<T> response) throws JsonProcessingException {
String body;
T bodyObject = response.getBody();
if (bodyObject instanceof String) {
body = (String) bodyObject;
} else {
body = objectMapper.writeValueAsString(bodyObject);
}
return body;
}
@SuppressWarnings("unchecked")
private Optional<String> getResponseBody(Map<String, Object> jsonFile, String adapterId) {
Map<String, Object> response = (Map<String, Object>) jsonFile.get(PayloadType.RESPONSE.value);
Optional<Map<String, Object>> headers = getHeaders(jsonFile, PayloadType.RESPONSE);
if ((!response.containsKey(BODY) && !response.containsKey(BODY_FILE_NAME)) || !headers.isPresent()) {
return Optional.empty();
}
if (response.containsKey(BODY)) {
return Optional.ofNullable((String) response.get(BODY));
}
if (response.containsKey(BODY_FILE_NAME)) {
try {
String fileName = (String) response.get(BODY_FILE_NAME);
String filePath = adapterId + File.separator + "__files" + File.separator + fileName;
InputStream is = getClass().getResourceAsStream(File.separator + filePath);
return Optional.ofNullable(IOUtils.toString(is, (String) null));
} catch (IOException e) {
log.error("Can't get stub response file", e);
}
}
return Optional.empty();
}
private Optional<String> analyzeRequestBody(Request.Builder builder, List<Map<String, Object>> requestBody) {
if (builder.headers().get(CONTENT_TYPE).startsWith(APPLICATION_JSON)) {
return analyzeJsonPayloadStructure((String) requestBody.get(0).get(EQUAL_TO_JSON), builder.body(), PayloadType.REQUEST);
} else if (builder.headers().get(CONTENT_TYPE).startsWith(MULTIPART_FORMDATA)) {
return analyzeMultipartPayloadStructure(requestBody, builder);
}
return analyzeXmlPayloadStructure(builder.body(), (String) requestBody.get(0).get(EQUAL_TO_XML), PayloadType.REQUEST);
}
private Optional<String> analyzeMultipartPayloadStructure(List<Map<String, Object>> requestBody, Request.Builder builder) {
Optional<String> xmlResults = analyzeMultipartXmlPart(requestBody.get(0), builder);
Optional<String> jsonResults = analyzeMultipartJsonPart(requestBody.get(1), builder);
if (xmlResults.isPresent() || jsonResults.isPresent()) {
return Optional.of(PayloadType.REQUEST.value + PAYLOAD);
}
return Optional.empty();
}
@SuppressWarnings("unchecked")
private Optional<String> analyzeMultipartXmlPart(Map<String, Object> xmlPart, Request.Builder builder) {
Map<String, Object> xmlHeadersPart = (Map<String, Object>) xmlPart.get(HEADERS);
Optional<String> headersResult = analyzeMultipartHeader(builder.xmlParts(), xmlHeadersPart);
List<Map<String, Object>> xmlBodyPart = (List<Map<String, Object>>) xmlPart.get(BODY_PATTERNS);
Optional<String> bodyResult = analyzeXmlPayloadStructure(builder.xmlParts().get("xml_sct"),
(String) xmlBodyPart.get(0).get(EQUAL_TO_XML),
PayloadType.REQUEST);
if (headersResult.isPresent() || bodyResult.isPresent()) {
return Optional.of(PayloadType.REQUEST.value + PAYLOAD);
}
return Optional.empty();
}
@SuppressWarnings("unchecked")
private Optional<String> analyzeMultipartHeader(Map<String, String> builder, Map<String, Object> headersPart) {
Map<String, Object> contentDisposition = (Map<String, Object>) headersPart.get("Content-Disposition");
String rawDispositionValue = (String) contentDisposition.get("contains");
String dispositionValue = getDispositionValue(rawDispositionValue);
if (!builder.containsKey(dispositionValue)) {
final String nextKey = builder.keySet().iterator().next();
log.warn("Multipart Difference:\n" +
"{} {}-stub Content-Disposition header value doesn't match with a {} value;\n" +
"stub is '{}', but '{}' was in request",
aspsp.getAdapterId(),
PayloadType.REQUEST.value,
PayloadType.REQUEST.value,
dispositionValue,
nextKey);
return Optional.of(PayloadType.REQUEST.value + PAYLOAD);
}
return Optional.empty();
}
// Stub Content Disposition header has a value format like "name=\"xml_sct\""
// Header value should be extracted for an appropriate comparison
private String getDispositionValue(String target) {
return target.substring(target.indexOf("\"") + 1, target.lastIndexOf("\""));
}
@SuppressWarnings("unchecked")
private Optional<String> analyzeMultipartJsonPart(Map<String, Object> jsonPart, Request.Builder builder) {
Map<String, Object> jsonHeadersPart = (Map<String, Object>) jsonPart.get(HEADERS);
Optional<String> headersResult = analyzeMultipartHeader(builder.jsonParts(), jsonHeadersPart);
List<Map<String, Object>> jsonBodyPart = (List<Map<String, Object>>) jsonPart.get(BODY_PATTERNS);
Optional<String> bodyResult = analyzeJsonPayloadStructure((String) jsonBodyPart.get(0).get(EQUAL_TO_JSON),
builder.jsonParts().get("json_standingorderType"),
PayloadType.REQUEST);
if (headersResult.isPresent() || bodyResult.isPresent()) {
return Optional.of(PayloadType.REQUEST.value + PAYLOAD);
}
return Optional.empty();
}
private Optional<String> analyzeRequestHeaders(Request.Builder builder, Map<String, Object> stubHeaders) {
Map<String, String> currentHeaders = builder.headers();
Sets.SetView<String> headers = Sets.intersection(WiremockSupportedHeader.set(), currentHeaders.keySet());
Sets.SetView<String> presentHeaders = Sets.intersection(headers, stubHeaders.keySet());
Sets.SetView<String> requestDiff = Sets.difference(headers, stubHeaders.keySet());
Sets.SetView<String> stubDiff = Sets.difference(stubHeaders.keySet(), headers);
StringBuilder differences = new StringBuilder();
presentHeaders.forEach(key -> {
WiremockSupportedHeader supportedHeader = WiremockSupportedHeader.resolve(key).get();
if (!supportedHeader.isEqual(getStubRequestHeader(stubHeaders, key), currentHeaders.get(key))) {
differences
.append("\nHeader ")
.append(key)
.append(" is different. Req/Stub ")
.append(currentHeaders.get(key))
.append("/")
.append(stubHeaders.get(key));
}
});
processAbsentHeaders(differences, stubDiff, "current request");
processAbsentHeaders(differences, requestDiff, "wiremock mapping");
if (differences.length() == 0) {
return Optional.empty();
}
log.warn("Headers differences:\n {}", differences);
return Optional.of("request-headers");
}
private void processAbsentHeaders(StringBuilder differences, Sets.SetView<String> diff, String request) {
diff.forEach(key -> differences
.append("\nHeader ")
.append(key)
.append(" is absent in the ")
.append(request));
}
@SuppressWarnings("unchecked")
private Optional<List<Map<String, Object>>> getRequestBody(Map<String, Object> jsonFile) {
Map<String, Object> request = (Map<String, Object>) jsonFile.get(PayloadType.REQUEST.value);
Optional<Map<String, Object>> headers = getHeaders(jsonFile, PayloadType.REQUEST);
if (!(request.containsKey(BODY_PATTERNS) || request.containsKey(MULTIPART_PATTERNS)) || !headers.isPresent()) {
return Optional.empty();
}
List<Map<String, Object>> multipartBodyMap = (List<Map<String, Object>>) request.get(MULTIPART_PATTERNS);
if (multipartBodyMap != null) {
return Optional.of(multipartBodyMap);
}
List<Map<String, Object>> bodyMap = (List<Map<String, Object>>) (request).get(BODY_PATTERNS);
return Optional.ofNullable(bodyMap);
}
@SuppressWarnings("unchecked")
private Optional<Map<String, Object>> getHeaders(Map<String, Object> jsonFile, PayloadType payloadType) {
Map<String, Object> request = (Map<String, Object>) jsonFile.get(payloadType.value);
return Optional.ofNullable((Map<String, Object>) request.get(HEADERS));
}
@SuppressWarnings("unchecked")
private Map<String, Object> readStubFile(String fileName) throws IOException {
InputStream is = getClass().getResourceAsStream(File.separator + fileName);
return objectMapper.readValue(is, Map.class);
}
private String buildStubFilePath(String adapterName, String fileName) {
return String.format(MAPPINGS_DIR_PATH, adapterName) + fileName;
}
public static boolean isWiremockSupported(String adapterId) {
URL mappingsUrl = currentThread().getContextClassLoader().getResource(String.format(MAPPINGS_DIR_PATH, adapterId));
return mappingsUrl != null;
}
@SuppressWarnings("unchecked")
private String getStubRequestHeader(Map<String, Object> map, String header) {
Map<String, String> valueMap = (Map<String, String>) map.get(header);
return valueMap
.values()
.stream()
.findFirst()
.orElseThrow(() -> new IllegalStateException(header + " is absent"));
}
}
| 24,228 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ResourceUtils.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/ResourceUtils.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.impl.http.wiremock;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.*;
/**
* @deprecated Will be deleted with https://jira.adorsys.de/browse/XS2AAD-624.
*
* Utility methods for resolving resource locations to files in the
* file system. Mainly for internal use within the framework.
*
* <p>Consider using Spring's Resource abstraction in the core package
* for handling all kinds of file resources in a uniform manner.
* {@link org.springframework.core.io.ResourceLoader}'s {@code getResource()}
* method can resolve any location to a {@link org.springframework.core.io.Resource}
* object, which in turn allows one to obtain a {@code java.io.File} in the
* file system through its {@code getFile()} method.
*
* <p>Removed usage of Nullable annotation and Assert class
*
* @author Juergen Hoeller
* @since 1.1.5
* @see org.springframework.core.io.Resource
* @see org.springframework.core.io.ClassPathResource
* @see org.springframework.core.io.FileSystemResource
* @see org.springframework.core.io.UrlResource
* @see org.springframework.core.io.ResourceLoader
*/
@Deprecated
final class ResourceUtils {
private ResourceUtils() {
}
public static boolean isUrl(String resourceLocation) {
if (resourceLocation == null) {
return false;
} else if (resourceLocation.startsWith("classpath:")) {
return true;
} else {
try {
new URL(resourceLocation);
return true;
} catch (MalformedURLException var2) {
return false;
}
}
}
public static URL getURL(String resourceLocation) throws FileNotFoundException {
if (resourceLocation.startsWith("classpath:")) {
String path = resourceLocation.substring("classpath:".length());
ClassLoader cl = ClassUtils.getDefaultClassLoader();
URL url = cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path);
if (url == null) {
String description = "class path resource [" + path + "]";
throw new FileNotFoundException(description + " cannot be resolved to URL because it does not exist");
} else {
return url;
}
} else {
try {
return new URL(resourceLocation);
} catch (MalformedURLException var6) {
try {
return (new File(resourceLocation)).toURI().toURL();
} catch (MalformedURLException var5) {
throw new FileNotFoundException("Resource location [" + resourceLocation + "] is neither a URL not a well-formed file path");
}
}
}
}
public static File getFile(String resourceLocation) throws FileNotFoundException {
if (resourceLocation.startsWith("classpath:")) {
String path = resourceLocation.substring("classpath:".length());
String description = "class path resource [" + path + "]";
ClassLoader cl = ClassUtils.getDefaultClassLoader();
URL url = cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path);
if (url == null) {
throw new FileNotFoundException(description + " cannot be resolved to absolute file path because it does not exist");
} else {
return getFile(url, description);
}
} else {
try {
return getFile(new URL(resourceLocation));
} catch (MalformedURLException var5) {
return new File(resourceLocation);
}
}
}
public static File getFile(URL resourceUrl) throws FileNotFoundException {
return getFile(resourceUrl, "URL");
}
public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
if (!"file".equals(resourceUrl.getProtocol())) {
throw new FileNotFoundException(description + " cannot be resolved to absolute file path because it does not reside in the file system: " + resourceUrl);
} else {
try {
return new File(toURI(resourceUrl).getSchemeSpecificPart());
} catch (URISyntaxException var3) {
return new File(resourceUrl.getFile());
}
}
}
public static File getFile(URI resourceUri) throws FileNotFoundException {
return getFile(resourceUri, "URI");
}
public static File getFile(URI resourceUri, String description) throws FileNotFoundException {
if (!"file".equals(resourceUri.getScheme())) {
throw new FileNotFoundException(description + " cannot be resolved to absolute file path because it does not reside in the file system: " + resourceUri);
} else {
return new File(resourceUri.getSchemeSpecificPart());
}
}
public static boolean isFileURL(URL url) {
String protocol = url.getProtocol();
return "file".equals(protocol) || "vfsfile".equals(protocol) || "vfs".equals(protocol);
}
public static boolean isJarURL(URL url) {
String protocol = url.getProtocol();
return "jar".equals(protocol) || "war".equals(protocol) || "zip".equals(protocol) || "vfszip".equals(protocol) || "wsjar".equals(protocol);
}
public static boolean isJarFileURL(URL url) {
return "file".equals(url.getProtocol()) && url.getPath().toLowerCase().endsWith(".jar");
}
public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException {
String urlFile = jarUrl.getFile();
int separatorIndex = urlFile.indexOf("!/");
if (separatorIndex != -1) {
String jarFile = urlFile.substring(0, separatorIndex);
try {
return new URL(jarFile);
} catch (MalformedURLException var5) {
if (!jarFile.startsWith("/")) {
jarFile = "/" + jarFile;
}
return new URL("file:" + jarFile);
}
} else {
return jarUrl;
}
}
public static URL extractArchiveURL(URL jarUrl) throws MalformedURLException {
String urlFile = jarUrl.getFile();
int endIndex = urlFile.indexOf("*/");
if (endIndex != -1) {
String warFile = urlFile.substring(0, endIndex);
if ("war".equals(jarUrl.getProtocol())) {
return new URL(warFile);
}
int startIndex = warFile.indexOf("war:");
if (startIndex != -1) {
return new URL(warFile.substring(startIndex + "war:".length()));
}
}
return extractJarFileURL(jarUrl);
}
public static URI toURI(URL url) throws URISyntaxException {
return toURI(url.toString());
}
public static URI toURI(String location) throws URISyntaxException {
return new URI(StringUtils.replace(location, " ", "%20"));
}
public static void useCachesIfNecessary(URLConnection con) {
con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP"));
}
}
| 8,061 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
JarReadingClasspathFileSource.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/JarReadingClasspathFileSource.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.impl.http.wiremock;
import com.github.tomakehurst.wiremock.common.BinaryFile;
import com.github.tomakehurst.wiremock.common.FileSource;
import com.github.tomakehurst.wiremock.common.TextFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;
import static com.google.common.collect.Lists.newArrayList;
/**
* @deprecated Will be deleted with https://jira.adorsys.de/browse/XS2AAD-624.
*/
@Deprecated
class JarReadingClasspathFileSource implements FileSource {
private final String path;
private URI pathUri;
private ZipFile warFile;
private String jarFileName;
private File rootDirectory;
JarReadingClasspathFileSource(String path) {
this.path = path;
try {
pathUri = new JarClassPathResource(path).getURI();
if (Arrays.asList("jar", "war", "ear", "zip").contains(pathUri.getScheme())) {
String[] pathElements = pathUri.getSchemeSpecificPart().split("!", 3);
String warFileUri = pathElements[0];
String warFilePath = warFileUri.replace("file:", "");
warFile = new ZipFile(new File(warFilePath));
jarFileName = pathElements[1].substring(1);
} else if (pathUri.getScheme().equals("file")) {
rootDirectory = new File(pathUri);
} else {
throw new RuntimeException("ClasspathFileSource can't handle paths of type " + pathUri.getScheme());
}
} catch (Exception e) {
throwUnchecked(e);
}
}
@Override
public BinaryFile getBinaryFileNamed(final String name) {
if (isFileSystem()) {
return new BinaryFile(new File(rootDirectory, name).toURI());
}
return new BinaryFile(getUri(name));
}
private boolean isFileSystem() {
return rootDirectory != null;
}
@Override
public TextFile getTextFileNamed(String name) {
if (isFileSystem()) {
return new TextFile(new File(rootDirectory, name).toURI());
}
return new TextFile(getUri(name));
}
private URI getUri(final String name) {
try {
return new JarClassPathResource(path + "/" + name).getURI();
} catch (IOException e) {
return throwUnchecked(e, URI.class);
}
}
@Override
public void createIfNecessary() {
}
@Override
public FileSource child(String subDirectoryName) {
return new JarReadingClasspathFileSource(path + "/" + subDirectoryName);
}
@Override
public String getPath() {
return path;
}
@Override
public URI getUri() {
return pathUri;
}
@Override
public List<TextFile> listFilesRecursively() {
if (isFileSystem()) {
assertExistsAndIsDirectory();
List<File> fileList = newArrayList();
recursivelyAddFilesToList(rootDirectory, fileList);
return toTextFileList(fileList);
}
List<TextFile> files = new ArrayList<>();
ZipEntry zipEntry = warFile.getEntry(jarFileName);
try (InputStream zipFileStream = warFile.getInputStream(zipEntry)) {
final ZipInputStream zipInputStream = new ZipInputStream(zipFileStream);
ZipEntry nestedZipEntry;
while ((nestedZipEntry = zipInputStream.getNextEntry()) != null) {
if (!nestedZipEntry.isDirectory() && nestedZipEntry.getName().startsWith(path)) {
files.add(new TextFile(new JarClassPathResource(nestedZipEntry.getName()).getURI()));
}
}
} catch (IOException e) {
// log.error("Unable to read war file", e);
}
return files;
}
@Override
public void writeTextFile(String name, String contents) {
}
@Override
public void writeBinaryFile(String name, byte[] contents) {
}
@Override
public boolean exists() {
return !isFileSystem() || rootDirectory.exists();
}
@Override
public void deleteFile(String name) {
}
private List<TextFile> toTextFileList(List<File> fileList) {
return fileList.stream()
.map(input -> new TextFile(input.toURI()))
.collect(Collectors.toList());
}
private void recursivelyAddFilesToList(File root, List<File> fileList) {
File[] files = root.listFiles();
for (File file : files) {
if (file.isDirectory()) {
recursivelyAddFilesToList(file, fileList);
} else {
fileList.add(file);
}
}
}
private void assertExistsAndIsDirectory() {
if (rootDirectory.exists() && !rootDirectory.isDirectory()) {
throw new RuntimeException(rootDirectory + " is not a directory");
} else if (!rootDirectory.exists()) {
throw new RuntimeException(rootDirectory + " does not exist");
}
}
}
| 6,168 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
FlatMapUtils.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/FlatMapUtils.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.impl.http.wiremock;
import java.util.AbstractMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class FlatMapUtils {
private FlatMapUtils() {
throw new AssertionError("No instances for you!");
}
public static Map<String, Object> flatten(Map<String, Object> map) {
return map.entrySet()
.stream()
.flatMap(FlatMapUtils::flatten)
.collect(LinkedHashMap::new, (m, e) -> m.put("/" + e.getKey(), e.getValue()), LinkedHashMap::putAll);
}
private static Stream<Map.Entry<String, Object>> flatten(Map.Entry<String, Object> entry) {
if (entry == null) {
return Stream.empty();
}
if (entry.getValue() instanceof Map<?, ?>) {
Map<?, ?> properties = (Map<?, ?>) entry.getValue();
return properties.entrySet()
.stream()
.flatMap(e -> flatten(new AbstractMap.SimpleEntry<>(entry.getKey() + "/" + e.getKey(), e.getValue())));
}
if (entry.getValue() instanceof List<?>) {
List<?> list = (List<?>) entry.getValue();
return IntStream.range(0, list.size())
.mapToObj(i -> new AbstractMap.SimpleEntry<String, Object>(entry.getKey() + "/" + i, list.get(i)))
.flatMap(FlatMapUtils::flatten);
}
return Stream.of(entry);
}
}
| 2,382 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ReflectionUtils.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/ReflectionUtils.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.impl.http.wiremock;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* @deprecated Will be deleted with https://jira.adorsys.de/browse/XS2AAD-624.
*
* Simple utility class for working with the reflection API and handling
* reflection exceptions.
*
* <p>Only intended for internal use.
*
* <p>Removed usage of Nullable annotation and Assert class
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Rod Johnson
* @author Costin Leau
* @author Sam Brannen
* @author Chris Beams
* @since 1.2.2
*/
@Deprecated
final class ReflectionUtils {
public static final ReflectionUtils.MethodFilter USER_DECLARED_METHODS = (method) -> {
return !method.isBridge() && !method.isSynthetic();
};
public static final ReflectionUtils.FieldFilter COPYABLE_FIELDS = (field) -> {
return !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers());
};
private static final String CGLIB_RENAMED_METHOD_PREFIX = "CGLIB$";
private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0];
private static final Method[] EMPTY_METHOD_ARRAY = new Method[0];
private static final Field[] EMPTY_FIELD_ARRAY = new Field[0];
private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
private static final Map<Class<?>, Method[]> declaredMethodsCache = new ConcurrentHashMap<>(256);
private static final Map<Class<?>, Field[]> declaredFieldsCache = new ConcurrentHashMap(256);
private ReflectionUtils() {
}
public static void handleReflectionException(Exception ex) {
if (ex instanceof NoSuchMethodException) {
throw new IllegalStateException("Method not found: " + ex.getMessage());
} else if (ex instanceof IllegalAccessException) {
throw new IllegalStateException("Could not access method or field: " + ex.getMessage());
} else {
if (ex instanceof InvocationTargetException) {
handleInvocationTargetException((InvocationTargetException) ex);
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new UndeclaredThrowableException(ex);
}
}
}
public static void handleInvocationTargetException(InvocationTargetException ex) {
rethrowRuntimeException(ex.getTargetException());
}
public static void rethrowRuntimeException(Throwable ex) {
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else if (ex instanceof Error) {
throw (Error) ex;
} else {
throw new UndeclaredThrowableException(ex);
}
}
public static void rethrowException(Throwable ex) throws Exception {
if (ex instanceof Exception) {
throw (Exception) ex;
} else if (ex instanceof Error) {
throw (Error) ex;
} else {
throw new UndeclaredThrowableException(ex);
}
}
public static <T> Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes) throws NoSuchMethodException {
Constructor<T> ctor = clazz.getDeclaredConstructor(parameterTypes);
makeAccessible(ctor);
return ctor;
}
public static void makeAccessible(Constructor<?> ctor) {
if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
ctor.setAccessible(true);
}
}
public static Method findMethod(Class<?> clazz, String name) {
return findMethod(clazz, name, EMPTY_CLASS_ARRAY);
}
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
for (Class searchType = clazz; searchType != null; searchType = searchType.getSuperclass()) {
Method[] methods = searchType.isInterface() ? searchType.getMethods() : getDeclaredMethods(searchType, false);
Method[] var5 = methods;
int var6 = methods.length;
for (int var7 = 0; var7 < var6; ++var7) {
Method method = var5[var7];
if (name.equals(method.getName()) && (paramTypes == null || hasSameParams(method, paramTypes))) {
return method;
}
}
}
return null;
}
private static boolean hasSameParams(Method method, Class<?>[] paramTypes) {
return paramTypes.length == method.getParameterCount() && Arrays.equals(paramTypes, method.getParameterTypes());
}
public static Object invokeMethod(Method method, Object target) {
return invokeMethod(method, target, EMPTY_OBJECT_ARRAY);
}
public static Object invokeMethod(Method method, Object target, Object... args) {
try {
return method.invoke(target, args);
} catch (Exception var4) {
handleReflectionException(var4);
throw new IllegalStateException("Should never get here");
}
}
public static boolean declaresException(Method method, Class<?> exceptionType) {
Class<?>[] declaredExceptions = method.getExceptionTypes();
Class[] var3 = declaredExceptions;
int var4 = declaredExceptions.length;
for (int var5 = 0; var5 < var4; ++var5) {
Class<?> declaredException = var3[var5];
if (declaredException.isAssignableFrom(exceptionType)) {
return true;
}
}
return false;
}
public static void doWithLocalMethods(Class<?> clazz, ReflectionUtils.MethodCallback mc) {
Method[] methods = getDeclaredMethods(clazz, false);
Method[] var3 = methods;
int var4 = methods.length;
for (int var5 = 0; var5 < var4; ++var5) {
Method method = var3[var5];
try {
mc.doWith(method);
} catch (IllegalAccessException var8) {
throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + var8);
}
}
}
public static void doWithMethods(Class<?> clazz, ReflectionUtils.MethodCallback mc) {
doWithMethods(clazz, mc, (ReflectionUtils.MethodFilter) null);
}
public static void doWithMethods(Class<?> clazz, ReflectionUtils.MethodCallback mc, ReflectionUtils.MethodFilter mf) {
Method[] methods = getDeclaredMethods(clazz, false);
Method[] var4 = methods;
int var5 = methods.length;
int var6;
for (var6 = 0; var6 < var5; ++var6) {
Method method = var4[var6];
if (mf == null || mf.matches(method)) {
try {
mc.doWith(method);
} catch (IllegalAccessException var9) {
throw new IllegalStateException("Not allowed to access method '" + method.getName() + "': " + var9);
}
}
}
if (clazz.getSuperclass() == null || mf == USER_DECLARED_METHODS && clazz.getSuperclass() == Object.class) {
if (clazz.isInterface()) {
Class[] var10 = clazz.getInterfaces();
var5 = var10.length;
for (var6 = 0; var6 < var5; ++var6) {
Class<?> superIfc = var10[var6];
doWithMethods(superIfc, mc, mf);
}
}
} else {
doWithMethods(clazz.getSuperclass(), mc, mf);
}
}
public static Method[] getAllDeclaredMethods(Class<?> leafClass) {
List<Method> methods = new ArrayList(32);
doWithMethods(leafClass, methods::add);
return (Method[]) methods.toArray(EMPTY_METHOD_ARRAY);
}
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) {
return getUniqueDeclaredMethods(leafClass, (ReflectionUtils.MethodFilter) null);
}
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass, ReflectionUtils.MethodFilter mf) {
List<Method> methods = new ArrayList(32);
doWithMethods(leafClass, (method) -> {
boolean knownSignature = false;
Method methodBeingOverriddenWithCovariantReturnType = null;
Iterator var4 = methods.iterator();
while (var4.hasNext()) {
Method existingMethod = (Method) var4.next();
if (method.getName().equals(existingMethod.getName()) && method.getParameterCount() == existingMethod.getParameterCount() && Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {
if (existingMethod.getReturnType() != method.getReturnType() && existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {
methodBeingOverriddenWithCovariantReturnType = existingMethod;
break;
}
knownSignature = true;
break;
}
}
if (methodBeingOverriddenWithCovariantReturnType != null) {
methods.remove(methodBeingOverriddenWithCovariantReturnType);
}
if (!knownSignature && !isCglibRenamedMethod(method)) {
methods.add(method);
}
}, mf);
return (Method[]) methods.toArray(EMPTY_METHOD_ARRAY);
}
public static Method[] getDeclaredMethods(Class<?> clazz) {
return getDeclaredMethods(clazz, true);
}
private static Method[] getDeclaredMethods(Class<?> clazz, boolean defensive) {
Method[] result = (Method[]) declaredMethodsCache.get(clazz);
if (result == null) {
try {
Method[] declaredMethods = clazz.getDeclaredMethods();
List<Method> defaultMethods = findConcreteMethodsOnInterfaces(clazz);
if (defaultMethods != null) {
result = new Method[declaredMethods.length + defaultMethods.size()];
System.arraycopy(declaredMethods, 0, result, 0, declaredMethods.length);
int index = declaredMethods.length;
for (Iterator var6 = defaultMethods.iterator(); var6.hasNext(); ++index) {
Method defaultMethod = (Method) var6.next();
result[index] = defaultMethod;
}
} else {
result = declaredMethods;
}
declaredMethodsCache.put(clazz, result.length == 0 ? EMPTY_METHOD_ARRAY : result);
} catch (Throwable var8) {
throw new IllegalStateException("Failed to introspect Class [" + clazz.getName() + "] from ClassLoader [" + clazz.getClassLoader() + "]", var8);
}
}
return result.length != 0 && defensive ? (Method[]) result.clone() : result;
}
private static List<Method> findConcreteMethodsOnInterfaces(Class<?> clazz) {
List<Method> result = null;
Class[] var2 = clazz.getInterfaces();
int var3 = var2.length;
for (int var4 = 0; var4 < var3; ++var4) {
Class<?> ifc = var2[var4];
Method[] var6 = ifc.getMethods();
int var7 = var6.length;
for (int var8 = 0; var8 < var7; ++var8) {
Method ifcMethod = var6[var8];
if (!Modifier.isAbstract(ifcMethod.getModifiers())) {
if (result == null) {
result = new ArrayList();
}
result.add(ifcMethod);
}
}
}
return result;
}
public static boolean isEqualsMethod(Method method) {
if (method != null && method.getName().equals("equals")) {
if (method.getParameterCount() != 1) {
return false;
} else {
return method.getParameterTypes()[0] == Object.class;
}
} else {
return false;
}
}
public static boolean isHashCodeMethod(Method method) {
return method != null && method.getName().equals("hashCode") && method.getParameterCount() == 0;
}
public static boolean isToStringMethod(Method method) {
return method != null && method.getName().equals("toString") && method.getParameterCount() == 0;
}
public static boolean isObjectMethod(Method method) {
return method != null && (method.getDeclaringClass() == Object.class || isEqualsMethod(method) || isHashCodeMethod(method) || isToStringMethod(method));
}
public static boolean isCglibRenamedMethod(Method renamedMethod) {
String name = renamedMethod.getName();
if (!name.startsWith("CGLIB$")) {
return false;
} else {
int i;
for (i = name.length() - 1; i >= 0 && Character.isDigit(name.charAt(i)); --i) {
int y = 0; //empty cycle
}
return i > "CGLIB$".length() && i < name.length() - 1 && name.charAt(i) == '$';
}
}
public static void makeAccessible(Method method) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
method.setAccessible(true);
}
}
public static Field findField(Class<?> clazz, String name) {
return findField(clazz, name, (Class) null);
}
public static Field findField(Class<?> clazz, String name, Class<?> type) {
for (Class searchType = clazz; Object.class != searchType && searchType != null; searchType = searchType.getSuperclass()) {
Field[] fields = getDeclaredFields(searchType);
Field[] var5 = fields;
int var6 = fields.length;
for (int var7 = 0; var7 < var6; ++var7) {
Field field = var5[var7];
if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) {
return field;
}
}
}
return null;
}
public static void setField(Field field, Object target, Object value) {
try {
field.set(target, value);
} catch (IllegalAccessException var4) {
handleReflectionException(var4);
}
}
public static Object getField(Field field, Object target) {
try {
return field.get(target);
} catch (IllegalAccessException var3) {
handleReflectionException(var3);
throw new IllegalStateException("Should never get here");
}
}
public static void doWithLocalFields(Class<?> clazz, ReflectionUtils.FieldCallback fc) {
Field[] var2 = getDeclaredFields(clazz);
int var3 = var2.length;
for (int var4 = 0; var4 < var3; ++var4) {
Field field = var2[var4];
try {
fc.doWith(field);
} catch (IllegalAccessException var7) {
throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + var7);
}
}
}
public static void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc) {
doWithFields(clazz, fc, (ReflectionUtils.FieldFilter) null);
}
public static void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc, ReflectionUtils.FieldFilter ff) {
Class targetClass = clazz;
do {
Field[] fields = getDeclaredFields(targetClass);
Field[] var5 = fields;
int var6 = fields.length;
for (int var7 = 0; var7 < var6; ++var7) {
Field field = var5[var7];
if (ff == null || ff.matches(field)) {
try {
fc.doWith(field);
} catch (IllegalAccessException var10) {
throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + var10);
}
}
}
targetClass = targetClass.getSuperclass();
} while (targetClass != null && targetClass != Object.class);
}
private static Field[] getDeclaredFields(Class<?> clazz) {
Field[] result = (Field[]) declaredFieldsCache.get(clazz);
if (result == null) {
try {
result = clazz.getDeclaredFields();
declaredFieldsCache.put(clazz, result.length == 0 ? EMPTY_FIELD_ARRAY : result);
} catch (Throwable var3) {
throw new IllegalStateException("Failed to introspect Class [" + clazz.getName() + "] from ClassLoader [" + clazz.getClassLoader() + "]", var3);
}
}
return result;
}
public static void shallowCopyFieldState(Object src, Object dest) {
if (!src.getClass().isAssignableFrom(dest.getClass())) {
throw new IllegalArgumentException("Destination class [" + dest.getClass().getName() + "] must be same or subclass as source class [" + src.getClass().getName() + "]");
} else {
doWithFields(src.getClass(), (field) -> {
makeAccessible(field);
Object srcValue = field.get(src);
field.set(dest, srcValue);
}, COPYABLE_FIELDS);
}
}
public static boolean isPublicStaticFinal(Field field) {
int modifiers = field.getModifiers();
return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers);
}
public static void makeAccessible(Field field) {
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
field.setAccessible(true);
}
}
public static void clearCache() {
declaredMethodsCache.clear();
declaredFieldsCache.clear();
}
@FunctionalInterface
public interface FieldFilter {
boolean matches(Field var1);
}
@FunctionalInterface
public interface FieldCallback {
void doWith(Field var1) throws IllegalArgumentException, IllegalAccessException;
}
@FunctionalInterface
public interface MethodFilter {
boolean matches(Method var1);
}
@FunctionalInterface
public interface MethodCallback {
void doWith(Method var1) throws IllegalArgumentException, IllegalAccessException;
}
}
| 19,492 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
StringUtils.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/http/wiremock/StringUtils.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.impl.http.wiremock;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.*;
/**
* @deprecated Will be deleted with https://jira.adorsys.de/browse/XS2AAD-624.
* Miscellaneous {@link String} utility methods.
*
* <p>Mainly for internal use within the framework; consider
* <a href="https://commons.apache.org/proper/commons-lang/">Apache's Commons Lang</a>
* for a more comprehensive suite of {@code String} utilities.
*
* <p>This class delivers some simple functionality that should really be
* provided by the core Java {@link String} and {@link StringBuilder}
* classes. It also provides easy-to-use methods to convert between
* delimited strings, such as CSV strings, and collections and arrays.
*
* <p>Removed usage of Nullable annotation and Assert class
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Keith Donald
* @author Rob Harrop
* @author Rick Evans
* @author Arjen Poutsma
* @author Sam Brannen
* @author Brian Clozel
* @since 16 April 2001
*/
@Deprecated
final class StringUtils {
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private StringUtils() {
}
public static boolean isEmpty(Object str) {
return str == null || "".equals(str);
}
public static boolean hasLength(CharSequence str) {
return str != null && str.length() > 0;
}
public static boolean hasLength(String str) {
return str != null && !str.isEmpty();
}
public static boolean hasText(CharSequence str) {
return str != null && str.length() > 0 && containsText(str);
}
public static boolean hasText(String str) {
return str != null && !str.isEmpty() && containsText(str);
}
private static boolean containsText(CharSequence str) {
int strLen = str.length();
for (int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
public static boolean containsWhitespace(CharSequence str) {
if (!hasLength(str)) {
return false;
} else {
int strLen = str.length();
for (int i = 0; i < strLen; ++i) {
if (Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
}
public static boolean containsWhitespace(String str) {
return containsWhitespace((CharSequence) str);
}
public static String trimWhitespace(String str) {
if (!hasLength(str)) {
return str;
} else {
int beginIndex = 0;
int endIndex;
for (endIndex = str.length() - 1; beginIndex <= endIndex && Character.isWhitespace(str.charAt(beginIndex)); ++beginIndex) {
int i = 0; // empty cycle
}
while (endIndex > beginIndex && Character.isWhitespace(str.charAt(endIndex))) {
--endIndex;
}
return str.substring(beginIndex, endIndex + 1);
}
}
public static String trimAllWhitespace(String str) {
if (!hasLength(str)) {
return str;
} else {
int len = str.length();
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
return sb.toString();
}
}
public static String trimLeadingWhitespace(String str) {
if (!hasLength(str)) {
return str;
} else {
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
sb.deleteCharAt(0);
}
return sb.toString();
}
}
public static String trimTrailingWhitespace(String str) {
if (!hasLength(str)) {
return str;
} else {
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}
public static String trimLeadingCharacter(String str, char leadingCharacter) {
if (!hasLength(str)) {
return str;
} else {
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {
sb.deleteCharAt(0);
}
return sb.toString();
}
}
public static String trimTrailingCharacter(String str, char trailingCharacter) {
if (!hasLength(str)) {
return str;
} else {
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}
public static boolean startsWithIgnoreCase(String str, String prefix) {
return str != null && prefix != null && str.length() >= prefix.length() && str.regionMatches(true, 0, prefix, 0, prefix.length());
}
public static boolean endsWithIgnoreCase(String str, String suffix) {
return str != null && suffix != null && str.length() >= suffix.length() && str.regionMatches(true, str.length() - suffix.length(), suffix, 0, suffix.length());
}
public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {
if (index + substring.length() > str.length()) {
return false;
} else {
for (int i = 0; i < substring.length(); ++i) {
if (str.charAt(index + i) != substring.charAt(i)) {
return false;
}
}
return true;
}
}
public static int countOccurrencesOf(String str, String sub) {
if (hasLength(str) && hasLength(sub)) {
int count = 0;
int idx;
int pos = 0;
while ((idx = str.indexOf(sub, pos)) != -1) {
++count;
pos = idx + sub.length();
}
return count;
} else {
return 0;
}
}
public static String replace(String inString, String oldPattern, String newPattern) {
if (hasLength(inString) && hasLength(oldPattern) && newPattern != null) {
int index = inString.indexOf(oldPattern);
if (index == -1) {
return inString;
} else {
int capacity = inString.length();
if (newPattern.length() > oldPattern.length()) {
capacity += 16;
}
StringBuilder sb = new StringBuilder(capacity);
int pos = 0;
for (int patLen = oldPattern.length(); index >= 0; index = inString.indexOf(oldPattern, pos)) {
sb.append(inString, pos, index);
sb.append(newPattern);
pos = index + patLen;
}
sb.append(inString, pos, inString.length());
return sb.toString();
}
} else {
return inString;
}
}
public static String delete(String inString, String pattern) {
return replace(inString, pattern, "");
}
public static String deleteAny(String inString, String charsToDelete) {
if (hasLength(inString) && hasLength(charsToDelete)) {
int lastCharIndex = 0;
char[] result = new char[inString.length()];
for (int i = 0; i < inString.length(); ++i) {
char c = inString.charAt(i);
if (charsToDelete.indexOf(c) == -1) {
result[lastCharIndex++] = c;
}
}
if (lastCharIndex == inString.length()) {
return inString;
} else {
return new String(result, 0, lastCharIndex);
}
} else {
return inString;
}
}
public static String quote(String str) {
return str != null ? "'" + str + "'" : null;
}
public static Object quoteIfString(Object obj) {
return obj instanceof String ? quote((String) obj) : obj;
}
public static String unqualify(String qualifiedName) {
return unqualify(qualifiedName, '.');
}
public static String unqualify(String qualifiedName, char separator) {
return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);
}
public static String capitalize(String str) {
return changeFirstCharacterCase(str, true);
}
public static String uncapitalize(String str) {
return changeFirstCharacterCase(str, false);
}
private static String changeFirstCharacterCase(String str, boolean capitalize) {
if (!hasLength(str)) {
return str;
} else {
char baseChar = str.charAt(0);
char updatedChar;
if (capitalize) {
updatedChar = Character.toUpperCase(baseChar);
} else {
updatedChar = Character.toLowerCase(baseChar);
}
if (baseChar == updatedChar) {
return str;
} else {
char[] chars = str.toCharArray();
chars[0] = updatedChar;
return new String(chars, 0, chars.length);
}
}
}
public static String getFilename(String path) {
if (path == null) {
return null;
} else {
int separatorIndex = path.lastIndexOf("/");
return separatorIndex != -1 ? path.substring(separatorIndex + 1) : path;
}
}
public static String getFilenameExtension(String path) {
if (path == null) {
return null;
} else {
int extIndex = path.lastIndexOf(46);
if (extIndex == -1) {
return null;
} else {
int folderIndex = path.lastIndexOf("/");
return folderIndex > extIndex ? null : path.substring(extIndex + 1);
}
}
}
public static String stripFilenameExtension(String path) {
int extIndex = path.lastIndexOf(46);
if (extIndex == -1) {
return path;
} else {
int folderIndex = path.lastIndexOf("/");
return folderIndex > extIndex ? path : path.substring(0, extIndex);
}
}
public static String applyRelativePath(String path, String relativePath) {
int separatorIndex = path.lastIndexOf("/");
if (separatorIndex != -1) {
String newPath = path.substring(0, separatorIndex);
if (!relativePath.startsWith("/")) {
newPath = newPath + "/";
}
return newPath + relativePath;
} else {
return relativePath;
}
}
public static String cleanPath(String path) {
if (!hasLength(path)) {
return path;
} else {
String pathToUse = replace(path, "\\", "/");
if (pathToUse.indexOf(46) == -1) {
return pathToUse;
} else {
int prefixIndex = pathToUse.indexOf(58);
String prefix = "";
if (prefixIndex != -1) {
prefix = pathToUse.substring(0, prefixIndex + 1);
if (prefix.contains("/")) {
prefix = "";
} else {
pathToUse = pathToUse.substring(prefixIndex + 1);
}
}
if (pathToUse.startsWith("/")) {
prefix = prefix + "/";
pathToUse = pathToUse.substring(1);
}
String[] pathArray = delimitedListToStringArray(pathToUse, "/");
LinkedList<String> pathElements = new LinkedList();
int tops = 0;
int i;
for (i = pathArray.length - 1; i >= 0; --i) {
String element = pathArray[i];
if (!".".equals(element)) {
if ("..".equals(element)) {
++tops;
} else if (tops > 0) {
--tops;
} else {
pathElements.add(0, element);
}
}
}
if (pathArray.length == pathElements.size()) {
return prefix + pathToUse;
} else {
for (i = 0; i < tops; ++i) {
pathElements.add(0, "..");
}
if (pathElements.size() == 1 && "".equals(pathElements.getLast()) && !prefix.endsWith("/")) {
pathElements.add(0, ".");
}
return prefix + collectionToDelimitedString(pathElements, "/");
}
}
}
}
public static boolean pathEquals(String path1, String path2) {
return cleanPath(path1).equals(cleanPath(path2));
}
public static String uriDecode(String source, Charset charset) {
int length = source.length();
if (length == 0) {
return source;
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream(length);
boolean changed = false;
for (int i = 0; i < length; ++i) {
int ch = source.charAt(i);
if (ch == '%') {
if (i + 2 >= length) {
throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\"");
}
char hex1 = source.charAt(i + 1);
char hex2 = source.charAt(i + 2);
int u = Character.digit(hex1, 16);
int l = Character.digit(hex2, 16);
if (u == -1 || l == -1) {
throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\"");
}
baos.write((char) ((u << 4) + l));
i += 2;
changed = true;
} else {
baos.write(ch);
}
}
return changed ? copyToString(baos, charset) : source;
}
}
public static Locale parseLocale(String localeValue) {
String[] tokens = tokenizeLocaleSource(localeValue);
if (tokens.length == 1) {
validateLocalePart(localeValue);
Locale resolved = Locale.forLanguageTag(localeValue);
if (resolved.getLanguage().length() > 0) {
return resolved;
}
}
return parseLocaleTokens(localeValue, tokens);
}
public static Locale parseLocaleString(String localeString) {
return parseLocaleTokens(localeString, tokenizeLocaleSource(localeString));
}
private static String[] tokenizeLocaleSource(String localeSource) {
return tokenizeToStringArray(localeSource, "_ ", false, false);
}
private static Locale parseLocaleTokens(String localeString, String[] tokens) {
String language = tokens.length > 0 ? tokens[0] : "";
String country = tokens.length > 1 ? tokens[1] : "";
validateLocalePart(language);
validateLocalePart(country);
String variant = "";
if (tokens.length > 2) {
int endIndexOfCountryCode = localeString.indexOf(country, language.length()) + country.length();
variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));
if (variant.startsWith("_")) {
variant = trimLeadingCharacter(variant, '_');
}
}
if (variant.isEmpty() && country.startsWith("#")) {
variant = country;
country = "";
}
return language.length() > 0 ? new Locale(language, country, variant) : null;
}
private static void validateLocalePart(String localePart) {
for (int i = 0; i < localePart.length(); ++i) {
char ch = localePart.charAt(i);
if (ch != ' ' && ch != '_' && ch != '-' && ch != '#' && !Character.isLetterOrDigit(ch)) {
throw new IllegalArgumentException("Locale part \"" + localePart + "\" contains invalid characters");
}
}
}
/**
* @deprecated
*/
@Deprecated
public static String toLanguageTag(Locale locale) {
return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : "");
}
public static TimeZone parseTimeZoneString(String timeZoneString) {
TimeZone timeZone = TimeZone.getTimeZone(timeZoneString);
if ("GMT".equals(timeZone.getID()) && !timeZoneString.startsWith("GMT")) {
throw new IllegalArgumentException("Invalid time zone specification '" + timeZoneString + "'");
} else {
return timeZone;
}
}
public static String[] toStringArray(Collection<String> collection) {
return !isEmpty(collection) ? (String[]) collection.toArray(EMPTY_STRING_ARRAY) : EMPTY_STRING_ARRAY;
}
public static String[] toStringArray(Enumeration<String> enumeration) {
return enumeration != null ? toStringArray((Collection) Collections.list(enumeration)) : EMPTY_STRING_ARRAY;
}
public static String[] addStringToArray(String[] array, String str) {
if (isEmpty(array)) {
return new String[]{str};
} else {
String[] newArr = new String[array.length + 1];
System.arraycopy(array, 0, newArr, 0, array.length);
newArr[array.length] = str;
return newArr;
}
}
public static String[] concatenateStringArrays(String[] array1, String[] array2) {
if (isEmpty(array1)) {
return array2;
} else if (isEmpty(array2)) {
return array1;
} else {
String[] newArr = new String[array1.length + array2.length];
System.arraycopy(array1, 0, newArr, 0, array1.length);
System.arraycopy(array2, 0, newArr, array1.length, array2.length);
return newArr;
}
}
/**
* @deprecated
*/
@Deprecated
public static String[] mergeStringArrays(String[] array1, String[] array2) {
if (isEmpty(array1)) {
return array2;
} else if (isEmpty(array2)) {
return array1;
} else {
List<String> result = new ArrayList(Arrays.asList(array1));
String[] var3 = array2;
int var4 = array2.length;
for (int var5 = 0; var5 < var4; ++var5) {
String str = var3[var5];
if (!result.contains(str)) {
result.add(str);
}
}
return toStringArray((Collection) result);
}
}
public static String[] sortStringArray(String[] array) {
if (isEmpty(array)) {
return array;
} else {
Arrays.sort(array);
return array;
}
}
public static String[] trimArrayElements(String[] array) {
if (isEmpty(array)) {
return array;
} else {
String[] result = new String[array.length];
for (int i = 0; i < array.length; ++i) {
String element = array[i];
result[i] = element != null ? element.trim() : null;
}
return result;
}
}
public static String[] removeDuplicateStrings(String[] array) {
if (isEmpty(array)) {
return array;
} else {
Set<String> set = new LinkedHashSet(Arrays.asList(array));
return toStringArray((Collection) set);
}
}
public static String[] split(String toSplit, String delimiter) {
if (hasLength(toSplit) && hasLength(delimiter)) {
int offset = toSplit.indexOf(delimiter);
if (offset < 0) {
return null;
} else {
String beforeDelimiter = toSplit.substring(0, offset);
String afterDelimiter = toSplit.substring(offset + delimiter.length());
return new String[]{beforeDelimiter, afterDelimiter};
}
} else {
return null;
}
}
public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {
return splitArrayElementsIntoProperties(array, delimiter, (String) null);
}
public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter, String charsToDelete) {
if (isEmpty(array)) {
return null;
} else {
Properties result = new Properties();
String[] var4 = array;
int var5 = array.length;
for (int var6 = 0; var6 < var5; ++var6) {
String element = var4[var6];
if (charsToDelete != null) {
element = deleteAny(element, charsToDelete);
}
String[] splittedElement = split(element, delimiter);
if (splittedElement != null) {
result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());
}
}
return result;
}
}
public static String[] tokenizeToStringArray(String str, String delimiters) {
return tokenizeToStringArray(str, delimiters, true, true);
}
public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {
if (str == null) {
return EMPTY_STRING_ARRAY;
} else {
StringTokenizer st = new StringTokenizer(str, delimiters);
ArrayList tokens = new ArrayList();
while (true) {
String token;
do {
if (!st.hasMoreTokens()) {
return toStringArray((Collection) tokens);
}
token = st.nextToken();
if (trimTokens) {
token = token.trim();
}
} while (ignoreEmptyTokens && token.length() <= 0);
tokens.add(token);
}
}
}
public static String[] delimitedListToStringArray(String str, String delimiter) {
return delimitedListToStringArray(str, delimiter, (String) null);
}
public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {
if (str == null) {
return EMPTY_STRING_ARRAY;
} else if (delimiter == null) {
return new String[]{str};
} else {
List<String> result = new ArrayList();
int pos;
if (delimiter.isEmpty()) {
for (pos = 0; pos < str.length(); ++pos) {
result.add(deleteAny(str.substring(pos, pos + 1), charsToDelete));
}
} else {
int delPos;
pos = 0;
while ((delPos = str.indexOf(delimiter, pos)) != -1) {
result.add(deleteAny(str.substring(pos, delPos), charsToDelete));
pos = delPos + delimiter.length();
}
if (str.length() > 0 && pos <= str.length()) {
result.add(deleteAny(str.substring(pos), charsToDelete));
}
}
return toStringArray((Collection) result);
}
}
public static String[] commaDelimitedListToStringArray(String str) {
return delimitedListToStringArray(str, ",");
}
public static Set<String> commaDelimitedListToSet(String str) {
String[] tokens = commaDelimitedListToStringArray(str);
return new LinkedHashSet(Arrays.asList(tokens));
}
public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) {
if (isEmpty(coll)) {
return "";
} else {
StringBuilder sb = new StringBuilder();
Iterator it = coll.iterator();
while (it.hasNext()) {
sb.append(prefix).append(it.next()).append(suffix);
if (it.hasNext()) {
sb.append(delim);
}
}
return sb.toString();
}
}
public static String collectionToDelimitedString(Collection<?> coll, String delim) {
return collectionToDelimitedString(coll, delim, "", "");
}
public static String collectionToCommaDelimitedString(Collection<?> coll) {
return collectionToDelimitedString(coll, ",");
}
public static String arrayToDelimitedString(Object[] arr, String delim) {
if (isEmpty(arr)) {
return "";
} else if (arr.length == 1) {
return nullSafeToString(arr[0]);
} else {
StringJoiner sj = new StringJoiner(delim);
Object[] var3 = arr;
int var4 = arr.length;
for (int var5 = 0; var5 < var4; ++var5) {
Object o = var3[var5];
sj.add(String.valueOf(o));
}
return sj.toString();
}
}
public static String arrayToCommaDelimitedString(Object[] arr) {
return arrayToDelimitedString(arr, ",");
}
public static String copyToString(ByteArrayOutputStream baos, Charset charset) {
try {
return baos.toString(charset.name());
} catch (UnsupportedEncodingException var3) {
throw new RuntimeException("Failed to copy contents of ByteArrayOutputStream into a String", var3);
}
}
public static boolean isEmpty(Object[] array) {
return array == null || array.length == 0;
}
public static String nullSafeToString(Object obj) {
if (obj == null) {
return "null";
} else if (obj instanceof String) {
return (String) obj;
} else if (obj instanceof Object[]) {
return nullSafeToString((Object[]) ((Object[]) obj));
} else if (obj instanceof boolean[]) {
return nullSafeToString((boolean[]) ((boolean[]) obj));
} else if (obj instanceof byte[]) {
return nullSafeToString((byte[]) ((byte[]) obj));
} else if (obj instanceof char[]) {
return nullSafeToString((char[]) ((char[]) obj));
} else if (obj instanceof double[]) {
return nullSafeToString((double[]) ((double[]) obj));
} else if (obj instanceof float[]) {
return nullSafeToString((float[]) ((float[]) obj));
} else if (obj instanceof int[]) {
return nullSafeToString((int[]) ((int[]) obj));
} else if (obj instanceof long[]) {
return nullSafeToString((long[]) ((long[]) obj));
} else if (obj instanceof short[]) {
return nullSafeToString((short[]) ((short[]) obj));
} else {
String str = obj.toString();
return str != null ? str : "";
}
}
}
| 28,705 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
IdentityLinksRewriter.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/link/identity/IdentityLinksRewriter.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.impl.link.identity;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.HrefType;
import java.util.Map;
public class IdentityLinksRewriter implements LinksRewriter {
@Override
public Map<String, HrefType> rewrite(Map<String, HrefType> links) {
return links;
}
}
| 1,192 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
BerlinGroupLinksRewriter.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/link/bg/BerlinGroupLinksRewriter.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.impl.link.bg;
import de.adorsys.xs2a.adapter.api.link.LinksRewriter;
import de.adorsys.xs2a.adapter.api.model.HrefType;
import de.adorsys.xs2a.adapter.impl.http.StringUri;
import de.adorsys.xs2a.adapter.impl.link.bg.template.LinksTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static de.adorsys.xs2a.adapter.impl.link.bg.template.LinksTemplate.*;
public class BerlinGroupLinksRewriter implements LinksRewriter {
private static final Logger logger = LoggerFactory.getLogger(BerlinGroupLinksRewriter.class);
private static final Set<String> UNCHANGEABLE_LINKS
= new HashSet<>(Arrays.asList(SCA_REDIRECT, SCA_OAUTH));
private static final String START_OF_PLACEHOLDER = "{";
private static final String END_OF_PLACEHOLDER = "}";
private static final Pattern CONSENT_ID_PATTERN = Pattern.compile("/consents/([^/]+)");
private static final Pattern AUTHORISATION_ID_PATTERN = Pattern.compile("/authorisations/([^/]+)");
private static final Pattern ACCOUNT_ID_PATTERN = Pattern.compile("/accounts/([^/]+)");
private static final Pattern TRANSACTION_ID_PATTERN = Pattern.compile("/transactions/([^/]+)");
private final LinksTemplate linksTemplate;
private final String host;
private final String version;
private final Map<String, Function<String, Optional<String>>> placeholdersToParamRetrievers;
public BerlinGroupLinksRewriter(LinksTemplate linksTemplate,
String host,
String version) {
this.linksTemplate = linksTemplate;
this.host = host;
this.version = version;
this.placeholdersToParamRetrievers = new HashMap<>();
registerPlaceholder(HOST_PLACEHOLDER, this::retrieveHost);
registerPlaceholder(VERSION_PLACEHOLDER, this::retrieveVersion);
registerPlaceholder(CONSENT_ID_PLACEHOLDER, this::retrieveConsentId);
registerPlaceholder(AUTHORISATION_ID_PLACEHOLDER, this::retrieveAuthorisationId);
registerPlaceholder(ACCOUNT_ID_PLACEHOLDER, this::retrieveAccountId);
registerPlaceholder(TRANSACTION_ID_PLACEHOLDER, this::retrieveTransactionId);
registerPlaceholder(PAYMENT_SERVICE_PLACEHOLDER, this::retrievePaymentService);
registerPlaceholder(PAYMENT_PRODUCT_PLACEHOLDER, this::retrievePaymentProduct);
registerPlaceholder(PAYMENT_ID_PLACEHOLDER, this::retrievePaymentId);
}
public void registerPlaceholder(String placeholder,
Function<String, Optional<String>> paramRetriever) {
placeholdersToParamRetrievers.put(placeholder, paramRetriever);
}
@Override
public Map<String, HrefType> rewrite(Map<String, HrefType> links) {
if (links == null || links.isEmpty()) {
return links;
}
Map<String, HrefType> rewrittenLinks = new HashMap<>();
for (Map.Entry<String, HrefType> linkEntry : links.entrySet()) {
String linkName = linkEntry.getKey();
HrefType linkFromAspsp = linkEntry.getValue();
if (linkUnchangeable(linkName)) {
rewrittenLinks.put(linkName, linkFromAspsp);
continue;
}
Optional<String> linkTemplateOptional = linksTemplate.get(linkName);
if (!linkTemplateOptional.isPresent()) {
// business decision to leave unknown links untouched
logger.warn("Links rewriting: unknown link [{}] - will be leaved unmapped", linkName);
rewrittenLinks.put(linkName, linkFromAspsp);
continue;
}
Optional<String> rewrittenLinksOptional
= replacePlaceholdersWithValues(linkTemplateOptional.get(), linkFromAspsp.getHref());
if (rewrittenLinksOptional.isPresent()) {
String rewrittenLink = rewrittenLinksOptional.get();
rewrittenLink = StringUri.copyQueryParams(linkFromAspsp.getHref(), rewrittenLink);
HrefType link = new HrefType();
link.setHref(rewrittenLink);
rewrittenLinks.put(linkName, link);
} else {
// business decision to leave unknown links untouched
logger.warn("Links rewriting: unknown format of the link [{}] - will be leaved unmapped. " +
"Custom rewriting should be provided to handle it", linkName);
rewrittenLinks.put(linkName, linkFromAspsp);
}
}
return rewrittenLinks;
}
protected boolean linkUnchangeable(String linkName) {
return UNCHANGEABLE_LINKS.contains(linkName);
}
private Optional<String> replacePlaceholdersWithValues(String linkTemplate, String linkFromAspsp) {
Set<String> placeholders = getTemplatePlaceholders(linkTemplate);
String rewrittenLink = linkTemplate;
for (String placeholder : placeholders) {
Function<String, Optional<String>> paramRetriever
= placeholdersToParamRetrievers.get(placeholder);
if (paramRetriever == null) {
return Optional.empty();
}
Optional<String> paramOptional = paramRetriever.apply(linkFromAspsp);
if (!paramOptional.isPresent()) {
return Optional.empty();
}
String param = paramOptional.get();
rewrittenLink = rewrittenLink.replace(placeholder, param);
}
return Optional.of(rewrittenLink);
}
private Set<String> getTemplatePlaceholders(String linkTemplate) {
Set<String> placeholders = new LinkedHashSet<>();
int from = 0;
while (true) {
int start = linkTemplate.indexOf(START_OF_PLACEHOLDER, from);
int end = linkTemplate.indexOf(END_OF_PLACEHOLDER, from);
if (start == -1 || end == -1) {
break;
}
String placeholder = linkTemplate.substring(start, end + 1);
placeholders.add(placeholder);
from = end + 1;
}
return placeholders;
}
protected Optional<String> retrieveHost(String link) {
return Optional.ofNullable(host);
}
protected Optional<String> retrieveVersion(String link) {
return Optional.ofNullable(version);
}
protected Optional<String> retrieveConsentId(String link) {
return findUsingPattern(link, CONSENT_ID_PATTERN);
}
private Optional<String> findUsingPattern(String link, Pattern pattern) {
Matcher matcher = pattern.matcher(link);
if (matcher.find()) {
return Optional.of(matcher.group(1));
}
return Optional.empty();
}
protected Optional<String> retrieveAuthorisationId(String link) {
return findUsingPattern(link, AUTHORISATION_ID_PATTERN);
}
protected Optional<String> retrieveAccountId(String link) {
return findUsingPattern(link, ACCOUNT_ID_PATTERN);
}
protected Optional<String> retrieveTransactionId(String link) {
return findUsingPattern(link, TRANSACTION_ID_PATTERN);
}
protected Optional<String> retrievePaymentService(String link) {
String[] linkPaths = getLinkPathsAsArray(link);
// < 1 as payment service is the first path param in the URI
if (linkPaths.length < 1) {
return Optional.empty();
}
// as payment links are compliant with
// the following pattern: `{paymentService}/{paymentProduct}`
// it means that the linkPaths[0] returns payment service value
return Optional.of(linkPaths[0]);
}
private String[] getLinkPathsAsArray(String link) {
Optional<String> aspspApiVersionOptional = StringUri.getVersion(link);
if (!aspspApiVersionOptional.isPresent()) {
return new String[]{};
}
String aspspApiVersion = aspspApiVersionOptional.get();
// `aspspApiVersion.length() + 1` - (+ 1) to include a slash after the version (e.g. `v1/`)
String linkWithoutHostAndVersion
= link.substring(link.indexOf(aspspApiVersion) + aspspApiVersion.length() + 1);
if (linkWithoutHostAndVersion.isEmpty()) {
return new String[]{};
}
return linkWithoutHostAndVersion.split("/");
}
protected Optional<String> retrievePaymentProduct(String link) {
String[] linkPaths = getLinkPathsAsArray(link);
// < 2 as payment product is the second path param in the URI
if (linkPaths.length < 2) {
return Optional.empty();
}
// as payment links are compliant
// with the following pattern: `{paymentService}/{paymentProduct}`
// it means that the linkPaths[1] returns payment product value
return Optional.of(linkPaths[1]);
}
protected Optional<String> retrievePaymentId(String link) {
String[] linkPaths = getLinkPathsAsArray(link);
// < 3 as payment id is the third path param in the URI
if (linkPaths.length < 3) {
return Optional.empty();
}
// as payment links (that contains payment id) are compliant
// with the following pattern: `{paymentService}/{paymentProduct}/{paymentId}`
// it means that the linkPaths[2] returns payment id value
return Optional.of(linkPaths[2]);
}
}
| 10,440 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PaymentInitiationLinksTemplate.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/link/bg/template/PaymentInitiationLinksTemplate.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.impl.link.bg.template;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class PaymentInitiationLinksTemplate extends LinksTemplate {
// link templates:
private static final String START_AUTHORISATION_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/authorisations";
private static final String START_AUTHORISATION_WITH_PSU_IDENTIFICATION_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/authorisations";
private static final String UPDATE_PSU_IDENTIFICATION_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/authorisations/{authorisationId}";
private static final String START_AUTHORISATION_WITH_PSU_AUTHENTICATION_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/authorisations";
private static final String UPDATE_PSU_AUTHENTICATION_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/authorisations/{authorisationId}";
private static final String START_AUTHORISATION_WITH_ENCRYPTED_PSU_AUTHENTICATION_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/authorisations/{authorisationId}";
private static final String UPDATE_ENCRYPTED_PSU_AUTHENTICATION_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/authorisations/{authorisationId}";
private static final String START_AUTHORISATION_WITH_TRANSACTION_AUTHORISATION_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/authorisations/{authorisationId}";
private static final String SELECT_AUTHENTICATION_METHOD_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/authorisations/{authorisationId}";
private static final String AUTHORISE_TRANSACTION_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/authorisations/{authorisationId}";
private static final String SELF_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}";
private static final String STATUS_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/status";
private static final String SCA_STATUS_TEMPLATE = "{host}/{version}/{paymentService}/{paymentProduct}/{paymentId}/authorisations/{authorisationId}";
private final Map<String, String> linkNameToTemplate;
public PaymentInitiationLinksTemplate() {
linkNameToTemplate = new HashMap<>();
linkNameToTemplate.put(START_AUTHORISATION, START_AUTHORISATION_TEMPLATE);
linkNameToTemplate.put(START_AUTHORISATION_WITH_PSU_IDENTIFICATION,
START_AUTHORISATION_WITH_PSU_IDENTIFICATION_TEMPLATE);
linkNameToTemplate.put(UPDATE_PSU_IDENTIFICATION, UPDATE_PSU_IDENTIFICATION_TEMPLATE);
linkNameToTemplate.put(START_AUTHORISATION_WITH_PSU_AUTHENTICATION,
START_AUTHORISATION_WITH_PSU_AUTHENTICATION_TEMPLATE);
linkNameToTemplate.put(UPDATE_PSU_AUTHENTICATION, UPDATE_PSU_AUTHENTICATION_TEMPLATE);
linkNameToTemplate.put(START_AUTHORISATION_WITH_ENCRYPTED_PSU_AUTHENTICATION,
START_AUTHORISATION_WITH_ENCRYPTED_PSU_AUTHENTICATION_TEMPLATE);
linkNameToTemplate.put(UPDATE_ENCRYPTED_PSU_AUTHENTICATION,
UPDATE_ENCRYPTED_PSU_AUTHENTICATION_TEMPLATE);
linkNameToTemplate.put(START_AUTHORISATION_WITH_TRANSACTION_AUTHORISATION,
START_AUTHORISATION_WITH_TRANSACTION_AUTHORISATION_TEMPLATE);
linkNameToTemplate.put(SELECT_AUTHENTICATION_METHOD, SELECT_AUTHENTICATION_METHOD_TEMPLATE);
linkNameToTemplate.put(AUTHORISE_TRANSACTION, AUTHORISE_TRANSACTION_TEMPLATE);
linkNameToTemplate.put(SELF, SELF_TEMPLATE);
linkNameToTemplate.put(STATUS, STATUS_TEMPLATE);
linkNameToTemplate.put(SCA_STATUS, SCA_STATUS_TEMPLATE);
}
@Override
public Optional<String> get(String linkName) {
return Optional.ofNullable(linkNameToTemplate.get(linkName));
}
@Override
public void set(String linkName, String linkTemplate) {
linkNameToTemplate.put(linkName, linkTemplate);
}
}
| 4,971 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AccountInformationLinksTemplate.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/link/bg/template/AccountInformationLinksTemplate.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.impl.link.bg.template;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class AccountInformationLinksTemplate extends LinksTemplate {
// link templates:
private static final String START_AUTHORISATION_TEMPLATE = "{host}/{version}/consents/{consentId}/authorisations";
private static final String START_AUTHORISATION_WITH_PSU_IDENTIFICATION_TEMPLATE = "{host}/{version}/consents/{consentId}/authorisations";
private static final String UPDATE_PSU_IDENTIFICATION_TEMPLATE = "{host}/{version}/consents/{consentId}/authorisations/{authorisationId}";
private static final String START_AUTHORISATION_WITH_PSU_AUTHENTICATION_TEMPLATE = "{host}/{version}/consents/{consentId}/authorisations";
private static final String UPDATE_PSU_AUTHENTICATION_TEMPLATE = "{host}/{version}/consents/{consentId}/authorisations/{authorisationId}";
private static final String START_AUTHORISATION_WITH_ENCRYPTED_PSU_AUTHENTICATION_TEMPLATE = "{host}/{version}/consents/{consentId}/authorisations/{authorisationId}";
private static final String UPDATE_ENCRYPTED_PSU_AUTHENTICATION_TEMPLATE = "{host}/{version}/consents/{consentId}/authorisations/{authorisationId}";
private static final String SELECT_AUTHENTICATION_METHOD_TEMPLATE = "{host}/{version}/consents/{consentId}/authorisations/{authorisationId}";
private static final String AUTHORISE_TRANSACTION_TEMPLATE = "{host}/{version}/consents/{consentId}/authorisations/{authorisationId}";
private static final String SELF_TEMPLATE = "{host}/{version}/consents/{consentId}";
private static final String STATUS_TEMPLATE = "{host}/{version}/consents/{consentId}/status";
private static final String SCA_STATUS_TEMPLATE = "{host}/{version}/consents/{consentId}/authorisations/{authorisationId}";
private static final String ACCOUNT_TEMPLATE = "{host}/{version}/accounts";
private static final String BALANCES_TEMPLATE = "{host}/{version}/accounts/{accountId}/balances";
private static final String TRANSACTIONS_TEMPLATE = "{host}/{version}/accounts/{accountId}/transactions";
private static final String TRANSACTION_DETAILS_TEMPLATE = "{host}/{version}/accounts/{accountId}/transactions/{transactionId}";
private static final String FIRST_TEMPLATE = "{host}/{version}/accounts/{accountId}/transactions";
private static final String NEXT_TEMPLATE = "{host}/{version}/accounts/{accountId}/transactions";
private static final String PREVIOUS_TEMPLATE = "{host}/{version}/accounts/{accountId}/transactions";
private static final String LAST_TEMPLATE = "{host}/{version}/accounts/{accountId}/transactions";
private final Map<String, String> linkNameToTemplate;
public AccountInformationLinksTemplate() {
linkNameToTemplate = new HashMap<>();
linkNameToTemplate.put(START_AUTHORISATION, START_AUTHORISATION_TEMPLATE);
linkNameToTemplate.put(START_AUTHORISATION_WITH_PSU_IDENTIFICATION,
START_AUTHORISATION_WITH_PSU_IDENTIFICATION_TEMPLATE);
linkNameToTemplate.put(UPDATE_PSU_IDENTIFICATION, UPDATE_PSU_IDENTIFICATION_TEMPLATE);
linkNameToTemplate.put(START_AUTHORISATION_WITH_PSU_AUTHENTICATION,
START_AUTHORISATION_WITH_PSU_AUTHENTICATION_TEMPLATE);
linkNameToTemplate.put(UPDATE_PSU_AUTHENTICATION, UPDATE_PSU_AUTHENTICATION_TEMPLATE);
linkNameToTemplate.put(START_AUTHORISATION_WITH_ENCRYPTED_PSU_AUTHENTICATION,
START_AUTHORISATION_WITH_ENCRYPTED_PSU_AUTHENTICATION_TEMPLATE);
linkNameToTemplate.put(UPDATE_ENCRYPTED_PSU_AUTHENTICATION,
UPDATE_ENCRYPTED_PSU_AUTHENTICATION_TEMPLATE);
linkNameToTemplate.put(SELECT_AUTHENTICATION_METHOD, SELECT_AUTHENTICATION_METHOD_TEMPLATE);
linkNameToTemplate.put(AUTHORISE_TRANSACTION, AUTHORISE_TRANSACTION_TEMPLATE);
linkNameToTemplate.put(SELF, SELF_TEMPLATE);
linkNameToTemplate.put(STATUS, STATUS_TEMPLATE);
linkNameToTemplate.put(SCA_STATUS, SCA_STATUS_TEMPLATE);
linkNameToTemplate.put(ACCOUNT, ACCOUNT_TEMPLATE);
linkNameToTemplate.put(BALANCES, BALANCES_TEMPLATE);
linkNameToTemplate.put(TRANSACTIONS, TRANSACTIONS_TEMPLATE);
linkNameToTemplate.put(TRANSACTION_DETAILS, TRANSACTION_DETAILS_TEMPLATE);
linkNameToTemplate.put(FIRST, FIRST_TEMPLATE);
linkNameToTemplate.put(NEXT, NEXT_TEMPLATE);
linkNameToTemplate.put(PREVIOUS, PREVIOUS_TEMPLATE);
linkNameToTemplate.put(LAST, LAST_TEMPLATE);
}
@Override
public Optional<String> get(String linkName) {
return Optional.ofNullable(linkNameToTemplate.get(linkName));
}
@Override
public void set(String linkName, String linkTemplate) {
linkNameToTemplate.put(linkName, linkTemplate);
}
}
| 5,655 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
LinksTemplate.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/link/bg/template/LinksTemplate.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.impl.link.bg.template;
import java.util.Optional;
public abstract class LinksTemplate {
// BG placeholders:
public static final String HOST_PLACEHOLDER = "{host}";
public static final String VERSION_PLACEHOLDER = "{version}";
public static final String CONSENT_ID_PLACEHOLDER = "{consentId}";
public static final String AUTHORISATION_ID_PLACEHOLDER = "{authorisationId}";
public static final String ACCOUNT_ID_PLACEHOLDER = "{accountId}";
public static final String TRANSACTION_ID_PLACEHOLDER = "{transactionId}";
public static final String PAYMENT_SERVICE_PLACEHOLDER = "{paymentService}";
public static final String PAYMENT_PRODUCT_PLACEHOLDER = "{paymentProduct}";
public static final String PAYMENT_ID_PLACEHOLDER = "{paymentId}";
// BG link names:
public static final String SCA_REDIRECT = "scaRedirect";
public static final String SCA_OAUTH = "scaOAuth";
protected static final String START_AUTHORISATION = "startAuthorisation";
protected static final String START_AUTHORISATION_WITH_PSU_IDENTIFICATION = "startAuthorisationWithPsuIdentification";
protected static final String UPDATE_PSU_IDENTIFICATION = "updatePsuIdentification";
protected static final String START_AUTHORISATION_WITH_PROPRIETARY_DATA = "startAuthorisationWithProprietaryData";
protected static final String UPDATE_PROPRIETARY_DATA = "updateProprietaryData";
protected static final String START_AUTHORISATION_WITH_PSU_AUTHENTICATION = "startAuthorisationWithPsuAuthentication";
protected static final String UPDATE_PSU_AUTHENTICATION = "updatePsuAuthentication";
protected static final String START_AUTHORISATION_WITH_ENCRYPTED_PSU_AUTHENTICATION = "startAuthorisationWithEncryptedPsuAuthentication";
protected static final String UPDATE_ENCRYPTED_PSU_AUTHENTICATION = "updateEncryptedPsuAuthentication";
protected static final String START_AUTHORISATION_WITH_TRANSACTION_AUTHORISATION = "startAuthorisationWithTransactionAuthorisation";
protected static final String SELECT_AUTHENTICATION_METHOD = "selectAuthenticationMethod";
protected static final String AUTHORISE_TRANSACTION = "authoriseTransaction";
protected static final String SELF = "self";
protected static final String STATUS = "status";
protected static final String SCA_STATUS = "scaStatus";
protected static final String ACCOUNT = "account";
protected static final String BALANCES = "balances";
protected static final String TRANSACTIONS = "transactions";
protected static final String TRANSACTION_DETAILS = "transactionDetails";
protected static final String FIRST = "first";
protected static final String NEXT = "next";
protected static final String PREVIOUS = "previous";
protected static final String LAST = "last";
protected static final String DOWNLOAD = "download";
public abstract Optional<String> get(String linkName);
public abstract void set(String linkName, String linkTemplate);
}
| 3,859 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
BaseOauth2Api.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/oauth2/api/BaseOauth2Api.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.impl.oauth2.api;
import de.adorsys.xs2a.adapter.api.http.HttpClient;
import de.adorsys.xs2a.adapter.api.http.HttpLogSanitizer;
import de.adorsys.xs2a.adapter.api.oauth.Oauth2Api;
import de.adorsys.xs2a.adapter.impl.http.ResponseHandlers;
import de.adorsys.xs2a.adapter.impl.oauth2.api.model.AuthorisationServerMetaData;
public class BaseOauth2Api<T extends AuthorisationServerMetaData> implements Oauth2Api {
private final HttpClient httpClient;
private final Class<T> metaDataModelClass;
private final ResponseHandlers responseHandlers;
public BaseOauth2Api(HttpClient httpClient, Class<T> metaDataModelClass) {
this(httpClient, metaDataModelClass, null);
}
public BaseOauth2Api(HttpClient httpClient, Class<T> metaDataModelClass, HttpLogSanitizer logSanitizer) {
this.httpClient = httpClient;
this.metaDataModelClass = metaDataModelClass;
this.responseHandlers = new ResponseHandlers(logSanitizer);
}
@Override
public String getAuthorisationUri(String scaOAuthUrl) {
return getAuthorisationServerMetaData(scaOAuthUrl)
.getAuthorisationEndpoint();
}
@Override
public String getTokenUri(String scaOAuthUrl) {
return getAuthorisationServerMetaData(scaOAuthUrl)
.getTokenEndpoint();
}
private T getAuthorisationServerMetaData(String scaOAuthUrl) {
return httpClient.get(scaOAuthUrl)
.send(responseHandlers.jsonResponseHandler(metaDataModelClass))
.getBody();
}
}
| 2,423 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AuthorisationServerMetaData.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-impl/src/main/java/de/adorsys/xs2a/adapter/impl/oauth2/api/model/AuthorisationServerMetaData.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.impl.oauth2.api.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Objects;
// According to RFC 8414 (https://tools.ietf.org/html/rfc8414#section-2)
public class AuthorisationServerMetaData {
/*
* The authorization server's issuer identifier, which is
* a URL that uses the "https" scheme and has no query or fragment
* components.
*/
@JsonProperty("issuer")
private String issuer;
/*
* URL of the authorization server's authorization endpoint
*/
@JsonProperty("authorization_endpoint")
private String authorisationEndpoint;
/*
* URL of the authorization server's token endpoint
*/
@JsonProperty("token_endpoint")
private String tokenEndpoint;
/*
* URL of the authorization server's JWK Set [JWK] document.
*/
@JsonProperty("jwks_uri")
private String jwksUri;
/*
* URL of the authorization server's OAuth 2.0 Dynamic Client Registration endpoint
*/
@JsonProperty("registration_endpoint")
private String registrationEndpoint;
/*
* JSON array containing a list of the OAuth 2.0
* [RFC6749] "scope" values that this authorization server supports.
*/
@JsonProperty("scopes_supported")
private List<String> scopesSupported;
/*
* JSON array containing a list of the OAuth 2.0
* "response_type" values that this authorization server supports.
*/
@JsonProperty("response_types_supported")
private List<String> responseTypesSupported;
/*
* JSON array containing a list of the OAuth 2.0
* "response_mode" values that this authorization server supports
*/
@JsonProperty("response_modes_supported")
private List<String> responseModesSupported;
/*
* JSON array containing a list of the OAuth 2.0 grant
* type values that this authorization server supports
*/
@JsonProperty("grant_types_supported")
private List<String> grantTypesSupported;
/*
* JSON array containing a list of client authentication
* methods supported by this token endpoint.
*/
@JsonProperty("token_endpoint_auth_methods_supported")
private List<String> tokenEndpointAuthMethodsSupported;
/*
* JSON array containing a list of the JWS signing
* algorithms ("alg" values) supported by the token endpoint for the
* signature on the JWT used to authenticate the client at the
* token endpoint for the "private_key_jwt" and "client_secret_jwt"
* authentication methods.
*/
@JsonProperty("token_endpoint_auth_signing_alg_values_supported")
private List<String> tokenEndpointAuthSigningAlgValuesSupported;
/*
* URL of a page containing human-readable information
* that developers might want or need to know when using the
* authorization server.
*/
@JsonProperty("service_documentation")
private String serviceDocumentation;
/*
* Languages and scripts supported for the user interface,
* represented as a JSON array of language tag values from BCP 47
*/
@JsonProperty("ui_locales_supported")
private List<String> uiLocalesSupported;
/*
* URL that the authorization server provides to the
* person registering the client to read about the authorization
* server's requirements on how the client can use the data provided
* by the authorization server
*/
@JsonProperty("op_policy_uri")
private String opPolicyUri;
/*
* URL that the authorization server provides to the person
* registering the client to read about the authorization
* server's terms of service
*/
@JsonProperty("op_tos_uri")
private String opTosUri;
/*
* URL of the authorization server's OAuth 2.0 revocation endpoint
*/
@JsonProperty("revocation_endpoint")
private String revocationEndpoint;
/*
* JSON array containing a list of client authentication
* methods supported by this revocation endpoint
*/
@JsonProperty("revocation_endpoint_auth_methods_supported")
private List<String> revocationEndpointAuthMethodsSupported;
/*
* JSON array containing a list of the JWS signing
* algorithms ("alg" values) supported by the revocation endpoint for
* the signature on the JWT used to authenticate the client at
* the revocation endpoint for the "private_key_jwt" and
* "client_secret_jwt" authentication methods.
*/
@JsonProperty("revocation_endpoint_auth_signing_alg_values_supported")
private List<String> revocationEndpointAuthSigningAlgValuesSupported;
/*
* URL of the authorization server's OAuth 2.0 introspection endpoint
*/
@JsonProperty("introspection_endpoint")
private String introspectionEndpoint;
/*
* JSON array containing a list of client authentication
* methods supported by this introspection endpoint
*/
@JsonProperty("introspection_endpoint_auth_methods_supported")
private List<String> introspectionEndpointAuthMethodsSupported;
/*
* JSON array containing a list of the JWS signing
* algorithms ("alg" values) supported by the introspection endpoint
* for the signature on the JWT used to authenticate the client
* at the introspection endpoint for the "private_key_jwt" and
* "client_secret_jwt" authentication methods.
*/
@JsonProperty("introspection_endpoint_auth_signing_alg_values_supported")
private List<String> introspectionEndpointAuthSigningAlgValuesSupported;
/*
* JSON array containing a list of Proof Key for Code
* Exchange (PKCE) code challenge methods supported by this
* authorization server.
*/
@JsonProperty("code_challenge_methods_supported")
private List<String> codeChallengeMethodsSupported;
public String getIssuer() {
return issuer;
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
public String getAuthorisationEndpoint() {
return authorisationEndpoint;
}
public void setAuthorisationEndpoint(String authorisationEndpoint) {
this.authorisationEndpoint = authorisationEndpoint;
}
public String getTokenEndpoint() {
return tokenEndpoint;
}
public void setTokenEndpoint(String tokenEndpoint) {
this.tokenEndpoint = tokenEndpoint;
}
public String getJwksUri() {
return jwksUri;
}
public void setJwksUri(String jwksUri) {
this.jwksUri = jwksUri;
}
public String getRegistrationEndpoint() {
return registrationEndpoint;
}
public void setRegistrationEndpoint(String registrationEndpoint) {
this.registrationEndpoint = registrationEndpoint;
}
public List<String> getScopesSupported() {
return scopesSupported;
}
public void setScopesSupported(List<String> scopesSupported) {
this.scopesSupported = scopesSupported;
}
public List<String> getResponseTypesSupported() {
return responseTypesSupported;
}
public void setResponseTypesSupported(List<String> responseTypesSupported) {
this.responseTypesSupported = responseTypesSupported;
}
public List<String> getResponseModesSupported() {
return responseModesSupported;
}
public void setResponseModesSupported(List<String> responseModesSupported) {
this.responseModesSupported = responseModesSupported;
}
public List<String> getGrantTypesSupported() {
return grantTypesSupported;
}
public void setGrantTypesSupported(List<String> grantTypesSupported) {
this.grantTypesSupported = grantTypesSupported;
}
public List<String> getTokenEndpointAuthMethodsSupported() {
return tokenEndpointAuthMethodsSupported;
}
public void setTokenEndpointAuthMethodsSupported(List<String> tokenEndpointAuthMethodsSupported) {
this.tokenEndpointAuthMethodsSupported = tokenEndpointAuthMethodsSupported;
}
public List<String> getTokenEndpointAuthSigningAlgValuesSupported() {
return tokenEndpointAuthSigningAlgValuesSupported;
}
public void setTokenEndpointAuthSigningAlgValuesSupported(List<String> tokenEndpointAuthSigningAlgValuesSupported) {
this.tokenEndpointAuthSigningAlgValuesSupported = tokenEndpointAuthSigningAlgValuesSupported;
}
public String getServiceDocumentation() {
return serviceDocumentation;
}
public void setServiceDocumentation(String serviceDocumentation) {
this.serviceDocumentation = serviceDocumentation;
}
public List<String> getUiLocalesSupported() {
return uiLocalesSupported;
}
public void setUiLocalesSupported(List<String> uiLocalesSupported) {
this.uiLocalesSupported = uiLocalesSupported;
}
public String getOpPolicyUri() {
return opPolicyUri;
}
public void setOpPolicyUri(String opPolicyUri) {
this.opPolicyUri = opPolicyUri;
}
public String getOpTosUri() {
return opTosUri;
}
public void setOpTosUri(String opTosUri) {
this.opTosUri = opTosUri;
}
public String getRevocationEndpoint() {
return revocationEndpoint;
}
public void setRevocationEndpoint(String revocationEndpoint) {
this.revocationEndpoint = revocationEndpoint;
}
public List<String> getRevocationEndpointAuthMethodsSupported() {
return revocationEndpointAuthMethodsSupported;
}
public void setRevocationEndpointAuthMethodsSupported(List<String> revocationEndpointAuthMethodsSupported) {
this.revocationEndpointAuthMethodsSupported = revocationEndpointAuthMethodsSupported;
}
public List<String> getRevocationEndpointAuthSigningAlgValuesSupported() {
return revocationEndpointAuthSigningAlgValuesSupported;
}
public void setRevocationEndpointAuthSigningAlgValuesSupported(List<String> revocationEndpointAuthSigningAlgValuesSupported) {
this.revocationEndpointAuthSigningAlgValuesSupported = revocationEndpointAuthSigningAlgValuesSupported;
}
public String getIntrospectionEndpoint() {
return introspectionEndpoint;
}
public void setIntrospectionEndpoint(String introspectionEndpoint) {
this.introspectionEndpoint = introspectionEndpoint;
}
public List<String> getIntrospectionEndpointAuthMethodsSupported() {
return introspectionEndpointAuthMethodsSupported;
}
public void setIntrospectionEndpointAuthMethodsSupported(List<String> introspectionEndpointAuthMethodsSupported) {
this.introspectionEndpointAuthMethodsSupported = introspectionEndpointAuthMethodsSupported;
}
public List<String> getIntrospectionEndpointAuthSigningAlgValuesSupported() {
return introspectionEndpointAuthSigningAlgValuesSupported;
}
public void setIntrospectionEndpointAuthSigningAlgValuesSupported(List<String> introspectionEndpointAuthSigningAlgValuesSupported) {
this.introspectionEndpointAuthSigningAlgValuesSupported = introspectionEndpointAuthSigningAlgValuesSupported;
}
public List<String> getCodeChallengeMethodsSupported() {
return codeChallengeMethodsSupported;
}
public void setCodeChallengeMethodsSupported(List<String> codeChallengeMethodsSupported) {
this.codeChallengeMethodsSupported = codeChallengeMethodsSupported;
}
@Override
public String toString() {
return "AuthorisationServerMetaData{" +
"issuer='" + issuer + '\'' +
", authorisationEndpoint='" + authorisationEndpoint + '\'' +
", tokenEndpoint='" + tokenEndpoint + '\'' +
", jwksUri='" + jwksUri + '\'' +
", registrationEndpoint='" + registrationEndpoint + '\'' +
", scopesSupported=" + scopesSupported +
", responseTypesSupported=" + responseTypesSupported +
", responseModesSupported=" + responseModesSupported +
", grantTypesSupported=" + grantTypesSupported +
", tokenEndpointAuthMethodsSupported=" + tokenEndpointAuthMethodsSupported +
", tokenEndpointAuthSigningAlgValuesSupported=" + tokenEndpointAuthSigningAlgValuesSupported +
", serviceDocumentation='" + serviceDocumentation + '\'' +
", uiLocalesSupported=" + uiLocalesSupported +
", opPolicyUri='" + opPolicyUri + '\'' +
", opTosUri='" + opTosUri + '\'' +
", revocationEndpoint='" + revocationEndpoint + '\'' +
", revocationEndpointAuthMethodsSupported=" + revocationEndpointAuthMethodsSupported +
", revocationEndpointAuthSigningAlgValuesSupported=" + revocationEndpointAuthSigningAlgValuesSupported +
", introspectionEndpoint='" + introspectionEndpoint + '\'' +
", introspectionEndpointAuthMethodsSupported=" + introspectionEndpointAuthMethodsSupported +
", introspectionEndpointAuthSigningAlgValuesSupported=" + introspectionEndpointAuthSigningAlgValuesSupported +
", codeChallengeMethodsSupported=" + codeChallengeMethodsSupported +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AuthorisationServerMetaData that = (AuthorisationServerMetaData) o;
return Objects.equals(issuer, that.issuer) &&
Objects.equals(authorisationEndpoint, that.authorisationEndpoint) &&
Objects.equals(tokenEndpoint, that.tokenEndpoint) &&
Objects.equals(jwksUri, that.jwksUri) &&
Objects.equals(registrationEndpoint, that.registrationEndpoint) &&
Objects.equals(scopesSupported, that.scopesSupported) &&
Objects.equals(responseTypesSupported, that.responseTypesSupported) &&
Objects.equals(responseModesSupported, that.responseModesSupported) &&
Objects.equals(grantTypesSupported, that.grantTypesSupported) &&
Objects.equals(tokenEndpointAuthMethodsSupported, that.tokenEndpointAuthMethodsSupported) &&
Objects.equals(tokenEndpointAuthSigningAlgValuesSupported, that.tokenEndpointAuthSigningAlgValuesSupported) &&
Objects.equals(serviceDocumentation, that.serviceDocumentation) &&
Objects.equals(uiLocalesSupported, that.uiLocalesSupported) &&
Objects.equals(opPolicyUri, that.opPolicyUri) &&
Objects.equals(opTosUri, that.opTosUri) &&
Objects.equals(revocationEndpoint, that.revocationEndpoint) &&
Objects.equals(revocationEndpointAuthMethodsSupported, that.revocationEndpointAuthMethodsSupported) &&
Objects.equals(revocationEndpointAuthSigningAlgValuesSupported, that.revocationEndpointAuthSigningAlgValuesSupported) &&
Objects.equals(introspectionEndpoint, that.introspectionEndpoint) &&
Objects.equals(introspectionEndpointAuthMethodsSupported, that.introspectionEndpointAuthMethodsSupported) &&
Objects.equals(introspectionEndpointAuthSigningAlgValuesSupported, that.introspectionEndpointAuthSigningAlgValuesSupported) &&
Objects.equals(codeChallengeMethodsSupported, that.codeChallengeMethodsSupported);
}
@Override
public int hashCode() {
return Objects.hash(
issuer, authorisationEndpoint, tokenEndpoint, jwksUri,
registrationEndpoint, scopesSupported, responseTypesSupported,
responseModesSupported, grantTypesSupported, tokenEndpointAuthMethodsSupported,
tokenEndpointAuthSigningAlgValuesSupported, serviceDocumentation,
uiLocalesSupported, opPolicyUri, opTosUri, revocationEndpoint,
revocationEndpointAuthMethodsSupported,
revocationEndpointAuthSigningAlgValuesSupported, introspectionEndpoint,
introspectionEndpointAuthMethodsSupported,
introspectionEndpointAuthSigningAlgValuesSupported,
codeChallengeMethodsSupported
);
}
}
| 17,290 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
HeadersMapperTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest2api-mapper/src/test/java/de/adorsys/xs2a/adapter/mapper/HeadersMapperTest.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.mapper;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import de.adorsys.xs2a.adapter.api.http.ContentType;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class HeadersMapperTest {
private final HeadersMapper headersMapper = new HeadersMapper();
private final ResponseHeaders responseHeaders = buildResponseHeaders();
private static final String LOCATION = "Location";
private static final String LOCATION_VALUE = "example.com";
@Test
void toHttpHeaders() {
HttpHeaders actualHeaders = headersMapper.toHttpHeaders(responseHeaders);
assertFalse(actualHeaders.isEmpty());
assertTrue(actualHeaders.containsKey(ResponseHeaders.CONTENT_TYPE));
assertEquals(MediaType.APPLICATION_JSON, actualHeaders.getContentType());
assertTrue(actualHeaders.containsKey(LOCATION));
assertEquals(URI.create(LOCATION_VALUE), actualHeaders.getLocation());
}
private ResponseHeaders buildResponseHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put(ResponseHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON);
headers.put(LOCATION, LOCATION_VALUE);
return ResponseHeaders.fromMap(headers);
}
}
| 2,276 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
HeadersMapper.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest2api-mapper/src/main/java/de/adorsys/xs2a/adapter/mapper/HeadersMapper.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.mapper;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
@Component
public class HeadersMapper {
public HttpHeaders toHttpHeaders(ResponseHeaders responseHeaders) {
HttpHeaders httpHeaders = new HttpHeaders();
responseHeaders.getHeadersMap().forEach(httpHeaders::add);
return httpHeaders;
}
}
| 1,287 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Oauth2Mapper.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest2api-mapper/src/main/java/de/adorsys/xs2a/adapter/mapper/Oauth2Mapper.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.mapper;
import de.adorsys.xs2a.adapter.api.model.TokenResponse;
import de.adorsys.xs2a.adapter.rest.api.model.TokenResponseTO;
import org.mapstruct.Mapper;
@Mapper
public interface Oauth2Mapper {
TokenResponseTO map(TokenResponse token);
TokenResponse toTokenResponse(TokenResponseTO tokenResponseTO);
}
| 1,177 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
EmbeddedPreAuthorisationMapper.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-rest2api-mapper/src/main/java/de/adorsys/xs2a/adapter/mapper/EmbeddedPreAuthorisationMapper.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.mapper;
import de.adorsys.xs2a.adapter.api.model.EmbeddedPreAuthorisationRequest;
import de.adorsys.xs2a.adapter.rest.api.model.EmbeddedPreAuthorisationRequestTO;
import org.mapstruct.Mapper;
@Mapper
public interface EmbeddedPreAuthorisationMapper {
EmbeddedPreAuthorisationRequestTO toEmbeddedPreAuthorisationRequestTO(EmbeddedPreAuthorisationRequest value);
EmbeddedPreAuthorisationRequest toEmbeddedPreAuthorisationRequest(EmbeddedPreAuthorisationRequestTO value);
}
| 1,342 | 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-rest2api-mapper/src/main/java/de/adorsys/xs2a/adapter/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.mapper;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import de.adorsys.xs2a.adapter.rest.api.model.AspspTO;
import org.mapstruct.Mapper;
import java.util.List;
@Mapper
public interface AspspMapper {
AspspTO toAspspTO(Aspsp aspsp);
Aspsp toAspsp(AspspTO to);
List<AspspTO> toAspspTOs(Iterable<Aspsp> aspsps);
List<Aspsp> toAspsps(Iterable<AspspTO> aspsps);
}
| 1,246 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AdapterConfigTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/test/java/de/adorsys/xs2a/adapter/api/config/AdapterConfigTest.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.api.config;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class AdapterConfigTest {
@Test
void readProperty() {
String property = AdapterConfig.readProperty("adorsys.oauth_approach.header_name");
assertThat(property).isEqualTo("X-OAUTH-PREFERRED");
}
@Test
void externalConfigFile() {
String file = getClass().getResource("/external.adapter.config.properties").getFile();
System.setProperty("adapter.config.file.path", file);
AdapterConfig.reload();
String property = AdapterConfig.readProperty("some-adapter-property");
assertThat(property).isEqualTo("test");
}
}
| 1,561 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AspspTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/test/java/de/adorsys/xs2a/adapter/api/model/AspspTest.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.api.model;
import org.junit.jupiter.api.Test;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
class AspspTest {
private final Aspsp aspsp = new Aspsp();
@Test
void setIdTreatsEmptyAsNull() {
aspsp.setId("");
assertThat(aspsp.getId()).isNull();
}
@Test
void setNameTreatsEmptyAsNull() {
aspsp.setName("");
assertThat(aspsp.getName()).isNull();
}
@Test
void setBicTreatsEmptyAsNull() {
aspsp.setBic("");
assertThat(aspsp.getBic()).isNull();
}
@Test
void setBankCodeTreatsEmptyAsNull() {
aspsp.setBankCode("");
assertThat(aspsp.getBankCode()).isNull();
}
@Test
void setUrlTreatsEmptyAsNull() {
aspsp.setUrl("");
assertThat(aspsp.getUrl()).isNull();
}
@Test
void setAdapterId() {
aspsp.setAdapterId("");
assertThat(aspsp.getAdapterId()).isNull();
}
@Test
void setIdpUrl() {
aspsp.setIdpUrl("");
assertThat(aspsp.getIdpUrl()).isNull();
}
@Test
void setScaApproaches() {
aspsp.setScaApproaches(emptyList());
assertThat(aspsp.getScaApproaches()).isNull();
}
}
| 2,112 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PropertyUtilTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/test/java/de/adorsys/xs2a/adapter/service/PropertyUtilTest.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.service;
import de.adorsys.xs2a.adapter.api.PropertyUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class PropertyUtilTest {
private static final String PROPERTY_NAME = "p1";
private static final String DEFAULT_VALUE = "42";
private static final String PROPERTY_VALUE = "value";
private static final String NOT_EXISTING_PROPERTY = "not-existing-property";
@BeforeEach
public void setUp() {
System.setProperty(PROPERTY_NAME, PROPERTY_VALUE);
}
@Test
void readProperty() {
Assertions.assertEquals(PROPERTY_VALUE, PropertyUtil.readProperty(PROPERTY_NAME));
Assertions.assertEquals("", PropertyUtil.readProperty(NOT_EXISTING_PROPERTY));
}
@Test
void readPropertyWithDefaultValue() {
Assertions.assertEquals("42", PropertyUtil.readProperty(NOT_EXISTING_PROPERTY, DEFAULT_VALUE));
Assertions.assertEquals(PROPERTY_VALUE, PropertyUtil.readProperty(PROPERTY_NAME, "42"));
}
}
| 1,904 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
RequestParamsTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/test/java/de/adorsys/xs2a/adapter/service/RequestParamsTest.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.service;
import de.adorsys.xs2a.adapter.api.RequestParams;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
class RequestParamsTest {
@Test
void fromMap() {
RequestParams requestParams = RequestParams.fromMap(emptyMap());
assertThat(requestParams.toMap()).isEqualTo(emptyMap());
}
@Test
void dateFromIsTypeChecked() {
Map<String, String> map = singletonMap("dateFrom", "asdf");
assertThrows(IllegalArgumentException.class, () -> RequestParams.fromMap(map));
}
@Test
void dateToIsTypeChecked() {
Map<String, String> map = singletonMap("dateTo", "asdf");
assertThrows(IllegalArgumentException.class, () -> RequestParams.fromMap(map));
}
@Test
void withBalanceIsTypeChecked() {
Map<String, String> map = singletonMap("withBalance", "asdf");
assertThrows(IllegalArgumentException.class, () -> RequestParams.fromMap(map));
}
@Test
void deltaListIsTypeChecked() {
Map<String, String> map = singletonMap("deltaList", "asdf");
assertThrows(IllegalArgumentException.class, () -> RequestParams.fromMap(map));
}
}
| 2,242 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PkceOauth2ExtensionTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/test/java/de/adorsys/xs2a/adapter/service/PkceOauth2ExtensionTest.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.service;
import de.adorsys.xs2a.adapter.api.PkceOauth2Extension;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PkceOauth2ExtensionTest {
private final PkceExample pkceExample = new PkceExample();
// https://tools.ietf.org/html/rfc7636#appendix-B
static class PkceExample implements PkceOauth2Extension {
@Override
public byte[] octetSequence() {
return new byte[]{116, 24, (byte) 223, (byte) 180, (byte) 151, (byte) 153, (byte) 224, 37, 79, (byte) 250, 96,
125, (byte) 216, (byte) 173, (byte) 187, (byte) 186, 22, (byte) 212, 37, 77, 105, (byte) 214, (byte) 191,
(byte) 240, 91, 88, 5, 88, 83, (byte) 132, (byte) 141, 121};
}
}
@Test
void codeVerifier() {
assertEquals("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", pkceExample.codeVerifier());
}
@Test
void codeChallenge() {
assertEquals("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", pkceExample.codeChallenge());
}
}
| 1,919 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
RequestHeadersTest.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/test/java/de/adorsys/xs2a/adapter/service/RequestHeadersTest.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.service;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
class RequestHeadersTest {
@Test
void getIsCaseAgnostic() {
RequestHeaders requestHeaders = RequestHeaders.fromMap(singletonMap("X-gtw-ASPSP-id", "1"));
Optional<String> aspspId = requestHeaders.get(RequestHeaders.X_GTW_ASPSP_ID);
assertThat(aspspId).get().isEqualTo("1");
}
@Test
void getUnknownHeaderReturnsEmpty() {
RequestHeaders requestHeaders = RequestHeaders.fromMap(emptyMap());
Optional<String> headerValue = requestHeaders.get("asdfasdf");
assertThat(headerValue).isEmpty();
}
@Test
void permitsOauthPreferredHeaders() {
RequestHeaders requestHeaders = RequestHeaders.fromMap(singletonMap("X-OAUTH-PREFERRED", "pre-step"));
assertThat(requestHeaders.get("X-OAUTH-PREFERRED")).get().isEqualTo("pre-step");
}
@Test
void notPermitsCustomHeaders() {
RequestHeaders requestHeaders = RequestHeaders.fromMap(singletonMap("x-custom-header", "value"));
assertThat(requestHeaders.toMap())
.isEmpty();
}
}
| 2,191 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PaymentInitiationServiceProvider.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/PaymentInitiationServiceProvider.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.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;
public interface PaymentInitiationServiceProvider extends AdapterServiceProvider, WiremockValidation {
PaymentInitiationService getPaymentInitiationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter);
}
| 1,388 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Oauth2Service.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/Oauth2Service.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.api;
import de.adorsys.xs2a.adapter.api.model.TokenResponse;
import de.adorsys.xs2a.adapter.api.validation.Oauth2ValidationService;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
public interface Oauth2Service extends Oauth2ValidationService {
// https://tools.ietf.org/html/rfc6749#section-4.1.1
URI getAuthorizationRequestUri(Map<String, String> headers, Parameters parameters) throws IOException;
TokenResponse getToken(Map<String, String> headers, Parameters parameters) throws IOException;
class Parameters {
// rfc6749
public static final String CODE = "code";
public static final String REFRESH_TOKEN = "refresh_token";
public static final String GRANT_TYPE = "grant_type";
public static final String REDIRECT_URI = "redirect_uri";
public static final String CLIENT_ID = "client_id";
public static final String STATE = "state";
public static final String SCOPE = "scope";
public static final String RESPONSE_TYPE = "response_type";
// PKCE
public static final String CODE_CHALLENGE_METHOD = "code_challenge_method";
public static final String CODE_CHALLENGE = "code_challenge";
public static final String CODE_VERIFIER = "code_verifier";
// additional
public static final String BIC = "bic";
public static final String CONSENT_ID = "consent_id";
public static final String PAYMENT_ID = "payment_id";
public static final String SCA_OAUTH_LINK = "sca_oauth_link";
public static final String AUTHORIZATION_ENDPOINT = "authorization_endpoint";
public static final String TOKEN_ENDPOINT = "token_endpoint";
private final Map<String, String> parameters;
public Parameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public Parameters() {
this(new LinkedHashMap<>());
}
public Map<String, String> asMap() {
return parameters;
}
public String get(String key) {
return parameters.get(key);
}
public void set(String key, String value) {
if (key != null && value != null) {
parameters.put(key, value);
}
}
public String remove(String key) {
return parameters.remove(key);
}
public String getAuthorizationCode() {
return get(CODE);
}
public void setAuthorizationCode(String value) {
set(CODE, value);
}
public String getRedirectUri() {
return get(REDIRECT_URI);
}
public void setRedirectUri(String value) {
set(REDIRECT_URI, value);
}
public String getClientId() {
return get(CLIENT_ID);
}
public void setClientId(String value) {
set(CLIENT_ID, value);
}
public String getGrantType() {
return get(GRANT_TYPE);
}
public void setGrantType(String value) {
set(GRANT_TYPE, value);
}
public String getCodeVerifier() {
return get(CODE_VERIFIER);
}
public void setCodeVerifier(String value) {
set(CODE_VERIFIER, value);
}
public String getState() {
return get(STATE);
}
public void setState(String value) {
set(STATE, value);
}
public String getScaOAuthLink() {
return get(SCA_OAUTH_LINK);
}
public void setScaOAuthLink(String value) {
set(SCA_OAUTH_LINK, value);
}
public String removeScaOAuthLink() {
return remove(SCA_OAUTH_LINK);
}
public String getBic() {
return get(BIC);
}
public void setBic(String value) {
set(BIC, value);
}
public String getScope() {
return get(SCOPE);
}
public void setScope(String value) {
set(SCOPE, value);
}
public String getResponseType() {
return get(RESPONSE_TYPE);
}
public void setResponseType(String value) {
set(RESPONSE_TYPE, value);
}
public String getCodeChallenge() {
return get(CODE_CHALLENGE);
}
public void setCodeChallenge(String value) {
set(CODE_CHALLENGE, value);
}
public String getCodeChallengeMethod() {
return get(CODE_CHALLENGE_METHOD);
}
public void setCodeChallengeMethod(String value) {
set(CODE_CHALLENGE_METHOD, value);
}
public String getRefreshToken() {
return get(REFRESH_TOKEN);
}
public void setRefreshToken(String value) {
set(REFRESH_TOKEN, value);
}
public String getConsentId() {
return get(CONSENT_ID);
}
public void setConsentId(String value) {
set(CONSENT_ID, value);
}
public String getPaymentId() {
return get(PAYMENT_ID);
}
public void setPaymentId(String value) {
set(PAYMENT_ID, value);
}
public String getAuthorizationEndpoint() {
return get(AUTHORIZATION_ENDPOINT);
}
public void setAuthorizationEndpoint(String value) {
set(AUTHORIZATION_ENDPOINT, value);
}
public String getTokenEndpoint() {
return get(TOKEN_ENDPOINT);
}
public void setTokenEndpoint(String value) {
set(TOKEN_ENDPOINT, value);
}
public String removeTokenEndpoint() {
return remove(TOKEN_ENDPOINT);
}
}
enum GrantType {
AUTHORIZATION_CODE("authorization_code"),
REFRESH_TOKEN("refresh_token");
private final String value;
GrantType(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
enum ResponseType {
CODE("code");
private final String value;
ResponseType(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
}
| 7,303 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Response.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/Response.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.api;
import java.util.function.Function;
public class Response<T> {
private final int statusCode;
private final T body;
private final ResponseHeaders headers;
public Response(int statusCode, T body, ResponseHeaders headers) {
this.statusCode = statusCode;
this.body = body;
this.headers = headers;
}
public int getStatusCode() {
return statusCode;
}
public T getBody() {
return body;
}
public ResponseHeaders getHeaders() {
return headers;
}
public <U> Response<U> map(Function<? super T, ? extends U> bodyMapper) {
return new Response<>(statusCode, bodyMapper.apply(body), headers);
}
}
| 1,565 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
EmbeddedPreAuthorisationServiceProvider.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/EmbeddedPreAuthorisationServiceProvider.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.api;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
public interface EmbeddedPreAuthorisationServiceProvider extends AdapterServiceProvider {
EmbeddedPreAuthorisationService getEmbeddedPreAuthorisationService(Aspsp aspsp, HttpClientFactory httpClientFactory);
}
| 1,191 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PaymentInitiationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/PaymentInitiationService.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.api;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.api.validation.PaymentInitiationValidationService;
public interface PaymentInitiationService extends PaymentInitiationValidationService {
Response<PaymentInitationRequestResponse201> initiatePayment(PaymentService paymentService,
PaymentProduct paymentProduct,
RequestHeaders requestHeaders,
RequestParams requestParams,
Object body);
Response<PaymentInitiationWithStatusResponse> getSinglePaymentInformation(PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<PeriodicPaymentInitiationWithStatusResponse> getPeriodicPaymentInformation(PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<PeriodicPaymentInitiationMultipartBody> getPeriodicPain001PaymentInformation(PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<String> getPaymentInformationAsString(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<ScaStatusResponse> getPaymentInitiationScaStatus(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<PaymentInitiationStatusResponse200Json> getPaymentInitiationStatus(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<String> getPaymentInitiationStatusAsString(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<Authorisations> getPaymentInitiationAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<StartScaprocessResponse> startPaymentAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<StartScaprocessResponse> startPaymentAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication body);
Response<SelectPsuAuthenticationMethodResponse> updatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
SelectPsuAuthenticationMethod body);
Response<ScaStatusResponse> updatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
TransactionAuthorisation body);
Response<UpdatePsuAuthenticationResponse> updatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication body);
}
| 8,223 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AccountInformationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/AccountInformationService.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.api;
import de.adorsys.xs2a.adapter.api.exception.NotAcceptableException;
import de.adorsys.xs2a.adapter.api.model.*;
import de.adorsys.xs2a.adapter.api.validation.AccountInformationValidationService;
public interface AccountInformationService extends AccountInformationValidationService {
Response<ConsentsResponse201> createConsent(RequestHeaders requestHeaders,
RequestParams requestParams,
Consents body);
Response<ConsentInformationResponse200Json> getConsentInformation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<Void> deleteConsent(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<ConsentStatusResponse200> getConsentStatus(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<Authorisations> getConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<StartScaprocessResponse> startConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<StartScaprocessResponse> startConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication);
Response<SelectPsuAuthenticationMethodResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
SelectPsuAuthenticationMethod selectPsuAuthenticationMethod);
Response<ScaStatusResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
TransactionAuthorisation transactionAuthorisation);
Response<UpdatePsuAuthenticationResponse> updateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication);
Response<AccountList> getAccountList(RequestHeaders requestHeaders,
RequestParams requestParams);
Response<OK200AccountDetails> readAccountDetails(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams);
/**
* @throws NotAcceptableException if response content type is not json
* @return
*/
Response<TransactionsResponse200Json> getTransactionList(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<OK200TransactionDetails> getTransactionDetails(String accountId,
String transactionId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<String> getTransactionListAsString(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<ScaStatusResponse> getConsentScaStatus(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<ReadAccountBalanceResponse200> getBalances(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<CardAccountList> getCardAccountList(RequestHeaders requestHeaders, RequestParams requestParams);
Response<OK200CardAccountDetails> getCardAccountDetails(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<ReadCardAccountBalanceResponse200> getCardAccountBalances(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams);
Response<CardAccountsTransactionsResponse200> getCardAccountTransactionList(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams);
}
| 7,303 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
EmbeddedPreAuthorisationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/EmbeddedPreAuthorisationService.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.api;
import de.adorsys.xs2a.adapter.api.model.EmbeddedPreAuthorisationRequest;
import de.adorsys.xs2a.adapter.api.model.TokenResponse;
public interface EmbeddedPreAuthorisationService {
TokenResponse getToken(EmbeddedPreAuthorisationRequest request, RequestHeaders requestHeaders);
}
| 1,153 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PsuPasswordEncryptionService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/PsuPasswordEncryptionService.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.api;
public interface PsuPasswordEncryptionService {
String encrypt(String password);
}
| 956 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
DownloadServiceProvider.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/DownloadServiceProvider.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.api;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
public interface DownloadServiceProvider extends AdapterServiceProvider {
DownloadService getDownloadService(String baseUrl, HttpClientFactory httpClientFactory);
}
| 1,098 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
WiremockValidation.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/WiremockValidation.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.api;
public interface WiremockValidation {
void wiremockValidationEnabled(boolean value);
}
| 959 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PkceOauth2Extension.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/PkceOauth2Extension.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.api;
import de.adorsys.xs2a.adapter.api.exception.Xs2aAdapterException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public interface PkceOauth2Extension {
static byte[] random(int numBytes) {
try {
return SecureRandom.getInstanceStrong().generateSeed(numBytes);
} catch (NoSuchAlgorithmException e) {
// Every implementation of the Java platform is required to
// support at least one strong {@code SecureRandom} implementation.
throw new Xs2aAdapterException(e);
}
}
default byte[] octetSequence() {
return StaticCodeVerifier.codeVerifier;
}
default String codeVerifier() {
return base64urlNoPadding(octetSequence());
}
static String base64urlNoPadding(byte[] bytes) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
default String codeChallenge() {
return base64urlNoPadding(sha256(codeVerifier().getBytes()));
}
@SuppressWarnings("java:S4790")
static byte[] sha256(byte[] bytes) {
try {
return MessageDigest.getInstance("SHA-256").digest(bytes);
} catch (NoSuchAlgorithmException e) {
// Every implementation of the Java platform is required to support SHA-256
throw new Xs2aAdapterException(e);
}
}
class StaticCodeVerifier {
private StaticCodeVerifier() {
}
// The client SHOULD create a "code_verifier" with a minimum of 256 bits
// of entropy. This can be done by having a suitable random number
// generator create a 32-octet sequence. The octet sequence can then be
// base64url-encoded to produce a 43-octet URL safe string to use as a
// "code_challenge" that has the required entropy.
private static final byte[] codeVerifier = random(32);
}
}
| 2,844 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AccountInformationServiceProvider.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/AccountInformationServiceProvider.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.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;
public interface AccountInformationServiceProvider extends AdapterServiceProvider, WiremockValidation {
AccountInformationService getAccountInformationService(Aspsp aspsp,
HttpClientFactory httpClientFactory,
LinksRewriter linksRewriter);
}
| 1,395 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
RequestHeaders.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/RequestHeaders.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.api;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class RequestHeaders {
private static final String BEARER_SPACE = "Bearer ";
public static final String X_REQUEST_ID = "X-Request-ID";
public static final String CONSENT_ID = "Consent-ID";
public static final String DIGEST = "Digest";
public static final String PSU_ID = "PSU-ID";
public static final String PSU_CORPORATE_ID = "PSU-Corporate-ID";
public static final String TPP_REDIRECT_URI = "TPP-Redirect-URI";
public static final String DATE = "Date";
public static final String SIGNATURE = "Signature";
public static final String TPP_SIGNATURE_CERTIFICATE = "TPP-Signature-Certificate";
public static final String PSU_IP_ADDRESS = "PSU-IP-Address";
public static final String PSU_ID_TYPE = "PSU-ID-Type";
public static final String PSU_CORPORATE_ID_TYPE = "PSU-Corporate-ID-Type";
public static final String TPP_REDIRECT_PREFERRED = "TPP-Redirect-Preferred";
public static final String TPP_NOK_REDIRECT_URI = "TPP-Nok-Redirect-URI";
public static final String TPP_EXPLICIT_AUTHORISATION_PREFERRED = "TPP-Explicit-Authorisation-Preferred";
public static final String PSU_IP_PORT = "PSU-IP-Port";
public static final String PSU_ACCEPT = "PSU-Accept";
public static final String PSU_ACCEPT_CHARSET = "PSU-Accept-Charset";
public static final String PSU_ACCEPT_ENCODING = "PSU-Accept-Encoding";
public static final String PSU_ACCEPT_LANGUAGE = "PSU-Accept-Language";
public static final String PSU_USER_AGENT = "PSU-User-Agent";
public static final String PSU_HTTP_METHOD = "PSU-Http-Method";
public static final String PSU_DEVICE_ID = "PSU-Device-ID";
public static final String PSU_GEO_LOCATION = "PSU-Geo-Location";
public static final String TPP_DECOUPLED_PREFERRED = "TPP-Decoupled-Preferred";
public static final String TPP_BRAND_LOGGING_INFORMATION = "TPP-Brand-Logging-Information";
public static final String TPP_NOTIFICATION_URI = "TPP-Notification-URI";
public static final String TPP_NOTIFICATION_CONTENT_PREFERRED = "TPP-Notification-Content-Preferred";
public static final String PSU_IP_ADDRESS_MANDATORY = "PSU-IP-Address_mandatory";
// technical
public static final String ACCEPT = "Accept";
public static final String CONTENT_TYPE = "Content-Type";
public static final String AUTHORIZATION = "Authorization";
public static final String CORRELATION_ID = "Correlation-ID";
// gateway
public static final String X_GTW_ASPSP_ID = "X-GTW-ASPSP-ID";
public static final String X_GTW_BANK_CODE = "X-GTW-Bank-Code";
public static final String X_GTW_BIC = "X-GTW-BIC";
public static final String X_GTW_IBAN = "X-GTW-IBAN";
// Open Banking Gateway
public static final String X_OAUTH_PREFERRED = "X-OAUTH-PREFERRED";
// Crealogix
public static final String PSD2_AUTHORIZATION = "PSD2-AUTHORIZATION";
private static final RequestHeaders EMPTY = new RequestHeaders(Collections.emptyMap());
private static final Map<String, String> headerNamesLowerCased = new HashMap<>();
static {
headerNamesLowerCased.put(X_GTW_ASPSP_ID.toLowerCase(), X_GTW_ASPSP_ID);
headerNamesLowerCased.put(X_GTW_BANK_CODE.toLowerCase(), X_GTW_BANK_CODE);
headerNamesLowerCased.put(X_GTW_BIC.toLowerCase(), X_GTW_BIC);
headerNamesLowerCased.put(X_GTW_IBAN.toLowerCase(), X_GTW_IBAN);
headerNamesLowerCased.put(X_REQUEST_ID.toLowerCase(), X_REQUEST_ID);
headerNamesLowerCased.put(PSU_IP_ADDRESS.toLowerCase(), PSU_IP_ADDRESS);
headerNamesLowerCased.put(DIGEST.toLowerCase(), DIGEST);
headerNamesLowerCased.put(SIGNATURE.toLowerCase(), SIGNATURE);
headerNamesLowerCased.put(TPP_SIGNATURE_CERTIFICATE.toLowerCase(), TPP_SIGNATURE_CERTIFICATE);
headerNamesLowerCased.put(PSU_ID.toLowerCase(), PSU_ID);
headerNamesLowerCased.put(PSU_ID_TYPE.toLowerCase(), PSU_ID_TYPE);
headerNamesLowerCased.put(PSU_CORPORATE_ID.toLowerCase(), PSU_CORPORATE_ID);
headerNamesLowerCased.put(PSU_CORPORATE_ID_TYPE.toLowerCase(), PSU_CORPORATE_ID_TYPE);
headerNamesLowerCased.put(CONSENT_ID.toLowerCase(), CONSENT_ID);
headerNamesLowerCased.put(TPP_REDIRECT_PREFERRED.toLowerCase(), TPP_REDIRECT_PREFERRED);
headerNamesLowerCased.put(TPP_REDIRECT_URI.toLowerCase(), TPP_REDIRECT_URI);
headerNamesLowerCased.put(TPP_NOK_REDIRECT_URI.toLowerCase(), TPP_NOK_REDIRECT_URI);
headerNamesLowerCased.put(TPP_EXPLICIT_AUTHORISATION_PREFERRED.toLowerCase(), TPP_EXPLICIT_AUTHORISATION_PREFERRED);
headerNamesLowerCased.put(PSU_IP_PORT.toLowerCase(), PSU_IP_PORT);
headerNamesLowerCased.put(PSU_ACCEPT.toLowerCase(), PSU_ACCEPT);
headerNamesLowerCased.put(PSU_ACCEPT_CHARSET.toLowerCase(), PSU_ACCEPT_CHARSET);
headerNamesLowerCased.put(PSU_ACCEPT_ENCODING.toLowerCase(), PSU_ACCEPT_ENCODING);
headerNamesLowerCased.put(PSU_ACCEPT_LANGUAGE.toLowerCase(), PSU_ACCEPT_LANGUAGE);
headerNamesLowerCased.put(PSU_USER_AGENT.toLowerCase(), PSU_USER_AGENT);
headerNamesLowerCased.put(PSU_HTTP_METHOD.toLowerCase(), PSU_HTTP_METHOD);
headerNamesLowerCased.put(PSU_DEVICE_ID.toLowerCase(), PSU_DEVICE_ID);
headerNamesLowerCased.put(PSU_GEO_LOCATION.toLowerCase(), PSU_GEO_LOCATION);
headerNamesLowerCased.put(ACCEPT.toLowerCase(), ACCEPT);
headerNamesLowerCased.put(AUTHORIZATION.toLowerCase(), AUTHORIZATION);
headerNamesLowerCased.put(CORRELATION_ID.toLowerCase(), CORRELATION_ID);
headerNamesLowerCased.put(X_OAUTH_PREFERRED.toLowerCase(), X_OAUTH_PREFERRED);
headerNamesLowerCased.put(PSD2_AUTHORIZATION.toLowerCase(), PSD2_AUTHORIZATION);
headerNamesLowerCased.put(TPP_DECOUPLED_PREFERRED.toLowerCase(), TPP_DECOUPLED_PREFERRED);
headerNamesLowerCased.put(TPP_BRAND_LOGGING_INFORMATION.toLowerCase(), TPP_BRAND_LOGGING_INFORMATION);
headerNamesLowerCased.put(TPP_NOTIFICATION_URI.toLowerCase(), TPP_NOTIFICATION_URI);
headerNamesLowerCased.put(TPP_NOTIFICATION_CONTENT_PREFERRED.toLowerCase(), TPP_NOTIFICATION_CONTENT_PREFERRED);
headerNamesLowerCased.put(PSU_IP_ADDRESS_MANDATORY.toLowerCase(), PSU_IP_ADDRESS_MANDATORY);
}
private final Map<String, String> headers;
private RequestHeaders(Map<String, String> headers) {
this.headers = headers;
}
public static RequestHeaders fromMap(Map<String, String> headersMap) {
Map<String, String> headers = new HashMap<>();
headersMap.forEach((name, value) -> {
String headerNameInLowerCase = name.toLowerCase();
if (headerNamesLowerCased.containsKey(headerNameInLowerCase)) {
headers.put(headerNamesLowerCased.get(headerNameInLowerCase), value);
}
});
return new RequestHeaders(headers);
}
public static RequestHeaders empty() {
return EMPTY;
}
public Map<String, String> toMap() {
return new HashMap<>(headers);
}
public boolean isAcceptJson() {
return Optional.ofNullable(headers.get(ACCEPT))
.map(a -> a.toLowerCase().startsWith("application/json"))
.orElse(false);
}
public Optional<String> get(String headerName) {
return Optional.ofNullable(headers.get(headerNamesLowerCased.get(headerName.toLowerCase())));
}
public Optional<String> getAspspId() {
return get(X_GTW_ASPSP_ID);
}
public Optional<String> getBankCode() {
return get(X_GTW_BANK_CODE);
}
public Optional<String> getBic() {
return get(X_GTW_BIC);
}
public Optional<String> getIban() {
return get(X_GTW_IBAN);
}
public Optional<String> getAuthorization() {
return get(AUTHORIZATION);
}
public Optional<String> getAccessToken() {
return getAuthorization().flatMap(authorization -> {
if (!authorization.startsWith(BEARER_SPACE)) {
return Optional.empty();
}
return Optional.of(authorization.substring(BEARER_SPACE.length()));
});
}
}
| 9,135 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Pkcs12KeyStore.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/Pkcs12KeyStore.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.api;
import de.adorsys.xs2a.adapter.api.exception.Xs2aAdapterException;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.security.auth.x500.X500Principal;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* A PKCS #12 {@code java.security.KeyStore} that holds certificates and keys
* used for signing http messages (QSEAL) and client tls authentication (QWAC).
* By default a key store is expected to have two bags named "default_qwac" and
* "default_qseal" and an empty password.
* <p>
* A key store file may be created using {@code openssl} and {@code keytool}
* command line tools. First create a p12 file for each certificate/key pair
* with a specific alias.
* <pre>
* openssl pkcs12 -export -out <p12_file> -in <cert_file> -inkey <key_file> -name <alias>
* </pre>
* And then combine all p12 files into one.
* <pre>
* keytool -importkeystore -srckeystore <src_p12> -destkeystore <dest_p12> -srcstorepass '' -deststorepass ''
* </pre>
*/
public class Pkcs12KeyStore {
private static final String KEY_STORE_TYPE = "PKCS12";
private static final String DEFAULT_QWAC_ALIAS = "default_qwac";
private static final String DEFAULT_QSEAL_ALIAS = "default_qseal";
private static final char[] DEFAULT_PASSWORD = new char[]{};
private static final String ORGANIZATION_IDENTIFIER_ATTRIBUTE = "OID.2.5.4.97";
private final KeyStore keyStore;
private final char[] password;
private final String defaultQwacAlias;
private final String defaultQsealAlias;
public Pkcs12KeyStore(String filename)
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
this(filename, DEFAULT_PASSWORD);
}
public Pkcs12KeyStore(String filename, char[] password)
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
this(filename, password, DEFAULT_QWAC_ALIAS, DEFAULT_QSEAL_ALIAS);
}
public Pkcs12KeyStore(String filename, char[] password, String defaultQwacAlias, String defaultQsealAlias)
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
this(new FileInputStream(filename), password, defaultQwacAlias, defaultQsealAlias);
}
public Pkcs12KeyStore(InputStream keyStore, char[] password, String defaultQwacAlias, String defaultQsealAlias)
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
this.keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
this.keyStore.load(Objects.requireNonNull(keyStore), password);
this.password = password;
this.defaultQwacAlias = defaultQwacAlias;
this.defaultQsealAlias = defaultQsealAlias;
}
public Pkcs12KeyStore(InputStream keyStore)
throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
this(keyStore, DEFAULT_PASSWORD, DEFAULT_QWAC_ALIAS, DEFAULT_QSEAL_ALIAS);
}
public SSLContext getSslContext()
throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableEntryException, KeyManagementException, IOException, CertificateException {
return getSslContext(null);
}
public SSLContext getSslContext(String qwacAlias)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException, KeyManagementException {
if (qwacAlias == null) {
qwacAlias = defaultQwacAlias;
}
KeyStore qwacKeyStore = KeyStore.getInstance(KEY_STORE_TYPE);
qwacKeyStore.load(null, password);
KeyStore.Entry entry = keyStore.getEntry(qwacAlias, new KeyStore.PasswordProtection(password));
qwacKeyStore.setEntry("", entry, new KeyStore.PasswordProtection(password));
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(qwacKeyStore, password);
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
sslContext.init(keyManagers, null, null);
return sslContext;
}
public X509Certificate getQsealCertificate() throws KeyStoreException {
return getQsealCertificate(null);
}
public X509Certificate getQsealCertificate(String qsealAlias) throws KeyStoreException {
if (qsealAlias == null) {
qsealAlias = defaultQsealAlias;
}
return (X509Certificate) keyStore.getCertificate(qsealAlias);
}
public PrivateKey getQsealPrivateKey()
throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
return getQsealPrivateKey(null);
}
public PrivateKey getQsealPrivateKey(String qsealAlias)
throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
if (qsealAlias == null) {
qsealAlias = defaultQsealAlias;
}
return (PrivateKey) keyStore.getKey(qsealAlias, password);
}
public String getOrganizationIdentifier() throws KeyStoreException {
return getOrganizationIdentifier(null);
}
public String getOrganizationIdentifier(String qsealAlias) throws KeyStoreException {
String name = getQsealCertificate(qsealAlias)
.getSubjectX500Principal()
.getName(X500Principal.RFC1779);
try {
return new LdapName(name).getRdns().stream()
.filter(rdn -> ORGANIZATION_IDENTIFIER_ATTRIBUTE.equals(rdn.getType()))
.map(rdn -> rdn.getValue().toString())
.collect(Collectors.joining());
} catch (InvalidNameException e) {
throw new Xs2aAdapterException(e);
}
}
}
| 7,097 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AdapterServiceProvider.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/AdapterServiceProvider.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.api;
public interface AdapterServiceProvider {
String getAdapterId();
}
| 939 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
DownloadService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/DownloadService.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.api;
import de.adorsys.xs2a.adapter.api.validation.DownloadValidationService;
public interface DownloadService extends DownloadValidationService {
Response<byte[]> download(String downloadUrl, RequestHeaders requestHeaders);
}
| 1,096 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
RequestParams.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/RequestParams.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.api;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
public class RequestParams {
public static final String WITH_BALANCE = "withBalance";
public static final String BOOKING_STATUS = "bookingStatus";
public static final String DATE_FROM = "dateFrom";
public static final String DATE_TO = "dateTo";
public static final String ENTRY_REFERENCE_FROM = "entryReferenceFrom";
public static final String DELTA_LIST = "deltaList";
private static final RequestParams EMPTY = new RequestParams(Collections.emptyMap());
private final Map<String, String> requestParams;
private RequestParams(Map<String, String> requestParams) {
this.requestParams = Collections.unmodifiableMap(new LinkedHashMap<>(requestParams));
}
public static RequestParams fromMap(Map<String, String> map) {
RequestParams requestParams = new RequestParams(map);
verifyTypeBoolean(map.get(WITH_BALANCE));
verifyTypeLocalDate(map.get(DATE_FROM));
verifyTypeLocalDate(map.get(DATE_TO));
verifyTypeBoolean(map.get(DELTA_LIST));
return requestParams;
}
private static void verifyTypeLocalDate(String value) {
if (value != null) {
try {
LocalDate.parse(value);
} catch (DateTimeParseException e) {
throw new IllegalArgumentException(e);
}
}
}
private static void verifyTypeBoolean(String value) {
if (value != null && !"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value)) {
throw new IllegalArgumentException(value + " is not a boolean");
}
}
public static RequestParams empty() {
return EMPTY;
}
public static RequestParamsBuilder builder() {
return new RequestParamsBuilder();
}
public Map<String, String> toMap() {
return requestParams;
}
public <T> T get(String name, Function<? super String, T> parseFunction) {
String value = requestParams.get(name);
if (value != null) {
return parseFunction.apply(value);
}
return null;
}
public LocalDate dateFrom() {
return localDate(requestParams.get(DATE_FROM));
}
private LocalDate localDate(String value) {
if (value == null) {
return null;
}
return LocalDate.parse(value);
}
public LocalDate dateTo() {
return localDate(requestParams.get(DATE_TO));
}
public String entryReferenceFrom() {
return requestParams.get(ENTRY_REFERENCE_FROM);
}
public String bookingStatus() {
return requestParams.get(BOOKING_STATUS);
}
public Boolean deltaList() {
return bool(requestParams.get(DELTA_LIST));
}
private Boolean bool(String value) {
if (value == null) {
return null;
}
return Boolean.valueOf(value);
}
public Boolean withBalance() {
return bool(requestParams.get(WITH_BALANCE));
}
public static final class RequestParamsBuilder {
private Map<String, String> requestParams;
private Boolean withBalance;
private String bookingStatus;
private LocalDate dateFrom;
private LocalDate dateTo;
private String entryReferenceFrom;
private Boolean deltaList;
private RequestParamsBuilder() {
}
public RequestParamsBuilder requestParams(Map<String, String> requestParams) {
this.requestParams = new LinkedHashMap<>(requestParams);
return this;
}
public RequestParamsBuilder withBalance(Boolean withBalance) {
this.withBalance = withBalance;
return this;
}
public RequestParamsBuilder bookingStatus(String bookingStatus) {
this.bookingStatus = bookingStatus;
return this;
}
public RequestParamsBuilder dateFrom(LocalDate dateFrom) {
this.dateFrom = dateFrom;
return this;
}
public RequestParamsBuilder dateTo(LocalDate dateTo) {
this.dateTo = dateTo;
return this;
}
public RequestParamsBuilder entryReferenceFrom(String entryReferenceFrom) {
this.entryReferenceFrom = entryReferenceFrom;
return this;
}
public RequestParamsBuilder deltaList(Boolean deltaList) {
this.deltaList = deltaList;
return this;
}
public RequestParams build() {
if (requestParams == null) {
requestParams = new HashMap<>();
}
putIntoAs(withBalance, requestParams, WITH_BALANCE);
putIntoAs(bookingStatus, requestParams, BOOKING_STATUS);
putIntoAs(dateFrom, requestParams, DATE_FROM);
putIntoAs(dateTo, requestParams, DATE_TO);
putIntoAs(entryReferenceFrom, requestParams, ENTRY_REFERENCE_FROM);
putIntoAs(deltaList, requestParams, DELTA_LIST);
return new RequestParams(requestParams);
}
private void putIntoAs(Object requestParamValue, Map<String, String> requestParams, String requestParamName) {
if (requestParamValue != null) {
requestParams.put(requestParamName, requestParamValue.toString());
}
}
}
}
| 6,416 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AspspRepository.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/AspspRepository.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.api;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import java.util.List;
public interface AspspRepository extends AspspReadOnlyRepository {
Aspsp save(Aspsp aspsp);
/**
* Saves a list of aspsps into existing Lucene indexes.
* <p>
* Writes all Aspsp objects into the current Lucene repository. The iteration through input
* collection of aspsps is taken place, each object is either added or updated, if it
* already exists within the repository.
*
* @param aspsps a list of aspsp objects to be added into the repository
*/
void saveAll(List<Aspsp> aspsps);
void deleteById(String aspspId);
/**
* Deletes all records from the existing Lucene indexes.
*/
void deleteAll();
}
| 1,619 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ResponseHeaders.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/ResponseHeaders.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.api;
import java.util.*;
public class ResponseHeaders {
public static final String LOCATION = "Location";
public static final String X_REQUEST_ID = "X-Request-ID";
public static final String ASPSP_SCA_APPROACH = "ASPSP-SCA-Approach";
public static final String CONTENT_TYPE = "Content-Type";
public static final String X_GTW_ASPSP_CHANGES_DETECTED = "X-GTW-ASPSP-CHANGES-DETECTED";
private static Map<String, String> headerNamesLowerCased = new HashMap<>();
static {
headerNamesLowerCased.put(LOCATION.toLowerCase(), LOCATION);
headerNamesLowerCased.put(X_REQUEST_ID.toLowerCase(), X_REQUEST_ID);
headerNamesLowerCased.put(ASPSP_SCA_APPROACH.toLowerCase(), ASPSP_SCA_APPROACH);
headerNamesLowerCased.put(CONTENT_TYPE.toLowerCase(), CONTENT_TYPE);
headerNamesLowerCased.put(X_GTW_ASPSP_CHANGES_DETECTED.toLowerCase(), X_GTW_ASPSP_CHANGES_DETECTED);
}
private Map<String, String> headers;
private ResponseHeaders(Map<String, String> headers) {
this.headers = headers;
}
public static ResponseHeaders fromMap(Map<String, String> headersMap) {
if (Objects.isNull(headersMap) || headersMap.isEmpty()) {
return emptyResponseHeaders();
}
Map<String, String> headers = new HashMap<>();
Set<String> headerNamesLowerCased = ResponseHeaders.headerNamesLowerCased.keySet();
headersMap.forEach((name, value) -> {
String headerNameInLowerCase = name.toLowerCase();
if (isHeaderExistInBGSpecification(headerNamesLowerCased, headerNameInLowerCase)) {
headers.put(ResponseHeaders.headerNamesLowerCased.get(headerNameInLowerCase), value);
}
});
return new ResponseHeaders(headers);
}
public static ResponseHeaders emptyResponseHeaders() {
return new ResponseHeaders(Collections.emptyMap());
}
private static boolean isHeaderExistInBGSpecification(Set<String> headerNames, String headerName) {
return headerNames.contains(headerName);
}
public Map<String, String> getHeadersMap() {
return new HashMap<>(headers);
}
public String getHeader(String headerName) {
return headers.get(headerName);
}
}
| 3,136 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Oauth2ServiceProvider.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/Oauth2ServiceProvider.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.api;
import de.adorsys.xs2a.adapter.api.http.HttpClientFactory;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
public interface Oauth2ServiceProvider extends AdapterServiceProvider {
Oauth2Service getOauth2Service(Aspsp aspsp, HttpClientFactory httpClientFactory);
}
| 1,137 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PropertyUtil.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/PropertyUtil.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.api;
public final class PropertyUtil {
private PropertyUtil() {
}
public static String readProperty(String key) {
return readProperty(key, "");
}
public static String readProperty(String key, String defaultValue) {
String property = System.getProperty(key, "");
if (!property.isEmpty()) {
return property;
}
property = System.getenv(key);
return property == null || property.trim().isEmpty() ? defaultValue : property;
}
}
| 1,373 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AspspReadOnlyRepository.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/AspspReadOnlyRepository.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.api;
import de.adorsys.xs2a.adapter.api.model.Aspsp;
import java.util.List;
import java.util.Optional;
public interface AspspReadOnlyRepository {
int DEFAULT_SIZE = 10;
int MAX_SIZE = Integer.MAX_VALUE;
Optional<Aspsp> findById(String id);
default List<Aspsp> findByBic(String bic) {
return findByBic(bic, DEFAULT_SIZE);
}
default List<Aspsp> findByBic(String bic, int size) {
return findByBic(bic, null, size);
}
List<Aspsp> findByBic(String bic, String after, int size);
default List<Aspsp> findByBankCode(String bankCode) {
return findByBankCode(bankCode, DEFAULT_SIZE);
}
default List<Aspsp> findByBankCode(String bankCode, int size) {
return findByBankCode(bankCode, null, size);
}
List<Aspsp> findByBankCode(String bankCode, String after, int size);
default List<Aspsp> findByName(String name) {
return findByName(name, DEFAULT_SIZE);
}
default List<Aspsp> findByName(String name, int size) {
return findByName(name, null, size);
}
List<Aspsp> findByName(String name, String after, int size);
default List<Aspsp> findAll() {
return findAll(MAX_SIZE);
}
default List<Aspsp> findAll(int size) {
return findAll(null, size);
}
List<Aspsp> findAll(String after, int size);
default List<Aspsp> findLike(Aspsp aspsp) {
return findLike(aspsp, DEFAULT_SIZE);
}
default List<Aspsp> findLike(Aspsp aspsp, int size) {
return findLike(aspsp, null, size);
}
List<Aspsp> findLike(Aspsp aspsp, String after, int size);
default List<Aspsp> findByIban(String iban) {
return findByIban(iban, DEFAULT_SIZE);
}
default List<Aspsp> findByIban(String iban, int size) {
return findByIban(iban, null, size);
}
List<Aspsp> findByIban(String iban, String after, int size);
}
| 2,767 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Oauth2Api.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/oauth/Oauth2Api.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.api.oauth;
public interface Oauth2Api {
String getAuthorisationUri(String scaOAuthUrl);
String getTokenUri(String scaOAuthUrl);
}
| 1,003 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AdapterConfig.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/config/AdapterConfig.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.api.config;
import de.adorsys.xs2a.adapter.api.PropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public final class AdapterConfig {
private static final Logger logger = LoggerFactory.getLogger(AdapterConfig.class);
private static final String ADAPTER_CONFIG_FILE_PATH_PROPERTY = "adapter.config.file.path";
private static final String DEFAULT_ADAPTER_CONFIG_FILE = "adapter.config.properties";
private static final Properties properties = new Properties();
static {
reload();
}
public static void reload() {
try {
properties.clear();
InputStream configFileAsStream = getConfigFileAsStream();
properties.load(configFileAsStream);
logger.debug("Adapter configuration file is loaded");
} catch (IOException e) {
throw new IllegalStateException("Can't load adapter config file");
}
}
private AdapterConfig() {
}
public static void setConfigFile(String file) {
System.setProperty(ADAPTER_CONFIG_FILE_PATH_PROPERTY, file);
reload();
}
public static String readProperty(String property) {
return properties.getProperty(property);
}
public static String readProperty(String property, String defaultValue) {
return properties.getProperty(property, defaultValue);
}
private static InputStream getConfigFileAsStream() throws FileNotFoundException {
String filePath = PropertyUtil.readProperty(ADAPTER_CONFIG_FILE_PATH_PROPERTY);
InputStream inputStream;
if (filePath == null || filePath.isEmpty()) {
inputStream = getResourceAsStream(DEFAULT_ADAPTER_CONFIG_FILE);
logger.debug("Default configuration file [{}] will be used", DEFAULT_ADAPTER_CONFIG_FILE);
} else {
inputStream = getFileAsStream(filePath);
logger.debug("[{}] configuration file will be used", filePath);
}
return inputStream;
}
private static InputStream getResourceAsStream(String fileName) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
}
private static InputStream getFileAsStream(String filePath) throws FileNotFoundException {
return new FileInputStream(filePath);
}
}
| 3,344 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ContentType.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/http/ContentType.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.api.http;
public class ContentType {
private ContentType() {
}
public static final String APPLICATION_JSON = "application/json";
public static final String APPLICATION_XML = "application/xml";
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
public static final String ALL = "*/*";
public static final String TEXT_PLAIN = "text/plain";
}
| 1,253 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
HttpClient.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/http/HttpClient.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.api.http;
import de.adorsys.xs2a.adapter.api.Response;
import de.adorsys.xs2a.adapter.api.ResponseHeaders;
import java.io.InputStream;
public interface HttpClient {
Request.Builder get(String uri);
Request.Builder post(String uri);
Request.Builder put(String uri);
Request.Builder delete(String uri);
<T> Response<T> send(Request.Builder requestBuilder, ResponseHandler<T> responseHandler);
String content(Request.Builder requestBuilder);
@FunctionalInterface
interface ResponseHandler<T> {
T apply(int statusCode, InputStream responseBody, ResponseHeaders responseHeaders);
}
}
| 1,495 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Request.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/http/Request.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.api.http;
import de.adorsys.xs2a.adapter.api.Response;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public interface Request {
interface Builder {
String method();
String uri();
String body();
Builder jsonBody(String body);
boolean jsonBody();
Builder emptyBody(boolean empty);
boolean emptyBody();
Builder urlEncodedBody(Map<String, String> formData);
Map<String, String> urlEncodedBody();
Builder xmlBody(String body);
boolean xmlBody();
Builder addXmlPart(String name, String xmlPart);
Map<String, String> xmlParts();
Builder addJsonPart(String name, String jsonPart);
Map<String, String> jsonParts();
Builder addPlainTextPart(String name, Object part);
Map<String, String> plainTextParts();
boolean multipartBody();
Builder headers(Map<String, String> headers);
Map<String, String> headers();
Builder header(String name, String value);
<T> Response<T> send(HttpClient.ResponseHandler<T> responseHandler, List<Interceptor> interceptors);
default <T> Response<T> send(HttpClient.ResponseHandler<T> responseHandler) {
return send(responseHandler, Collections.emptyList());
}
String content();
}
}
| 2,238 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
HttpClientConfig.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/http/HttpClientConfig.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.api.http;
import de.adorsys.xs2a.adapter.api.Pkcs12KeyStore;
/**
* Container for passing necessary configuration into {@link HttpClientFactory} for creating and setting up an {@link HttpClient}.
*/
public interface HttpClientConfig {
HttpLogSanitizer getLogSanitizer();
/**
* @return Key Store with Application Certificates
*/
Pkcs12KeyStore getKeyStore();
/**
* @return Url for standalone wiremock server
*/
String getWiremockStandaloneUrl();
}
| 1,355 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
HttpClientFactory.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/http/HttpClientFactory.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.api.http;
public interface HttpClientFactory {
HttpClient getHttpClient(String adapterId, String qwacAlias, String[] supportedCipherSuites);
default HttpClient getHttpClient(String adapterId, String qwacAlias) {
return getHttpClient(adapterId, qwacAlias, null);
}
default HttpClient getHttpClient(String adapterId) {
return getHttpClient(adapterId, null);
}
/**
* @return An object with all necessary configurations for creating an {@link HttpClient}
*/
HttpClientConfig getHttpClientConfig();
}
| 1,417 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
HttpLogSanitizer.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/http/HttpLogSanitizer.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.api.http;
/**
* Service that masks all sensitive data that may appear in logs, e.g. IBAN, PSU-ID, ConsentId, Location, etc.
*/
public interface HttpLogSanitizer {
String sanitize(String data);
String sanitizeHeader(String name, String value);
String sanitizeRequestBody(Object httpEntity, String contentType);
String sanitizeResponseBody(Object responseBody, String contentType);
}
| 1,264 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Interceptor.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/http/Interceptor.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.api.http;
import de.adorsys.xs2a.adapter.api.Response;
public interface Interceptor {
Request.Builder preHandle(Request.Builder builder);
/**
* the method will be executed when the response from ASPSP will be received.
* @param builder request builder object
* @param response response received from ASPSP
* @return modified response object
*/
default <T> Response<T> postHandle(Request.Builder builder, Response<T> response) {
return response;
}
}
| 1,363 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AccessTokenService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/security/AccessTokenService.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.api.security;
public interface AccessTokenService {
String retrieveToken();
}
| 946 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
RequestValidationException.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/validation/RequestValidationException.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.api.validation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RequestValidationException extends RuntimeException {
private final List<ValidationError> validationErrors;
public RequestValidationException(List<ValidationError> validationErrors) {
super(validationErrors.toString());
this.validationErrors = Collections.unmodifiableList(new ArrayList<>(validationErrors));
}
public List<ValidationError> getValidationErrors() {
return validationErrors;
}
@Override
public String toString() {
return validationErrors.toString();
}
}
| 1,509 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Validation.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/validation/Validation.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.api.validation;
import java.util.List;
public class Validation {
private Validation() {
}
public static void requireValid(List<ValidationError> validationErrors) {
if (!validationErrors.isEmpty()) {
throw new RequestValidationException(validationErrors);
}
}
}
| 1,171 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
PaymentInitiationValidationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/validation/PaymentInitiationValidationService.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.api.validation;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.model.*;
import java.util.Collections;
import java.util.List;
public interface PaymentInitiationValidationService {
default List<ValidationError> validateInitiatePayment(PaymentService paymentService,
PaymentProduct paymentProduct,
RequestHeaders requestHeaders,
RequestParams requestParams,
Object body) {
return Collections.emptyList();
}
default List<ValidationError> validateGetSinglePaymentInformation(PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetPeriodicPaymentInformation(PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetPeriodicPain001PaymentInformation(PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetPaymentInitiationScaStatus(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetPaymentInitiationStatus(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetPaymentInitiationStatusAsString(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetPaymentInitiationAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateStartPaymentAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateStartPaymentAuthorisation(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication body) {
return Collections.emptyList();
}
default List<ValidationError> validateUpdatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
SelectPsuAuthenticationMethod body) {
return Collections.emptyList();
}
default List<ValidationError> validateUpdatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
TransactionAuthorisation body) {
return Collections.emptyList();
}
default List<ValidationError> validateUpdatePaymentPsuData(PaymentService paymentService,
PaymentProduct paymentProduct,
String paymentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication body) {
return Collections.emptyList();
}
}
| 8,504 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
ValidationError.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/validation/ValidationError.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.api.validation;
import java.io.Serializable;
import java.util.Objects;
public class ValidationError implements Serializable {
private final Code code;
private final String path;
private final String message;
public enum Code {
NOT_SUPPORTED,
REQUIRED
}
public ValidationError(Code code, String path, String message) {
this.code = Objects.requireNonNull(code);
this.path = Objects.requireNonNull(path);
this.message = Objects.requireNonNull(message);
}
public static ValidationError required(String path) {
return new ValidationError(ValidationError.Code.REQUIRED, path, "Missing required parameter");
}
public Code getCode() {
return code;
}
public String getPath() {
return path;
}
public String getMessage() {
return message;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ValidationError that = (ValidationError) o;
return code == that.code &&
Objects.equals(path, that.path) &&
Objects.equals(message, that.message);
}
@Override
public int hashCode() {
return Objects.hash(code, path, message);
}
@Override
public String toString() {
return "ValidationError{" +
"code=" + code +
", path='" + path + '\'' +
", message='" + message + '\'' +
'}';
}
}
| 2,399 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
DownloadValidationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/validation/DownloadValidationService.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.api.validation;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import java.util.Collections;
import java.util.List;
public interface DownloadValidationService {
default List<ValidationError> validateDownload(String downloadUrl, RequestHeaders requestHeaders) {
return Collections.emptyList();
}
}
| 1,182 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Oauth2ValidationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/validation/Oauth2ValidationService.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.api.validation;
import de.adorsys.xs2a.adapter.api.Oauth2Service;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public interface Oauth2ValidationService {
default List<ValidationError> validateGetAuthorizationRequestUri(Map<String, String> headers,
Oauth2Service.Parameters parameters) {
return Collections.emptyList();
}
default List<ValidationError> validateGetToken(Map<String, String> headers, Oauth2Service.Parameters parameters) {
return Collections.emptyList();
}
}
| 1,469 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
AccountInformationValidationService.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/validation/AccountInformationValidationService.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.api.validation;
import de.adorsys.xs2a.adapter.api.RequestHeaders;
import de.adorsys.xs2a.adapter.api.RequestParams;
import de.adorsys.xs2a.adapter.api.model.Consents;
import de.adorsys.xs2a.adapter.api.model.SelectPsuAuthenticationMethod;
import de.adorsys.xs2a.adapter.api.model.TransactionAuthorisation;
import de.adorsys.xs2a.adapter.api.model.UpdatePsuAuthentication;
import java.util.Collections;
import java.util.List;
public interface AccountInformationValidationService {
default List<ValidationError> validateCreateConsent(RequestHeaders requestHeaders,
RequestParams requestParams,
Consents body) {
return Collections.emptyList();
}
default List<ValidationError> validateGetConsentInformation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateDeleteConsent(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetConsentStatus(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateStartConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateStartConsentAuthorisation(String consentId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
return Collections.emptyList();
}
default List<ValidationError> validateUpdateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
SelectPsuAuthenticationMethod selectPsuAuthenticationMethod) {
return Collections.emptyList();
}
default List<ValidationError> validateUpdateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
TransactionAuthorisation transactionAuthorisation) {
return Collections.emptyList();
}
default List<ValidationError> validateUpdateConsentsPsuData(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams,
UpdatePsuAuthentication updatePsuAuthentication) {
return Collections.emptyList();
}
default List<ValidationError> validateGetAccountList(RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateReadAccountDetails(RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetTransactionList(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetTransactionDetails(String accountId,
String transactionId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetTransactionListAsString(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetConsentScaStatus(String consentId,
String authorisationId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetBalances(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetCardAccountList(RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetCardAccountDetails(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetCardAccountBalances(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
default List<ValidationError> validateGetCardAccountTransactionList(String accountId,
RequestHeaders requestHeaders,
RequestParams requestParams) {
return Collections.emptyList();
}
}
| 8,645 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
LinksRewriter.java | /FileExtraction/Java_unseen/adorsys_xs2a-adapter/xs2a-adapter-service-api/src/main/java/de/adorsys/xs2a/adapter/api/link/LinksRewriter.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.api.link;
import de.adorsys.xs2a.adapter.api.model.HrefType;
import java.util.Map;
public interface LinksRewriter {
Map<String, HrefType> rewrite(Map<String, HrefType> links);
}
| 1,048 | Java | .java | adorsys/xs2a-adapter | 37 | 25 | 5 | 2019-04-01T09:31:44Z | 2024-03-09T08:27:14Z |
Subsets and Splits