From 0f8161ba015f7cbc7163a7b8ce5b590207ff55e3 Mon Sep 17 00:00:00 2001 From: Felix Dittrich Date: Mon, 24 Oct 2022 14:34:02 +0200 Subject: [PATCH] Update Dependencies Reformating Code Remove Workaround Spring Boot Source File Forks --- codestyle/checkstyle.xml | 14 +- owasp/suppressions.xml | 8 + pom.xml | 62 +- .../connector/DgcGatewayConnectorUtils.java | 10 +- .../DgcGatewayDownloadConnector.java | 4 +- .../DgcGatewayDownloadConnectorBuilder.java | 9 +- ...atewayRevocationListDownloadConnector.java | 7 +- ...cGatewayRevocationListUploadConnector.java | 18 +- .../client/DgcGatewayConnectorRestClient.java | 8 +- .../DgcFeignClientBuilder.java | 140 ---- .../DgcFeignClientFactoryBean.java | 614 ------------------ .../DgcFeignClientRegistrar.java | 453 ------------- .../ec/dgc/generation/DccRecoveryBuilder.java | 3 + .../ec/dgc/generation/DccTestBuilder.java | 14 +- .../dgc/generation/DccVaccinationBuilder.java | 6 + .../dgc/generation/DgcCryptedFinalizer.java | 7 +- .../dgc/generation/DgcCryptedPublisher.java | 6 +- .../ec/dgc/generation/DgcGenerator.java | 4 +- .../europa/ec/dgc/generation/DgcSigner.java | 7 +- .../SignedCertificateMessageParser.java | 2 +- .../ec/dgc/signing/SignedMessageParser.java | 1 + .../ec/dgc/DgcLibAutoConfigurationTest.java | 8 +- .../RevocationListDownloadConnectorTest.java | 20 +- .../RevocationListUploadConnectorTest.java | 155 +++-- .../TrustedIssuerDownloadConnectorTest.java | 17 +- .../ValidationRuleDownloadConnectorTest.java | 2 +- .../ec/dgc/generation/Base45EncoderTest.java | 8 +- .../generation/DccRecoveryBuilderTest.java | 12 +- .../ec/dgc/generation/DccTestBuilderTest.java | 18 +- .../generation/DccVaccinationBuilderTest.java | 18 +- .../generation/DgcCryptedPublisherTest.java | 122 ++-- .../ec/dgc/generation/DgcSignerTest.java | 16 +- ...edSignedCertificateMessageBuilderTest.java | 2 +- .../SignedCertificateMessageBuilderTest.java | 4 +- .../dgc/testdata/TrustedIssuerTestHelper.java | 8 +- 35 files changed, 307 insertions(+), 1500 deletions(-) delete mode 100644 src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientBuilder.java delete mode 100644 src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientFactoryBean.java delete mode 100644 src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientRegistrar.java diff --git a/codestyle/checkstyle.xml b/codestyle/checkstyle.xml index cd94d54..64a48ec 100644 --- a/codestyle/checkstyle.xml +++ b/codestyle/checkstyle.xml @@ -1,7 +1,7 @@ + "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" + "https://checkstyle.org/dtds/configuration_1_3.dtd"> - 6.5.3 - 2.6.3 - 3.1.0 - 11.7 + 7.3.0 + 2.7.5 + 3.1.4 + 11.10 1.70 - 1.18.22 - 1.4.2.Final + 1.18.24 + 1.5.3.Final 2.11.0 - 4.5.1 - 2.13.2 - 2.13.2.1 - 4.9.3 - 3.1.2 - 3.9.1.2184 - 3.0.0-M5 - 0.8.7 + 4.5.2 + 2.13.4 + 2.13.4.2 + 4.10.0 + 3.2.0 + 3.0.0-M7 + 0.8.8 EU Digital Green Certificate Gateway Service / dgc-lib @@ -74,9 +73,21 @@ org.springframework.boot - spring-boot-starter + spring-boot-starter-web ${spring.boot.version} true + + + org.yaml + snakeyaml + + + + + + org.yaml + snakeyaml + 1.33 org.springframework.boot @@ -149,24 +160,6 @@ ${mockwebserver.version} test - - - net.minidev - json-smart - 2.4.7 - test - - - - org.springframework.security - spring-security-crypto - 5.5.1 - - - org.springframework - spring-web - 5.3.15 - @@ -185,7 +178,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + 3.10.1 org.codehaus.mojo @@ -243,7 +236,6 @@ codestyle/checkstyle.xml target/**/* **/springbootworkaroundforks/* - UTF-8 true true warning diff --git a/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayConnectorUtils.java b/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayConnectorUtils.java index 74e74d2..132bf71 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayConnectorUtils.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayConnectorUtils.java @@ -135,14 +135,14 @@ public boolean trustListItemSignedByCa(TrustListItemDto certificate, X509Certifi } public boolean trustListItemSignedByCa(TrustListItemDto certificate, Map> caMap) { + List> caMap) { X509CertificateHolder dcs; try { dcs = new X509CertificateHolder(Base64.getDecoder().decode(certificate.getRawData())); } catch (IOException e) { log.error("Could not parse certificate. KID: {}, Country: {}", - certificate.getKid(), certificate.getCountry()); + certificate.getKid(), certificate.getCountry()); return false; } catch (NullPointerException e) { return false; @@ -151,13 +151,13 @@ public boolean trustListItemSignedByCa(TrustListItemDto certificate, Map caList = caMap.get(dcs.getIssuer().toString()); if (caList == null) { log.error("Failed to find issuer certificate from cert. KID: {}, Country: {}", - certificate.getKid(), certificate.getCountry()); + certificate.getKid(), certificate.getCountry()); return false; } return caList - .stream() - .anyMatch(ca -> trustListItemSignedByCa(certificate, ca)); + .stream() + .anyMatch(ca -> trustListItemSignedByCa(certificate, ca)); } boolean checkTrustAnchorSignature(TrustListItemDto trustListItem, List trustAnchors) { diff --git a/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayDownloadConnector.java b/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayDownloadConnector.java index 383f005..801408e 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayDownloadConnector.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayDownloadConnector.java @@ -103,8 +103,8 @@ private synchronized void updateIfRequired() { trustedCscaCertificates = connectorUtils.fetchCertificatesAndVerifyByTrustAnchor(CertificateTypeDto.CSCA); log.info("CSCA TrustStore contains {} trusted certificates.", trustedCscaCertificates.size()); trustedCscaCertificateMap = trustedCscaCertificates.stream() - .collect(Collectors.groupingBy((ca) -> ca.getSubject().toString(), - Collectors.mapping((ca) -> ca, Collectors.toList()))); + .collect(Collectors.groupingBy((ca) -> ca.getSubject().toString(), + Collectors.mapping((ca) -> ca, Collectors.toList()))); trustedUploadCertificates = connectorUtils.fetchCertificatesAndVerifyByTrustAnchor(CertificateTypeDto.UPLOAD); diff --git a/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayDownloadConnectorBuilder.java b/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayDownloadConnectorBuilder.java index bffc12c..dbdeaa5 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayDownloadConnectorBuilder.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayDownloadConnectorBuilder.java @@ -25,8 +25,6 @@ import eu.europa.ec.dgc.gateway.connector.mapper.TrustListMapper; import eu.europa.ec.dgc.gateway.connector.mapper.TrustedIssuerMapper; import eu.europa.ec.dgc.gateway.connector.mapper.TrustedIssuerMapperImpl; -import eu.europa.ec.dgc.gateway.connector.springbootworkaroundforks.DgcFeignClientBuilder; -import eu.europa.ec.dgc.gateway.connector.springbootworkaroundforks.DgcFeignClientFactoryBean; import eu.europa.ec.dgc.utils.CertificateUtils; import feign.Client; import feign.httpclient.ApacheHttpClient; @@ -58,6 +56,8 @@ import org.apache.http.ssl.SSLContextBuilder; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.springframework.cloud.openfeign.FeignClientBuilder; +import org.springframework.cloud.openfeign.FeignClientFactoryBean; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpHeaders; @@ -287,9 +287,8 @@ public DgcGatewayDownloadConnector build() throws DgcGatewayDownloadConnectorBui "Failed to create HTTP Client", e); } - - DgcGatewayConnectorRestClient restClient = new DgcFeignClientBuilder(springBootContext) - .forType(DgcGatewayConnectorRestClient.class, new DgcFeignClientFactoryBean(), UUID.randomUUID().toString()) + DgcGatewayConnectorRestClient restClient = new FeignClientBuilder(springBootContext) + .forType(DgcGatewayConnectorRestClient.class, new FeignClientFactoryBean(), UUID.randomUUID().toString()) .customize(builder -> builder.client(client)) .url(url) .build(); diff --git a/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayRevocationListDownloadConnector.java b/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayRevocationListDownloadConnector.java index 415b0b6..eb318d4 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayRevocationListDownloadConnector.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayRevocationListDownloadConnector.java @@ -56,6 +56,7 @@ public class DgcGatewayRevocationListDownloadConnector { /** * Gets a revocation list iterator, for partly downloading the revocation list. * The if-modified-since header is set to the default value to start at the beginning of the list. + * * @return revocation list iterator */ public DgcGatewayRevocationListDownloadIterator getRevocationListDownloadIterator() { @@ -65,6 +66,7 @@ public DgcGatewayRevocationListDownloadIterator getRevocationListDownloadIterato /** * Gets a revocation list iterator, for partly downloading the revocation list. * The if-modified-since header is set to the value of the parameter. Only newer part of the list are downloaded. + * * @param ifModifiedSinceDate The value for the if-modified-since header * @return revocation list iterator */ @@ -76,6 +78,7 @@ public DgcGatewayRevocationListDownloadIterator getRevocationListDownloadIterato /** * Gets the revocation list batch data for a given batchId. + * * @param batchId the id of the batch to download. * @return the batch data. */ @@ -90,7 +93,7 @@ public RevocationBatchDto getRevocationListBatchById(String batchId) throws Revo log.error("Download of revocation list batch failed. DGCG responded with status code: {}", e.status()); if (e.status() == HttpStatus.GONE.value()) { - throw new RevocationBatchGoneException(String.format("Batch already gone: %s", batchId),batchId); + throw new RevocationBatchGoneException(String.format("Batch already gone: %s", batchId), batchId); } throw new RevocationBatchDownloadException("Batch download failed with exception.", e); @@ -102,7 +105,7 @@ public RevocationBatchDto getRevocationListBatchById(String batchId) throws Revo throw new RevocationBatchDownloadException( String.format("Batch download failed with unexpected response. Response status code: %d", statusCode), - statusCode); + statusCode); } String cms = responseEntity.getBody(); diff --git a/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayRevocationListUploadConnector.java b/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayRevocationListUploadConnector.java index 8c92568..4520162 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayRevocationListUploadConnector.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/connector/DgcGatewayRevocationListUploadConnector.java @@ -67,7 +67,7 @@ public class DgcGatewayRevocationListUploadConnector { private final DgcGatewayConnectorRestClient dgcGatewayConnectorRestClient; private final DgcGatewayConnectorConfigProperties properties; - + private final ObjectMapper objectMapper; private final CertificateUtils certificateUtils; @@ -111,12 +111,12 @@ void init() throws KeyStoreException, CertificateEncodingException, IOException * @throws DgcRevocationBatchUploadException with detailed information why the upload has failed. */ public String uploadRevocationBatch(RevocationBatchDto revocationBatchDto) - throws DgcRevocationBatchUploadException, JsonProcessingException { + throws DgcRevocationBatchUploadException, JsonProcessingException { objectMapper.registerModule(new JavaTimeModule()); String jsonString = objectMapper.writeValueAsString(revocationBatchDto); String payload = new SignedStringMessageBuilder().withPayload(jsonString) - .withSigningCertificate(uploadCertificateHolder, uploadCertificatePrivateKey).buildAsString(); + .withSigningCertificate(uploadCertificateHolder, uploadCertificatePrivateKey).buildAsString(); try { ResponseEntity response = dgcGatewayConnectorRestClient.uploadBatch(payload); @@ -132,7 +132,7 @@ public String uploadRevocationBatch(RevocationBatchDto revocationBatchDto) } else if (e.status() == HttpStatus.UNAUTHORIZED.value() || e.status() == HttpStatus.FORBIDDEN.value()) { log.error("Client is not authorized. (Invalid Client Certificate)"); throw new DgcRevocationBatchUploadException( - DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION); + DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION); } } return null; @@ -145,14 +145,14 @@ public String uploadRevocationBatch(RevocationBatchDto revocationBatchDto) * @throws DgcRevocationBatchUploadException with detailed information why the delete has failed. */ public void deleteRevocationBatch(String batchId) throws DgcRevocationBatchUploadException, - JsonProcessingException { + JsonProcessingException { RevocationBatchDeleteRequestDto deleteRequest = new RevocationBatchDeleteRequestDto(); deleteRequest.setBatchId(batchId); String jsonString = objectMapper.writeValueAsString(deleteRequest); String payload = new SignedStringMessageBuilder().withPayload(jsonString) - .withSigningCertificate(uploadCertificateHolder, uploadCertificatePrivateKey).buildAsString(); + .withSigningCertificate(uploadCertificateHolder, uploadCertificatePrivateKey).buildAsString(); try { ResponseEntity response = dgcGatewayConnectorRestClient.deleteBatch(payload); @@ -167,7 +167,7 @@ public void deleteRevocationBatch(String batchId) throws DgcRevocationBatchUploa } else if (e.status() == HttpStatus.UNAUTHORIZED.value() || e.status() == HttpStatus.FORBIDDEN.value()) { log.error("Client is not authorized. (Invalid Client Certificate)"); throw new DgcRevocationBatchUploadException( - DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION); + DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION); } else if (e.status() == HttpStatus.NOT_FOUND.value()) { log.info("ValidationRules with ID {} does not exists on DGCG", batchId); @@ -181,8 +181,8 @@ private void handleBadRequest(FeignException e) throws DgcRevocationBatchUploadE ProblemReportDto problemReport = objectMapper.readValue(e.contentUTF8(), ProblemReportDto.class); throw new DgcRevocationBatchUploadException(DgcRevocationBatchUploadException.Reason.INVALID_BATCH, - String.format("%s: %s, %s", problemReport.getCode(), problemReport.getProblem(), - problemReport.getDetails())); + String.format("%s: %s, %s", problemReport.getCode(), problemReport.getProblem(), + problemReport.getDetails())); } catch (JsonProcessingException jsonException) { throw new DgcRevocationBatchUploadException(DgcRevocationBatchUploadException.Reason.UNKNOWN_ERROR); } diff --git a/src/main/java/eu/europa/ec/dgc/gateway/connector/client/DgcGatewayConnectorRestClient.java b/src/main/java/eu/europa/ec/dgc/gateway/connector/client/DgcGatewayConnectorRestClient.java index 6b86709..d56adf1 100644 --- a/src/main/java/eu/europa/ec/dgc/gateway/connector/client/DgcGatewayConnectorRestClient.java +++ b/src/main/java/eu/europa/ec/dgc/gateway/connector/client/DgcGatewayConnectorRestClient.java @@ -42,9 +42,9 @@ @ConditionalOnProperty("dgc.gateway.connector.enabled") @FeignClient( - name = "dgc-gateway-connector", - url = "${dgc.gateway.connector.endpoint}", - configuration = DgcGatewayConnectorRestClientConfig.class + name = "dgc-gateway-connector", + url = "${dgc.gateway.connector.endpoint}", + configuration = DgcGatewayConnectorRestClientConfig.class ) public interface DgcGatewayConnectorRestClient { @@ -130,7 +130,7 @@ public interface DgcGatewayConnectorRestClient { */ @GetMapping(value = "/revocation-list", produces = MediaType.APPLICATION_JSON_VALUE) ResponseEntity downloadRevocationList( - @RequestHeader(HttpHeaders.IF_MODIFIED_SINCE) String lastUpdate); + @RequestHeader(HttpHeaders.IF_MODIFIED_SINCE) String lastUpdate); /** * Downloads a batch of the revocation list. diff --git a/src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientBuilder.java b/src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientBuilder.java deleted file mode 100644 index 487736d..0000000 --- a/src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientBuilder.java +++ /dev/null @@ -1,140 +0,0 @@ -/*- - * ---license-start - * EU Digital Green Certificate Gateway Service / dgc-lib - * --- - * Copyright (C) 2021 - 2022 T-Systems International GmbH and all other contributors - * --- - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ---license-end - */ - -package eu.europa.ec.dgc.gateway.connector.springbootworkaroundforks; - -import feign.Feign; -import org.springframework.cloud.openfeign.FeignBuilderCustomizer; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.cloud.openfeign.FeignClientBuilder; -import org.springframework.context.ApplicationContext; - -//CHECKSTYLE:OFF -/** - * Temporary Fork of Spring-Boot's {@link FeignClientBuilder}. - * Used until https://github.com/spring-cloud/spring-cloud-openfeign/pull/672 will be merged and released. - * Fore more information see: https://github.com/spring-cloud/spring-cloud-openfeign/issues/671 - * - *

A builder for creating Feign clients without using the {@link FeignClient} annotation. - * - *

This builder builds the Feign client exactly like it would be created by using the {@link FeignClient} annotation. - * - * @author Sven Döring - * @author Matt King - * @author Sam Kruglov - */ -public class DgcFeignClientBuilder { - - private final ApplicationContext applicationContext; - - public DgcFeignClientBuilder(final ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - public DgcFeignClientBuilder.Builder forType(final Class type, final String name) { - return new DgcFeignClientBuilder.Builder<>(this.applicationContext, type, name); - } - - public DgcFeignClientBuilder.Builder forType(final Class type, final DgcFeignClientFactoryBean clientFactoryBean, - final String name) { - return new DgcFeignClientBuilder.Builder<>(this.applicationContext, clientFactoryBean, type, name); - } - - /** - * Builder of feign targets. - * - * @param type of target - */ - public static final class Builder { - - private DgcFeignClientFactoryBean feignClientFactoryBean; - - private Builder(final ApplicationContext applicationContext, final Class type, final String name) { - this(applicationContext, new DgcFeignClientFactoryBean(), type, name); - } - - private Builder(final ApplicationContext applicationContext, final DgcFeignClientFactoryBean clientFactoryBean, - final Class type, final String name) { - this.feignClientFactoryBean = clientFactoryBean; - - this.feignClientFactoryBean.setApplicationContext(applicationContext); - this.feignClientFactoryBean.setType(type); - this.feignClientFactoryBean.setName(DgcFeignClientRegistrar.getName(name)); - this.feignClientFactoryBean.setContextId(DgcFeignClientRegistrar.getName(name)); - this.feignClientFactoryBean.setInheritParentContext(true); - // preset default values - these values resemble the default values on the - // FeignClient annotation - this.url("").path("").decode404(false); - } - - public DgcFeignClientBuilder.Builder url(final String url) { - this.feignClientFactoryBean.setUrl(DgcFeignClientRegistrar.getUrl(url)); - return this; - } - - /** - * Applies a {@link FeignBuilderCustomizer} to the underlying - * {@link Feign.Builder}. May be called multiple times. - * - * @param customizer applied in the same order as supplied here after applying - * customizers found in the context. - * @return the {@link DgcFeignClientBuilder.Builder} with the customizer added - */ - public DgcFeignClientBuilder.Builder customize(final FeignBuilderCustomizer customizer) { - this.feignClientFactoryBean.addCustomizer(customizer); - return this; - } - - public DgcFeignClientBuilder.Builder contextId(final String contextId) { - this.feignClientFactoryBean.setContextId(contextId); - return this; - } - - public DgcFeignClientBuilder.Builder path(final String path) { - this.feignClientFactoryBean.setPath(DgcFeignClientRegistrar.getPath(path)); - return this; - } - - public DgcFeignClientBuilder.Builder decode404(final boolean decode404) { - this.feignClientFactoryBean.setDecode404(decode404); - return this; - } - - public DgcFeignClientBuilder.Builder inheritParentContext(final boolean inheritParentContext) { - this.feignClientFactoryBean.setInheritParentContext(inheritParentContext); - return this; - } - - public DgcFeignClientBuilder.Builder fallback(final Class fallback) { - DgcFeignClientRegistrar.validateFallback(fallback); - this.feignClientFactoryBean.setFallback(fallback); - return this; - } - - /** - * @return the created Feign client - */ - public T build() { - return this.feignClientFactoryBean.getTarget(); - } - - } - -} diff --git a/src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientFactoryBean.java b/src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientFactoryBean.java deleted file mode 100644 index 378a480..0000000 --- a/src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientFactoryBean.java +++ /dev/null @@ -1,614 +0,0 @@ -/*- - * ---license-start - * EU Digital Green Certificate Gateway Service / dgc-lib - * --- - * Copyright (C) 2021 - 2022 T-Systems International GmbH and all other contributors - * --- - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ---license-end - */ - -package eu.europa.ec.dgc.gateway.connector.springbootworkaroundforks; - -import feign.Capability; -import feign.Client; -import feign.Contract; -import feign.ExceptionPropagationPolicy; -import feign.Feign; -import feign.Logger; -import feign.QueryMapEncoder; -import feign.Request; -import feign.RequestInterceptor; -import feign.Retryer; -import feign.Target; -import feign.codec.Decoder; -import feign.codec.Encoder; -import feign.codec.ErrorDecoder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.TimeUnit; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.cloud.openfeign.FeignBuilderCustomizer; -import org.springframework.cloud.openfeign.FeignClientFactoryBean; -import org.springframework.cloud.openfeign.FeignClientProperties; -import org.springframework.cloud.openfeign.FeignContext; -import org.springframework.cloud.openfeign.FeignErrorDecoderFactory; -import org.springframework.cloud.openfeign.FeignLoggerFactory; -import org.springframework.cloud.openfeign.Targeter; -import org.springframework.cloud.openfeign.clientconfig.FeignClientConfigurer; -import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient; -import org.springframework.cloud.openfeign.loadbalancer.RetryableFeignBlockingLoadBalancerClient; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.core.annotation.AnnotationAwareOrderComparator; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -//CHECKSTYLE:OFF -/** - * Temporary Fork of Spring-Boot's {@link FeignClientFactoryBean}. - * Used until https://github.com/spring-cloud/spring-cloud-openfeign/pull/672 will be merged and released. - * Fore more information see: https://github.com/spring-cloud/spring-cloud-openfeign/issues/671 - * - * @author Spencer Gibb - * @author Venil Noronha - * @author Eko Kurniawan Khannedy - * @author Gregor Zurowski - * @author Matt King - * @author Olga Maciaszek-Sharma - * @author Ilia Ilinykh - * @author Marcin Grzejszczak - * @author Jonatan Ivanov - * @author Sam Kruglov - * @author Jasbir Singh - * @author Hyeonmin Park - */ -public class DgcFeignClientFactoryBean - extends FeignClientFactoryBean - implements FactoryBean, InitializingBean, ApplicationContextAware, BeanFactoryAware { - - /*********************************** - * WARNING! Nothing in this class should be @Autowired. It causes NPEs because of some - * lifecycle race condition. - ***********************************/ - - private static final Log LOG = LogFactory.getLog(FeignClientFactoryBean.class); - - private Class type; - - private String name; - - private String url; - - private String contextId; - - private String path; - - private boolean decode404; - - private boolean inheritParentContext = true; - - private ApplicationContext applicationContext; - - private BeanFactory beanFactory; - - private Class fallback = void.class; - - private Class fallbackFactory = void.class; - - private int readTimeoutMillis = new Request.Options().readTimeoutMillis(); - - private int connectTimeoutMillis = new Request.Options().connectTimeoutMillis(); - - private boolean followRedirects = new Request.Options().isFollowRedirects(); - - private boolean refreshableClient = false; - - private final List additionalCustomizers = new ArrayList<>(); - - @Override - public void afterPropertiesSet() { - Assert.hasText(contextId, "Context id must be set"); - Assert.hasText(name, "Name must be set"); - } - - protected Feign.Builder feign(FeignContext context) { - FeignLoggerFactory loggerFactory = get(context, FeignLoggerFactory.class); - Logger logger = loggerFactory.create(type); - - // @formatter:off - Feign.Builder builder = get(context, Feign.Builder.class) - // required values - .logger(logger) - .encoder(get(context, Encoder.class)) - .decoder(get(context, Decoder.class)) - .contract(get(context, Contract.class)); - // @formatter:on - - configureFeign(context, builder); - - return builder; - } - - private void applyBuildCustomizers(FeignContext context, Feign.Builder builder) { - Map customizerMap = context.getInstances(contextId, - FeignBuilderCustomizer.class); - - if (customizerMap != null) { - customizerMap.values().stream().sorted(AnnotationAwareOrderComparator.INSTANCE) - .forEach(feignBuilderCustomizer -> feignBuilderCustomizer.customize(builder)); - } - additionalCustomizers.forEach(customizer -> customizer.customize(builder)); - } - - protected void configureFeign(FeignContext context, Feign.Builder builder) { - FeignClientProperties properties = beanFactory != null ? beanFactory.getBean(FeignClientProperties.class) - : applicationContext.getBean(FeignClientProperties.class); - - FeignClientConfigurer feignClientConfigurer = getOptional(context, FeignClientConfigurer.class); - setInheritParentContext(feignClientConfigurer.inheritParentConfiguration()); - - if (properties != null && inheritParentContext) { - if (properties.isDefaultToProperties()) { - configureUsingConfiguration(context, builder); - configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder); - configureUsingProperties(properties.getConfig().get(contextId), builder); - } else { - configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder); - configureUsingProperties(properties.getConfig().get(contextId), builder); - configureUsingConfiguration(context, builder); - } - } else { - configureUsingConfiguration(context, builder); - } - } - - protected void configureUsingConfiguration(FeignContext context, Feign.Builder builder) { - Logger.Level level = getInheritedAwareOptional(context, Logger.Level.class); - if (level != null) { - builder.logLevel(level); - } - Retryer retryer = getInheritedAwareOptional(context, Retryer.class); - if (retryer != null) { - builder.retryer(retryer); - } - ErrorDecoder errorDecoder = getInheritedAwareOptional(context, ErrorDecoder.class); - if (errorDecoder != null) { - builder.errorDecoder(errorDecoder); - } else { - FeignErrorDecoderFactory errorDecoderFactory = getOptional(context, FeignErrorDecoderFactory.class); - if (errorDecoderFactory != null) { - ErrorDecoder factoryErrorDecoder = errorDecoderFactory.create(type); - builder.errorDecoder(factoryErrorDecoder); - } - } - Request.Options options = getInheritedAwareOptional(context, Request.Options.class); - if (options == null) { - options = getOptionsByName(context, contextId); - } - - if (options != null) { - builder.options(options); - readTimeoutMillis = options.readTimeoutMillis(); - connectTimeoutMillis = options.connectTimeoutMillis(); - followRedirects = options.isFollowRedirects(); - } - Map requestInterceptors = getInheritedAwareInstances(context, - RequestInterceptor.class); - if (requestInterceptors != null) { - List interceptors = new ArrayList<>(requestInterceptors.values()); - AnnotationAwareOrderComparator.sort(interceptors); - builder.requestInterceptors(interceptors); - } - QueryMapEncoder queryMapEncoder = getInheritedAwareOptional(context, QueryMapEncoder.class); - if (queryMapEncoder != null) { - builder.queryMapEncoder(queryMapEncoder); - } - if (decode404) { - builder.decode404(); - } - ExceptionPropagationPolicy exceptionPropagationPolicy = getInheritedAwareOptional(context, - ExceptionPropagationPolicy.class); - if (exceptionPropagationPolicy != null) { - builder.exceptionPropagationPolicy(exceptionPropagationPolicy); - } - - Map capabilities = getInheritedAwareInstances(context, Capability.class); - if (capabilities != null) { - capabilities.values().stream().sorted(AnnotationAwareOrderComparator.INSTANCE) - .forEach(builder::addCapability); - } - } - - protected void configureUsingProperties(FeignClientProperties.FeignClientConfiguration config, - Feign.Builder builder) { - if (config == null) { - return; - } - - if (config.getLoggerLevel() != null) { - builder.logLevel(config.getLoggerLevel()); - } - - if (!refreshableClient) { - connectTimeoutMillis = config.getConnectTimeout() != null ? config.getConnectTimeout() - : connectTimeoutMillis; - readTimeoutMillis = config.getReadTimeout() != null ? config.getReadTimeout() : readTimeoutMillis; - followRedirects = config.isFollowRedirects() != null ? config.isFollowRedirects() : followRedirects; - - builder.options(new Request.Options(connectTimeoutMillis, TimeUnit.MILLISECONDS, readTimeoutMillis, - TimeUnit.MILLISECONDS, followRedirects)); - } - - if (config.getRetryer() != null) { - Retryer retryer = getOrInstantiate(config.getRetryer()); - builder.retryer(retryer); - } - - if (config.getErrorDecoder() != null) { - ErrorDecoder errorDecoder = getOrInstantiate(config.getErrorDecoder()); - builder.errorDecoder(errorDecoder); - } - - if (config.getRequestInterceptors() != null && !config.getRequestInterceptors().isEmpty()) { - // this will add request interceptor to builder, not replace existing - for (Class bean : config.getRequestInterceptors()) { - RequestInterceptor interceptor = getOrInstantiate(bean); - builder.requestInterceptor(interceptor); - } - } - - if (config.getDecode404() != null) { - if (config.getDecode404()) { - builder.decode404(); - } - } - - if (Objects.nonNull(config.getEncoder())) { - builder.encoder(getOrInstantiate(config.getEncoder())); - } - - addDefaultRequestHeaders(config, builder); - addDefaultQueryParams(config, builder); - - if (Objects.nonNull(config.getDecoder())) { - builder.decoder(getOrInstantiate(config.getDecoder())); - } - - if (Objects.nonNull(config.getContract())) { - builder.contract(getOrInstantiate(config.getContract())); - } - - if (Objects.nonNull(config.getExceptionPropagationPolicy())) { - builder.exceptionPropagationPolicy(config.getExceptionPropagationPolicy()); - } - - if (config.getCapabilities() != null) { - config.getCapabilities().stream().map(this::getOrInstantiate).forEach(builder::addCapability); - } - } - - private void addDefaultQueryParams(FeignClientProperties.FeignClientConfiguration config, Feign.Builder builder) { - Map> defaultQueryParameters = config.getDefaultQueryParameters(); - if (Objects.nonNull(defaultQueryParameters)) { - builder.requestInterceptor(requestTemplate -> { - Map> queries = requestTemplate.queries(); - defaultQueryParameters.keySet().forEach(key -> { - if (!queries.containsKey(key)) { - requestTemplate.query(key, defaultQueryParameters.get(key)); - } - }); - }); - } - } - - private void addDefaultRequestHeaders(FeignClientProperties.FeignClientConfiguration config, - Feign.Builder builder) { - Map> defaultRequestHeaders = config.getDefaultRequestHeaders(); - if (Objects.nonNull(defaultRequestHeaders)) { - builder.requestInterceptor(requestTemplate -> { - Map> headers = requestTemplate.headers(); - defaultRequestHeaders.keySet().forEach(key -> { - if (!headers.containsKey(key)) { - requestTemplate.header(key, defaultRequestHeaders.get(key)); - } - }); - }); - } - } - - private T getOrInstantiate(Class tClass) { - try { - return beanFactory != null ? beanFactory.getBean(tClass) : applicationContext.getBean(tClass); - } catch (NoSuchBeanDefinitionException e) { - return BeanUtils.instantiateClass(tClass); - } - } - - protected T get(FeignContext context, Class type) { - T instance = context.getInstance(contextId, type); - if (instance == null) { - throw new IllegalStateException("No bean found of type " + type + " for " + contextId); - } - return instance; - } - - protected T getOptional(FeignContext context, Class type) { - return context.getInstance(contextId, type); - } - - protected T getInheritedAwareOptional(FeignContext context, Class type) { - if (inheritParentContext) { - return getOptional(context, type); - } else { - return context.getInstanceWithoutAncestors(contextId, type); - } - } - - protected Map getInheritedAwareInstances(FeignContext context, Class type) { - if (inheritParentContext) { - return context.getInstances(contextId, type); - } else { - return context.getInstancesWithoutAncestors(contextId, type); - } - } - - protected T loadBalance(Feign.Builder builder, FeignContext context, Target.HardCodedTarget target) { - Client client = getOptional(context, Client.class); - if (client != null) { - builder.client(client); - Targeter targeter = get(context, Targeter.class); - return targeter.target(this, builder, context, target); - } - - throw new IllegalStateException( - "No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalancer?"); - } - - /** - * Meant to get Options bean from context with bean name. - * @param context context of Feign client - * @param contextId name of feign client - * @return returns Options found in context - */ - protected Request.Options getOptionsByName(FeignContext context, String contextId) { - if (refreshableClient) { - return context.getInstance(contextId, Request.Options.class.getCanonicalName() + "-" + contextId, - Request.Options.class); - } - return null; - } - - @Override - public Object getObject() { - return getTarget(); - } - - /** - * @param the target type of the Feign client - * @return a {@link Feign} client created with the specified data and the context - * information - */ - T getTarget() { - FeignContext context = beanFactory != null ? beanFactory.getBean(FeignContext.class) - : applicationContext.getBean(FeignContext.class); - Feign.Builder builder = feign(context); - - if (!StringUtils.hasText(url)) { - - if (LOG.isInfoEnabled()) { - LOG.info("For '" + name + "' URL not provided. Will try picking an instance via load-balancing."); - } - if (!name.startsWith("http")) { - url = "http://" + name; - } else { - url = name; - } - url += cleanPath(); - return (T) loadBalance(builder, context, new Target.HardCodedTarget<>(type, name, url)); - } - if (StringUtils.hasText(url) && !url.startsWith("http")) { - url = "http://" + url; - } - String url = this.url + cleanPath(); - Client client = getOptional(context, Client.class); - if (client != null) { - if (client instanceof FeignBlockingLoadBalancerClient) { - // not load balancing because we have a url, - // but Spring Cloud LoadBalancer is on the classpath, so unwrap - client = ((FeignBlockingLoadBalancerClient) client).getDelegate(); - } - if (client instanceof RetryableFeignBlockingLoadBalancerClient) { - // not load balancing because we have a url, - // but Spring Cloud LoadBalancer is on the classpath, so unwrap - client = ((RetryableFeignBlockingLoadBalancerClient) client).getDelegate(); - } - builder.client(client); - } - Targeter targeter = get(context, Targeter.class); - applyBuildCustomizers(context, builder); - return (T) targeter.target(this, builder, context, new Target.HardCodedTarget<>(type, name, url)); - } - - private String cleanPath() { - if (path == null) { - return ""; - } - String path = this.path.trim(); - if (StringUtils.hasLength(path)) { - if (!path.startsWith("/")) { - path = "/" + path; - } - if (path.endsWith("/")) { - path = path.substring(0, path.length() - 1); - } - } - return path; - } - - @Override - public Class getObjectType() { - return type; - } - - @Override - public boolean isSingleton() { - return true; - } - - public Class getType() { - return type; - } - - public void setType(Class type) { - this.type = type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getContextId() { - return contextId; - } - - public void setContextId(String contextId) { - this.contextId = contextId; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public boolean isDecode404() { - return decode404; - } - - public void setDecode404(boolean decode404) { - this.decode404 = decode404; - } - - public boolean isInheritParentContext() { - return inheritParentContext; - } - - public void setInheritParentContext(boolean inheritParentContext) { - this.inheritParentContext = inheritParentContext; - } - - public void addCustomizer(FeignBuilderCustomizer customizer) { - additionalCustomizers.add(customizer); - } - - public ApplicationContext getApplicationContext() { - return applicationContext; - } - - @Override - public void setApplicationContext(ApplicationContext context) throws BeansException { - applicationContext = context; - beanFactory = context; - } - - public Class getFallback() { - return fallback; - } - - public void setFallback(Class fallback) { - this.fallback = fallback; - } - - public Class getFallbackFactory() { - return fallbackFactory; - } - - public void setFallbackFactory(Class fallbackFactory) { - this.fallbackFactory = fallbackFactory; - } - - public void setRefreshableClient(boolean refreshableClient) { - this.refreshableClient = refreshableClient; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DgcFeignClientFactoryBean that = (DgcFeignClientFactoryBean) o; - return Objects.equals(applicationContext, that.applicationContext) - && Objects.equals(beanFactory, that.beanFactory) && decode404 == that.decode404 - && inheritParentContext == that.inheritParentContext && Objects.equals(fallback, that.fallback) - && Objects.equals(fallbackFactory, that.fallbackFactory) && Objects.equals(name, that.name) - && Objects.equals(path, that.path) && Objects.equals(type, that.type) && Objects.equals(url, that.url) - && Objects.equals(connectTimeoutMillis, that.connectTimeoutMillis) - && Objects.equals(readTimeoutMillis, that.readTimeoutMillis) - && Objects.equals(followRedirects, that.followRedirects) - && Objects.equals(refreshableClient, that.refreshableClient); - } - - @Override - public int hashCode() { - return Objects.hash(applicationContext, beanFactory, decode404, inheritParentContext, fallback, fallbackFactory, - name, path, type, url, readTimeoutMillis, connectTimeoutMillis, followRedirects, refreshableClient); - } - - @Override - public String toString() { - return new StringBuilder("FeignClientFactoryBean{").append("type=").append(type).append(", ").append("name='") - .append(name).append("', ").append("url='").append(url).append("', ").append("path='").append(path) - .append("', ").append("decode404=").append(decode404).append(", ").append("inheritParentContext=") - .append(inheritParentContext).append(", ").append("applicationContext=").append(applicationContext) - .append(", ").append("beanFactory=").append(beanFactory).append(", ").append("fallback=") - .append(fallback).append(", ").append("fallbackFactory=").append(fallbackFactory).append("}") - .append("connectTimeoutMillis=").append(connectTimeoutMillis).append("}").append("readTimeoutMillis=") - .append(readTimeoutMillis).append("}").append("followRedirects=").append(followRedirects) - .append("refreshableClient=").append(refreshableClient).append("}").toString(); - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory; - } - -} diff --git a/src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientRegistrar.java b/src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientRegistrar.java deleted file mode 100644 index 40d7aaf..0000000 --- a/src/main/java/eu/europa/ec/dgc/gateway/connector/springbootworkaroundforks/DgcFeignClientRegistrar.java +++ /dev/null @@ -1,453 +0,0 @@ -/*- - * ---license-start - * EU Digital Green Certificate Gateway Service / dgc-lib - * --- - * Copyright (C) 2021 - 2022 T-Systems International GmbH and all other contributors - * --- - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ---license-end - */ - -package eu.europa.ec.dgc.gateway.connector.springbootworkaroundforks; - -import feign.Request; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import lombok.NoArgsConstructor; -import org.springframework.aop.scope.ScopedProxyUtils; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; -import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.BeanDefinitionHolder; -import org.springframework.beans.factory.config.BeanExpressionContext; -import org.springframework.beans.factory.config.BeanExpressionResolver; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.cloud.openfeign.EnableFeignClients; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.cloud.openfeign.FeignClientFactoryBean; -import org.springframework.cloud.openfeign.FeignClientSpecification; -import org.springframework.cloud.openfeign.OptionsFactoryBean; -import org.springframework.context.EnvironmentAware; -import org.springframework.context.ResourceLoaderAware; -import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; -import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; -import org.springframework.core.annotation.AnnotationAttributes; -import org.springframework.core.env.Environment; -import org.springframework.core.io.ResourceLoader; -import org.springframework.core.type.AnnotationMetadata; -import org.springframework.core.type.filter.AnnotationTypeFilter; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; - -//CHECKSTYLE:OFF -/** - * Temporary Fork of Spring-Boot's org.springframework.cloud.openfeign.FeignClientsRegistrar. - * Used until https://github.com/spring-cloud/spring-cloud-openfeign/pull/672 will be merged and released. - * Fore more information see: https://github.com/spring-cloud/spring-cloud-openfeign/issues/671 - * - * @author Spencer Gibb - * @author Jakub Narloch - * @author Venil Noronha - * @author Gang Li - * @author Michal Domagala - * @author Marcin Grzejszczak - * @author Olga Maciaszek-Sharma - * @author Jasbir Singh - */ -@NoArgsConstructor -public class DgcFeignClientRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware { - - // patterned after Spring Integration IntegrationComponentScanRegistrar - // and RibbonClientsConfigurationRegistgrar - - private ResourceLoader resourceLoader; - - private Environment environment; - - static void validateFallback(final Class clazz) { - Assert.isTrue(!clazz.isInterface(), "Fallback class must implement the interface annotated by @FeignClient"); - } - - static void validateFallbackFactory(final Class clazz) { - Assert.isTrue(!clazz.isInterface(), "Fallback factory must produce instances " - + "of fallback classes that implement the interface annotated by @FeignClient"); - } - - static String getName(String name) { - if (!StringUtils.hasText(name)) { - return ""; - } - - String host = null; - try { - String url; - if (!name.startsWith("http://") && !name.startsWith("https://")) { - url = "http://" + name; - } else { - url = name; - } - host = new URI(url).getHost(); - - } catch (URISyntaxException e) { - } - Assert.state(host != null, "Service id not legal hostname (" + name + ")"); - return name; - } - - static String getUrl(String url) { - if (StringUtils.hasText(url) && !(url.startsWith("#{") && url.contains("}"))) { - if (!url.contains("://")) { - url = "http://" + url; - } - try { - new URL(url); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(url + " is malformed", e); - } - } - return url; - } - - static String getPath(String path) { - if (StringUtils.hasText(path)) { - path = path.trim(); - if (!path.startsWith("/")) { - path = "/" + path; - } - if (path.endsWith("/")) { - path = path.substring(0, path.length() - 1); - } - } - return path; - } - - @Override - public void setResourceLoader(ResourceLoader resourceLoader) { - this.resourceLoader = resourceLoader; - } - - @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { - registerDefaultConfiguration(metadata, registry); - registerFeignClients(metadata, registry); - } - - private void registerDefaultConfiguration(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { - Map defaultAttrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName(), true); - - if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) { - String name; - if (metadata.hasEnclosingClass()) { - name = "default." + metadata.getEnclosingClassName(); - } else { - name = "default." + metadata.getClassName(); - } - registerClientConfiguration(registry, name, defaultAttrs.get("defaultConfiguration")); - } - } - - public void registerFeignClients(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { - - LinkedHashSet candidateComponents = new LinkedHashSet<>(); - Map attrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName()); - final Class[] clients = attrs == null ? null : (Class[]) attrs.get("clients"); - if (clients == null || clients.length == 0) { - ClassPathScanningCandidateComponentProvider scanner = getScanner(); - scanner.setResourceLoader(this.resourceLoader); - scanner.addIncludeFilter(new AnnotationTypeFilter(FeignClient.class)); - Set basePackages = getBasePackages(metadata); - for (String basePackage : basePackages) { - candidateComponents.addAll(scanner.findCandidateComponents(basePackage)); - } - } else { - for (Class clazz : clients) { - candidateComponents.add(new AnnotatedGenericBeanDefinition(clazz)); - } - } - - for (BeanDefinition candidateComponent : candidateComponents) { - if (candidateComponent instanceof AnnotatedBeanDefinition) { - // verify annotated class is an interface - AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent; - AnnotationMetadata annotationMetadata = beanDefinition.getMetadata(); - Assert.isTrue(annotationMetadata.isInterface(), "@FeignClient can only be specified on an interface"); - - Map attributes = annotationMetadata - .getAnnotationAttributes(FeignClient.class.getCanonicalName()); - - String name = getClientName(attributes); - registerClientConfiguration(registry, name, attributes.get("configuration")); - - registerFeignClient(registry, annotationMetadata, attributes); - } - } - } - - private void registerFeignClient(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata, - Map attributes) { - String className = annotationMetadata.getClassName(); - Class clazz = ClassUtils.resolveClassName(className, null); - ConfigurableBeanFactory beanFactory = registry instanceof ConfigurableBeanFactory - ? (ConfigurableBeanFactory) registry : null; - String contextId = getContextId(beanFactory, attributes); - String name = getName(attributes); - FeignClientFactoryBean factoryBean = new FeignClientFactoryBean(); - factoryBean.setBeanFactory(beanFactory); - factoryBean.setName(name); - factoryBean.setContextId(contextId); - factoryBean.setType(clazz); - factoryBean.setRefreshableClient(isClientRefreshEnabled()); - BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(clazz, () -> { - factoryBean.setUrl(getUrl(beanFactory, attributes)); - factoryBean.setPath(getPath(beanFactory, attributes)); - factoryBean.setDecode404(Boolean.parseBoolean(String.valueOf(attributes.get("decode404")))); - Object fallback = attributes.get("fallback"); - if (fallback != null) { - factoryBean.setFallback(fallback instanceof Class ? (Class) fallback - : ClassUtils.resolveClassName(fallback.toString(), null)); - } - Object fallbackFactory = attributes.get("fallbackFactory"); - if (fallbackFactory != null) { - factoryBean.setFallbackFactory(fallbackFactory instanceof Class ? (Class) fallbackFactory - : ClassUtils.resolveClassName(fallbackFactory.toString(), null)); - } - return factoryBean.getObject(); - }); - definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); - definition.setLazyInit(true); - validate(attributes); - - AbstractBeanDefinition beanDefinition = definition.getBeanDefinition(); - beanDefinition.setAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE, className); - beanDefinition.setAttribute("feignClientsRegistrarFactoryBean", factoryBean); - - // has a default, won't be null - boolean primary = (Boolean) attributes.get("primary"); - - beanDefinition.setPrimary(primary); - - String[] qualifiers = getQualifiers(attributes); - if (ObjectUtils.isEmpty(qualifiers)) { - qualifiers = new String[]{contextId + "FeignClient"}; - } - - BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, qualifiers); - BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry); - - registerOptionsBeanDefinition(registry, contextId); - } - - private void validate(Map attributes) { - AnnotationAttributes annotation = AnnotationAttributes.fromMap(attributes); - // This blows up if an aliased property is overspecified - // FIXME annotation.getAliasedString("name", FeignClient.class, null); - validateFallback(annotation.getClass("fallback")); - validateFallbackFactory(annotation.getClass("fallbackFactory")); - } - - /* for testing */ String getName(Map attributes) { - return getName(null, attributes); - } - - String getName(ConfigurableBeanFactory beanFactory, Map attributes) { - String name = (String) attributes.get("serviceId"); - if (!StringUtils.hasText(name)) { - name = (String) attributes.get("name"); - } - if (!StringUtils.hasText(name)) { - name = (String) attributes.get("value"); - } - name = resolve(beanFactory, name); - return getName(name); - } - - private String getContextId(ConfigurableBeanFactory beanFactory, Map attributes) { - String contextId = (String) attributes.get("contextId"); - if (!StringUtils.hasText(contextId)) { - return getName(attributes); - } - - contextId = resolve(beanFactory, contextId); - return getName(contextId); - } - - private String resolve(ConfigurableBeanFactory beanFactory, String value) { - if (StringUtils.hasText(value)) { - if (beanFactory == null) { - return this.environment.resolvePlaceholders(value); - } - BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver(); - String resolved = beanFactory.resolveEmbeddedValue(value); - if (resolver == null) { - return resolved; - } - Object evaluateValue = resolver.evaluate(resolved, new BeanExpressionContext(beanFactory, null)); - if (evaluateValue != null) { - return String.valueOf(evaluateValue); - } - return null; - } - return value; - } - - private String getUrl(ConfigurableBeanFactory beanFactory, Map attributes) { - String url = resolve(beanFactory, (String) attributes.get("url")); - return getUrl(url); - } - - private String getPath(ConfigurableBeanFactory beanFactory, Map attributes) { - String path = resolve(beanFactory, (String) attributes.get("path")); - return getPath(path); - } - - protected ClassPathScanningCandidateComponentProvider getScanner() { - return new ClassPathScanningCandidateComponentProvider(false, this.environment) { - @Override - protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { - boolean isCandidate = false; - if (beanDefinition.getMetadata().isIndependent()) { - if (!beanDefinition.getMetadata().isAnnotation()) { - isCandidate = true; - } - } - return isCandidate; - } - }; - } - - protected Set getBasePackages(AnnotationMetadata importingClassMetadata) { - Map attributes = importingClassMetadata - .getAnnotationAttributes(EnableFeignClients.class.getCanonicalName()); - - Set basePackages = new HashSet<>(); - for (String pkg : (String[]) attributes.get("value")) { - if (StringUtils.hasText(pkg)) { - basePackages.add(pkg); - } - } - for (String pkg : (String[]) attributes.get("basePackages")) { - if (StringUtils.hasText(pkg)) { - basePackages.add(pkg); - } - } - for (Class clazz : (Class[]) attributes.get("basePackageClasses")) { - basePackages.add(ClassUtils.getPackageName(clazz)); - } - - if (basePackages.isEmpty()) { - basePackages.add(ClassUtils.getPackageName(importingClassMetadata.getClassName())); - } - return basePackages; - } - - private String getQualifier(Map client) { - if (client == null) { - return null; - } - String qualifier = (String) client.get("qualifier"); - if (StringUtils.hasText(qualifier)) { - return qualifier; - } - return null; - } - - private String[] getQualifiers(Map client) { - if (client == null) { - return null; - } - List qualifierList = new ArrayList<>(Arrays.asList((String[]) client.get("qualifiers"))); - qualifierList.removeIf(qualifier -> !StringUtils.hasText(qualifier)); - if (qualifierList.isEmpty() && getQualifier(client) != null) { - qualifierList = Collections.singletonList(getQualifier(client)); - } - return !qualifierList.isEmpty() ? qualifierList.toArray(new String[0]) : null; - } - - private String getClientName(Map client) { - if (client == null) { - return null; - } - String value = (String) client.get("contextId"); - if (!StringUtils.hasText(value)) { - value = (String) client.get("value"); - } - if (!StringUtils.hasText(value)) { - value = (String) client.get("name"); - } - if (!StringUtils.hasText(value)) { - value = (String) client.get("serviceId"); - } - if (StringUtils.hasText(value)) { - return value; - } - - throw new IllegalStateException( - "Either 'name' or 'value' must be provided in @" + FeignClient.class.getSimpleName()); - } - - private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name, Object configuration) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(FeignClientSpecification.class); - builder.addConstructorArgValue(name); - builder.addConstructorArgValue(configuration); - registry.registerBeanDefinition(name + "." + FeignClientSpecification.class.getSimpleName(), - builder.getBeanDefinition()); - } - - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - } - - /** - * This method is meant to create {@link Request.Options} beans definition with - * refreshScope. - * - * @param registry spring bean definition registry - * @param contextId name of feign client - */ - private void registerOptionsBeanDefinition(BeanDefinitionRegistry registry, String contextId) { - if (isClientRefreshEnabled()) { - String beanName = Request.Options.class.getCanonicalName() + "-" + contextId; - BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder - .genericBeanDefinition(OptionsFactoryBean.class); - definitionBuilder.setScope("refresh"); - definitionBuilder.addPropertyValue("contextId", contextId); - BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(definitionBuilder.getBeanDefinition(), - beanName); - definitionHolder = ScopedProxyUtils.createScopedProxy(definitionHolder, registry, true); - BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry); - } - } - - private boolean isClientRefreshEnabled() { - return environment.getProperty("feign.client.refresh-enabled", Boolean.class, false); - } - -} diff --git a/src/main/java/eu/europa/ec/dgc/generation/DccRecoveryBuilder.java b/src/main/java/eu/europa/ec/dgc/generation/DccRecoveryBuilder.java index 10b6606..ff67fc9 100644 --- a/src/main/java/eu/europa/ec/dgc/generation/DccRecoveryBuilder.java +++ b/src/main/java/eu/europa/ec/dgc/generation/DccRecoveryBuilder.java @@ -67,6 +67,7 @@ protected void validate() { /** * first Day Positive Test. + * * @param fr first Day Positive Test. * @return builder */ @@ -78,6 +79,7 @@ public DccRecoveryBuilder firstDayPositiveTest(LocalDate fr) { /** * certificate valid from. + * * @param df valid from. * @return builder */ @@ -89,6 +91,7 @@ public DccRecoveryBuilder certificateValidFrom(LocalDate df) { /** * certificate valid until. + * * @param du valid until. * @return builder */ diff --git a/src/main/java/eu/europa/ec/dgc/generation/DccTestBuilder.java b/src/main/java/eu/europa/ec/dgc/generation/DccTestBuilder.java index 0e6da7f..c857c2e 100644 --- a/src/main/java/eu/europa/ec/dgc/generation/DccTestBuilder.java +++ b/src/main/java/eu/europa/ec/dgc/generation/DccTestBuilder.java @@ -62,6 +62,7 @@ public ObjectNode getValueHolder() { /** * test result. + * * @param covidDetected covid detected * @return builder */ @@ -74,6 +75,7 @@ public DccTestBuilder detected(boolean covidDetected) { /** * test type. + * * @param isRapidTest true if rapid * @return builder */ @@ -84,27 +86,28 @@ public DccTestBuilder testTypeRapid(boolean isRapidTest) { } - /** * testing centre. + * * @param tc testing centre * @return builder */ public DccTestBuilder testingCentre(String tc) { testObject.set("tc", jsonNodeFactory.textNode(tc)); - assertNotNullMax("tc",tc,80); + assertNotNullMax("tc", tc, 80); requiredNotSet.remove(RequiredFields.tc); return this; } /** * NAA Test Name. + * * @param nm "NAA Test Name" * @return builder */ public DccTestBuilder testName(String nm) { testObject.set("nm", jsonNodeFactory.textNode(nm)); - assertNotNullMax("nm",nm,80); + assertNotNullMax("nm", nm, 80); return this; } @@ -113,18 +116,20 @@ public DccTestBuilder testName(String nm) { * Is required if test type is rapid. * There is value list for it but is not checked during setting * see https://github.com/ehn-dcc-development/ehn-dcc-schema/blob/main/valuesets/test-manf.json + * * @param ma test identifier * @return builder */ public DccTestBuilder testIdentifier(String ma) { testObject.set("ma", jsonNodeFactory.textNode(ma)); - assertNotNullMax("ma",ma,0); + assertNotNullMax("ma", ma, 0); return this; } /** * date time of sample collection. + * * @param dateTime sc * @return builder */ @@ -135,7 +140,6 @@ public DccTestBuilder sampleCollection(LocalDateTime dateTime) { } - protected void validate() { super.validate(); if (!requiredNotSet.isEmpty()) { diff --git a/src/main/java/eu/europa/ec/dgc/generation/DccVaccinationBuilder.java b/src/main/java/eu/europa/ec/dgc/generation/DccVaccinationBuilder.java index 91903e0..7a6eb9f 100644 --- a/src/main/java/eu/europa/ec/dgc/generation/DccVaccinationBuilder.java +++ b/src/main/java/eu/europa/ec/dgc/generation/DccVaccinationBuilder.java @@ -67,6 +67,7 @@ protected void validate() { /** * vaccine Or Prophylaxis. + * * @param vp vaccineOrProphylaxis * @return builder */ @@ -79,6 +80,7 @@ public DccVaccinationBuilder vaccineOrProphylaxis(String vp) { /** * medical product. + * * @param mp medical product * @return builder */ @@ -91,6 +93,7 @@ public DccVaccinationBuilder medicalProduct(String mp) { /** * marketing Authorization. + * * @param ma marketingAuthorization * @return builder */ @@ -103,6 +106,7 @@ public DccVaccinationBuilder marketingAuthorization(String ma) { /** * dose number. + * * @param dn dose number * @return builder */ @@ -117,6 +121,7 @@ public DccVaccinationBuilder doseNumber(int dn) { /** * total series of doses. + * * @param sd total series of doses * @return builder */ @@ -131,6 +136,7 @@ public DccVaccinationBuilder totalSeriesOfDoses(int sd) { /** * date time of vaccination. + * * @param dateTime sc * @return builder */ diff --git a/src/main/java/eu/europa/ec/dgc/generation/DgcCryptedFinalizer.java b/src/main/java/eu/europa/ec/dgc/generation/DgcCryptedFinalizer.java index 25c7baa..dfdc004 100644 --- a/src/main/java/eu/europa/ec/dgc/generation/DgcCryptedFinalizer.java +++ b/src/main/java/eu/europa/ec/dgc/generation/DgcCryptedFinalizer.java @@ -59,10 +59,11 @@ public String finalizeDcc(byte[] encodedDccData, byte[] dek, PrivateKey privateK /** * finalize dcc. + * * @param encodedDccData dcc data - * @param dek encoded key - * @param privateKey private key - * @param partialDcc cose with signature and key + * @param dek encoded key + * @param privateKey private key + * @param partialDcc cose with signature and key * @return qr code of final dcc */ public String finalizePartialDcc(byte[] encodedDccData, byte[] dek, PrivateKey privateKey, byte[] partialDcc) { diff --git a/src/main/java/eu/europa/ec/dgc/generation/DgcCryptedPublisher.java b/src/main/java/eu/europa/ec/dgc/generation/DgcCryptedPublisher.java index 0652443..69468d5 100644 --- a/src/main/java/eu/europa/ec/dgc/generation/DgcCryptedPublisher.java +++ b/src/main/java/eu/europa/ec/dgc/generation/DgcCryptedPublisher.java @@ -44,7 +44,7 @@ public class DgcCryptedPublisher { public static final String KEY_CIPHER = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"; public static final String DATA_CIPHER = "AES/CBC/PKCS5Padding"; public static final OAEPParameterSpec OAEP_PARAMETER_SPEC = new OAEPParameterSpec( - "SHA-256","MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT + "SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT ); private final DgcGenerator dgcGenerator = new DgcGenerator(); @@ -71,8 +71,8 @@ public DgcData createDgc(DgcInitData dgcInitData, String dgcPayloadJson, PublicK try { encryptData(dgcData, dgcInitData.isEncryptCose() ? edgcCoseUnsigned : edgcCbor, publicKey); } catch (NoSuchAlgorithmException | NoSuchPaddingException - | InvalidKeyException | InvalidAlgorithmParameterException - | IllegalBlockSizeException | BadPaddingException e) { + | InvalidKeyException | InvalidAlgorithmParameterException + | IllegalBlockSizeException | BadPaddingException e) { throw new IllegalArgumentException(e); } diff --git a/src/main/java/eu/europa/ec/dgc/generation/DgcGenerator.java b/src/main/java/eu/europa/ec/dgc/generation/DgcGenerator.java index c5bd245..3c6764b 100644 --- a/src/main/java/eu/europa/ec/dgc/generation/DgcGenerator.java +++ b/src/main/java/eu/europa/ec/dgc/generation/DgcGenerator.java @@ -112,7 +112,7 @@ public byte[] dgcSetCoseSignature(byte[] coseData, byte[] signature) { /** * Set signature and unprotected header from partialDcc into unsigned cose dcc. * - * @param cwtData cwt paylaod data (cbor) + * @param cwtData cwt paylaod data (cbor) * @param partialDcc cose with signature and unprotected header * @return signed cose dcc */ @@ -121,7 +121,7 @@ public byte[] dgcSetCosePartial(byte[] cwtData, byte[] partialDcc) { if (partialCose.getType() != CBORType.Array || partialCose.getValues().size() < 3) { throw new IllegalArgumentException("partial dcc is not cbor array"); } - partialCose.set(2,CBORObject.FromObject(cwtData)); + partialCose.set(2, CBORObject.FromObject(cwtData)); return partialCose.EncodeToBytes(); } diff --git a/src/main/java/eu/europa/ec/dgc/generation/DgcSigner.java b/src/main/java/eu/europa/ec/dgc/generation/DgcSigner.java index 7756d86..b7c056d 100644 --- a/src/main/java/eu/europa/ec/dgc/generation/DgcSigner.java +++ b/src/main/java/eu/europa/ec/dgc/generation/DgcSigner.java @@ -73,9 +73,10 @@ public byte[] signHash(byte[] hashBytes, PrivateKey privateKey) { /** * sign hash and build partial cose dcc containing key in unprotected header and signature. * This variant can be user together with @link {@link DgcGenerator#dgcSetCosePartial}. - * @param hashBytes hash to sign + * + * @param hashBytes hash to sign * @param privateKey private key - * @param keyId keyId bytes + * @param keyId keyId bytes * @return cose container but only with signature and unprotected header with keyId */ public byte[] signPartialDcc(byte[] hashBytes, PrivateKey privateKey, byte[] keyId) { @@ -92,7 +93,7 @@ public byte[] signPartialDcc(byte[] hashBytes, PrivateKey privateKey, byte[] key CBORObject coseObject = CBORObject.NewArray(); coseObject.Add(protectedHeaderBytes); CBORObject unprotectedHeader = CBORObject.NewMap(); - unprotectedHeader.Add(CBORObject.FromObject(4),CBORObject.FromObject(keyId)); + unprotectedHeader.Add(CBORObject.FromObject(4), CBORObject.FromObject(keyId)); coseObject.Add(unprotectedHeader); byte[] contentDummy = new byte[0]; coseObject.Add(CBORObject.FromObject(contentDummy)); diff --git a/src/main/java/eu/europa/ec/dgc/signing/SignedCertificateMessageParser.java b/src/main/java/eu/europa/ec/dgc/signing/SignedCertificateMessageParser.java index 18e4525..de293fe 100644 --- a/src/main/java/eu/europa/ec/dgc/signing/SignedCertificateMessageParser.java +++ b/src/main/java/eu/europa/ec/dgc/signing/SignedCertificateMessageParser.java @@ -38,8 +38,8 @@ X509CertificateHolder convertFromBytes(byte[] bytes) throws Exception { /** * The extracted payload certificate. * - * @deprecated use .getPayload() instead. * @return certificate. + * @deprecated use .getPayload() instead. */ @Deprecated public X509CertificateHolder getPayloadCertificate() { diff --git a/src/main/java/eu/europa/ec/dgc/signing/SignedMessageParser.java b/src/main/java/eu/europa/ec/dgc/signing/SignedMessageParser.java index beb33d0..f78e19f 100644 --- a/src/main/java/eu/europa/ec/dgc/signing/SignedMessageParser.java +++ b/src/main/java/eu/europa/ec/dgc/signing/SignedMessageParser.java @@ -84,6 +84,7 @@ public abstract class SignedMessageParser { *

Base64 encoded signature of the cms message.

* *

This string contains only the signature which signs the message.

+ * * @deprecated Use getDetachedSignature() or getEmbeddedSignature() instead. */ @Getter diff --git a/src/test/java/eu/europa/ec/dgc/DgcLibAutoConfigurationTest.java b/src/test/java/eu/europa/ec/dgc/DgcLibAutoConfigurationTest.java index d4591f9..1e35d3a 100644 --- a/src/test/java/eu/europa/ec/dgc/DgcLibAutoConfigurationTest.java +++ b/src/test/java/eu/europa/ec/dgc/DgcLibAutoConfigurationTest.java @@ -25,8 +25,8 @@ class DgcLibAutoConfigurationTest { - @Test - void testDefineConstructor() { - assertNotNull(new DgcLibAutoConfiguration()); - } + @Test + void testDefineConstructor() { + assertNotNull(new DgcLibAutoConfiguration()); + } } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/connector/RevocationListDownloadConnectorTest.java b/src/test/java/eu/europa/ec/dgc/gateway/connector/RevocationListDownloadConnectorTest.java index b2b9487..cdfe355 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/connector/RevocationListDownloadConnectorTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/connector/RevocationListDownloadConnectorTest.java @@ -40,19 +40,18 @@ import java.util.List; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; +import static org.mockito.Mockito.when; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.when; - @SpringBootTest @Slf4j class RevocationListDownloadConnectorTest { @@ -73,7 +72,6 @@ class RevocationListDownloadConnectorTest { ObjectMapper objectMapper; - @Test void getRevocationListDownloadIterator() { RevocationBatchListDto.RevocationBatchListItemDto batchItem1 = @@ -138,7 +136,7 @@ void getRevocationListDownloadIterator() { assertNotNull(downloadedData); assertFalse(downloadedData.isEmpty()); - Assertions.assertEquals(2 , downloadedData.size()); + Assertions.assertEquals(2, downloadedData.size()); assertEquals(batchItem1, downloadedData.get(0)); assertEquals(batchItem2, downloadedData.get(1)); @@ -147,7 +145,7 @@ void getRevocationListDownloadIterator() { assertNotNull(downloadedData); assertFalse(downloadedData.isEmpty()); - Assertions.assertEquals(2 , downloadedData.size()); + Assertions.assertEquals(2, downloadedData.size()); assertEquals(batchItem3, downloadedData.get(0)); assertEquals(batchItem4, downloadedData.get(1)); @@ -219,7 +217,7 @@ void GetRevocationListDownloadIteratorWithStartDate() { assertNotNull(downloadedData); assertFalse(downloadedData.isEmpty()); - Assertions.assertEquals(2 , downloadedData.size()); + Assertions.assertEquals(2, downloadedData.size()); assertEquals(batchItem3, downloadedData.get(0)); assertEquals(batchItem4, downloadedData.get(1)); @@ -325,7 +323,7 @@ private void assertEquals(RevocationBatchDto b1, RevocationBatchDto b2) { Assertions.assertEquals(b1.getHashType(), b2.getHashType()); Assertions.assertEquals(b1.getKid(), b2.getKid()); Assertions.assertEquals(b1.getEntries().size(), b2.getEntries().size()); - for (int i = 0; i < b1.getEntries().size(); i++){ + for (int i = 0; i < b1.getEntries().size(); i++) { Assertions.assertEquals(b1.getEntries().get(i).getHash(), b2.getEntries().get(i).getHash()); } } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/connector/RevocationListUploadConnectorTest.java b/src/test/java/eu/europa/ec/dgc/gateway/connector/RevocationListUploadConnectorTest.java index 0d2605e..0126075 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/connector/RevocationListUploadConnectorTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/connector/RevocationListUploadConnectorTest.java @@ -20,11 +20,6 @@ package eu.europa.ec.dgc.gateway.connector; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.util.StdDateFormat; @@ -51,6 +46,10 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; @@ -80,7 +79,7 @@ void testUploadOfRevocationList() throws Exception { ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); when(restClientMock.uploadBatch(argumentCaptor.capture())) - .thenReturn(ResponseEntity.status(HttpStatus.CREATED).build()); + .thenReturn(ResponseEntity.status(HttpStatus.CREATED).build()); connector.uploadRevocationBatch(getRevocation()); @@ -89,7 +88,7 @@ void testUploadOfRevocationList() throws Exception { SignedStringMessageParser parser = new SignedStringMessageParser(argumentCaptor.getValue()); Assertions.assertEquals(getRevocationJSON(), parser.getPayload()); Assertions.assertEquals(certificateUtils.convertCertificate(testKeyStore.getUpload()), - parser.getSigningCertificate()); + parser.getSigningCertificate()); } @Test @@ -99,7 +98,7 @@ void testDeleteCertificates() throws Exception { ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); when(restClientMock.deleteBatch(argumentCaptor.capture())) - .thenReturn(ResponseEntity.status(HttpStatus.NO_CONTENT).build()); + .thenReturn(ResponseEntity.status(HttpStatus.NO_CONTENT).build()); connector.deleteRevocationBatch(dummyRevocationListId); @@ -109,7 +108,7 @@ void testDeleteCertificates() throws Exception { Assertions.assertEquals(getDeleteJSON(dummyRevocationListId), parser.getPayload()); Assertions.assertEquals(certificateUtils.convertCertificate(testKeyStore.getUpload()), - parser.getSigningCertificate()); + parser.getSigningCertificate()); } @Test @@ -136,23 +135,23 @@ void shouldThrowAnExceptionWhenUploadRequestFailed() { String dummyRevocationList = "dummyRevocationList"; String problemReport = "{" + - "\"code\": \"0x500\"," + - "\"problem\": \"problem\"," + - "\"sendValue\": \"val\"," + - "\"details\": \"details\"" + - "}"; + "\"code\": \"0x500\"," + + "\"problem\": \"problem\"," + + "\"sendValue\": \"val\"," + + "\"details\": \"details\"" + + "}"; doThrow(new FeignException.BadRequest("", dummyRequest(), problemReport.getBytes(StandardCharsets.UTF_8), null)) - .when(restClientMock).uploadBatch(any()); + .when(restClientMock).uploadBatch(any()); DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException e = - Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, - () -> connector.uploadRevocationBatch(getRevocation())); + Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, + () -> connector.uploadRevocationBatch(getRevocation())); Assertions.assertEquals( - DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_BATCH, - e.getReason()); + DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_BATCH, + e.getReason()); } @Test @@ -160,23 +159,23 @@ void shouldThrowAnExceptionWhenUploadRequestFailedWithBadJson() { String dummyRevocationList = "dummyRevocationList"; String problemReport = "{" + - "code: \"0x500\"," + - "problem: \"problem\"," + - "sendValue: \"val\"," + - "details: \"details\"" + - "}"; + "code: \"0x500\"," + + "problem: \"problem\"," + + "sendValue: \"val\"," + + "details: \"details\"" + + "}"; doThrow(new FeignException.BadRequest("", dummyRequest(), problemReport.getBytes(StandardCharsets.UTF_8), null)) - .when(restClientMock).uploadBatch(any()); + .when(restClientMock).uploadBatch(any()); DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException e = - Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, - () -> connector.uploadRevocationBatch(getRevocation())); + Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, + () -> connector.uploadRevocationBatch(getRevocation())); Assertions.assertEquals( - DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.UNKNOWN_ERROR, - e.getReason()); + DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.UNKNOWN_ERROR, + e.getReason()); } @Test @@ -184,13 +183,13 @@ void shouldThrowAnExceptionWhenUploadRequestGetsInternalServerError() { String dummyRevocationList = "dummyRevocationList"; doThrow(new FeignException.InternalServerError("", dummyRequest(), null, null)) - .when(restClientMock).uploadBatch(any()); + .when(restClientMock).uploadBatch(any()); DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException e = - Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, - () -> connector.uploadRevocationBatch(getRevocation())); + Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, + () -> connector.uploadRevocationBatch(getRevocation())); Assertions.assertEquals( - DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.SERVER_ERROR, e.getReason()); + DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.SERVER_ERROR, e.getReason()); } @Test @@ -198,14 +197,14 @@ void shouldThrowAnExceptionWhenUploadRequestGetsUnauthorizedError() { String dummyRevocationList = "dummyRevocationList"; doThrow(new FeignException.Unauthorized("", dummyRequest(), null, null)) - .when(restClientMock).uploadBatch(any()); + .when(restClientMock).uploadBatch(any()); DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException e = - Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, - () -> connector.uploadRevocationBatch(getRevocation())); + Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, + () -> connector.uploadRevocationBatch(getRevocation())); Assertions.assertEquals( - DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION, - e.getReason()); + DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION, + e.getReason()); } @Test @@ -213,14 +212,14 @@ void shouldThrowAnExceptionWhenUploadRequestGetsForbiddenError() { String dummyRevocationList = "dummyRevocationList"; doThrow(new FeignException.Forbidden("", dummyRequest(), null, null)) - .when(restClientMock).uploadBatch(any()); + .when(restClientMock).uploadBatch(any()); DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException e = - Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, - () -> connector.uploadRevocationBatch(getRevocation())); + Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, + () -> connector.uploadRevocationBatch(getRevocation())); Assertions.assertEquals( - DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION, - e.getReason()); + DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION, + e.getReason()); } @Test @@ -228,23 +227,23 @@ void shouldThrowAnExceptionWhenDeleteRequestFailed() { String dummyRevocationList = "dummyRevocationList"; String problemReport = "{" + - "\"code\": \"0x500\"," + - "\"problem\": \"problem\"," + - "\"sendValue\": \"val\"," + - "\"details\": \"details\"" + - "}"; + "\"code\": \"0x500\"," + + "\"problem\": \"problem\"," + + "\"sendValue\": \"val\"," + + "\"details\": \"details\"" + + "}"; doThrow(new FeignException.BadRequest("", dummyRequest(), problemReport.getBytes(StandardCharsets.UTF_8), null)) - .when(restClientMock).deleteBatch(any()); + .when(restClientMock).deleteBatch(any()); DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException e = - Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, - () -> connector.deleteRevocationBatch(dummyRevocationList)); + Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, + () -> connector.deleteRevocationBatch(dummyRevocationList)); Assertions.assertEquals( - DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_BATCH, - e.getReason()); + DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_BATCH, + e.getReason()); } @Test @@ -252,23 +251,23 @@ void shouldThrowAnExceptionWhenDeleteRequestFailedWithBadJson() { String dummyRevocationList = "dummyRevocationList"; String problemReport = "{" + - "code: \"0x500\"," + - "problem: \"problem\"," + - "sendValue: \"val\"," + - "details: \"details\"" + - "}"; + "code: \"0x500\"," + + "problem: \"problem\"," + + "sendValue: \"val\"," + + "details: \"details\"" + + "}"; doThrow(new FeignException.BadRequest("", dummyRequest(), problemReport.getBytes(StandardCharsets.UTF_8), null)) - .when(restClientMock).deleteBatch(any()); + .when(restClientMock).deleteBatch(any()); DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException e = - Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, - () -> connector.deleteRevocationBatch(dummyRevocationList)); + Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, + () -> connector.deleteRevocationBatch(dummyRevocationList)); Assertions.assertEquals( - DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.UNKNOWN_ERROR, - e.getReason()); + DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.UNKNOWN_ERROR, + e.getReason()); } @Test @@ -276,13 +275,13 @@ void shouldThrowAnExceptionWhenDeleteRequestGetsInternalServerError() { String dummyRevocationList = "dummyRevocationList"; doThrow(new FeignException.InternalServerError("", dummyRequest(), null, null)) - .when(restClientMock).deleteBatch(any()); + .when(restClientMock).deleteBatch(any()); DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException e = - Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, - () -> connector.deleteRevocationBatch(dummyRevocationList)); + Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, + () -> connector.deleteRevocationBatch(dummyRevocationList)); Assertions.assertEquals( - DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.SERVER_ERROR, e.getReason()); + DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.SERVER_ERROR, e.getReason()); } @Test @@ -290,14 +289,14 @@ void shouldThrowAnExceptionWhenDeleteRequestGetsUnauthorizedError() { String dummyRevocationList = "dummyRevocationList"; doThrow(new FeignException.Unauthorized("", dummyRequest(), null, null)) - .when(restClientMock).deleteBatch(any()); + .when(restClientMock).deleteBatch(any()); DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException e = - Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, - () -> connector.deleteRevocationBatch(dummyRevocationList)); + Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, + () -> connector.deleteRevocationBatch(dummyRevocationList)); Assertions.assertEquals( - DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION, - e.getReason()); + DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION, + e.getReason()); } @Test @@ -305,14 +304,14 @@ void shouldThrowAnExceptionWhenDeleteRequestGetsForbiddenError() { String dummyRevocationList = "dummyRevocationList"; doThrow(new FeignException.Forbidden("", dummyRequest(), null, null)) - .when(restClientMock).deleteBatch(any()); + .when(restClientMock).deleteBatch(any()); DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException e = - Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, - () -> connector.deleteRevocationBatch(dummyRevocationList)); + Assertions.assertThrows(DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.class, + () -> connector.deleteRevocationBatch(dummyRevocationList)); Assertions.assertEquals( - DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION, - e.getReason()); + DgcGatewayRevocationListUploadConnector.DgcRevocationBatchUploadException.Reason.INVALID_AUTHORIZATION, + e.getReason()); } @Test @@ -320,7 +319,7 @@ void shouldNotThrowAnExceptionWhenDeleteRequestGetsNotFoundError() { String dummyRevocationList = "dummyRevocationList"; doThrow(new FeignException.NotFound("", dummyRequest(), null, null)) - .when(restClientMock).deleteBatch(any()); + .when(restClientMock).deleteBatch(any()); Assertions.assertDoesNotThrow(() -> connector.deleteRevocationBatch(dummyRevocationList)); } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/connector/TrustedIssuerDownloadConnectorTest.java b/src/test/java/eu/europa/ec/dgc/gateway/connector/TrustedIssuerDownloadConnectorTest.java index 4b66991..a5cf421 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/connector/TrustedIssuerDownloadConnectorTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/connector/TrustedIssuerDownloadConnectorTest.java @@ -32,16 +32,15 @@ import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.ResponseEntity; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.when; - @SpringBootTest @Slf4j class TrustedIssuerDownloadConnectorTest { @@ -57,7 +56,7 @@ class TrustedIssuerDownloadConnectorTest { @Test void testDownloadOfTrustedIssuerList() throws Exception { - Map param = new HashMap<>(); + Map param = new HashMap<>(); when(restClientMock.downloadTrustedIssuers(param)) .thenReturn(ResponseEntity.ok( @@ -73,7 +72,7 @@ void testDownloadOfTrustedIssuerList() throws Exception { @Test void shouldReturnEmptyListWhenDownloadFails() { - Map param = new HashMap<>(); + Map param = new HashMap<>(); when(restClientMock.downloadTrustedIssuers(param)) .thenReturn(ResponseEntity.status(500).build()); @@ -95,8 +94,8 @@ private Request dummyRequest() { @Test void setQueryParameters() throws Exception { - Map param = new HashMap<>(); - param.put("country","DE"); + Map param = new HashMap<>(); + param.put("country", "DE"); when(restClientMock.downloadTrustedIssuers(param)) .thenReturn(ResponseEntity.ok( @@ -113,7 +112,7 @@ void setQueryParameters() throws Exception { @Test void setWrongQueryFormat() { assertThrows(IllegalArgumentException.class, () -> - connector.setQueryParameter(QueryParameter.WITH_FEDERATION, List.of(true,false))); + connector.setQueryParameter(QueryParameter.WITH_FEDERATION, List.of(true, false))); } } diff --git a/src/test/java/eu/europa/ec/dgc/gateway/connector/ValidationRuleDownloadConnectorTest.java b/src/test/java/eu/europa/ec/dgc/gateway/connector/ValidationRuleDownloadConnectorTest.java index 326b94b..7a9acbc 100644 --- a/src/test/java/eu/europa/ec/dgc/gateway/connector/ValidationRuleDownloadConnectorTest.java +++ b/src/test/java/eu/europa/ec/dgc/gateway/connector/ValidationRuleDownloadConnectorTest.java @@ -460,7 +460,7 @@ void testTrustAnchorCheckWrongSignature() throws Exception { private Request dummyRequest() { return Request.create(Request.HttpMethod.GET, "url", new HashMap<>(), null, new RequestTemplate()); } - + private void assertEquals(ValidationRule v1, ValidationRule v2) { Assertions.assertEquals(v1.getIdentifier(), v2.getIdentifier()); Assertions.assertEquals(v1.getType(), v2.getType()); diff --git a/src/test/java/eu/europa/ec/dgc/generation/Base45EncoderTest.java b/src/test/java/eu/europa/ec/dgc/generation/Base45EncoderTest.java index be9db15..8bbce82 100644 --- a/src/test/java/eu/europa/ec/dgc/generation/Base45EncoderTest.java +++ b/src/test/java/eu/europa/ec/dgc/generation/Base45EncoderTest.java @@ -30,15 +30,15 @@ class Base45EncoderTest { @Test void encodeTest() { - assertEquals("7WE QE",Base45Encoder.encodeToString("test".getBytes(StandardCharsets.UTF_8))); + assertEquals("7WE QE", Base45Encoder.encodeToString("test".getBytes(StandardCharsets.UTF_8))); - byte[] bytes = new byte[] { 0, 2, -2, 30, -12, 23, -23, -40}; - assertEquals("200T5WR%UEPT",Base45Encoder.encodeToString(bytes)); + byte[] bytes = new byte[]{0, 2, -2, 30, -12, 23, -23, -40}; + assertEquals("200T5WR%UEPT", Base45Encoder.encodeToString(bytes)); } @Test void encodingDecoding() { - for (int i = 16; i<20; i++) { + for (int i = 16; i < 20; i++) { byte[] in = new byte[i]; Random rnd = new Random(); rnd.nextBytes(in); diff --git a/src/test/java/eu/europa/ec/dgc/generation/DccRecoveryBuilderTest.java b/src/test/java/eu/europa/ec/dgc/generation/DccRecoveryBuilderTest.java index 86ceeb7..ec9dffa 100644 --- a/src/test/java/eu/europa/ec/dgc/generation/DccRecoveryBuilderTest.java +++ b/src/test/java/eu/europa/ec/dgc/generation/DccRecoveryBuilderTest.java @@ -26,15 +26,15 @@ class DccRecoveryBuilderTest { @Test - void genTestJson() { + void genTestJson() { DccRecoveryBuilder dccRecoveryBuilder = new DccRecoveryBuilder(); dccRecoveryBuilder.gn("Artur").fn("Trzewik").gnt("ARTUR").fnt("TRZEWIK").dob(LocalDate.parse("1973-01-01")); dccRecoveryBuilder.dgci("URN:UVCI:01:OS:B5921A35D6A0D696421B3E2462178297I") - .country("DE") - .certificateIssuer("Dr Who") - .firstDayPositiveTest(LocalDate.now()) - .certificateValidFrom(LocalDate.now()) - .certificateValidUnitl(LocalDate.now()); + .country("DE") + .certificateIssuer("Dr Who") + .firstDayPositiveTest(LocalDate.now()) + .certificateValidFrom(LocalDate.now()) + .certificateValidUnitl(LocalDate.now()); String jsonString = dccRecoveryBuilder.toJsonString(); assertNotNull(jsonString); System.out.println(jsonString); diff --git a/src/test/java/eu/europa/ec/dgc/generation/DccTestBuilderTest.java b/src/test/java/eu/europa/ec/dgc/generation/DccTestBuilderTest.java index f17ee05..8c728b2 100644 --- a/src/test/java/eu/europa/ec/dgc/generation/DccTestBuilderTest.java +++ b/src/test/java/eu/europa/ec/dgc/generation/DccTestBuilderTest.java @@ -46,18 +46,18 @@ void patternMatch() { } @Test - void genTestJson() { + void genTestJson() { DccTestBuilder dccTestBuilder = new DccTestBuilder(); dccTestBuilder.gn("Artur").fn("Trzewik").gnt("ARTUR").fnt("TRZEWIK").dob(LocalDate.parse("1973-01-01")); dccTestBuilder.detected(false) - .dgci("URN:UVCI:01:OS:B5921A35D6A0D696421B3E2462178297I") - .country("DE") - .testTypeRapid(true) - .testingCentre("Hochdahl") - .testIdentifier("1833") - .testName("Example name") - .certificateIssuer("Dr Who") - .sampleCollection(LocalDateTime.now()); + .dgci("URN:UVCI:01:OS:B5921A35D6A0D696421B3E2462178297I") + .country("DE") + .testTypeRapid(true) + .testingCentre("Hochdahl") + .testIdentifier("1833") + .testName("Example name") + .certificateIssuer("Dr Who") + .sampleCollection(LocalDateTime.now()); String jsonString = dccTestBuilder.toJsonString(); assertNotNull(jsonString); System.out.println(jsonString); diff --git a/src/test/java/eu/europa/ec/dgc/generation/DccVaccinationBuilderTest.java b/src/test/java/eu/europa/ec/dgc/generation/DccVaccinationBuilderTest.java index 98cbcda..14063ac 100644 --- a/src/test/java/eu/europa/ec/dgc/generation/DccVaccinationBuilderTest.java +++ b/src/test/java/eu/europa/ec/dgc/generation/DccVaccinationBuilderTest.java @@ -27,18 +27,18 @@ class DccVaccinationBuilderTest { @Test - void genTestJson() { + void genTestJson() { DccVaccinationBuilder dccVaccinationBuilder = new DccVaccinationBuilder(); dccVaccinationBuilder.gn("Artur").fn("Trzewik").gnt("ARTUR").fnt("TRZEWIK").dob(LocalDate.parse("1973-01-01")); dccVaccinationBuilder.dgci("URN:UVCI:01:OS:B5921A35D6A0D696421B3E2462178297I") - .country("DE") - .certificateIssuer("Dr Who") - .doseNumber(1) - .totalSeriesOfDoses(2) - .dateOfVaccination(LocalDateTime.now()) - .vaccineOrProphylaxis("1119349007") - .medicalProduct("EU/1/20/1507") - .marketingAuthorization("ORG-100001699"); + .country("DE") + .certificateIssuer("Dr Who") + .doseNumber(1) + .totalSeriesOfDoses(2) + .dateOfVaccination(LocalDateTime.now()) + .vaccineOrProphylaxis("1119349007") + .medicalProduct("EU/1/20/1507") + .marketingAuthorization("ORG-100001699"); String jsonString = dccVaccinationBuilder.toJsonString(); assertNotNull(jsonString); System.out.println(jsonString); diff --git a/src/test/java/eu/europa/ec/dgc/generation/DgcCryptedPublisherTest.java b/src/test/java/eu/europa/ec/dgc/generation/DgcCryptedPublisherTest.java index 772ccdd..453e870 100644 --- a/src/test/java/eu/europa/ec/dgc/generation/DgcCryptedPublisherTest.java +++ b/src/test/java/eu/europa/ec/dgc/generation/DgcCryptedPublisherTest.java @@ -77,7 +77,7 @@ void getEncodedDGCData() throws Exception { // Test coding of public key // Base64-kodierte RSA-3072 Public Key in x.509 Format (ohne PEM Header/Footer). Immer 564 Zeichen (als Base64-Darstellung). String publicKeyBase64 = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()); - assertEquals(564,publicKeyBase64.length()); + assertEquals(564, publicKeyBase64.length()); DgcInitData dgcInitData = new DgcInitData(); dgcInitData.setExpriation(expirationSec); @@ -90,11 +90,11 @@ void getEncodedDGCData() throws Exception { // Base64-kodierte und mit dem RSA Public Key verschlüsselter DEK. Der DEK selbst muss 32 Bytes haben (für AES-256). // Der verschlüsselte DEK hat 384 Bytes und die base64-kodierte Darstellung entsprechend 512 Zeichen. - assertEquals(384,dgcData.getDek().length); + assertEquals(384, dgcData.getDek().length); String dekBase64 = Base64.getEncoder().encodeToString(dgcData.getDek()); - assertEquals(512,dekBase64.length()); + assertEquals(512, dekBase64.length()); - byte[] signature = dgcSigner.signHash(dgcData.getHash(),keyHelper.getPrivateKey()); + byte[] signature = dgcSigner.signHash(dgcData.getHash(), keyHelper.getPrivateKey()); DgcCryptedFinalizer dgcCryptedFinalizer = new DgcCryptedFinalizer(); String edgcQRCode = dgcCryptedFinalizer.finalizeDcc(dgcData.getDataEncrypted(), dgcData.getDek(), keyPair.getPrivate(), signature); @@ -123,7 +123,7 @@ void dccWithPartialDCCSigning() throws Exception { // Test coding of public key // Base64-kodierte RSA-3072 Public Key in x.509 Format (ohne PEM Header/Footer). Immer 564 Zeichen (als Base64-Darstellung). String publicKeyBase64 = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()); - assertEquals(564,publicKeyBase64.length()); + assertEquals(564, publicKeyBase64.length()); DgcInitData dgcInitData = new DgcInitData(); dgcInitData.setExpriation(expirationSec); @@ -136,11 +136,11 @@ void dccWithPartialDCCSigning() throws Exception { // Base64-kodierte und mit dem RSA Public Key verschlüsselter DEK. Der DEK selbst muss 32 Bytes haben (für AES-256). // Der verschlüsselte DEK hat 384 Bytes und die base64-kodierte Darstellung entsprechend 512 Zeichen. - assertEquals(384,dgcData.getDek().length); + assertEquals(384, dgcData.getDek().length); String dekBase64 = Base64.getEncoder().encodeToString(dgcData.getDek()); - assertEquals(512,dekBase64.length()); + assertEquals(512, dekBase64.length()); - byte[] partialDcc = dgcSigner.signPartialDcc(dgcData.getHash(),keyHelper.getPrivateKey(),keyId); + byte[] partialDcc = dgcSigner.signPartialDcc(dgcData.getHash(), keyHelper.getPrivateKey(), keyId); DgcCryptedFinalizer dgcCryptedFinalizer = new DgcCryptedFinalizer(); String edgcQRCode = dgcCryptedFinalizer.finalizePartialDcc(dgcData.getDataEncrypted(), dgcData.getDek(), keyPair.getPrivate(), partialDcc); @@ -163,7 +163,7 @@ void rsaCrypt() throws Exception { cipherDecrypt.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); byte[] decrypted = cipherDecrypt.doFinal(encrypted); - assertArrayEquals(testData,decrypted); + assertArrayEquals(testData, decrypted); } @Test @@ -172,72 +172,72 @@ void testExampleData() throws Exception { // see CWA DCC Test Certificates v2.1.docx APPENDIX A byte[] clearText = Base64.getDecoder().decode("Yfj9EpJCA1mjnLdgCq38cRDpT/eClO8wecILFtC+jwZX5FGIvV8Cq4d0Hw" + - "vTmR3hlflgo3oqWDG5nAECBXA5S3GrMpiLIL3VkMdSk9DqBA++Ue+25F5RMuNcE2SYmnHR0AoIqMFToPTwaeTlzgdnXK638RogN0" + - "mHUrNN0bXfKJ5NBHYJ7R6MfPHL8iFZW/RnW3pthra20pjMSviVZJBu2ir1LGxnOpu86jL14PQSe8TdXwbglLop280p33MFiw7CDn" + - "C0TQQJ59aphsLCqu9gbguD1uYQoSyNu3qeB3n7BNn0evHmhOi5Qjt1TXp6NtlJ4MlMeusiXGXGdlgCLBsVZaOm/QiSGbtcZ8uAH/" + - "u+Me35CHLwBYoSLBU42diwrpRXGUGDwe0Oh1hKpy8Kd/i/YDj1/H1nQgwdZcjd7Ci5RRnFJ6QjZLqVT8A3SBfUtXP+ig2zRGDevJ" + - "RXL34mBLM5NEYT9acaF6kST2LKEuEnVARBAEGCcqTWP39fm0TS2KnrYXX06+jLmkFT5sr1hLSBLmXtzrqA21mKpNwOYMMET4+W3/" + - "5hjFBxZkVGCFwcXEaLNWGRTZBSog=="); + "vTmR3hlflgo3oqWDG5nAECBXA5S3GrMpiLIL3VkMdSk9DqBA++Ue+25F5RMuNcE2SYmnHR0AoIqMFToPTwaeTlzgdnXK638RogN0" + + "mHUrNN0bXfKJ5NBHYJ7R6MfPHL8iFZW/RnW3pthra20pjMSviVZJBu2ir1LGxnOpu86jL14PQSe8TdXwbglLop280p33MFiw7CDn" + + "C0TQQJ59aphsLCqu9gbguD1uYQoSyNu3qeB3n7BNn0evHmhOi5Qjt1TXp6NtlJ4MlMeusiXGXGdlgCLBsVZaOm/QiSGbtcZ8uAH/" + + "u+Me35CHLwBYoSLBU42diwrpRXGUGDwe0Oh1hKpy8Kd/i/YDj1/H1nQgwdZcjd7Ci5RRnFJ6QjZLqVT8A3SBfUtXP+ig2zRGDevJ" + + "RXL34mBLM5NEYT9acaF6kST2LKEuEnVARBAEGCcqTWP39fm0TS2KnrYXX06+jLmkFT5sr1hLSBLmXtzrqA21mKpNwOYMMET4+W3/" + + "5hjFBxZkVGCFwcXEaLNWGRTZBSog=="); byte[] dek = Hex.decode("7427A22B0A0673B9F293935643DD4209ACEFA1CF944D2B9D9F97DD27474F12A7"); byte[] encryptedDek = Base64.getDecoder().decode("B++o5TT1onTB3M7mw2CxdAVTWYn961WWRyB4XvAtLotmbmUe1hkPY230" + - "z90/L+q5BC6DQtIpyZ4oURDKwuC477JrCjws3j6J7g48q1QLxU96oJvjQAAo4rXb0liAVHW8x3Cv72gkbZS9cbzwZXsdb2VbNnHX4" + - "tGt1TOPtDZMRUbwezwrOJv3K1ZH5lzkUEWcJVa5j5Ev/jkGhBf8b4stKrzxoyp/Ec4jRm48T+Dhiz2WjqUYU0Kh5/oR4mDhJS+f8U" + - "nc/JBELGeKvBM+qVJEeHYiMvyl2aTkAwlPFYquattlgkKoVsAlWSrRs32XwagAog/Kjze+na0BJqqoYLysf9cpjqYmAA8bqKT1k58" + - "WT6aviNjMXjdrwjjdloMvChszjszpgFV78XpfL8SEW+JDdQg7lj5yO/rxyC8Q7MLX/45nsxpahoCvqLMoEj99P3ZU8ykKbFA6Caac" + - "/ccHMVGTyYjMeyKUK2iFa4HercdT/8rjaEj99v81YDRkVICMPlNG"); + "z90/L+q5BC6DQtIpyZ4oURDKwuC477JrCjws3j6J7g48q1QLxU96oJvjQAAo4rXb0liAVHW8x3Cv72gkbZS9cbzwZXsdb2VbNnHX4" + + "tGt1TOPtDZMRUbwezwrOJv3K1ZH5lzkUEWcJVa5j5Ev/jkGhBf8b4stKrzxoyp/Ec4jRm48T+Dhiz2WjqUYU0Kh5/oR4mDhJS+f8U" + + "nc/JBELGeKvBM+qVJEeHYiMvyl2aTkAwlPFYquattlgkKoVsAlWSrRs32XwagAog/Kjze+na0BJqqoYLysf9cpjqYmAA8bqKT1k58" + + "WT6aviNjMXjdrwjjdloMvChszjszpgFV78XpfL8SEW+JDdQg7lj5yO/rxyC8Q7MLX/45nsxpahoCvqLMoEj99P3ZU8ykKbFA6Caac" + + "/ccHMVGTyYjMeyKUK2iFa4HercdT/8rjaEj99v81YDRkVICMPlNG"); byte[] privateKey = Base64.getDecoder().decode("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"); + "dd9HpYtZUAkTYcMz0Z2tOAhS0O+mKjQdg48PxajR5FuheUpCBoJQOhcNJFwNt/FsYvxVLEg/WUE7oujOaRuk4gn6vzabU1pY7fj0C" + + "468nNtkAl8eSKwGnzQWUAnhUWkpMb30Qe2Fm+kerEjQ8vymG671V2jXmfx0TmE347VYzrwuSonaSRdQkj1G2Kcu91HyoUGHwAD06x" + + "qfH5T0o5m6fmQhdfy4t0jZef12sR5tISvRg1ojLnGatGTuVzbFZ6YrL5xV2Qxo8DL9NwN49GzwcQX1dYffEFEZjTMrn9A2/kCYT1q" + + "F9Zh6YQ/4JUqu60m3bW2wqbVAzVB3fH4sMiqm+cUFftYnUS/TuDS7ZvaarN+SgBn60qPjAR3cG5vxx6VSs7tSI93t+8r1fyfpKu3L" + + "ZGCKGQIM77/pNdvSKu0we5xbQSpvpPrKCrP96eJ5Ooqy1irCPpGv7FVUqsQjW1ghLxAgMBAAECggGAZb/bSKSGv+deDHMDUkUPtmA" + + "gUtf8qzw/RpWoXb885Bh0w1dGO3vxH4nHL+GvzGu4I9YePVo4irzoqpdN65EvOX9KB9B781xqJ6MZ+ukREiDUewlW+q30ChHnwCvv" + + "KAo1POPjmfE9SxWdLmLppAdeX4wMIZoiQrzkpRgWyboPtm77lVdu54ilqiYqQlVrbO/WmOE0zkdEQ07DAm1sv5vyoaj050SO5VFud" + + "a7GK/V7ba/E3JiNXvuZsNIPqtwap2hpqSCxJkw1oL+0RD9HoO2ZKr6UxO3FjAYubiFIftvJyo/J3Zhu+dq4YKB9s5ZnOdATCewU2F" + + "ahzBw4JIYlQVPnB9INQRdFX7GhtP36pxRIyd8eK5pJcEHBsUag5+40aH6aDqv039tvf+bARqQcbHGVkfWfhGaHmCMY9XrPiAM5DSG" + + "kgiXjAqZxr5SEGmTXmKaXdEEQHer7Mw/YNFamTrSPH1n0+mR+NqetPQNRbWPHCzPP3iqlIbWHrvXeJ95VWv+RAoHBAN7Iveweqe1k" + + "D2Aye8zWwNMQ24gAp2t+stvsSrbkOBfdhXxuKYQoEFNNBua9Vr/cv6Uc7djxCagAcA4VBMxeLuGvbLWPcXzmCgIYJf0p/u2FZ7AKI" + + "UjclV7qbMn5b1yFUrlTcPtikYmdQ/g1ego4qPGWSKUk0A4bfjekUiSDqJBTTn8u1qXOj4N52KZ63XVnHxh1Nw44LBlnhokci+izI9" + + "7k93be06H5yulQE45sHVhKZEADIIK6CPmtCjG+H6yYzwKBwQDthnr3B8HLO66nH5s1129N/JBCG5C0JM+5kemzGFw0+5K27134+B6" + + "LMeU8ePlbozbXgFqsx+iZckNU5+5pNmYOdq5Y9DtHKcflxPexbVtCyFPxg2eU1B4dXEwH4FyQQ5bnTx1+x/r3M/kyZMdn57OOIWAl" + + "8IenL+XjWOGhPa3t5Xer4qp66591ZYPnMdzJgHp+FonF6EkBvylZrd9TX76IPaErJNf5NeAUJd5L6piRfb5yRB47bvk0HcRdHtMeC" + + "D8CgcEAzbgmkHPcTAaaoCTd5s/jrMMjRNn9vyh2ttfiQjJJjdgTnEwJcCyirpkxJz5tbavFGA23oB0r4oPM9WP5U1IhDmu0AY/cpw" + + "2w7jAoXDc8XU5T6d3g0GxITiZAoN0BNTkzo0hmyutBIwcirX+MGwYpEzTIDh8JNA21JmJJK8ibjfIvSQgSU3eDVE/efBR2jSPVNft" + + "/BFVge3D6bX/7vbw2AmwCCzVFzYthEMLN3DT/f/jpy6ZXjf+FrDBaeoZqrzFHAoHBAJdvEMCkQmrHPz+vx+3Yz07CQlrTZjtj6Mff" + + "/kY/trHU3qIhFCGiVx7ZjdQzMI+7DEDyxVy5C1OhZMoiIH8VvpVkFx4BgDWLrrWQEXceSHvYaqRk6coaPqTrblHrOjiDzxbj+uMUr" + + "q2ihjMZy4Q0Vea84qbtph7yS7fZt+hsAZLVpKmClrxNstlPAnyI7sHNVstCpU33HWyuqrdRQjvOpBQKbtGp6MQrFBTkW8i85c6Eg8" + + "IoKboss1cFz2arO2A/UwKBwQCTvvM6sF8+3zw1EJRSecRzmAsxhJ8t0nkSM91ljITFeo8p5HdTeX/vYVgPAF2CCUQDW+kMgw4o5U+N" + + "d24xm6zL2oYfjGe6lz/I+zM6hU9CPf1EdHxxccars7ilc/NrXAsaBJ7nO1p9peS1YqhoSC/x1aeJrcBDM1SlkoR0UG6l+hBVVLgs" + + "96yJhG8WjgXJDjB24Nz+L8zuYIB3KUtMTtib4CxYZIvpXYSmzU8RCIa2g16i24dWhlos1QiWOlG28bI="); byte[] publicKey = Base64.getDecoder().decode("MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAzrTf6abtRow4Z3" + - "zW/9glzOTZpbpanhU5QONkXSDPfidd9HpYtZUAkTYcMz0Z2tOAhS0O+mKjQdg48PxajR5FuheUpCBoJQOhcNJFwNt/FsYvxVLEg/W" + - "UE7oujOaRuk4gn6vzabU1pY7fj0C468nNtkAl8eSKwGnzQWUAnhUWkpMb30Qe2Fm+kerEjQ8vymG671V2jXmfx0TmE347VYzrwuSo" + - "naSRdQkj1G2Kcu91HyoUGHwAD06xqfH5T0o5m6fmQhdfy4t0jZef12sR5tISvRg1ojLnGatGTuVzbFZ6YrL5xV2Qxo8DL9NwN49Gz" + - "wcQX1dYffEFEZjTMrn9A2/kCYT1qF9Zh6YQ/4JUqu60m3bW2wqbVAzVB3fH4sMiqm+cUFftYnUS/TuDS7ZvaarN+SgBn60qPjAR3c" + - "G5vxx6VSs7tSI93t+8r1fyfpKu3LZGCKGQIM77/pNdvSKu0we5xbQSpvpPrKCrP96eJ5Ooqy1irCPpGv7FVUqsQjW1ghLxAgM" + - "BAAE="); + "zW/9glzOTZpbpanhU5QONkXSDPfidd9HpYtZUAkTYcMz0Z2tOAhS0O+mKjQdg48PxajR5FuheUpCBoJQOhcNJFwNt/FsYvxVLEg/W" + + "UE7oujOaRuk4gn6vzabU1pY7fj0C468nNtkAl8eSKwGnzQWUAnhUWkpMb30Qe2Fm+kerEjQ8vymG671V2jXmfx0TmE347VYzrwuSo" + + "naSRdQkj1G2Kcu91HyoUGHwAD06xqfH5T0o5m6fmQhdfy4t0jZef12sR5tISvRg1ojLnGatGTuVzbFZ6YrL5xV2Qxo8DL9NwN49Gz" + + "wcQX1dYffEFEZjTMrn9A2/kCYT1qF9Zh6YQ/4JUqu60m3bW2wqbVAzVB3fH4sMiqm+cUFftYnUS/TuDS7ZvaarN+SgBn60qPjAR3c" + + "G5vxx6VSs7tSI93t+8r1fyfpKu3LZGCKGQIM77/pNdvSKu0we5xbQSpvpPrKCrP96eJ5Ooqy1irCPpGv7FVUqsQjW1ghLxAgM" + + "BAAE="); byte[] cipherText = Base64.getDecoder().decode( - "y4N3agJtqoJrziH06swEHIoKi/CQDWF0Z0+/jdFuDif0h5VtQnjUcYzw33nnQE54mBjVyRH79ekdj/B3F9jJc/79f2V9DuPg" + - "/z0v0d/2Avpg85r8BiuDKDGskF7aZDVZO/wKWUZlj3vtT0aStFJCcgnZuQX83yTdJ22Ogmbn9uVcdv9xfT231aRnUr6y" + - "f4bON32LcWKxweXgvjp1gNZB/iJFURLKZfF/fZ66gGtcYh/bfT18re2DBNz0ZOpIUyOXuC4tNZA9x0A5hA4CXhaxunHX" + - "vFCgMCTsXl90JAG0cgfKD54oTp/EAnRcmMsZfAgfXqMLU4iEaWhj80A0nUltnrJx4JAvcrlSvBJa4716nDZaTzHTktzD" + - "NHl7r8J2wWh2SGFjSfi76s/mK54ZvM0x8B3+ppt/YxrJgAJ2e7SK0qz77dooMoL1G/qf6N2ZlIOSMsoSBrmYgGa5GAQb" + - "jMsLwoo7fKGYcR12ztp5J7it/w0xvx3jNbeNgxdLuco8gPoNLDxWElXGX1NS3umJ4yVkFKSPE5inUye3BO1pvWlXFmIM" + - "Fc0u+ZHurGbEMG/dHtVuK5ZKgp6tefd+L3VitTFeuQ=="); + "y4N3agJtqoJrziH06swEHIoKi/CQDWF0Z0+/jdFuDif0h5VtQnjUcYzw33nnQE54mBjVyRH79ekdj/B3F9jJc/79f2V9DuPg" + + "/z0v0d/2Avpg85r8BiuDKDGskF7aZDVZO/wKWUZlj3vtT0aStFJCcgnZuQX83yTdJ22Ogmbn9uVcdv9xfT231aRnUr6y" + + "f4bON32LcWKxweXgvjp1gNZB/iJFURLKZfF/fZ66gGtcYh/bfT18re2DBNz0ZOpIUyOXuC4tNZA9x0A5hA4CXhaxunHX" + + "vFCgMCTsXl90JAG0cgfKD54oTp/EAnRcmMsZfAgfXqMLU4iEaWhj80A0nUltnrJx4JAvcrlSvBJa4716nDZaTzHTktzD" + + "NHl7r8J2wWh2SGFjSfi76s/mK54ZvM0x8B3+ppt/YxrJgAJ2e7SK0qz77dooMoL1G/qf6N2ZlIOSMsoSBrmYgGa5GAQb" + + "jMsLwoo7fKGYcR12ztp5J7it/w0xvx3jNbeNgxdLuco8gPoNLDxWElXGX1NS3umJ4yVkFKSPE5inUye3BO1pvWlXFmIM" + + "Fc0u+ZHurGbEMG/dHtVuK5ZKgp6tefd+L3VitTFeuQ=="); - assertEquals(439,clearText.length); - assertEquals(384,encryptedDek.length); + assertEquals(439, clearText.length); + assertEquals(384, encryptedDek.length); // Test data decoding Cipher cipher = Cipher.getInstance(DgcCryptedPublisher.DATA_CIPHER); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("AES"); - SecretKeySpec secretKeySpec = new SecretKeySpec(dek,0,dek.length,"AES"); + SecretKeySpec secretKeySpec = new SecretKeySpec(dek, 0, dek.length, "AES"); SecretKey secretKey = secretKeyFactory.generateSecret(secretKeySpec); byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; IvParameterSpec ivspec = new IvParameterSpec(iv); @@ -255,8 +255,8 @@ void testExampleData() throws Exception { PrivateKey privateKeyInst = keyFactory.generatePrivate(specPrivate); Cipher keyCipher = Cipher.getInstance(DgcCryptedPublisher.KEY_CIPHER); - keyCipher.init(Cipher.DECRYPT_MODE, privateKeyInst,DgcCryptedPublisher.OAEP_PARAMETER_SPEC); - assertArrayEquals(dek,keyCipher.doFinal(encryptedDek)); + keyCipher.init(Cipher.DECRYPT_MODE, privateKeyInst, DgcCryptedPublisher.OAEP_PARAMETER_SPEC); + assertArrayEquals(dek, keyCipher.doFinal(encryptedDek)); } } diff --git a/src/test/java/eu/europa/ec/dgc/generation/DgcSignerTest.java b/src/test/java/eu/europa/ec/dgc/generation/DgcSignerTest.java index c729f0f..698ebdb 100644 --- a/src/test/java/eu/europa/ec/dgc/generation/DgcSignerTest.java +++ b/src/test/java/eu/europa/ec/dgc/generation/DgcSignerTest.java @@ -41,12 +41,12 @@ public static String genSampleJson() { DccTestBuilder dccTestBuilder = new DccTestBuilder(); dccTestBuilder.gn("Artur").fn("Trzewik").gnt("ARTUR").fnt("TRZEWIK").dob(LocalDate.parse("1973-01-01")); dccTestBuilder.detected(false) - .dgci("URN:UVCI:01:OS:B5921A35D6A0D696421B3E2462178297I") - .country("DE") - .testTypeRapid(true) - .testingCentre("Hochdahl") - .certificateIssuer("Dr Who") - .sampleCollection(LocalDateTime.now()); + .dgci("URN:UVCI:01:OS:B5921A35D6A0D696421B3E2462178297I") + .country("DE") + .testTypeRapid(true) + .testingCentre("Hochdahl") + .certificateIssuer("Dr Who") + .sampleCollection(LocalDateTime.now()); return dccTestBuilder.toJsonString(); } @@ -72,9 +72,9 @@ void genEdgc() throws IOException { byte[] coseBytes = dgcGenerator.genCoseUnsigned(dgcCbor, keyId, algId); byte[] hash = dgcGenerator.computeCoseSignHash(coseBytes); - byte[] signature = dgcSigner.signHash(hash,keyHelper.getPrivateKey()); + byte[] signature = dgcSigner.signHash(hash, keyHelper.getPrivateKey()); - byte[] coseSigned = dgcGenerator.dgcSetCoseSignature(coseBytes,signature); + byte[] coseSigned = dgcGenerator.dgcSetCoseSignature(coseBytes, signature); String edgcQR = dgcGenerator.coseToQrCode(coseSigned); System.out.println(edgcQR); diff --git a/src/test/java/eu/europa/ec/dgc/signing/DeprecatedSignedCertificateMessageBuilderTest.java b/src/test/java/eu/europa/ec/dgc/signing/DeprecatedSignedCertificateMessageBuilderTest.java index 7bd243e..00a1bca 100644 --- a/src/test/java/eu/europa/ec/dgc/signing/DeprecatedSignedCertificateMessageBuilderTest.java +++ b/src/test/java/eu/europa/ec/dgc/signing/DeprecatedSignedCertificateMessageBuilderTest.java @@ -79,7 +79,7 @@ void testCatchExceptionDuringBuild() throws IOException { @Test void testSignedMessage() throws Exception { CMSSignedData cmsSignedData = new CMSSignedData(builder.build()); - + Assertions.assertEquals(CMSObjectIdentifiers.data, cmsSignedData.getSignedContent().getContentType()); Assertions.assertArrayEquals(payloadCertificate.getEncoded(), (byte[]) cmsSignedData.getSignedContent().getContent()); diff --git a/src/test/java/eu/europa/ec/dgc/signing/SignedCertificateMessageBuilderTest.java b/src/test/java/eu/europa/ec/dgc/signing/SignedCertificateMessageBuilderTest.java index 88bb9ab..f568ee9 100644 --- a/src/test/java/eu/europa/ec/dgc/signing/SignedCertificateMessageBuilderTest.java +++ b/src/test/java/eu/europa/ec/dgc/signing/SignedCertificateMessageBuilderTest.java @@ -58,7 +58,7 @@ void setupTestData() throws Exception { .withPayload(new X509CertificateHolder(payloadCertificate.getEncoded())) .withSigningCertificate(new X509CertificateHolder(signingCertificate.getEncoded()), signingKeyPair.getPrivate()); } - + @Test void testUnreadyBuilder() { builder = new SignedCertificateMessageBuilder(); @@ -78,7 +78,7 @@ void testCatchExceptionDuringBuild() throws IOException { @Test void testSignedMessage() throws Exception { CMSSignedData cmsSignedData = new CMSSignedData(builder.build()); - + Assertions.assertEquals(CMSObjectIdentifiers.data, cmsSignedData.getSignedContent().getContentType()); Assertions.assertArrayEquals(payloadCertificate.getEncoded(), (byte[]) cmsSignedData.getSignedContent().getContent()); diff --git a/src/test/java/eu/europa/ec/dgc/testdata/TrustedIssuerTestHelper.java b/src/test/java/eu/europa/ec/dgc/testdata/TrustedIssuerTestHelper.java index ef2d411..1934095 100644 --- a/src/test/java/eu/europa/ec/dgc/testdata/TrustedIssuerTestHelper.java +++ b/src/test/java/eu/europa/ec/dgc/testdata/TrustedIssuerTestHelper.java @@ -49,10 +49,10 @@ public TrustedIssuerDto createTrustedIssuer(final String country) throws Excepti } private String getHashData(TrustedIssuerDto entity) { - return entity.getCountry() + ";" - + entity.getName() + ";" - + entity.getUrl() + ";" - + entity.getType().name() + ";"; + return entity.getCountry() + ";" + + entity.getName() + ";" + + entity.getUrl() + ";" + + entity.getType().name() + ";"; } public String signString(final String hashdata) throws Exception {