From e7344099d9ec5a611c632e68c25d07913b7892c9 Mon Sep 17 00:00:00 2001 From: forkimenjeckayang Date: Tue, 30 Jul 2024 11:53:36 +0100 Subject: [PATCH 1/7] Modified checkstyle rules --- checkstyle.xml | 107 ++++++++++++++++++++++++++----------------------- 1 file changed, 56 insertions(+), 51 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index b2e6fa633..41a571168 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -1,7 +1,7 @@ + "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" + "https://checkstyle.org/dtds/configuration_1_3.dtd"> + + + + + @@ -32,7 +37,7 @@ + default="checkstyle-suppressions.xml" /> @@ -44,9 +49,9 @@ - + + value="^package.*|^import.*|href\s*=\s*"[^"]*"|http://|https://|ftp://"/> @@ -54,9 +59,9 @@ + value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/> + value="Consider using special escape sequence instead of octal value or Unicode escaped value."/> @@ -71,15 +76,15 @@ + value="LITERAL_IF, LITERAL_ELSE"/> + value="LITERAL_DO, LITERAL_ELSE, LITERAL_FOR, LITERAL_IF, LITERAL_WHILE"/> @@ -87,14 +92,14 @@ @@ -106,7 +111,7 @@ @@ -118,17 +123,17 @@ + value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/> @@ -139,7 +144,7 @@ @@ -174,48 +179,48 @@ + value="Package name ''{0}'' must match pattern ''{1}''."/> + value="Type name ''{0}'' must match pattern ''{1}''."/> + value="Member name ''{0}'' must match pattern ''{1}''."/> + value="Parameter name ''{0}'' must match pattern ''{1}''."/> + value="Lambda parameter name ''{0}'' must match pattern ''{1}''."/> + value="Catch parameter name ''{0}'' must match pattern ''{1}''."/> + value="Local variable name ''{0}'' must match pattern ''{1}''."/> + value="Pattern variable name ''{0}'' must match pattern ''{1}''."/> + value="Class type name ''{0}'' must match pattern ''{1}''."/> @@ -230,37 +235,37 @@ + value="Method type name ''{0}'' must match pattern ''{1}''."/> + value="Interface type name ''{0}'' must match pattern ''{1}''."/> + value="GenericWhitespace ''{0}'' is followed by whitespace."/> + value="GenericWhitespace ''{0}'' is preceded with whitespace."/> + value="GenericWhitespace ''{0}'' should followed by whitespace."/> + value="GenericWhitespace ''{0}'' is not preceded with whitespace."/> - - - - - - + + + + + + @@ -270,24 +275,24 @@ - + @@ -295,14 +300,14 @@ @@ -315,14 +320,14 @@ + value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/> - + + value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/> @@ -348,7 +353,7 @@ + value="Method name ''{0}'' must match pattern ''{1}''."/> @@ -360,7 +365,7 @@ + default="checkstyle-xpath-suppressions.xml" /> @@ -377,4 +382,4 @@ - \ No newline at end of file + From 182a7b000850b0a4c3bf6787677fc7ad2caf9a54 Mon Sep 17 00:00:00 2001 From: forkimenjeckayang Date: Tue, 30 Jul 2024 11:54:37 +0100 Subject: [PATCH 2/7] Added suppression.xml to supress unnecessary checkstyle warnings --- suppression.xml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 suppression.xml diff --git a/suppression.xml b/suppression.xml new file mode 100644 index 000000000..74642dd49 --- /dev/null +++ b/suppression.xml @@ -0,0 +1,12 @@ + + + + + + + + From 7cb197d7a24cddc2b3a3044035f1adee6b512c4e Mon Sep 17 00:00:00 2001 From: forkimenjeckayang Date: Mon, 5 Aug 2024 10:23:15 +0100 Subject: [PATCH 3/7] modified pom.xml --- pom.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 0b87ab326..6e7ebf073 100644 --- a/pom.xml +++ b/pom.xml @@ -371,7 +371,7 @@ checkstyle.xml true UTF-8 - true + false false false org.checkstyle.google.severity=warning @@ -403,7 +403,6 @@ Max Low - true false true true From 5274115e8e063045754984a467504b30863e500f Mon Sep 17 00:00:00 2001 From: forkimenjeckayang Date: Tue, 6 Aug 2024 11:36:39 +0100 Subject: [PATCH 4/7] Modified checkstyle and removed rules for checks not really necessary --- checkstyle.xml | 37 ------------------------------------- 1 file changed, 37 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index 41a571168..89b2b21d5 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -261,14 +261,6 @@ - - - - - @@ -297,13 +289,6 @@ METHOD_DEF, QUESTION, RESOURCE_SPECIFICATION, SUPER_CTOR_CALL, LAMBDA, RECORD_DEF"/> - - - - - - - - - - - @@ -336,20 +313,6 @@ - - - - - - - - - - - Date: Wed, 25 Sep 2024 17:05:17 +0200 Subject: [PATCH 5/7] fix checkstyle in datasafe-types-api --- checkstyle.xml | 102 +++++++++++++----- .../types/api/actions/ReadRequest.java | 24 ++--- .../types/api/actions/RemoveRequest.java | 24 ++--- .../types/api/actions/WriteInboxRequest.java | 3 +- .../api/types/BaseTypePasswordString.java | 5 +- .../types/api/types/ReadKeyPassword.java | 4 +- .../types/api/utils/ExecutorServiceUtil.java | 2 + .../datasafe/types/api/utils/Obfuscate.java | 19 ++-- .../VersionedPrivateResourceTest.java | 5 +- .../types/api/shared/AwsClientRetry.java | 1 + pom.xml | 19 ++-- suppression.xml | 12 --- 12 files changed, 133 insertions(+), 87 deletions(-) delete mode 100644 suppression.xml diff --git a/checkstyle.xml b/checkstyle.xml index 89b2b21d5..623fd7a06 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -17,11 +17,6 @@ --> - - - - - @@ -49,7 +44,7 @@ - + @@ -76,7 +71,7 @@ + value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/> @@ -101,7 +97,7 @@ + COMPACT_CTOR_DEF, LITERAL_SWITCH, LITERAL_CASE"/> @@ -109,11 +105,18 @@ + + + + + + value="COMMA, SEMI, TYPECAST, LITERAL_IF, LITERAL_ELSE, LITERAL_RETURN, + LITERAL_WHILE, LITERAL_DO, LITERAL_FOR, LITERAL_FINALLY, DO_WHILE, ELLIPSIS, + LITERAL_SWITCH, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_CATCH, LAMBDA, + LITERAL_YIELD, LITERAL_CASE"/> @@ -125,10 +128,12 @@ + SR_ASSIGN, STAR, STAR_ASSIGN, LITERAL_ASSERT, + TYPE_EXTENSION_AND"/> @@ -265,12 +270,23 @@ - - - - - + + + + + + + + + + + + + + + + + + + + - - + + + + + + + + + + + @@ -313,8 +346,23 @@ + + + + + + + + + + + + + + + - + diff --git a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/ReadRequest.java b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/ReadRequest.java index f10c5f45b..bd5cb2d68 100644 --- a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/ReadRequest.java +++ b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/ReadRequest.java @@ -43,6 +43,18 @@ public static ReadRequest forPrivate(T owner, PrivateRes return new ReadRequest<>(owner, path); } + public static ReadRequest forPrivate(T owner, StorageIdentifier storage, String path) { + return new ReadRequest<>(owner, BasePrivateResource.forPrivate(new Uri(path)), storage); + } + + public static ReadRequest forPrivate(T owner, StorageIdentifier storage, URI path) { + return forPrivate(owner, storage, new Uri(path)); + } + + public static ReadRequest forPrivate(T owner, StorageIdentifier storage, Uri path) { + return new ReadRequest<>(owner, BasePrivateResource.forPrivate(path), storage); + } + public static ReadRequest forDefaultPrivateWithVersion( T owner, String path, Version version) { return forDefaultPrivateWithVersion(owner, BasePrivateResource.forPrivate(path), version); @@ -64,16 +76,4 @@ public static ReadRequest forDefaultPrivate(T owner, URI public static ReadRequest forDefaultPrivate(T owner, Uri path) { return new ReadRequest<>(owner, BasePrivateResource.forPrivate(path)); } - - public static ReadRequest forPrivate(T owner, StorageIdentifier storage, String path) { - return new ReadRequest<>(owner, BasePrivateResource.forPrivate(new Uri(path)), storage); - } - - public static ReadRequest forPrivate(T owner, StorageIdentifier storage, URI path) { - return forPrivate(owner, storage, new Uri(path)); - } - - public static ReadRequest forPrivate(T owner, StorageIdentifier storage, Uri path) { - return new ReadRequest<>(owner, BasePrivateResource.forPrivate(path), storage); - } } diff --git a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/RemoveRequest.java b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/RemoveRequest.java index 306822925..cf98ddd3d 100644 --- a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/RemoveRequest.java +++ b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/RemoveRequest.java @@ -43,6 +43,18 @@ public static RemoveRequest forPrivate(T owner, PrivateR return new RemoveRequest<>(owner, path); } + public static RemoveRequest forPrivate(T owner, StorageIdentifier storage, String path) { + return new RemoveRequest<>(owner, BasePrivateResource.forPrivate(new Uri(path)), storage); + } + + public static RemoveRequest forPrivate(T owner, StorageIdentifier storage, URI path) { + return forPrivate(owner, storage, new Uri(path)); + } + + public static RemoveRequest forPrivate(T owner, StorageIdentifier storage, Uri path) { + return new RemoveRequest<>(owner, BasePrivateResource.forPrivate(path), storage); + } + public static RemoveRequest forDefaultPrivateWithVersion( T owner, String path, Version version) { return forDefaultPrivateWithVersion(owner, BasePrivateResource.forPrivate(path), version); @@ -60,16 +72,4 @@ public static RemoveRequest forDefaultPrivate(T owner, U public static RemoveRequest forDefaultPrivate(T owner, Uri path) { return new RemoveRequest<>(owner, BasePrivateResource.forPrivate(path)); } - - public static RemoveRequest forPrivate(T owner, StorageIdentifier storage, String path) { - return new RemoveRequest<>(owner, BasePrivateResource.forPrivate(new Uri(path)), storage); - } - - public static RemoveRequest forPrivate(T owner, StorageIdentifier storage, URI path) { - return forPrivate(owner, storage, new Uri(path)); - } - - public static RemoveRequest forPrivate(T owner, StorageIdentifier storage, Uri path) { - return new RemoveRequest<>(owner, BasePrivateResource.forPrivate(path), storage); - } } diff --git a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/WriteInboxRequest.java b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/WriteInboxRequest.java index 2d9797086..f4005c733 100644 --- a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/WriteInboxRequest.java +++ b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/actions/WriteInboxRequest.java @@ -37,7 +37,8 @@ public class WriteInboxRequest { @Singular List callbacks; - private WriteInboxRequest(@NonNull T owner, @NonNull R recipients, @NonNull L location, List callbacks) { + private WriteInboxRequest(@NonNull T owner, @NonNull R recipients, @NonNull L location, + List callbacks) { this.owner = owner; this.recipients = recipients; this.location = location; diff --git a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/types/BaseTypePasswordString.java b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/types/BaseTypePasswordString.java index bbb0e3800..373214951 100644 --- a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/types/BaseTypePasswordString.java +++ b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/types/BaseTypePasswordString.java @@ -22,8 +22,8 @@ public class BaseTypePasswordString { /** * ATTENTION - *

- * caller of method gives ownership of {@code value[]} + * + *

caller of method gives ownership of {@code value[]} * to this class. Value will be nullyfied after successful read/write/list. * * @param value will be nullified asap @@ -35,6 +35,7 @@ public BaseTypePasswordString(char[] value) { /** * Argument provider is responsible for password cleanup + * * @param value will stay unchanged */ public BaseTypePasswordString(Supplier value) { diff --git a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/types/ReadKeyPassword.java b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/types/ReadKeyPassword.java index c88667aa4..110ce0a8e 100644 --- a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/types/ReadKeyPassword.java +++ b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/types/ReadKeyPassword.java @@ -11,6 +11,7 @@ public class ReadKeyPassword extends BaseTypePasswordString { /** * Caller of method makes sure, supplied char[] is deleted asap + * * @param readKeyPassword will stay unchanged */ public ReadKeyPassword(Supplier readKeyPassword) { @@ -20,8 +21,9 @@ public ReadKeyPassword(Supplier readKeyPassword) { /** * ATTENTION: * caller of method gives ownership of {@code readKeyPassword} to this class. - * @code readKeyPassword} will be nullyfied after successful read/write/list. + * * @param readKeyPassword Password to read key that will be cleared after read/write/list. + * @code readKeyPassword} will be nullyfied after successful read/write/list. */ public ReadKeyPassword(char[] readKeyPassword) { super(readKeyPassword); diff --git a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/utils/ExecutorServiceUtil.java b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/utils/ExecutorServiceUtil.java index ec1f92134..7f5712f02 100644 --- a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/utils/ExecutorServiceUtil.java +++ b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/utils/ExecutorServiceUtil.java @@ -12,6 +12,7 @@ public class ExecutorServiceUtil { /** * Submitter will execute task if it can't be submitted, effectively blocking submitting threads. + * * @param poolSize executor and queue size * @return ExecutorService with limited queue size that executes task using submitter thread on starvation */ @@ -24,6 +25,7 @@ public ExecutorService submitterExecutesOnStarvationExecutingService(int poolSiz /** * Submitter will execute task if it can't be submitted, effectively blocking submitting threads. + * * @return ExecutorService with limited queue size that executes task using submitter thread on starvation that has * thread pool with size equal to processor count */ diff --git a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/utils/Obfuscate.java b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/utils/Obfuscate.java index 302d3bd39..7b83c351b 100644 --- a/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/utils/Obfuscate.java +++ b/datasafe-types-api/src/main/java/de/adorsys/datasafe/types/api/utils/Obfuscate.java @@ -23,7 +23,7 @@ *

  • SECURE_SENSITIVE=off,0,false AND SECURE_LOGS=off,0,false - passwords are not obscured in logs
  • *
  • SECURE_SENSITIVE=hash - first 4 chars of SHA-256 hashed value is logged
  • *
  • all other values yield string with stars
  • - *
      + *
    */ @UtilityClass public class Obfuscate { @@ -34,9 +34,10 @@ public class Obfuscate { /** * By default, protects moderately sensitive data, but preserves delimiters in it. + * * @param value String with delimiters to obfuscate - * @param delim Delimiters to split on and preserve - * I.e. a/b/c with {@code delim} equal to "/" will create sha(a)/sha(b)/sha(c) + * @param delim Delimiters to split on and preserve. + * I.e. a/b/c with {@code delim} equal to "/" will create sha(a)/sha(b)/sha(c) */ public static String secure(String value, String delim) { if (null == value) { @@ -50,6 +51,7 @@ public static String secure(String value, String delim) { /** * By default, protects moderately sensitive data, but allows to log it using SECURE_LOGS property. + * * @param value Its toString() result will get encrypted. * @return Secured string value that is safe to log. */ @@ -78,10 +80,10 @@ public static String secure(String value) { * because is call sometimes with null and thus can not * be clearly assigned. * - * By default, protects highly sensitive data, but allows to log it using SECURE_SENSITIVE property. + *

    By default, protects highly sensitive data, but allows to log it using SECURE_SENSITIVE property. + * * @param value Its toString() result will get encrypted. * @return Secured string value that is safe to log. - * */ public static String secureSensitiveChar(char[] value) { if (value == null) { @@ -101,6 +103,7 @@ public static String secureSensitiveChar(char[] value) { /** * By default, protects highly sensitive data, but allows to log it using SECURE_SENSITIVE property. + * * @param value Its toString() result will get encrypted. * @return Secured string value that is safe to log. */ @@ -136,9 +139,9 @@ private static String computeShaChar(char[] s) { } private static boolean isDisabled(String value) { - return "0".equals(value) - || "false".equalsIgnoreCase(value) - || "off".equalsIgnoreCase(value); + return "0".equals(value) || + "false".equalsIgnoreCase(value) || + "off".equalsIgnoreCase(value); } @SneakyThrows diff --git a/datasafe-types-api/src/test/java/de/adorsys/datasafe/types/api/resource/VersionedPrivateResourceTest.java b/datasafe-types-api/src/test/java/de/adorsys/datasafe/types/api/resource/VersionedPrivateResourceTest.java index be0f76e81..e44246385 100644 --- a/datasafe-types-api/src/test/java/de/adorsys/datasafe/types/api/resource/VersionedPrivateResourceTest.java +++ b/datasafe-types-api/src/test/java/de/adorsys/datasafe/types/api/resource/VersionedPrivateResourceTest.java @@ -16,7 +16,8 @@ class VersionedPrivateResourceTest extends BaseMockitoTest { .forAbsolutePrivate("file://some/path/").getResource(); private VersionedPrivateResource tested = new VersionedPrivateResource<>(resource, version); - private VersionedPrivateResource absoluteTested = new VersionedPrivateResource<>(absoluteResource, version); + private VersionedPrivateResource absoluteTested = new VersionedPrivateResource<>(absoluteResource, + version); @Test void encryptedPath() { @@ -25,7 +26,7 @@ void encryptedPath() { @Test void decryptedPath() { - assertThat(tested.decryptedPath().asString()).isEqualTo(""); + assertThat(tested.decryptedPath().asString()).isEmpty(); } @Test diff --git a/datasafe-types-api/src/test/java/de/adorsys/datasafe/types/api/shared/AwsClientRetry.java b/datasafe-types-api/src/test/java/de/adorsys/datasafe/types/api/shared/AwsClientRetry.java index 220777938..9ff41c526 100644 --- a/datasafe-types-api/src/test/java/de/adorsys/datasafe/types/api/shared/AwsClientRetry.java +++ b/datasafe-types-api/src/test/java/de/adorsys/datasafe/types/api/shared/AwsClientRetry.java @@ -22,6 +22,7 @@ public static void createBucketWithRetry(AmazonS3 client, String bucket) { @NoArgsConstructor static class RetryLogger { int counter = 0; + public void log() { if (counter > 0) { log.info("this is the {} retry to create bucket", counter); diff --git a/pom.xml b/pom.xml index 6e7ebf073..10e3a044d 100644 --- a/pom.xml +++ b/pom.xml @@ -361,22 +361,20 @@ org.apache.maven.plugins maven-checkstyle-plugin ${checkstyle-maven-plugin.version} + + checkstyle.xml + true + true + false + ${project.basedir}/target/checkstyle-report.xml + org.checkstyle.google.severity=error + validate check - - checkstyle.xml - true - UTF-8 - false - false - false - org.checkstyle.google.severity=warning - ${project.basedir}/target/checkstyle-report.xml - @@ -403,6 +401,7 @@ Max Low + true false true true diff --git a/suppression.xml b/suppression.xml deleted file mode 100644 index 74642dd49..000000000 --- a/suppression.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - From 3ac9af653c1348c56c6c119e506ef5f375ea0552 Mon Sep 17 00:00:00 2001 From: Calebasah Date: Fri, 27 Sep 2024 17:36:21 +0100 Subject: [PATCH 6/7] DAT-343 Fix checkstyle warnings --- checkstyle.xml | 94 +++++--- .../datasafe/business/impl/e2e/BaseE2EIT.java | 58 +++-- .../impl/e2e/BasicFunctionalityIT.java | 46 ++-- .../BasicFunctionalityWithConcurrencyIT.java | 40 ++-- .../impl/e2e/DataTamperingResistanceIT.java | 6 +- .../impl/e2e/MultiDFSFunctionalityIT.java | 196 ++++++++--------- .../impl/e2e/SchemeDelegationWithDbIT.java | 82 ++++--- .../datasafe/cli/commands/inbox/Inbox.java | 2 +- .../datasafe/cli/commands/inbox/Share.java | 2 +- .../cli/commands/privatespace/Copy.java | 2 +- .../commands/privatespace/Privatespace.java | 2 +- ...eOnMissingServiceTypeInKnownProviders.java | 16 +- .../api/types/UserPrivateProfile.java | 2 +- .../profile/dfs/BucketAccessServiceImpl.java | 2 +- ...cessServiceWithStorageCredentialsImpl.java | 4 +- .../keys/DFSPrivateKeyServiceImpl.java | 6 +- .../keys/StorageKeyStoreOperationsImpl.java | 8 +- .../impl/profile/keys/UserKeyStoreCache.java | 6 +- .../ProfileRegistrationServiceImpl.java | 4 +- .../actions/ProfileStoreService.java | 4 +- .../resource/ResourceResolverImpl.java | 8 +- .../keys/DFSPrivateKeyServiceImplTest.java | 3 +- .../encryption/MutableEncryptionConfig.java | 4 +- .../decryptors/KekDecryptor.java | 2 +- .../impl/document/CMSDocumentReadService.java | 4 +- .../impl/keystore/KeyStoreServiceImpl.java | 4 +- .../impl/keystore/PublicKeySerdeImpl.java | 3 +- .../IntegrityPreservingUriEncryption.java | 6 +- .../CmsEncryptionServiceImplTest.java | 4 +- .../cmsencryption/SymetricEncryptionTest.java | 2 +- .../impl/keystore/KeyStoreServiceTest.java | 6 +- .../impl/keystore/PublicKeySerdeImplTest.java | 2 +- ...erationsTestWithVersionedDatasafeTest.java | 30 ++- .../CustomlyBuiltDatasafeServiceTest.java | 2 +- .../s3/MultiDfsWithCredentialsExampleIT.java | 78 ++++--- ...thDefaultDatasafeOnVersionedStorageIT.java | 2 +- ...andomActionsOnSimpleDatasafeAdapterIT.java | 2 +- .../framework/BaseRandomActions.java | 4 +- .../EncryptedLatestLinkServiceImpl.java | 2 +- .../api/actions/RemoveFromPrivate.java | 5 +- .../impl/actions/RemoveFromPrivateImpl.java | 6 +- .../EncryptedResourceResolverImplTest.java | 4 +- .../impl/actions/ListPrivateImplTest.java | 2 +- .../impl/actions/ReadFromPrivateImplTest.java | 2 +- .../impl/actions/WriteToPrivateImplTest.java | 2 +- datasafe-rest-impl/package-lock.json | 6 + .../rest/impl/DatasafeRestApplication.java | 6 +- .../rest/impl/config/DatasafeConfig.java | 67 +++--- .../impl/controller/DocumentController.java | 24 +- .../controller/GenericControllerAdvice.java | 15 +- .../rest/impl/controller/InboxController.java | 4 +- .../impl/controller/VersionController.java | 6 +- .../AuthenticateControllerTest.java | 6 +- .../controller/BaseDatasafeEndpointTest.java | 6 +- .../rest/impl/controller/TestHelper.java | 8 +- .../impl/controller/UserControllerTest.java | 207 +++++++++--------- .../RuntimeDelegateGenerator.java | 58 ++--- .../RuntimeDelegateProcessor.java | 12 +- .../simple/adapter/api/types/DocumentFQN.java | 2 +- .../simple/adapter/api/DocumentFQNTest.java | 2 +- .../simple/adapter/impl/LogStringFrame.java | 6 +- .../impl/SimpleDatasafeServiceImpl.java | 101 +++++---- .../pathencryption/NoPathEncryptionImpl.java | 9 +- .../impl/SimpleAdapterFeatureTest.java | 2 +- .../adapter/impl/SimpleDatasafeAdapterIT.java | 6 +- .../SpringSimpleDatasafeServiceFactory.java | 20 +- .../api/RegexDelegatingStorageTest.java | 9 +- .../api/UriBasedAuthStorageServiceTest.java | 14 +- .../api/UserBasedDelegatingStorageTest.java | 11 +- .../impl/db/DatabaseStorageService.java | 4 +- .../impl/fs/FileSystemStorageService.java | 12 +- .../impl/s3/S3SystemStorageServiceIT.java | 2 +- .../teststorage/WithStorageProvider.java | 62 +++--- 73 files changed, 740 insertions(+), 718 deletions(-) create mode 100644 datasafe-rest-impl/package-lock.json diff --git a/checkstyle.xml b/checkstyle.xml index 623fd7a06..fe9aa729e 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -39,12 +39,12 @@ - + - + @@ -63,7 +63,12 @@ - + + + + + @@ -113,9 +118,9 @@ @@ -129,8 +134,8 @@ value="ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, DO_WHILE, EQUAL, GE, GT, LAMBDA, LAND, LCURLY, LE, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, - LITERAL_FOR, LITERAL_IF, LITERAL_RETURN, LITERAL_SWITCH, LITERAL_SYNCHRONIZED, - LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, + LITERAL_FOR, LITERAL_RETURN, LITERAL_SWITCH, LITERAL_SYNCHRONIZED, + LITERAL_WHILE, LOR, LT, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY, SL, SLIST, SL_ASSIGN, SR, SR_ASSIGN, STAR, STAR_ASSIGN, LITERAL_ASSERT, TYPE_EXTENSION_AND"/> @@ -143,17 +148,21 @@ - + + + - - - - - + + + + + + + + + + @@ -213,7 +222,7 @@ value="Catch parameter name ''{0}'' must match pattern ''{1}''."/> - + @@ -266,21 +275,30 @@ - - + + + + + + - - - - - - - - - - - + + + + + + + + + + + + + + + @@ -294,11 +312,12 @@ + - - + + + + + + @@ -371,7 +395,7 @@ - + diff --git a/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BaseE2EIT.java b/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BaseE2EIT.java index 7d3acd3eb..e259d041b 100644 --- a/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BaseE2EIT.java +++ b/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BaseE2EIT.java @@ -1,5 +1,7 @@ package de.adorsys.datasafe.business.impl.e2e; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; import com.google.common.io.ByteStreams; import de.adorsys.datasafe.business.impl.service.DefaultDatasafeServices; import de.adorsys.datasafe.business.impl.service.VersionedDatasafeServices; @@ -32,10 +34,6 @@ import de.adorsys.datasafe.types.api.types.ReadKeyPassword; import de.adorsys.datasafe.types.api.utils.Obfuscate; import de.adorsys.datasafe.types.api.utils.ReadKeyPasswordTestFactory; -import lombok.RequiredArgsConstructor; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; - import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; @@ -47,9 +45,9 @@ import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.assertj.core.api.Assertions.assertThat; +import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor @@ -120,7 +118,7 @@ protected void writeDataToPrivate(UserIDAuth auth, String path, String data) { @SneakyThrows protected void writeDataToInbox(UserIDAuth owner, UserIDAuth auth, String path, String data) { try (OutputStream stream = writeToInbox.write( - WriteInboxRequest.forDefaultPublic(owner, Collections.singleton(auth.getUserID()), path) + WriteInboxRequest.forDefaultPublic(owner, Collections.singleton(auth.getUserID()), path) )) { stream.write(data.getBytes(UTF_8)); @@ -134,7 +132,7 @@ protected AbsoluteLocation getFirstFileInPrivate(UserIDAuth ow protected List> getAllFilesInPrivate(UserIDAuth owner) { try (Stream> ls = listPrivate.list( - ListRequest.forDefaultPrivate(owner, "./") + ListRequest.forDefaultPrivate(owner, "./") )) { List> files = ls.collect(Collectors.toList()); log.info("{} has {} in PRIVATE", owner.getUserID(), files); @@ -178,7 +176,7 @@ protected AbsoluteLocation getFirstFileInInbox(UserIDAuth inbo protected List> getAllFilesInInbox(UserIDAuth inboxOwner) { try (Stream> ls = listInbox.list( - ListRequest.forDefaultPrivate(inboxOwner, "./") + ListRequest.forDefaultPrivate(inboxOwner, "./") )) { List> files = ls.collect(Collectors.toList()); log.info("{} has {} in INBOX", inboxOwner, files); @@ -194,7 +192,7 @@ protected void registerJohnAndJane() { @SneakyThrows protected void sendToInbox(UserIDAuth from, UserID to, String filename, String data) { try (OutputStream stream = writeToInbox.write( - WriteInboxRequest.forDefaultPublic(from, Collections.singleton(to), "./" + filename) + WriteInboxRequest.forDefaultPublic(from, Collections.singleton(to), "./" + filename) )) { stream.write(data.getBytes()); } @@ -229,11 +227,11 @@ protected UserIDAuth createJohnTestUser(int i) { protected void assertPrivateSpaceList(UserIDAuth user, String root, String... expected) { List paths; try (Stream> ls = - listPrivate.list(ListRequest.forDefaultPrivate(user, root)) + listPrivate.list(ListRequest.forDefaultPrivate(user, root)) ) { paths = ls - .map(it -> it.getResource().asPrivate().decryptedPath().asString()) - .collect(Collectors.toList()); + .map(it -> it.getResource().asPrivate().decryptedPath().asString()) + .collect(Collectors.toList()); } assertThat(paths).containsExactlyInAnyOrder(expected); @@ -242,11 +240,11 @@ protected void assertPrivateSpaceList(UserIDAuth user, String root, String... ex protected void assertInboxSpaceList(UserIDAuth user, String root, String... expected) { List paths; try (Stream> ls = - listInbox.list(ListRequest.forDefaultPrivate(user, root)) + listInbox.list(ListRequest.forDefaultPrivate(user, root)) ) { paths = ls - .map(it -> it.getResource().asPrivate().decryptedPath().asString()) - .collect(Collectors.toList()); + .map(it -> it.getResource().asPrivate().decryptedPath().asString()) + .collect(Collectors.toList()); } assertThat(paths).containsExactlyInAnyOrder(expected); @@ -255,8 +253,8 @@ protected void assertInboxSpaceList(UserIDAuth user, String root, String... expe @SneakyThrows protected void assertRootDirIsEmpty(WithStorageProvider.StorageDescriptor descriptor) { try (Stream> ls = descriptor.getStorageService().get() - .list( - new AbsoluteLocation<>(BasePrivateResource.forPrivate(descriptor.getLocation()))) + .list( + new AbsoluteLocation<>(BasePrivateResource.forPrivate(descriptor.getLocation()))) ) { assertThat(ls).isEmpty(); } @@ -267,17 +265,17 @@ protected void assertRootDirIsEmpty(WithStorageProvider.StorageDescriptor descri // however we can't remove anything above try (Stream files = Files.walk(Paths.get(descriptor.getLocation().asURI()))) { assertThat(files) - .allMatch(it -> it.toFile().isDirectory()) - .extracting(Path::toUri) - .extracting(it -> descriptor.getLocation().asURI().relativize(it)) - .extracting(URI::toString) - .containsExactlyInAnyOrder( - "", - "users/", - "profiles/", - "profiles/public/", - "profiles/private/" - ); + .allMatch(it -> it.toFile().isDirectory()) + .extracting(Path::toUri) + .extracting(it -> descriptor.getLocation().asURI().relativize(it)) + .extracting(URI::toString) + .containsExactlyInAnyOrder( + "", + "users/", + "profiles/", + "profiles/public/", + "profiles/private/" + ); } } } diff --git a/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BasicFunctionalityIT.java b/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BasicFunctionalityIT.java index 5dad99547..ec2c6f664 100644 --- a/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BasicFunctionalityIT.java +++ b/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BasicFunctionalityIT.java @@ -1,5 +1,14 @@ package de.adorsys.datasafe.business.impl.e2e; +import static de.adorsys.datasafe.business.impl.e2e.Const.FOLDER; +import static de.adorsys.datasafe.business.impl.e2e.Const.MESSAGE_ONE; +import static de.adorsys.datasafe.business.impl.e2e.Const.PRIVATE_FILE; +import static de.adorsys.datasafe.business.impl.e2e.Const.PRIVATE_FILE_PATH; +import static de.adorsys.datasafe.business.impl.e2e.Const.SHARED_FILE; +import static de.adorsys.datasafe.business.impl.e2e.Const.SHARED_FILE_PATH; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; @@ -23,14 +32,11 @@ import de.adorsys.datasafe.types.api.resource.Uri; import de.adorsys.datasafe.types.api.types.BaseTypePasswordStringException; import de.adorsys.datasafe.types.api.types.ReadKeyPassword; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; -import org.testcontainers.shaded.com.google.common.collect.ImmutableSet; - -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; import java.nio.charset.StandardCharsets; import java.security.UnrecoverableKeyException; import java.util.Arrays; @@ -39,16 +45,11 @@ import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; - -import static de.adorsys.datasafe.business.impl.e2e.Const.FOLDER; -import static de.adorsys.datasafe.business.impl.e2e.Const.MESSAGE_ONE; -import static de.adorsys.datasafe.business.impl.e2e.Const.PRIVATE_FILE; -import static de.adorsys.datasafe.business.impl.e2e.Const.PRIVATE_FILE_PATH; -import static de.adorsys.datasafe.business.impl.e2e.Const.SHARED_FILE; -import static de.adorsys.datasafe.business.impl.e2e.Const.SHARED_FILE_PATH; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.testcontainers.shaded.com.google.common.collect.ImmutableSet; /** * Tests that validates basic functionality - storing data to inbox, privatespace, listing files, etc. @@ -64,11 +65,9 @@ class BasicFunctionalityIT extends BaseE2EIT { /** - * * In this test, password is provided as char[]. * This means after every operation, the password in cleared. * This is tested for read/write/list/remove - * */ @SneakyThrows @ParameterizedTest @@ -284,9 +283,10 @@ void testWriteToPrivateListPrivateReadPrivateAndSendToAndReadFromInbox( removeFromPrivate(jane, privateJane.getResource().asPrivate()); removeFromInbox(john, inboxJohn.getResource().asPrivate()); } + @ParameterizedTest @MethodSource("allStorages") - void testWriteToPrivateListPrivateReadPrivateAndSendToAndReadFromInboxCustom( WithStorageProvider.StorageDescriptor descriptor) { + void testWriteToPrivateListPrivateReadPrivateAndSendToAndReadFromInboxCustom(WithStorageProvider.StorageDescriptor descriptor) { String yamlFixture = "config/mutable.yaml"; customInit(descriptor, yamlFixture); @@ -425,6 +425,7 @@ private void init(WithStorageProvider.StorageDescriptor descriptor) { this.location = descriptor.getLocation(); this.storage = descriptor.getStorageService().get(); } + private void customInit(WithStorageProvider.StorageDescriptor descriptor, String yamlFixture) { MutableEncryptionConfig config = readResource(mapper, yamlFixture, MutableEncryptionConfig.class); DefaultDatasafeServices datasafeServices = DatasafeServicesProvider @@ -438,8 +439,7 @@ private void customInit(WithStorageProvider.StorageDescriptor descriptor, String private static T readResource(ObjectMapper mapper, String path, Class type) { try (Reader reader = Resources.asCharSource(Resources.getResource(path), StandardCharsets.UTF_8).openStream()) { return mapper.readValue(reader, type); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } } diff --git a/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BasicFunctionalityWithConcurrencyIT.java b/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BasicFunctionalityWithConcurrencyIT.java index 665666f61..a074b0652 100644 --- a/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BasicFunctionalityWithConcurrencyIT.java +++ b/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/BasicFunctionalityWithConcurrencyIT.java @@ -1,5 +1,11 @@ package de.adorsys.datasafe.business.impl.e2e; +import static de.adorsys.datasafe.types.api.actions.ListRequest.forDefaultPrivate; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import com.google.common.io.ByteStreams; import com.google.common.io.MoreFiles; import de.adorsys.datasafe.business.impl.e2e.metrtics.TestMetricCollector; @@ -12,16 +18,6 @@ import de.adorsys.datasafe.types.api.resource.AbsoluteLocation; import de.adorsys.datasafe.types.api.resource.ResolvedResource; import de.adorsys.datasafe.types.api.resource.Uri; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.io.TempDir; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -44,13 +40,15 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; - -import static de.adorsys.datasafe.types.api.actions.ListRequest.forDefaultPrivate; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.bouncycastle.util.encoders.Hex; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; /** * Multithreaded test of basic operations. @@ -155,7 +153,7 @@ void writeToPrivateListPrivateInDifferentThreads(WithStorageProvider.StorageDesc metricCollector.setDataSize(size); metricCollector.setStorageType(storage.getClass().getSimpleName()); metricCollector.setNumberOfThreads(poolSize); - metricCollector.writeToJSON();//json files in target folder + metricCollector.writeToJSON(); //json files in target folder deleteTestFile(testFile); } @@ -299,7 +297,7 @@ private void init(WithStorageProvider.StorageDescriptor descriptor) { protected void writeDataToFileForUser(UserIDAuth john, String filePathForWriting, Path filePathForReading, CountDownLatch latch) { try (OutputStream write = writeToPrivate.write(WriteRequest.forDefaultPrivate(john, filePathForWriting)); - FileInputStream fis = new FileInputStream(filePathForReading.toFile()) + FileInputStream fis = new FileInputStream(filePathForReading.toFile()) ) { ByteStreams.copy(fis, write); } catch (IOException e) { @@ -311,10 +309,10 @@ protected void writeDataToFileForUser(UserIDAuth john, String filePathForWriting @BeforeAll public static void setUp() { - if(System.getenv("NUMBER_OF_TEST_USERS") != null) { + if (System.getenv("NUMBER_OF_TEST_USERS") != null) { NUMBER_OF_TEST_USERS = Integer.parseInt(System.getenv("NUMBER_OF_TEST_USERS")); } - if(System.getenv("NUMBER_OF_TEST_FILES") != null) { + if (System.getenv("NUMBER_OF_TEST_FILES") != null) { NUMBER_OF_TEST_FILES = Integer.parseInt(System.getenv("NUMBER_OF_TEST_FILES")); EXPECTED_NUMBER_OF_FILES_PER_USER = NUMBER_OF_TEST_FILES; } diff --git a/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/DataTamperingResistanceIT.java b/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/DataTamperingResistanceIT.java index 65544fe61..90fab60b4 100644 --- a/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/DataTamperingResistanceIT.java +++ b/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/DataTamperingResistanceIT.java @@ -143,9 +143,9 @@ private void tamperFilenameByReplacingOneCharOfPath(AbsoluteLocation minios = new HashMap<>(); private static Map endpointsByHost = new HashMap<>(); @@ -95,17 +93,17 @@ static void initDistributedMinios() { // Create all required minio-backed S3 buckets: Stream.of(CREDENTIALS, KEYSTORE, FILES_ONE, FILES_TWO, INBOX).forEach(it -> { GenericContainer minio = new GenericContainer("minio/minio:RELEASE.2019-08-01T22-18-54Z") - .withExposedPorts(9000) - .withEnv("MINIO_ACCESS_KEY", accessKey(it)) - .withEnv("MINIO_SECRET_KEY", secretKey(it)) - .withCommand("server /data") - .waitingFor(Wait.defaultWaitStrategy()); + .withExposedPorts(9000) + .withEnv("MINIO_ACCESS_KEY", accessKey(it)) + .withEnv("MINIO_SECRET_KEY", secretKey(it)) + .withCommand("server /data") + .waitingFor(Wait.defaultWaitStrategy()); minio.start(); minios.put(it, minio); String endpoint = LOCALHOST + ":" + minio.getFirstMappedPort() + "/"; log.info("Minio `{}` with endpoint `{}` and keys `{}`/`{}` has started", - it, endpoint, accessKey(it), secretKey(it)); + it, endpoint, accessKey(it), secretKey(it)); // http://localhost:1234/eu-central-1/bucket/ endpointsByHost.put(it, endpoint + REGION + "/" + it + "/"); @@ -113,10 +111,10 @@ static void initDistributedMinios() { endpointsByHostNoBucket.put(it, endpoint); AmazonS3 client = S3ClientFactory.getClient( - endpoint, - REGION, - accessKey(it), - secretKey(it) + endpoint, + REGION, + accessKey(it), + secretKey(it) ); AwsClientRetry.createBucketWithRetry(client, it); @@ -131,42 +129,42 @@ static void stopAll() { @BeforeEach void initDatasafe() { StorageService directoryStorage = new S3StorageService( - S3ClientFactory.getClient( - endpointsByHostNoBucket.get(CREDENTIALS), - REGION, - accessKey(CREDENTIALS), - secretKey(CREDENTIALS) - ), - CREDENTIALS, - EXECUTOR + S3ClientFactory.getClient( + endpointsByHostNoBucket.get(CREDENTIALS), + REGION, + accessKey(CREDENTIALS), + secretKey(CREDENTIALS) + ), + CREDENTIALS, + EXECUTOR ); OverridesRegistry registry = new BaseOverridesRegistry(); this.datasafeServices = DaggerDefaultDatasafeServices.builder() - .config(new DefaultDFSConfig(endpointsByHost.get(CREDENTIALS), new ReadStorePassword("PAZZWORT"))) - .overridesRegistry(registry) - .storage(new RegexDelegatingStorage( - ImmutableMap.builder() - .put(Pattern.compile(endpointsByHost.get(CREDENTIALS) + ".+"), directoryStorage) - .put( - Pattern.compile(LOCALHOST + ".+"), - new UriBasedAuthStorageService( - acc -> new S3StorageService( - S3ClientFactory.getClient( - acc.getEndpoint(), - acc.getRegion(), - acc.getAccessKey(), - acc.getSecretKey() - ), - acc.getBucketName(), - EXECUTOR - ) - ) - ).build()) - ).build(); + .config(new DefaultDFSConfig(endpointsByHost.get(CREDENTIALS), new ReadStorePassword("PAZZWORT"))) + .overridesRegistry(registry) + .storage(new RegexDelegatingStorage( + ImmutableMap.builder() + .put(Pattern.compile(endpointsByHost.get(CREDENTIALS) + ".+"), directoryStorage) + .put( + Pattern.compile(LOCALHOST + ".+"), + new UriBasedAuthStorageService( + acc -> new S3StorageService( + S3ClientFactory.getClient( + acc.getEndpoint(), + acc.getRegion(), + acc.getAccessKey(), + acc.getSecretKey() + ), + acc.getBucketName(), + EXECUTOR + ) + ) + ).build()) + ).build(); BucketAccessServiceImplRuntimeDelegatable.overrideWith( - registry, args -> new WithCredentialProvider(args.getStorageKeyStoreOperations()) + registry, args -> new WithCredentialProvider(args.getStorageKeyStoreOperations()) ); } @@ -219,10 +217,10 @@ private void validateBasicOperationsAndContent(UserIDAuth john) { assertThat(listInBucket(FILES_TWO)).hasSize(1); assertThat(listInBucket(KEYSTORE)).hasSize(1); assertThat(listInBucket(CREDENTIALS)).containsExactlyInAnyOrder( - "profiles/private/john", - "profiles/public/john", - "pubkeys", - "storagecreds"); + "profiles/private/john", + "profiles/public/john", + "pubkeys", + "storagecreds"); } private void deregisterAndValidateEmpty(UserIDAuth john) { @@ -241,28 +239,28 @@ private void registerUser(UserIDAuth auth) { // User does not declare his keystore location, so we are registering his stuff separately datasafeServices.userProfile().registerPublic(CreateUserPublicProfile.builder() - .id(auth.getUserID()) - .inbox(BasePublicResource.forAbsolutePublic(inboxLocation)) - .publicKeys(BasePublicResource.forAbsolutePublic(pubKeysLocation)) - .build() + .id(auth.getUserID()) + .inbox(BasePublicResource.forAbsolutePublic(inboxLocation)) + .publicKeys(BasePublicResource.forAbsolutePublic(pubKeysLocation)) + .build() ); datasafeServices.userProfile().registerPrivate(CreateUserPrivateProfile.builder() - .id(auth) - .storageCredentialsKeystore( - BasePrivateResource.forAbsolutePrivate(endpointsByHost.get(CREDENTIALS) + "storagecreds") - ) - .inboxWithWriteAccess(BasePrivateResource.forAbsolutePrivate(inboxLocation)) - .keystore( - BasePrivateResource.forAbsolutePrivate(endpointsByHost.get(KEYSTORE) + "keystore") - ) - // filesOneBucket is default private space, it is not directly accessible without credentials - .privateStorage( - BasePrivateResource.forAbsolutePrivate(endpointsByHost.get(FILES_ONE) + "private/") - ) - .associatedResources(Collections.emptyList()) - .publishPubKeysTo(BasePublicResource.forAbsolutePublic(pubKeysLocation)) - .build() + .id(auth) + .storageCredentialsKeystore( + BasePrivateResource.forAbsolutePrivate(endpointsByHost.get(CREDENTIALS) + "storagecreds") + ) + .inboxWithWriteAccess(BasePrivateResource.forAbsolutePrivate(inboxLocation)) + .keystore( + BasePrivateResource.forAbsolutePrivate(endpointsByHost.get(KEYSTORE) + "keystore") + ) + // filesOneBucket is default private space, it is not directly accessible without credentials + .privateStorage( + BasePrivateResource.forAbsolutePrivate(endpointsByHost.get(FILES_ONE) + "private/") + ) + .associatedResources(Collections.emptyList()) + .publishPubKeysTo(BasePublicResource.forAbsolutePublic(pubKeysLocation)) + .build() ); datasafeServices.userProfile().createStorageKeystore(auth); @@ -271,14 +269,14 @@ private void registerUser(UserIDAuth auth) { String endpoint = endpointsByHost.get(it); UserPrivateProfile profile = datasafeServices.userProfile().privateProfile(auth); profile.getPrivateStorage().put( - id(it), - new AbsoluteLocation<>(BasePrivateResource.forPrivate(endpoint + "/")) + id(it), + new AbsoluteLocation<>(BasePrivateResource.forPrivate(endpoint + "/")) ); datasafeServices.userProfile().registerStorageCredentials( - auth, - id(it), - new StorageCredentials(accessKey(it), secretKey(it)) + auth, + id(it), + new StorageCredentials(accessKey(it), secretKey(it)) ); datasafeServices.userProfile().updatePrivateProfile(auth, profile); @@ -291,16 +289,16 @@ private void registerUser(UserIDAuth auth) { private List listInBucket(String bucket) { return S3ClientFactory.getClient( - endpointsByHostNoBucket.get(bucket), - REGION, - accessKey(bucket), - secretKey(bucket) - ) - .listObjects(bucket, "") - .getObjectSummaries() - .stream() - .map(S3ObjectSummary::getKey) - .collect(Collectors.toList()); + endpointsByHostNoBucket.get(bucket), + REGION, + accessKey(bucket), + secretKey(bucket) + ) + .listObjects(bucket, "") + .getObjectSummaries() + .stream() + .map(S3ObjectSummary::getKey) + .collect(Collectors.toList()); } @SneakyThrows @@ -320,7 +318,7 @@ private String readFromPrivate(UserIDAuth user, StorageIdentifier id, String pat @SneakyThrows private String readFromPrivate(UserIDAuth user, AbsoluteLocation location) { try (InputStream is = datasafeServices.privateService().read( - ReadRequest.forPrivate(user, location.getResource().asPrivate()))) { + ReadRequest.forPrivate(user, location.getResource().asPrivate()))) { return new String(Streams.readAll(is)); } } @@ -329,9 +327,9 @@ private String readFromPrivate(UserIDAuth user, AbsoluteLocation getFirstFileInPrivate(UserIDAuth user, StorageIdentifier id, String path) { return datasafeServices.privateService() - .list(ListRequest.forPrivate(user, id, path)) - .findFirst() - .orElseThrow(() -> new IllegalArgumentException("Not found")); + .list(ListRequest.forPrivate(user, id, path)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Not found")); } private static StorageIdentifier id(String endpointId) { diff --git a/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/SchemeDelegationWithDbIT.java b/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/SchemeDelegationWithDbIT.java index 59f526289..635d0f62d 100644 --- a/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/SchemeDelegationWithDbIT.java +++ b/datasafe-business/src/test/java/de/adorsys/datasafe/business/impl/e2e/SchemeDelegationWithDbIT.java @@ -1,5 +1,7 @@ package de.adorsys.datasafe.business.impl.e2e; +import static de.adorsys.datasafe.types.api.global.PathEncryptionId.AES_SIV; +import static org.assertj.core.api.Assertions.assertThat; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import de.adorsys.datasafe.business.impl.service.DaggerDefaultDatasafeServices; @@ -21,11 +23,6 @@ import de.adorsys.datasafe.types.api.resource.Uri; import de.adorsys.datasafe.types.api.types.ReadStorePassword; import de.adorsys.datasafe.types.api.utils.ReadKeyPasswordTestFactory; -import lombok.SneakyThrows; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - import java.io.OutputStream; import java.net.URI; import java.nio.file.Files; @@ -34,9 +31,10 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; - -import static de.adorsys.datasafe.types.api.global.PathEncryptionId.AES_SIV; -import static org.assertj.core.api.Assertions.assertThat; +import lombok.SneakyThrows; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; class SchemeDelegationWithDbIT extends WithStorageProvider { @@ -51,22 +49,22 @@ void initialize(@TempDir Path tempDir) { this.fsPath = tempDir; StorageService filesystem = new FileSystemStorageService(tempDir); this.db = new DatabaseStorageService(ALLOWED_TABLES, new DatabaseConnectionRegistry( - uri -> uri.location().getWrapped().getScheme() + ":" + uri.location().getPath().split("/")[1], - ImmutableMap.of("jdbc://localhost:9999", new DatabaseCredentials("sa", "sa"))) + uri -> uri.location().getWrapped().getScheme() + ":" + uri.location().getPath().split("/")[1], + ImmutableMap.of("jdbc://localhost:9999", new DatabaseCredentials("sa", "sa"))) ); StorageService multiDfs = new SchemeDelegatingStorage( - ImmutableMap.of( - "file", filesystem, - "jdbc", db - ) + ImmutableMap.of( + "file", filesystem, + "jdbc", db + ) ); this.datasafeServices = DaggerDefaultDatasafeServices - .builder() - .config(new ProfilesOnDbDataOnFs(tempDir.toUri(), URI.create("jdbc://localhost:9999/h2:mem:test/"))) - .storage(multiDfs) - .build(); + .builder() + .config(new ProfilesOnDbDataOnFs(tempDir.toUri(), URI.create("jdbc://localhost:9999/h2:mem:test/"))) + .storage(multiDfs) + .build(); } @Test @@ -79,34 +77,34 @@ void testProfileOnDbDataOnFsWorks() { // But this data - it will be saved to FS try (OutputStream os = - datasafeServices.privateService().write(WriteRequest.forDefaultPrivate(userJohn, "file.txt"))) { + datasafeServices.privateService().write(WriteRequest.forDefaultPrivate(userJohn, "file.txt"))) { os.write("Hello".getBytes()); } // Profiles are on DB assertThat(listDb("jdbc://localhost:9999/h2:mem:test/private_profiles/")) - .containsExactly("jdbc://localhost:9999/h2:mem:test/private_profiles/john"); + .containsExactly("jdbc://localhost:9999/h2:mem:test/private_profiles/john"); assertThat(listDb("jdbc://localhost:9999/h2:mem:test/public_profiles/")) - .containsExactly("jdbc://localhost:9999/h2:mem:test/public_profiles/john"); + .containsExactly("jdbc://localhost:9999/h2:mem:test/public_profiles/john"); Path path = fsPath.resolve(new Uri("users/john/private/files/").resolve(AES_SIV.asUriRoot()).asString()); Path encryptedFile = walk(path).get(1); // File and keystore/pub keys are on FS assertThat(walk(fsPath)) - .extracting(it -> fsPath.toUri().relativize(it.toUri())) - .extracting(URI::toString) - .containsExactlyInAnyOrder( - "", - "users/", - "users/john/", - "users/john/public/", - "users/john/public/pubkeys", - "users/john/private/", - "users/john/private/keystore", - "users/john/private/files/", - "users/john/private/files/SIV/", - fsPath.toUri().relativize(encryptedFile.toUri()).toString() - ); + .extracting(it -> fsPath.toUri().relativize(it.toUri())) + .extracting(URI::toString) + .containsExactlyInAnyOrder( + "", + "users/", + "users/john/", + "users/john/public/", + "users/john/public/pubkeys", + "users/john/private/", + "users/john/private/keystore", + "users/john/private/files/", + "users/john/private/files/SIV/", + fsPath.toUri().relativize(encryptedFile.toUri()).toString() + ); } @SneakyThrows @@ -117,7 +115,7 @@ private List walk(Path at) { } private List listDb(String path) { - try (Stream> stream = db.list(BasePrivateResource.forAbsolutePrivate(URI.create(path)))){ + try (Stream> stream = db.list(BasePrivateResource.forAbsolutePrivate(URI.create(path)))) { return stream.map(it -> it.location().asURI().toString()).collect(Collectors.toList()); } } @@ -134,18 +132,18 @@ static class ProfilesOnDbDataOnFs extends DefaultDFSConfig { @Override public AbsoluteLocation publicProfile(UserID forUser) { return new AbsoluteLocation<>( - BasePrivateResource.forPrivate( - profilesPath.resolve("public_profiles/").resolve(forUser.getValue()) - ) + BasePrivateResource.forPrivate( + profilesPath.resolve("public_profiles/").resolve(forUser.getValue()) + ) ); } @Override public AbsoluteLocation privateProfile(UserID forUser) { return new AbsoluteLocation<>( - BasePrivateResource.forPrivate( - profilesPath.resolve("private_profiles/").resolve(forUser.getValue()) - ) + BasePrivateResource.forPrivate( + profilesPath.resolve("private_profiles/").resolve(forUser.getValue()) + ) ); } } diff --git a/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/inbox/Inbox.java b/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/inbox/Inbox.java index 6bcb4c664..c468ebf8d 100644 --- a/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/inbox/Inbox.java +++ b/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/inbox/Inbox.java @@ -13,7 +13,7 @@ List.class, Share.class, Delete.class, -}) + }) public class Inbox implements Runnable { @Getter diff --git a/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/inbox/Share.java b/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/inbox/Share.java index e64dc360e..4d4277f82 100644 --- a/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/inbox/Share.java +++ b/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/inbox/Share.java @@ -47,7 +47,7 @@ public void run() { filename ) ); - InputStream is = MoreFiles.asByteSource(path, StandardOpenOption.READ).openStream() + InputStream is = MoreFiles.asByteSource(path, StandardOpenOption.READ).openStream() ) { ByteStreams.copy(is, os); } diff --git a/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/privatespace/Copy.java b/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/privatespace/Copy.java index 3455fecb0..a6a8c6d38 100644 --- a/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/privatespace/Copy.java +++ b/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/privatespace/Copy.java @@ -42,7 +42,7 @@ public void run() { to ) ); - InputStream is = MoreFiles.asByteSource(from, StandardOpenOption.READ).openStream() + InputStream is = MoreFiles.asByteSource(from, StandardOpenOption.READ).openStream() ) { ByteStreams.copy(is, os); } diff --git a/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/privatespace/Privatespace.java b/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/privatespace/Privatespace.java index c60753d9c..88a1c4761 100644 --- a/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/privatespace/Privatespace.java +++ b/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/commands/privatespace/Privatespace.java @@ -12,7 +12,7 @@ Copy.class, List.class, Delete.class, -}) + }) public class Privatespace implements Runnable { @Getter diff --git a/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/hacks/graalfeature/GraalCompileFixNpeOnMissingServiceTypeInKnownProviders.java b/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/hacks/graalfeature/GraalCompileFixNpeOnMissingServiceTypeInKnownProviders.java index 96152628e..99d56d86e 100644 --- a/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/hacks/graalfeature/GraalCompileFixNpeOnMissingServiceTypeInKnownProviders.java +++ b/datasafe-cli/src/main/java/de/adorsys/datasafe/cli/hacks/graalfeature/GraalCompileFixNpeOnMissingServiceTypeInKnownProviders.java @@ -21,12 +21,12 @@ /** * This class fixes NPE exception in Graal-compilator - when it tries to get non-existing engines from * {@link java.security.Provider} - *

    - * Additionally can log access to null service types using property PROVIDER_ACCESS_LOGGER, + * + *

    Additionally can log access to null service types using property PROVIDER_ACCESS_LOGGER, * so you can add necessary fields to extra_engines.hack. (This will break build later, so you will need * to remove this property when you detected all nulls in Provider). - *

    - * Override string example: + * + *

    Override string example: * X509Store=false,null */ @AutomaticFeature @@ -39,8 +39,8 @@ public void afterRegistration(AfterRegistrationAccess access) { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); try (InputStream is = classloader.getResourceAsStream("extra_engines.hack"); - InputStreamReader streamReader = new InputStreamReader(is, StandardCharsets.UTF_8); - BufferedReader reader = new BufferedReader(streamReader)) { + InputStreamReader streamReader = new InputStreamReader(is, StandardCharsets.UTF_8); + BufferedReader reader = new BufferedReader(streamReader)) { reader.lines().forEach(it -> { System.out.println("Overriding " + it); String[] typeAndValue = it.split("="); @@ -86,8 +86,8 @@ private void addEngineInternal(String name, String sp, String paramNam) throws @SuppressWarnings("unchecked") Map originalEngine = (Map) knownEngines.get(null); - Map delegate = null != System.getProperty(PROVIDER_ACCESS_LOGGER) - ? new EngineDelegate(originalEngine) : originalEngine; + Map delegate = null != System.getProperty(PROVIDER_ACCESS_LOGGER) ? + new EngineDelegate(originalEngine) : originalEngine; knownEngines.set(Map.class, delegate); diff --git a/datasafe-directory/datasafe-directory-api/src/main/java/de/adorsys/datasafe/directory/api/types/UserPrivateProfile.java b/datasafe-directory/datasafe-directory-api/src/main/java/de/adorsys/datasafe/directory/api/types/UserPrivateProfile.java index ea08bfca6..122a7822f 100644 --- a/datasafe-directory/datasafe-directory-api/src/main/java/de/adorsys/datasafe/directory/api/types/UserPrivateProfile.java +++ b/datasafe-directory/datasafe-directory-api/src/main/java/de/adorsys/datasafe/directory/api/types/UserPrivateProfile.java @@ -17,7 +17,7 @@ */ @Data @Builder(toBuilder = true) -public class UserPrivateProfile{ +public class UserPrivateProfile { /** * Users' keystore location diff --git a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/dfs/BucketAccessServiceImpl.java b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/dfs/BucketAccessServiceImpl.java index 6d9a9d976..d244ced0a 100644 --- a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/dfs/BucketAccessServiceImpl.java +++ b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/dfs/BucketAccessServiceImpl.java @@ -19,7 +19,7 @@ * 1. To add user-specific credentials, if it is 1 user per bucket or similar * 2. To redirect requests * - * By default is no-op - simply wraps resource into {@link AbsoluteLocation} + *

    By default is no-op - simply wraps resource into {@link AbsoluteLocation} */ @Slf4j @RuntimeDelegate diff --git a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/dfs/RegexAccessServiceWithStorageCredentialsImpl.java b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/dfs/RegexAccessServiceWithStorageCredentialsImpl.java index fb2aca55d..1d791dc94 100644 --- a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/dfs/RegexAccessServiceWithStorageCredentialsImpl.java +++ b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/dfs/RegexAccessServiceWithStorageCredentialsImpl.java @@ -82,8 +82,8 @@ private Optional getStorageAccessCredentials(UserIDAuth user, .filter(it -> uri.matches(it.getId())) .findFirst(); - return directMatch.isPresent() - ? directMatch + return directMatch.isPresent() ? + directMatch : aliases.stream().filter(it -> StorageIdentifier.DEFAULT.getId().equals(it.getId())).findFirst(); } } diff --git a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/DFSPrivateKeyServiceImpl.java b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/DFSPrivateKeyServiceImpl.java index 9df1a2b23..ac481489b 100644 --- a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/DFSPrivateKeyServiceImpl.java +++ b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/DFSPrivateKeyServiceImpl.java @@ -75,9 +75,9 @@ public void validateUserHasAccessOrThrow(UserIDAuth forUser) { keyByPrefix(forUser, DOCUMENT_KEY_ID_PREFIX); // for access check } catch (RuntimeException ex) { // lombok @SneakyThrows handling - if (ex.getCause() instanceof KeyStoreException - || ex.getCause() instanceof UnrecoverableKeyException - || ex.getCause() instanceof BadPaddingException) { + if (ex.getCause() instanceof KeyStoreException || + ex.getCause() instanceof UnrecoverableKeyException || + ex.getCause() instanceof BadPaddingException) { throw ex.getCause(); } diff --git a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/StorageKeyStoreOperationsImpl.java b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/StorageKeyStoreOperationsImpl.java index a6a4f6ba1..98a622418 100644 --- a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/StorageKeyStoreOperationsImpl.java +++ b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/StorageKeyStoreOperationsImpl.java @@ -101,10 +101,10 @@ public void createAndWriteKeystore(UserIDAuth forUser) { AbsoluteLocation location = keystoreLocationWithAccess(forUser); genericOper.writeKeystore( - forUser.getUserID(), - genericOper.keystoreAuth(forUser), - location, - newKeystore(forUser) + forUser.getUserID(), + genericOper.keystoreAuth(forUser), + location, + newKeystore(forUser) ); } diff --git a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/UserKeyStoreCache.java b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/UserKeyStoreCache.java index f59739d0c..7c3304fef 100644 --- a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/UserKeyStoreCache.java +++ b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/keys/UserKeyStoreCache.java @@ -59,7 +59,9 @@ public KeyStore computeIfAbsent(UserIDAuth userIDAuth, Function { + private interface ExcludeComputeIfAbsent { KeyStore computeIfAbsent(UserID key, Function mappingFunction); } } diff --git a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/operations/actions/ProfileRegistrationServiceImpl.java b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/operations/actions/ProfileRegistrationServiceImpl.java index 3ee10a623..5e8576b61 100644 --- a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/operations/actions/ProfileRegistrationServiceImpl.java +++ b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/operations/actions/ProfileRegistrationServiceImpl.java @@ -95,8 +95,8 @@ public void createAllAllowableKeystores(UserIDAuth user, UserPrivateProfile prof @Override public void createDocumentKeystore(UserIDAuth user, UserPrivateProfile profile) { publishPublicKeysIfNeeded( - profile.getPublishPublicKeysTo(), - keyStoreOper.createAndWriteKeyStore(user) + profile.getPublishPublicKeysTo(), + keyStoreOper.createAndWriteKeyStore(user) ); } diff --git a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/operations/actions/ProfileStoreService.java b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/operations/actions/ProfileStoreService.java index f7b867eec..60426d72f 100644 --- a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/operations/actions/ProfileStoreService.java +++ b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/operations/actions/ProfileStoreService.java @@ -40,7 +40,7 @@ public ProfileStoreService(GsonSerde serde, UserProfileCache profileCache, DFSCo public void registerPrivate(UserID id, UserPrivateProfile profile) { log.debug("Register private {}", profile); try (OutputStream os = writeService.write( - WithCallback.noCallback(access.withSystemAccess(dfsConfig.privateProfile(id)))) + WithCallback.noCallback(access.withSystemAccess(dfsConfig.privateProfile(id)))) ) { os.write(serde.toJson(profile).getBytes()); } @@ -51,7 +51,7 @@ public void registerPrivate(UserID id, UserPrivateProfile profile) { public void registerPublic(UserID id, UserPublicProfile profile) { log.debug("Register public {}", profile); try (OutputStream os = writeService.write( - WithCallback.noCallback(access.withSystemAccess(dfsConfig.publicProfile(id)))) + WithCallback.noCallback(access.withSystemAccess(dfsConfig.publicProfile(id)))) ) { os.write(serde.toJson(profile).getBytes()); } diff --git a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/resource/ResourceResolverImpl.java b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/resource/ResourceResolverImpl.java index b6ebd276c..2adf54c3e 100644 --- a/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/resource/ResourceResolverImpl.java +++ b/datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/resource/ResourceResolverImpl.java @@ -36,7 +36,7 @@ public ResourceResolverImpl(ProfileRetrievalService profile, BucketAccessService */ @Override public AbsoluteLocation resolveRelativeToPublicInbox( - UserID userID, PublicResource resource) { + UserID userID, PublicResource resource) { return bucketAccessService.publicAccessFor( userID, @@ -51,7 +51,7 @@ public AbsoluteLocation resolveRelativeToPublicInbox( */ @Override public AbsoluteLocation resolveRelativeToPrivateInbox( - UserIDAuth userID, PrivateResource resource) { + UserIDAuth userID, PrivateResource resource) { return bucketAccessService.privateAccessFor( userID, @@ -64,7 +64,7 @@ public AbsoluteLocation resolveRelativeToPrivateInbox( */ @Override public AbsoluteLocation resolveRelativeToPrivate( - UserIDAuth userID, PrivateResource resource, StorageIdentifier identifier) { + UserIDAuth userID, PrivateResource resource, StorageIdentifier identifier) { return bucketAccessService.privateAccessFor( userID, @@ -81,7 +81,7 @@ public > boolean isAbsolute(T resource) { } private > T resolveRelative( - T resource, Supplier> resolveTo) { + T resource, Supplier> resolveTo) { if (isAbsolute(resource)) { return resource; } diff --git a/datasafe-directory/datasafe-directory-impl/src/test/java/de/adorsys/datasafe/directory/impl/profile/keys/DFSPrivateKeyServiceImplTest.java b/datasafe-directory/datasafe-directory-impl/src/test/java/de/adorsys/datasafe/directory/impl/profile/keys/DFSPrivateKeyServiceImplTest.java index 4e250960e..2178a40f9 100644 --- a/datasafe-directory/datasafe-directory-impl/src/test/java/de/adorsys/datasafe/directory/impl/profile/keys/DFSPrivateKeyServiceImplTest.java +++ b/datasafe-directory/datasafe-directory-impl/src/test/java/de/adorsys/datasafe/directory/impl/profile/keys/DFSPrivateKeyServiceImplTest.java @@ -25,6 +25,7 @@ public class DFSPrivateKeyServiceImplTest extends BaseMockitoTest { @Mock private KeyStoreService keyStoreService; DFSPrivateKeyServiceImpl privateKeyService; + @BeforeEach public void setUp() { privateKeyService = new DFSPrivateKeyServiceImpl(keyStoreOper); @@ -32,7 +33,7 @@ public void setUp() { @Test @SneakyThrows - public void getKeyPair(){ + public void getKeyPair() { ReadKeyPassword readKeyPassword = new ReadKeyPassword("keypass".toCharArray()); UserID user = new UserID("user1"); UserIDAuth userAuth = new UserIDAuth(user, readKeyPassword); diff --git a/datasafe-encryption/datasafe-encryption-api/src/main/java/de/adorsys/datasafe/encrypiton/api/types/encryption/MutableEncryptionConfig.java b/datasafe-encryption/datasafe-encryption-api/src/main/java/de/adorsys/datasafe/encrypiton/api/types/encryption/MutableEncryptionConfig.java index 7c13e358c..c69e282dd 100644 --- a/datasafe-encryption/datasafe-encryption-api/src/main/java/de/adorsys/datasafe/encrypiton/api/types/encryption/MutableEncryptionConfig.java +++ b/datasafe-encryption/datasafe-encryption-api/src/main/java/de/adorsys/datasafe/encrypiton/api/types/encryption/MutableEncryptionConfig.java @@ -201,7 +201,7 @@ KeyCreationConfig.EncryptingKeyCreationCfg toEncryptingKeyCreationCfg() { } - builder.curve(curve); + builder.curve(curve); return builder.build(); @@ -232,7 +232,7 @@ KeyCreationConfig.SigningKeyCreationCfg toSigningKeyCreationCfg() { } - builder.curve(curve); + builder.curve(curve); return builder.build(); diff --git a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/decryptors/KekDecryptor.java b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/decryptors/KekDecryptor.java index 7b7b45cae..ec20033f9 100644 --- a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/decryptors/KekDecryptor.java +++ b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/decryptors/KekDecryptor.java @@ -28,7 +28,7 @@ class KekDecryptor extends Decryptor { @Override @SneakyThrows public InputStream decryptionStream(Key key) { - return recipientInfo + return recipientInfo .getContentStream(new JceKEKEnvelopedRecipient((SecretKey) key)) .getContentStream(); } diff --git a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/document/CMSDocumentReadService.java b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/document/CMSDocumentReadService.java index b5ac6c8ed..2aeaded0d 100644 --- a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/document/CMSDocumentReadService.java +++ b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/document/CMSDocumentReadService.java @@ -58,6 +58,7 @@ public InputStream read(ReadRequest streamsToClose; + @Override public int read(byte[] b, int off, int len) throws IOException { return streamToRead.read(b, off, len); @@ -88,4 +89,5 @@ private static void doClose(InputStream stream, List exceptions) { exceptions.add(ex); } } - }} + } +} diff --git a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/keystore/KeyStoreServiceImpl.java b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/keystore/KeyStoreServiceImpl.java index 6044df2ae..b2a17d9dd 100644 --- a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/keystore/KeyStoreServiceImpl.java +++ b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/keystore/KeyStoreServiceImpl.java @@ -136,7 +136,9 @@ public List getPublicKeys(KeyStoreAccess keyStoreAcces for (Enumeration keyAliases = keyStore.aliases(); keyAliases.hasMoreElements(); ) { final String keyAlias = keyAliases.nextElement(); X509Certificate cert = (X509Certificate) keyStore.getCertificate(keyAlias); - if (cert == null) continue; // skip + if (cert == null) { + continue; // skip + } boolean[] keyUsage = cert.getKeyUsage(); // digitalSignature (0), nonRepudiation (1), keyEncipherment (2), dataEncipherment (3), // keyAgreement (4), keyCertSign (5), cRLSign (6), encipherOnly (7), decipherOnly (8) diff --git a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/keystore/PublicKeySerdeImpl.java b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/keystore/PublicKeySerdeImpl.java index a688b0836..105197d23 100644 --- a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/keystore/PublicKeySerdeImpl.java +++ b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/keystore/PublicKeySerdeImpl.java @@ -33,7 +33,8 @@ public PublicKey readPubKey(String encoded) { byte[] bytes = Base64.getDecoder().decode(encoded); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(bytes); if (RSA.equals(subjectPublicKeyInfo.getAlgorithm().getAlgorithm())) { - return new org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi().generatePublic(SubjectPublicKeyInfo.getInstance(bytes)); + return new org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi() + .generatePublic(SubjectPublicKeyInfo.getInstance(bytes)); } else if (EC.equals(subjectPublicKeyInfo.getAlgorithm().getAlgorithm())) { return new org.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi.ECDH().generatePublic(subjectPublicKeyInfo); } diff --git a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/pathencryption/IntegrityPreservingUriEncryption.java b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/pathencryption/IntegrityPreservingUriEncryption.java index f24d11f7f..04ab8be98 100644 --- a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/pathencryption/IntegrityPreservingUriEncryption.java +++ b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/pathencryption/IntegrityPreservingUriEncryption.java @@ -93,10 +93,10 @@ protected MessageDigest getDigest() { protected String decryptorAndDecoder(PathSegmentWithSecretKeyWith keyAndSegment, PathEncryptorDecryptor pathEncryptorDecryptor) { - byte[] segment = keyAndSegment.getPath().getBytes(StandardCharsets.UTF_8); - keyAndSegment.getDigest().update(segment); + byte[] segment = keyAndSegment.getPath().getBytes(StandardCharsets.UTF_8); + keyAndSegment.getDigest().update(segment); - return new String( + return new String( pathEncryptorDecryptor.decrypt( keyAndSegment.getPathEncryptionSecretKey(), decode(keyAndSegment.getPath()), diff --git a/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/CmsEncryptionServiceImplTest.java b/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/CmsEncryptionServiceImplTest.java index a46bd2a37..3d58e962e 100644 --- a/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/CmsEncryptionServiceImplTest.java +++ b/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/CmsEncryptionServiceImplTest.java @@ -94,7 +94,7 @@ void testCmsStreamEnvelopeEncryptAndDecryptTestWithMultipleRecipients() { byte[] byteArray = outputStream.toByteArray(); - for(KeyStoreAccess keyStoreAccessItem : Arrays.asList(keyStoreAccess1, keyStoreAccess2)) { + for (KeyStoreAccess keyStoreAccessItem : Arrays.asList(keyStoreAccess1, keyStoreAccess2)) { ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray); InputStream decryptionStream = cmsEncryptionService.buildDecryptionInputStream(inputStream, keyIds -> getKeys(keyIds, keyStoreAccessItem)); @@ -151,7 +151,7 @@ void cmsStreamEnvelopeEncryptAndDecryptTestCustom() { KeyStoreAuth keyStoreAuth = new KeyStoreAuth(readStorePassword, readKeyPassword); KeyCreationConfig config = KeyCreationConfig.builder() - .signing(KeyCreationConfig.SigningKeyCreationCfg.builder().algo("RSA").size(2048).sigAlgo( "SHA256withRSA").curve(null).build()) + .signing(KeyCreationConfig.SigningKeyCreationCfg.builder().algo("RSA").size(2048).sigAlgo("SHA256withRSA").curve(null).build()) .encrypting(KeyCreationConfig.EncryptingKeyCreationCfg.builder().algo("RSA").size(2048).sigAlgo("SHA256withRSA").curve(null).build()) .build(); diff --git a/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/SymetricEncryptionTest.java b/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/SymetricEncryptionTest.java index 84299d2f7..211abaa3f 100644 --- a/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/SymetricEncryptionTest.java +++ b/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/SymetricEncryptionTest.java @@ -91,7 +91,7 @@ void symetricNegativeStreamEncryptAndDecryptTest() { ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray); // Opening envelope with wrong key must throw a cms exception. Assertions.assertThrows(CMSException.class, () -> - cmsEncryptionService.buildDecryptionInputStream(inputStream, keyIds -> getKeys(keyIds, keyStoreAccess)) + cmsEncryptionService.buildDecryptionInputStream(inputStream, keyIds -> getKeys(keyIds, keyStoreAccess)) ); } diff --git a/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/keystore/KeyStoreServiceTest.java b/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/keystore/KeyStoreServiceTest.java index bf8f4f800..aec71b1e8 100644 --- a/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/keystore/KeyStoreServiceTest.java +++ b/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/keystore/KeyStoreServiceTest.java @@ -125,9 +125,9 @@ void getPrivateKeyException() throws Exception { KeyStoreAccess keyStoreAccess = new KeyStoreAccess(keyStore, keyStoreAuth); List list = Collections.list(keyStore.aliases()); Assertions.assertThrows(ClassCastException.class, () -> { - for(String id : list) { - keyStoreService.getPrivateKey(keyStoreAccess, new KeyID(id)); - } + for (String id : list) { + keyStoreService.getPrivateKey(keyStoreAccess, new KeyID(id)); + } }); } diff --git a/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/keystore/PublicKeySerdeImplTest.java b/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/keystore/PublicKeySerdeImplTest.java index 3d761cbdb..e75884862 100644 --- a/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/keystore/PublicKeySerdeImplTest.java +++ b/datasafe-encryption/datasafe-encryption-impl/src/test/java/de/adorsys/datasafe/encrypiton/impl/keystore/PublicKeySerdeImplTest.java @@ -31,7 +31,7 @@ public class PublicKeySerdeImplTest extends BaseMockitoTest { ); @Test - public void writeAndReadPubKey(){ + public void writeAndReadPubKey() { ReadStorePassword readStorePassword = new ReadStorePassword("storepass"); ReadKeyPassword readKeyPassword = ReadKeyPasswordTestFactory.getForString("keypass"); diff --git a/datasafe-examples/datasafe-examples-business/src/test/java/de/adorsys/datasafe/examples/business/filesystem/BaseUserOperationsTestWithVersionedDatasafeTest.java b/datasafe-examples/datasafe-examples-business/src/test/java/de/adorsys/datasafe/examples/business/filesystem/BaseUserOperationsTestWithVersionedDatasafeTest.java index 78e64bbb6..fb0c37524 100644 --- a/datasafe-examples/datasafe-examples-business/src/test/java/de/adorsys/datasafe/examples/business/filesystem/BaseUserOperationsTestWithVersionedDatasafeTest.java +++ b/datasafe-examples/datasafe-examples-business/src/test/java/de/adorsys/datasafe/examples/business/filesystem/BaseUserOperationsTestWithVersionedDatasafeTest.java @@ -1,5 +1,6 @@ package de.adorsys.datasafe.examples.business.filesystem; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import de.adorsys.datasafe.business.impl.service.DaggerVersionedDatasafeServices; import de.adorsys.datasafe.business.impl.service.VersionedDatasafeServices; import de.adorsys.datasafe.directory.impl.profile.config.DefaultDFSConfig; @@ -15,11 +16,6 @@ import de.adorsys.datasafe.types.api.resource.ResolvedResource; import de.adorsys.datasafe.types.api.resource.Versioned; import de.adorsys.datasafe.types.api.utils.ReadKeyPasswordTestFactory; -import lombok.SneakyThrows; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Path; @@ -27,8 +23,10 @@ import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; - -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import lombok.SneakyThrows; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * This test shows simplistic usage of Datasafe versioned services that reside on filesystem. @@ -96,7 +94,7 @@ void writeFileToVersionedPrivateSpace() { ).hasContent("Hello 3"); // but there are 3 versions of file stored physically in users' privatespace: assertThat(versionedServices.privateService().list( - ListRequest.forDefaultPrivate(user, "my/own/file.txt")) + ListRequest.forDefaultPrivate(user, "my/own/file.txt")) ).hasSize(3); // and still only one file visible on latest view assertThat(versionedServices.latestPrivate().list(ListRequest.forDefaultPrivate(user, ""))).hasSize(1); @@ -105,18 +103,18 @@ void writeFileToVersionedPrivateSpace() { // BEGIN_SNIPPET:Lets check how to read oldest file version // so lets collect all versions List, PrivateResource, DFSVersion>> withVersions = - versionedServices.versionInfo().versionsOf( - ListRequest.forDefaultPrivate(user, "my/own/file.txt") - ).collect(Collectors.toList()); + versionedServices.versionInfo().versionsOf( + ListRequest.forDefaultPrivate(user, "my/own/file.txt") + ).collect(Collectors.toList()); // so that we can find oldest Versioned, PrivateResource, DFSVersion> oldest = - withVersions.stream() - .sorted(Comparator.comparing(it -> it.absolute().getResource().getModifiedAt())) - .collect(Collectors.toList()) - .get(0); + withVersions.stream() + .sorted(Comparator.comparing(it -> it.absolute().getResource().getModifiedAt())) + .collect(Collectors.toList()) + .get(0); // and read oldest content assertThat(versionedServices.privateService() - .read(ReadRequest.forPrivate(user, oldest.absolute().getResource().asPrivate())) + .read(ReadRequest.forPrivate(user, oldest.absolute().getResource().asPrivate())) ).hasContent("Hello 1"); // END_SNIPPET } diff --git a/datasafe-examples/datasafe-examples-customize-dagger/src/test/java/de/adorsys/datasafe/examples/business/filesystem/CustomlyBuiltDatasafeServiceTest.java b/datasafe-examples/datasafe-examples-customize-dagger/src/test/java/de/adorsys/datasafe/examples/business/filesystem/CustomlyBuiltDatasafeServiceTest.java index 8b6d3061d..6bc1897d6 100644 --- a/datasafe-examples/datasafe-examples-customize-dagger/src/test/java/de/adorsys/datasafe/examples/business/filesystem/CustomlyBuiltDatasafeServiceTest.java +++ b/datasafe-examples/datasafe-examples-customize-dagger/src/test/java/de/adorsys/datasafe/examples/business/filesystem/CustomlyBuiltDatasafeServiceTest.java @@ -39,7 +39,7 @@ void testPathEncryptionOverridden(@TempDir Path root) { // not using lombok private List walk(Path root) { - try (Stream result = Files.walk(root)){ + try (Stream result = Files.walk(root)) { return result.collect(Collectors.toList()); } catch (IOException ex) { throw new IllegalStateException("IOException", ex); diff --git a/datasafe-examples/datasafe-examples-multidfs/src/test/java/de/adorsys/datasafe/examples/business/s3/MultiDfsWithCredentialsExampleIT.java b/datasafe-examples/datasafe-examples-multidfs/src/test/java/de/adorsys/datasafe/examples/business/s3/MultiDfsWithCredentialsExampleIT.java index 29b7e5f36..668c119c0 100644 --- a/datasafe-examples/datasafe-examples-multidfs/src/test/java/de/adorsys/datasafe/examples/business/s3/MultiDfsWithCredentialsExampleIT.java +++ b/datasafe-examples/datasafe-examples-multidfs/src/test/java/de/adorsys/datasafe/examples/business/s3/MultiDfsWithCredentialsExampleIT.java @@ -1,5 +1,9 @@ package de.adorsys.datasafe.examples.business.s3; +import static de.adorsys.datasafe.examples.business.s3.MinioContainerId.DIRECTORY_BUCKET; +import static de.adorsys.datasafe.examples.business.s3.MinioContainerId.FILES_BUCKET_ONE; +import static de.adorsys.datasafe.examples.business.s3.MinioContainerId.FILES_BUCKET_TWO; +import static org.assertj.core.api.Assertions.assertThat; import com.amazonaws.services.s3.AmazonS3; import dagger.Lazy; import de.adorsys.datasafe.business.impl.service.DaggerDefaultDatasafeServices; @@ -26,16 +30,6 @@ import de.adorsys.datasafe.types.api.resource.StorageIdentifier; import de.adorsys.datasafe.types.api.shared.AwsClientRetry; import de.adorsys.datasafe.types.api.utils.ExecutorServiceUtil; -import lombok.SneakyThrows; -import lombok.experimental.Delegate; -import lombok.extern.slf4j.Slf4j; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.wait.strategy.Wait; -import org.testcontainers.shaded.com.google.common.collect.ImmutableMap; - import java.io.OutputStream; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -45,11 +39,15 @@ import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.regex.Pattern; - -import static de.adorsys.datasafe.examples.business.s3.MinioContainerId.DIRECTORY_BUCKET; -import static de.adorsys.datasafe.examples.business.s3.MinioContainerId.FILES_BUCKET_ONE; -import static de.adorsys.datasafe.examples.business.s3.MinioContainerId.FILES_BUCKET_TWO; -import static org.assertj.core.api.Assertions.assertThat; +import lombok.SneakyThrows; +import lombok.experimental.Delegate; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.shaded.com.google.common.collect.ImmutableMap; /** * This example shows how client can register storage system and securely store its access details. @@ -58,7 +56,7 @@ * filesBucketOne, filesBucketTwo. */ @Slf4j -class MultiDfsWithCredentialsExampleIT{ +class MultiDfsWithCredentialsExampleIT { private static final String REGION = "eu-central-1"; private static final ExecutorService EXECUTOR = ExecutorServiceUtil.submitterExecutesOnStarvationExecutingService(4, 4); @@ -122,25 +120,25 @@ void testMultiUserStorageUserSetup() { .storage( new RegexDelegatingStorage( ImmutableMap.builder() - // bind URI that contains `directoryBucket` to directoryStorage - .put(Pattern.compile(directoryBucketS3Uri + ".+"), directoryStorage) - .put( - Pattern.compile(getDockerUri("http://127.0.0.1") + ".+"), - // Dynamically creates S3 client with bucket name equal to host value - new UriBasedAuthStorageService( - acc -> new S3StorageService( - S3ClientFactory.getClient( - acc.getEndpoint(), - acc.getRegion(), - acc.getAccessKey(), - acc.getSecretKey() - ), - // Bucket name is encoded in first path segment - acc.getBucketName(), - EXECUTOR - ) - ) - ).build() + // bind URI that contains `directoryBucket` to directoryStorage + .put(Pattern.compile(directoryBucketS3Uri + ".+"), directoryStorage) + .put( + Pattern.compile(getDockerUri("http://127.0.0.1") + ".+"), + // Dynamically creates S3 client with bucket name equal to host value + new UriBasedAuthStorageService( + acc -> new S3StorageService( + S3ClientFactory.getClient( + acc.getEndpoint(), + acc.getRegion(), + acc.getAccessKey(), + acc.getSecretKey() + ), + // Bucket name is encoded in first path segment + acc.getBucketName(), + EXECUTOR + ) + ) + ).build() ) ) .overridesRegistry(registry) @@ -148,7 +146,7 @@ void testMultiUserStorageUserSetup() { // Instead of default BucketAccessService we will use service that reads storage access credentials from // keystore BucketAccessServiceImplRuntimeDelegatable.overrideWith( - registry, args -> new WithCredentialProvider(args.getStorageKeyStoreOperations()) + registry, args -> new WithCredentialProvider(args.getStorageKeyStoreOperations()) ); // John will have all his private files stored on `filesBucketOne` and `filesBucketOne`. @@ -165,12 +163,12 @@ void testMultiUserStorageUserSetup() { // Set location for John's credentials keystore and put storage credentials into it: UserPrivateProfile profile = multiDfsDatasafe.userProfile().privateProfile(john); profile.getPrivateStorage().put( - bucketOne, - new AbsoluteLocation<>(BasePrivateResource.forPrivate(endpointsByHost.get(FILES_BUCKET_ONE) + "/")) + bucketOne, + new AbsoluteLocation<>(BasePrivateResource.forPrivate(endpointsByHost.get(FILES_BUCKET_ONE) + "/")) ); profile.getPrivateStorage().put( - bucketTwo, - new AbsoluteLocation<>(BasePrivateResource.forPrivate(endpointsByHost.get(FILES_BUCKET_TWO) + "/")) + bucketTwo, + new AbsoluteLocation<>(BasePrivateResource.forPrivate(endpointsByHost.get(FILES_BUCKET_TWO) + "/")) ); multiDfsDatasafe.userProfile().updatePrivateProfile(john, profile); diff --git a/datasafe-examples/datasafe-examples-versioned-s3/src/test/java/de/adorsys/datasafe/examples/business/s3/BaseUserOperationsWithDefaultDatasafeOnVersionedStorageIT.java b/datasafe-examples/datasafe-examples-versioned-s3/src/test/java/de/adorsys/datasafe/examples/business/s3/BaseUserOperationsWithDefaultDatasafeOnVersionedStorageIT.java index c8429a2cb..0258e85d6 100644 --- a/datasafe-examples/datasafe-examples-versioned-s3/src/test/java/de/adorsys/datasafe/examples/business/s3/BaseUserOperationsWithDefaultDatasafeOnVersionedStorageIT.java +++ b/datasafe-examples/datasafe-examples-versioned-s3/src/test/java/de/adorsys/datasafe/examples/business/s3/BaseUserOperationsWithDefaultDatasafeOnVersionedStorageIT.java @@ -43,7 +43,7 @@ */ @Slf4j @DisabledIfSystemProperty(named = "SKIP_CEPH", matches = "true") -class BaseUserOperationsWithDefaultDatasafeOnVersionedStorageIT{ +class BaseUserOperationsWithDefaultDatasafeOnVersionedStorageIT { private static final String MY_OWN_FILE_TXT = "my/own/file.txt"; diff --git a/datasafe-long-run-tests/datasafe-business-tests-random-actions/src/test/java/de/adorsys/datasafe/business/impl/e2e/randomactions/RandomActionsOnSimpleDatasafeAdapterIT.java b/datasafe-long-run-tests/datasafe-business-tests-random-actions/src/test/java/de/adorsys/datasafe/business/impl/e2e/randomactions/RandomActionsOnSimpleDatasafeAdapterIT.java index e677c74c4..e675a1690 100644 --- a/datasafe-long-run-tests/datasafe-business-tests-random-actions/src/test/java/de/adorsys/datasafe/business/impl/e2e/randomactions/RandomActionsOnSimpleDatasafeAdapterIT.java +++ b/datasafe-long-run-tests/datasafe-business-tests-random-actions/src/test/java/de/adorsys/datasafe/business/impl/e2e/randomactions/RandomActionsOnSimpleDatasafeAdapterIT.java @@ -91,7 +91,7 @@ void testRandomActionsParallelThreads(StorageDescriptor descriptor, int threadCo private DefaultDatasafeServices datasafeServicesFromSimpleDatasafeAdapter(StorageDescriptor descriptor) { SimpleDatasafeService datasafeService = new SimpleDatasafeServiceImpl( - DFSTestCredentialsFactory.credentials(descriptor), new MutableEncryptionConfig(), new PathEncryptionConfig(true) + DFSTestCredentialsFactory.credentials(descriptor), new MutableEncryptionConfig(), new PathEncryptionConfig(true) ); return new DefaultDatasafeServices() { diff --git a/datasafe-long-run-tests/datasafe-business-tests-random-actions/src/test/java/de/adorsys/datasafe/business/impl/e2e/randomactions/framework/BaseRandomActions.java b/datasafe-long-run-tests/datasafe-business-tests-random-actions/src/test/java/de/adorsys/datasafe/business/impl/e2e/randomactions/framework/BaseRandomActions.java index 367eaeb10..a6a356034 100644 --- a/datasafe-long-run-tests/datasafe-business-tests-random-actions/src/test/java/de/adorsys/datasafe/business/impl/e2e/randomactions/framework/BaseRandomActions.java +++ b/datasafe-long-run-tests/datasafe-business-tests-random-actions/src/test/java/de/adorsys/datasafe/business/impl/e2e/randomactions/framework/BaseRandomActions.java @@ -86,7 +86,7 @@ void prepare() { } protected Fixture getFixture() { - switch(FIXTURE_SIZE) { + switch (FIXTURE_SIZE) { case "MEDIUM" : return fixture("fixture/fixture_1000_ops.json"); case "LARGE" : return fixture("fixture/fixture_10000_ops.json"); default : return fixture("fixture/fixture_200_ops.json"); @@ -94,7 +94,7 @@ protected Fixture getFixture() { } protected Fixture getSimpleDatasafeAdapterFixture() { - switch(FIXTURE_SIZE) { + switch (FIXTURE_SIZE) { case "MEDIUM" : return fixture("fixture/fixture_simple_datasafe_1000_ops.json"); case "LARGE" : return fixture("fixture/fixture_simple_datasafe_10000_ops.json"); default : return fixture("fixture/fixture_simple_datasafe_200_ops.json"); diff --git a/datasafe-metainfo/datasafe-metainfo-version-impl/src/main/java/de/adorsys/datasafe/metainfo/version/impl/version/latest/EncryptedLatestLinkServiceImpl.java b/datasafe-metainfo/datasafe-metainfo-version-impl/src/main/java/de/adorsys/datasafe/metainfo/version/impl/version/latest/EncryptedLatestLinkServiceImpl.java index 7062b7513..7b86d5822 100644 --- a/datasafe-metainfo/datasafe-metainfo-version-impl/src/main/java/de/adorsys/datasafe/metainfo/version/impl/version/latest/EncryptedLatestLinkServiceImpl.java +++ b/datasafe-metainfo/datasafe-metainfo-version-impl/src/main/java/de/adorsys/datasafe/metainfo/version/impl/version/latest/EncryptedLatestLinkServiceImpl.java @@ -68,7 +68,7 @@ public AbsoluteLocation resolveLatestLinkLocation( @Override public Function, AbsoluteLocation> linkDecryptingReader( - UserIDAuth owner, StorageIdentifier identifier) { + UserIDAuth owner, StorageIdentifier identifier) { UserPrivateProfile privateProfile = profiles.privateProfile(owner); PrivateResource userPrivate = privateProfile.getPrivateStorage().get(identifier).getResource(); diff --git a/datasafe-privatestore/datasafe-privatestore-api/src/main/java/de/adorsys/datasafe/privatestore/api/actions/RemoveFromPrivate.java b/datasafe-privatestore/datasafe-privatestore-api/src/main/java/de/adorsys/datasafe/privatestore/api/actions/RemoveFromPrivate.java index 8c2d8af45..8d2c0fbd1 100644 --- a/datasafe-privatestore/datasafe-privatestore-api/src/main/java/de/adorsys/datasafe/privatestore/api/actions/RemoveFromPrivate.java +++ b/datasafe-privatestore/datasafe-privatestore-api/src/main/java/de/adorsys/datasafe/privatestore/api/actions/RemoveFromPrivate.java @@ -14,5 +14,8 @@ public interface RemoveFromPrivate { * @param request Resource location (relative or absolute) */ void remove(RemoveRequest request); - void makeSurePasswordClearanceIsDone(); // this abstract method will make sure new implementations dont forget to handle password clearance + + // this abstract method will make sure new implementations don't forget to handle password clearance + + void makeSurePasswordClearanceIsDone(); } diff --git a/datasafe-privatestore/datasafe-privatestore-impl/src/main/java/de/adorsys/datasafe/privatestore/impl/actions/RemoveFromPrivateImpl.java b/datasafe-privatestore/datasafe-privatestore-impl/src/main/java/de/adorsys/datasafe/privatestore/impl/actions/RemoveFromPrivateImpl.java index 1a84c0fb1..03e0e05f7 100644 --- a/datasafe-privatestore/datasafe-privatestore-impl/src/main/java/de/adorsys/datasafe/privatestore/impl/actions/RemoveFromPrivateImpl.java +++ b/datasafe-privatestore/datasafe-privatestore-impl/src/main/java/de/adorsys/datasafe/privatestore/impl/actions/RemoveFromPrivateImpl.java @@ -29,9 +29,9 @@ public RemoveFromPrivateImpl(EncryptedResourceResolver resolver, StorageRemoveSe public void remove(RemoveRequest request) { // Access check is implicit - on keystore access in EncryptedResourceResolver remover.remove(resolver.encryptAndResolvePath( - request.getOwner(), - request.getLocation(), - request.getStorageIdentifier()) + request.getOwner(), + request.getLocation(), + request.getStorageIdentifier()) ); request.getOwner().getReadKeyPassword().clear(); } diff --git a/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/EncryptedResourceResolverImplTest.java b/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/EncryptedResourceResolverImplTest.java index 15ec8bcdc..a5e93b7be 100644 --- a/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/EncryptedResourceResolverImplTest.java +++ b/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/EncryptedResourceResolverImplTest.java @@ -67,7 +67,7 @@ void encryptAndResolvePathAbsolute() { when(accessService.privateAccessFor(auth, absolute)).thenReturn(new AbsoluteLocation<>(absolute)); AbsoluteLocation resource = resolver.encryptAndResolvePath( - auth, absolute, StorageIdentifier.DEFAULT + auth, absolute, StorageIdentifier.DEFAULT ); assertThat(resource.location()).isEqualTo(absolute.location()); @@ -81,7 +81,7 @@ void encryptAndResolvePathRelative() { .thenAnswer(inv -> BasePrivateResource.forAbsolutePrivate(root.location().resolve(ENCRYPTED))); AbsoluteLocation resource = resolver - .encryptAndResolvePath(auth, relative, StorageIdentifier.DEFAULT); + .encryptAndResolvePath(auth, relative, StorageIdentifier.DEFAULT); verify(resourceResolver).resolveRelativeToPrivate(eq(auth), captor.capture(), eq(StorageIdentifier.DEFAULT)); assertThat(resource.location()).extracting(Uri::toASCIIString).isEqualTo("s3://root/" + ENCRYPTED); diff --git a/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/ListPrivateImplTest.java b/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/ListPrivateImplTest.java index 2e35d7b1d..98b6c556d 100644 --- a/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/ListPrivateImplTest.java +++ b/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/ListPrivateImplTest.java @@ -58,7 +58,7 @@ void list() { when(resolvedResource.withResource(resource.getResource())).thenReturn(resolvedResource); ListRequest request = ListRequest.forDefaultPrivate(auth, PATH); when(resolver.encryptAndResolvePath(request.getOwner(), request.getLocation(), request.getStorageIdentifier())) - .thenReturn(resource); + .thenReturn(resource); when(resolver.decryptingResolver(request.getOwner(), resource.getResource(), request.getStorageIdentifier())) .thenReturn(path -> resource); when(listService.list(resource)).thenReturn(Stream.of(absoluteResolvedResource)); diff --git a/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/ReadFromPrivateImplTest.java b/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/ReadFromPrivateImplTest.java index 48344d2e9..b65c3a4b9 100644 --- a/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/ReadFromPrivateImplTest.java +++ b/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/ReadFromPrivateImplTest.java @@ -49,7 +49,7 @@ void read() { BasePrivateResource.forPrivate(ABSOLUTE_PATH) ); when(resolver.encryptAndResolvePath(request.getOwner(), request.getLocation(), request.getStorageIdentifier())) - .thenReturn(resource); + .thenReturn(resource); when(readService.read(captor.capture())).thenReturn(new ByteArrayInputStream(BYTES.getBytes())); assertThat(inbox.read(request)).hasContent(BYTES); diff --git a/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/WriteToPrivateImplTest.java b/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/WriteToPrivateImplTest.java index 5b48a6271..0f1b5e6db 100644 --- a/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/WriteToPrivateImplTest.java +++ b/datasafe-privatestore/datasafe-privatestore-impl/src/test/java/de/adorsys/datasafe/privatestore/impl/actions/WriteToPrivateImplTest.java @@ -73,7 +73,7 @@ void write() { WriteRequest request = WriteRequest.forDefaultPrivate(auth, ABSOLUTE_PATH); when(privateKeyService.documentEncryptionSecretKey(auth)).thenReturn(secretKeyIDWithKey); when(resolver.encryptAndResolvePath(request.getOwner(), request.getLocation(), request.getStorageIdentifier())) - .thenReturn(resource); + .thenReturn(resource); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(writeService.write(captor.capture(), eq(secretKeyIDWithKey))).thenReturn(outputStream); diff --git a/datasafe-rest-impl/package-lock.json b/datasafe-rest-impl/package-lock.json new file mode 100644 index 000000000..ad1972f77 --- /dev/null +++ b/datasafe-rest-impl/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "datasafe-rest-impl", + "lockfileVersion": 3, + "requires": true, + "packages": {} +} diff --git a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/DatasafeRestApplication.java b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/DatasafeRestApplication.java index 3212355da..d778cc973 100644 --- a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/DatasafeRestApplication.java +++ b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/DatasafeRestApplication.java @@ -8,7 +8,7 @@ @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) public class DatasafeRestApplication { - public static void main(String[] args) { - SpringApplication.run(DatasafeRestApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(DatasafeRestApplication.class, args); + } } diff --git a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/config/DatasafeConfig.java b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/config/DatasafeConfig.java index 71c31b9fe..12dae475d 100644 --- a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/config/DatasafeConfig.java +++ b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/config/DatasafeConfig.java @@ -34,19 +34,18 @@ import de.adorsys.datasafe.types.api.context.overrides.OverridesRegistry; import de.adorsys.datasafe.types.api.types.ReadStorePassword; import de.adorsys.datasafe.types.api.utils.ExecutorServiceUtil; -import lombok.experimental.Delegate; -import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - import java.net.URI; import java.nio.file.Paths; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.regex.Pattern; +import lombok.experimental.Delegate; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; /** * Configures default (non-versioned) Datasafe service that uses S3 client as storage provider. @@ -84,7 +83,7 @@ DFSConfig withClientCredentials(DatasafeProperties properties) { OverridesRegistry withClientCredentialsOverrides() { OverridesRegistry registry = new BaseOverridesRegistry(); BucketAccessServiceImplRuntimeDelegatable.overrideWith(registry, args -> - new WithAccessCredentials(args.getStorageKeyStoreOperations())); + new WithAccessCredentials(args.getStorageKeyStoreOperations())); return registry; } @@ -131,31 +130,31 @@ VersionedDatasafeServices versionedDatasafeServices(StorageService storageServic StorageService clientCredentials(AmazonS3 s3, S3Factory factory, DatasafeProperties properties) { ExecutorService executorService = ExecutorServiceUtil.submitterExecutesOnStarvationExecutingService(); S3StorageService basicStorage = new S3StorageService( - s3, - properties.getBucketName(), - executorService + s3, + properties.getBucketName(), + executorService ); return new RegexDelegatingStorage( - ImmutableMap.builder() - .put(Pattern.compile(properties.getSystemRoot() + ".+"), basicStorage) - // here order is important, immutable map preserves key order, so properties.getAmazonUrl() - // will be tried first - .put( - Pattern.compile(".+"), - new UriBasedAuthStorageService( - acc -> new S3StorageService( - factory.getClient( - acc.getEndpoint(), - acc.getRegion(), - acc.getAccessKey(), - acc.getSecretKey() - ), - new BucketNameRemovingRouter(acc.getBucketName()), - executorService - ) - ) - ).build() + ImmutableMap.builder() + .put(Pattern.compile(properties.getSystemRoot() + ".+"), basicStorage) + // here order is important, immutable map preserves key order, so properties.getAmazonUrl() + // will be tried first + .put( + Pattern.compile(".+"), + new UriBasedAuthStorageService( + acc -> new S3StorageService( + factory.getClient( + acc.getEndpoint(), + acc.getRegion(), + acc.getAccessKey(), + acc.getSecretKey() + ), + new BucketNameRemovingRouter(acc.getBucketName()), + executorService + ) + ) + ).build() ); } @@ -184,9 +183,9 @@ StorageService singleStorageServiceFilesystem(DatasafeProperties properties) { @ConditionalOnProperty(name = DATASAFE_S3_STORAGE, havingValue = "true") StorageService singleStorageServiceS3(AmazonS3 s3, DatasafeProperties properties) { return new S3StorageService( - s3, - properties.getBucketName(), - ExecutorServiceUtil.submitterExecutesOnStarvationExecutingService() + s3, + properties.getBucketName(), + ExecutorServiceUtil.submitterExecutesOnStarvationExecutingService() ); } @@ -200,7 +199,7 @@ StorageService multiStorageService(DatasafeProperties properties) { StorageService db = new DatabaseStorageService(ALLOWED_TABLES, new DatabaseConnectionRegistry( ImmutableMap.of(properties.getDbUrl(), new DatabaseCredentials(properties.getDbUsername(), properties.getDbPassword())) - ) + ) ); S3StorageService s3StorageService = new S3StorageService(s3(properties), properties.getBucketName(), diff --git a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/DocumentController.java b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/DocumentController.java index 6c1209207..c8f7f4388 100644 --- a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/DocumentController.java +++ b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/DocumentController.java @@ -1,5 +1,8 @@ package de.adorsys.datasafe.rest.impl.controller; +import static org.springframework.http.HttpHeaders.CONTENT_TYPE; +import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE; +import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; import com.amazonaws.services.s3.model.AmazonS3Exception; import de.adorsys.datasafe.business.impl.service.DefaultDatasafeServices; import de.adorsys.datasafe.encrypiton.api.types.UserID; @@ -14,6 +17,10 @@ import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Optional; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; @@ -27,15 +34,6 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Optional; - -import static org.springframework.http.HttpHeaders.CONTENT_TYPE; -import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE; -import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; - /** * User private space REST api. */ @@ -63,7 +61,7 @@ public void readDocument(@RequestHeader @NotBlank String user, UserIDAuth userIDAuth = new UserIDAuth(new UserID(user), ReadKeyPasswordHelper.getForString(password)); ReadRequest request = - ReadRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path); + ReadRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path); // this is needed for swagger, produces is just a directive: response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM_VALUE); @@ -93,7 +91,7 @@ public void writeDocument(@RequestHeader @NotBlank String user, WriteRequest request = WriteRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path); try (OutputStream os = datasafeService.privateService().write(request); - InputStream is = file.getInputStream()) { + InputStream is = file.getInputStream()) { StreamUtils.copy(is, os); } log.debug("User: {}, write private file to: {}", user, path); @@ -119,7 +117,7 @@ public List listDocuments(@RequestHeader @NotBlank String user, try { List documentList = datasafeService.privateService().list( - ListRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path)) + ListRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path)) .map(e -> e.getResource().asPrivate().decryptedPath().asString()) .toList(); log.debug("List for path {} returned {} items", path, documentList.size()); @@ -145,7 +143,7 @@ public void removeDocument(@RequestHeader @NotBlank String user, UserIDAuth userIDAuth = new UserIDAuth(new UserID(user), ReadKeyPasswordHelper.getForString(password)); RemoveRequest request = - RemoveRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path); + RemoveRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path); datasafeService.privateService().remove(request); log.debug("User: {}, delete private file: {}", user, path); } diff --git a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/GenericControllerAdvice.java b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/GenericControllerAdvice.java index 9e052fabc..644a212e2 100644 --- a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/GenericControllerAdvice.java +++ b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/GenericControllerAdvice.java @@ -4,6 +4,11 @@ import de.adorsys.datasafe.rest.impl.exceptions.UnauthorizedException; import de.adorsys.datasafe.rest.impl.exceptions.UserDoesNotExistsException; import de.adorsys.datasafe.rest.impl.exceptions.UserExistsException; +import java.security.UnrecoverableKeyException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.crypto.BadPaddingException; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -12,12 +17,6 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; -import javax.crypto.BadPaddingException; -import java.security.UnrecoverableKeyException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - @ControllerAdvice(basePackageClasses = { DocumentController.class, InboxController.class, @@ -50,7 +49,7 @@ public ResponseEntity> handleFileNotFoundException(Exception ex) { } @ExceptionHandler({UnauthorizedException.class, BadCredentialsException.class}) - @ResponseStatus(value=HttpStatus.UNAUTHORIZED, reason="Access Denied") + @ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "Access Denied") public ResponseEntity> handleUnauthorizedException(Exception ex) { log.debug("Unauthorized exception: {}", ex.getMessage(), ex); List errors = Collections.singletonList(ex.getMessage()); @@ -58,7 +57,7 @@ public ResponseEntity> handleUnauthorizedException(Exception ex) { } @ExceptionHandler({UnrecoverableKeyException.class, BadPaddingException.class}) - @ResponseStatus(value=HttpStatus.FORBIDDEN, reason="Access Denied") + @ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "Access Denied") public ResponseEntity> handleBadCredentialsException(Exception ex) { log.debug("Bad credentials exception: {}", ex.getMessage(), ex); List errors = Collections.singletonList(ex.getMessage()); diff --git a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/InboxController.java b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/InboxController.java index bdaf2bc07..51e0697b3 100644 --- a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/InboxController.java +++ b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/InboxController.java @@ -61,7 +61,7 @@ public void writeToInbox(@RequestHeader @NotBlank String user, Set toUsers = recipients.stream().map(UserID::new).collect(Collectors.toSet()); path = path.replaceAll("^/", ""); try (OutputStream os = dataSafeService.inboxService().write(WriteInboxRequest.forDefaultPublic(fromUser, toUsers, path)); - InputStream is = file.getInputStream()) { + InputStream is = file.getInputStream()) { StreamUtils.copy(is, os); } log.debug("Users {}, write to INBOX file: {}", toUsers, path); @@ -83,7 +83,7 @@ public void readFromInbox(@RequestHeader @NotBlank String user, response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM_VALUE); try (InputStream is = dataSafeService.inboxService().read(ReadRequest.forPrivate(userIDAuth, resource)); - OutputStream os = response.getOutputStream()) { + OutputStream os = response.getOutputStream()) { StreamUtils.copy(is, os); } log.debug("User {}, read from INBOX file {}", user, resource); diff --git a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/VersionController.java b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/VersionController.java index cb329260b..f93a51b73 100644 --- a/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/VersionController.java +++ b/datasafe-rest-impl/src/main/java/de/adorsys/datasafe/rest/impl/controller/VersionController.java @@ -58,7 +58,7 @@ public List listVersionedDocuments(@RequestHeader @NotBlank String user, path = path.replaceAll("^/", ""); try { List documentList = versionedDatasafeServices.latestPrivate().listWithDetails( - ListRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path)) + ListRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path)) .map(e -> e.absolute().getResource().decryptedPath().asString()) .toList(); log.debug("List for path {} returned {} items", path, documentList.size()); @@ -87,7 +87,7 @@ public void readVersionedDocument(@RequestHeader @NotBlank String user, response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM_VALUE); try (InputStream is = versionedDatasafeServices.latestPrivate().read(request); - OutputStream os = response.getOutputStream()) { + OutputStream os = response.getOutputStream()) { StreamUtils.copy(is, os); } log.debug("User: {}, read private file from: {}", user, path); @@ -108,7 +108,7 @@ public void writeVersionedDocument(@RequestHeader @NotBlank String user, WriteRequest request = WriteRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path); try (OutputStream os = versionedDatasafeServices.latestPrivate().write(request); - InputStream is = file.getInputStream()) { + InputStream is = file.getInputStream()) { StreamUtils.copy(is, os); } log.debug("User: {}, write private file to: {}", user, path); diff --git a/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/AuthenticateControllerTest.java b/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/AuthenticateControllerTest.java index 2f6446144..58ae631bd 100644 --- a/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/AuthenticateControllerTest.java +++ b/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/AuthenticateControllerTest.java @@ -99,9 +99,9 @@ void testGetDataWithoutTokenFail() { String errorMessage = mvc .perform( - put("/inbox/document/{path}", TEST_PATH). - contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE). - header("user", TEST_USER)) + put("/inbox/document/{path}", TEST_PATH) + .contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE) + .header("user", TEST_USER)) .andExpect(status().isForbidden()) .andReturn() .getResponse() diff --git a/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/BaseDatasafeEndpointTest.java b/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/BaseDatasafeEndpointTest.java index 66ee7325e..4736034a9 100644 --- a/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/BaseDatasafeEndpointTest.java +++ b/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/BaseDatasafeEndpointTest.java @@ -51,9 +51,9 @@ MvcResult sendAuthenticateRequest(UserDTO userDTO) { @SneakyThrows MvcResult sendAuthenticateRequestWithStatus(UserDTO userDTO, ResultMatcher statusMatcher) { return this.mvc - .perform(post("/api/authenticate"). - content(jsonMapper.writeValueAsString(userDTO)). - contentType(MediaType.APPLICATION_JSON)) + .perform(post("/api/authenticate") + .content(jsonMapper.writeValueAsString(userDTO)) + .contentType(MediaType.APPLICATION_JSON)) .andDo(print()).andExpect(statusMatcher) .andReturn(); } diff --git a/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/TestHelper.java b/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/TestHelper.java index 497599cb5..74244bf70 100644 --- a/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/TestHelper.java +++ b/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/TestHelper.java @@ -12,10 +12,10 @@ public class TestHelper { public static MockHttpServletRequestBuilder putFileBuilder(String path, Object vars) { MockMultipartFile file = new MockMultipartFile( - "file", - "file.txt", - "text/plain", - "DATA".getBytes() + "file", + "file.txt", + "text/plain", + "DATA".getBytes() ); MockMultipartHttpServletRequestBuilder builder = RestDocumentationRequestBuilders.multipart(path, vars).file(file); diff --git a/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/UserControllerTest.java b/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/UserControllerTest.java index 6bf75ebde..d871e1683 100644 --- a/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/UserControllerTest.java +++ b/datasafe-rest-impl/src/test/java/de/adorsys/datasafe/rest/impl/controller/UserControllerTest.java @@ -1,5 +1,21 @@ package de.adorsys.datasafe.rest.impl.controller; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; +import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; +import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.google.gson.Gson; import de.adorsys.datasafe.business.impl.service.DefaultDatasafeServices; import de.adorsys.datasafe.directory.api.types.StorageCredentials; @@ -21,23 +37,6 @@ import org.springframework.http.MediaType; import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; -import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders; -import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; -import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; -import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - class UserControllerTest extends BaseTokenDatasafeEndpointTest { private Gson gson; @@ -70,13 +69,13 @@ void createUserTest() { )); mvc.perform(put("/user") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .characterEncoding("UTF-8") - .content(getLoginData()) - .header("token", token) - .content(gson.toJson(request)) - ) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .characterEncoding("UTF-8") + .content(getLoginData()) + .header("token", token) + .content(gson.toJson(request)) + ) .andExpect(status().isOk()) .andDo(document); verify(userProfile).registerUsingDefaults(any()); @@ -88,14 +87,14 @@ void changePasswordTest() { String newPassword = "NEW!"; mvc.perform(post("/user/password") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .characterEncoding("UTF-8") - .content("{\"newPassword\": \"" + newPassword + "\"}") - .header("user", TEST_USER) - .header("password", TEST_PASS) - .header("token", token) - ) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .characterEncoding("UTF-8") + .content("{\"newPassword\": \"" + newPassword + "\"}") + .header("user", TEST_USER) + .header("password", TEST_PASS) + .header("token", token) + ) .andExpect(status().isOk()); verify(userProfile).updateReadKeyPassword( @@ -110,20 +109,20 @@ void changePasswordTest() { @Test void getPrivateProfileTest() { when(userProfile.privateProfile(eq(new UserIDAuth(TEST_USER, TEST_PASS)))) - .thenReturn(mock(UserPrivateProfile.class)); + .thenReturn(mock(UserPrivateProfile.class)); mvc.perform(get("/user/privateProfile") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .characterEncoding("UTF-8") - .header("user", TEST_USER) - .header("password", TEST_PASS) - .header("token", token) - ) - .andExpect(status().isOk()); + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .characterEncoding("UTF-8") + .header("user", TEST_USER) + .header("password", TEST_PASS) + .header("token", token) + ) + .andExpect(status().isOk()); verify(userProfile).privateProfile( - eq(new UserIDAuth(TEST_USER, TEST_PASS)) + eq(new UserIDAuth(TEST_USER, TEST_PASS)) ); } @@ -131,20 +130,20 @@ void getPrivateProfileTest() { @Test void getPublicProfileTest() { when(userProfile.publicProfile(eq(new UserID(TEST_USER)))) - .thenReturn(mock(UserPublicProfile.class)); + .thenReturn(mock(UserPublicProfile.class)); mvc.perform(get("/user/publicProfile") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .characterEncoding("UTF-8") - .header("user", TEST_USER) - .header("password", TEST_PASS) - .header("token", token) - ) - .andExpect(status().isOk()); + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .characterEncoding("UTF-8") + .header("user", TEST_USER) + .header("password", TEST_PASS) + .header("token", token) + ) + .andExpect(status().isOk()); verify(userProfile).publicProfile( - eq(new UserID(TEST_USER)) + eq(new UserID(TEST_USER)) ); } @@ -152,19 +151,19 @@ void getPublicProfileTest() { @Test void changePrivateProfileTest() { mvc.perform(post("/user/privateProfile") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .characterEncoding("UTF-8") - .content(Fixture.read("endpoints/private_profile.json")) - .header("user", TEST_USER) - .header("password", TEST_PASS) - .header("token", token) - ) - .andExpect(status().isOk()); + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .characterEncoding("UTF-8") + .content(Fixture.read("endpoints/private_profile.json")) + .header("user", TEST_USER) + .header("password", TEST_PASS) + .header("token", token) + ) + .andExpect(status().isOk()); verify(userProfile).updatePrivateProfile( - eq(new UserIDAuth(TEST_USER, TEST_PASS)), - any() + eq(new UserIDAuth(TEST_USER, TEST_PASS)), + any() ); } @@ -172,19 +171,19 @@ void changePrivateProfileTest() { @Test void changePublicProfileTest() { mvc.perform(post("/user/publicProfile") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .characterEncoding("UTF-8") - .content(Fixture.read("endpoints/public_profile.json")) - .header("user", TEST_USER) - .header("password", TEST_PASS) - .header("token", token) - ) - .andExpect(status().isOk()); + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .characterEncoding("UTF-8") + .content(Fixture.read("endpoints/public_profile.json")) + .header("user", TEST_USER) + .header("password", TEST_PASS) + .header("token", token) + ) + .andExpect(status().isOk()); verify(userProfile).updatePublicProfile( - eq(new UserIDAuth(TEST_USER, TEST_PASS)), - any() + eq(new UserIDAuth(TEST_USER, TEST_PASS)), + any() ); } @@ -192,20 +191,20 @@ void changePublicProfileTest() { @Test void addStorageCredentialsTest() { mvc.perform(post("/user/storages") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .characterEncoding("UTF-8") - .content(Fixture.read("endpoints/storage_creds.json")) - .header("user", TEST_USER) - .header("password", TEST_PASS) - .header("token", token) - ) - .andExpect(status().isOk()); + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .characterEncoding("UTF-8") + .content(Fixture.read("endpoints/storage_creds.json")) + .header("user", TEST_USER) + .header("password", TEST_PASS) + .header("token", token) + ) + .andExpect(status().isOk()); verify(userProfile).registerStorageCredentials( - eq(new UserIDAuth(TEST_USER, TEST_PASS)), - eq(new StorageIdentifier("AAA")), - eq(new StorageCredentials("FOO", "BAR")) + eq(new UserIDAuth(TEST_USER, TEST_PASS)), + eq(new StorageIdentifier("AAA")), + eq(new StorageCredentials("FOO", "BAR")) ); } @@ -213,20 +212,20 @@ void addStorageCredentialsTest() { @Test void removeStorageCredentialsTest() { mvc.perform(delete("/user/storages") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .characterEncoding("UTF-8") - .content("{}") - .header("user", TEST_USER) - .header("password", TEST_PASS) - .header("token", token) - .header("storageId", "111") - ) - .andExpect(status().isOk()); + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .characterEncoding("UTF-8") + .content("{}") + .header("user", TEST_USER) + .header("password", TEST_PASS) + .header("token", token) + .header("storageId", "111") + ) + .andExpect(status().isOk()); verify(userProfile).deregisterStorageCredentials( - eq(new UserIDAuth(TEST_USER, TEST_PASS)), - eq(new StorageIdentifier("111")) + eq(new UserIDAuth(TEST_USER, TEST_PASS)), + eq(new StorageIdentifier("111")) ); } @@ -260,12 +259,12 @@ void deleteUserTest() { when(dataSafeService.userProfile().userExists(any())).thenReturn(true); mvc.perform(delete("/user") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .header("user", TEST_USER) - .header("password", TEST_PASS) - .header("token", token) - ) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .header("user", TEST_USER) + .header("password", TEST_PASS) + .header("token", token) + ) .andExpect(status().isOk()) .andDo(document); verify(userProfile).deregister(any()); diff --git a/datasafe-runtime-delegate/src/main/java/de/adorsys/datasafe/runtimedelegate/RuntimeDelegateGenerator.java b/datasafe-runtime-delegate/src/main/java/de/adorsys/datasafe/runtimedelegate/RuntimeDelegateGenerator.java index 45df3f70c..ee0d3a470 100644 --- a/datasafe-runtime-delegate/src/main/java/de/adorsys/datasafe/runtimedelegate/RuntimeDelegateGenerator.java +++ b/datasafe-runtime-delegate/src/main/java/de/adorsys/datasafe/runtimedelegate/RuntimeDelegateGenerator.java @@ -28,10 +28,10 @@ class RuntimeDelegateGenerator { - private static final String CLASS_PURPOSE_COMMENT = "This class performs functionality delegation based on " - + "contextClass content. If contextClass contains overriding class - it will be used."; - private static final String OVERRIDE_WITH_PURPOSE_COMMENT = "This is a typesafe function to register " - + "overriding class into context.\n"; + private static final String CLASS_PURPOSE_COMMENT = "This class performs functionality delegation based on " + + "contextClass content. If contextClass contains overriding class - it will be used."; + private static final String OVERRIDE_WITH_PURPOSE_COMMENT = "This is a typesafe function to register " + + "overriding class into context.\n"; private static final String CAPTOR_TYPE_NAME = "ArgumentsCaptor"; private static final String CAPTOR_NAME = "argumentsCaptor"; @@ -63,9 +63,9 @@ void generate(TypeElement forClass, delegator.addMethod(overrideWith(forClass, contextClass, argCaptor)); JavaFile javaFile = JavaFile - .builder(ClassName.get(forClass).packageName(), delegator.build()) - .indent(" ") - .build(); + .builder(ClassName.get(forClass).packageName(), delegator.build()) + .indent(" ") + .build(); try { javaFile.writeTo(filer); @@ -108,19 +108,19 @@ private TypeSpec.Builder buildDelegatingClass(TypeElement forClass) { // perform actual delegation private void addSuperClassOverrides(TypeSpec.Builder toClass, TypeElement baseClass) { baseClass.getEnclosedElements().stream() - // limiting to overridable-only methods: - .filter(it -> it instanceof ExecutableElement) - .filter(it -> it.getKind() == ElementKind.METHOD) - .filter(it -> !it.getModifiers().contains(Modifier.PRIVATE)) - .forEach(it -> { - MethodSpec overriddenBase = MethodSpec.overriding((ExecutableElement) it).build(); - MethodSpec.Builder overridden = MethodSpec.overriding((ExecutableElement) it); - overridden.addCode( + // limiting to overridable-only methods: + .filter(it -> it instanceof ExecutableElement) + .filter(it -> it.getKind() == ElementKind.METHOD) + .filter(it -> !it.getModifiers().contains(Modifier.PRIVATE)) + .forEach(it -> { + MethodSpec overriddenBase = MethodSpec.overriding((ExecutableElement) it).build(); + MethodSpec.Builder overridden = MethodSpec.overriding((ExecutableElement) it); + overridden.addCode( delegateToIfOverrideIsPresent(overriddenBase) ).build(); - toClass.addMethod(overridden.build()); - }); + toClass.addMethod(overridden.build()); + }); } private CodeBlock delegateToIfOverrideIsPresent(MethodSpec target) { @@ -143,15 +143,15 @@ private TypeSpec addArgsCaptor(ExecutableElement usingConstructor, List { FieldSpec argCaptor = FieldSpec.builder( - TypeName.get(it.asType()), - firstCharToLowerCase(it.getSimpleName().toString()), - Modifier.PRIVATE, - Modifier.FINAL + TypeName.get(it.asType()), + firstCharToLowerCase(it.getSimpleName().toString()), + Modifier.PRIVATE, + Modifier.FINAL ).build(); ctor.addParameter(argCaptor.type, argCaptor.name); @@ -159,10 +159,10 @@ private TypeSpec addArgsCaptor(ExecutableElement usingConstructor, List - method.addParameter( + method.addParameter( TypeName.get(it.asType()), firstCharToLowerCase(it.getSimpleName().toString()) ) - .addAnnotations( + .addAnnotations( it.getAnnotationMirrors().stream().map(AnnotationSpec::get).collect(Collectors.toList()) ) ); diff --git a/datasafe-runtime-delegate/src/main/java/de/adorsys/datasafe/runtimedelegate/RuntimeDelegateProcessor.java b/datasafe-runtime-delegate/src/main/java/de/adorsys/datasafe/runtimedelegate/RuntimeDelegateProcessor.java index 4403d5c4f..10873e824 100644 --- a/datasafe-runtime-delegate/src/main/java/de/adorsys/datasafe/runtimedelegate/RuntimeDelegateProcessor.java +++ b/datasafe-runtime-delegate/src/main/java/de/adorsys/datasafe/runtimedelegate/RuntimeDelegateProcessor.java @@ -52,8 +52,8 @@ public boolean process(Set annotations, RoundEnvironment for (Element annotated : annotatedElements) { if (annotated.getKind() != ElementKind.CLASS) { processingEnv.getMessager().printMessage( - Diagnostic.Kind.ERROR, - "Only classes should be annotated with @" + ANNOTATION_CLASS, + Diagnostic.Kind.ERROR, + "Only classes should be annotated with @" + ANNOTATION_CLASS, annotated ); return false; @@ -63,8 +63,8 @@ public boolean process(Set annotations, RoundEnvironment if (clazz.getModifiers().contains(Modifier.FINAL)) { processingEnv.getMessager().printMessage( - Diagnostic.Kind.ERROR, - "Class should not be final", + Diagnostic.Kind.ERROR, + "Class should not be final", clazz ); return false; @@ -111,8 +111,8 @@ private ExecutableElement findAnnotatedConstructor(TypeEl if (annotated.size() != 1) { processingEnv.getMessager().printMessage( - Diagnostic.Kind.ERROR, - "Class should have exactly one @Inject annotation", + Diagnostic.Kind.ERROR, + "Class should have exactly one @Inject annotation", element ); diff --git a/datasafe-simple-adapter/datasafe-simple-adapter-api/src/main/java/de/adorsys/datasafe/simple/adapter/api/types/DocumentFQN.java b/datasafe-simple-adapter/datasafe-simple-adapter-api/src/main/java/de/adorsys/datasafe/simple/adapter/api/types/DocumentFQN.java index f1ff91f78..03e213aa2 100644 --- a/datasafe-simple-adapter/datasafe-simple-adapter-api/src/main/java/de/adorsys/datasafe/simple/adapter/api/types/DocumentFQN.java +++ b/datasafe-simple-adapter/datasafe-simple-adapter-api/src/main/java/de/adorsys/datasafe/simple/adapter/api/types/DocumentFQN.java @@ -34,7 +34,7 @@ public DocumentFQN(String s) { throw new SimpleAdapterException("not a valid value for documentFQN: String with zero length: " + s); } // add leading slash - if (!value.substring(0,1).equals("/")) { + if (!value.substring(0, 1).equals("/")) { value = "/" + value; } diff --git a/datasafe-simple-adapter/datasafe-simple-adapter-api/src/test/java/de/adorsys/datasafe/simple/adapter/api/DocumentFQNTest.java b/datasafe-simple-adapter/datasafe-simple-adapter-api/src/test/java/de/adorsys/datasafe/simple/adapter/api/DocumentFQNTest.java index 45a4f1bb5..739c11ba5 100644 --- a/datasafe-simple-adapter/datasafe-simple-adapter-api/src/test/java/de/adorsys/datasafe/simple/adapter/api/DocumentFQNTest.java +++ b/datasafe-simple-adapter/datasafe-simple-adapter-api/src/test/java/de/adorsys/datasafe/simple/adapter/api/DocumentFQNTest.java @@ -27,6 +27,6 @@ public void startingSlashForDocumentFQN() { Assertions.assertEquals("", d.getDatasafePath()); } @Test void slashDocumentFQN() { - Assertions.assertThrows(SimpleAdapterException.class , () ->new DocumentFQN("/")); + Assertions.assertThrows(SimpleAdapterException.class , () -> new DocumentFQN("/")); } } diff --git a/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/LogStringFrame.java b/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/LogStringFrame.java index 769eac7cc..370d88801 100644 --- a/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/LogStringFrame.java +++ b/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/LogStringFrame.java @@ -16,7 +16,9 @@ public void add(String line) { public String toString() { int max = 0; for (String line : list) { - if (line.length() > max) max = line.length(); + if (line.length() > max) { + max = line.length(); + } } StringBuilder sb = new StringBuilder(); @@ -35,7 +37,7 @@ public String toString() { } private String fill(String start, int length, String el) { - while(start.length() < length) { + while (start.length() < length) { start = start + el; } return start; diff --git a/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/SimpleDatasafeServiceImpl.java b/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/SimpleDatasafeServiceImpl.java index 02f9cb024..f2113b056 100644 --- a/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/SimpleDatasafeServiceImpl.java +++ b/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/SimpleDatasafeServiceImpl.java @@ -45,17 +45,16 @@ import de.adorsys.datasafe.types.api.types.ReadKeyPassword; import de.adorsys.datasafe.types.api.types.ReadStorePassword; import de.adorsys.datasafe.types.api.utils.ExecutorServiceUtil; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; - import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.file.FileSystems; import java.util.List; import java.util.stream.Collectors; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; @Slf4j public class SimpleDatasafeServiceImpl implements SimpleDatasafeService { @@ -84,16 +83,16 @@ public SimpleDatasafeServiceImpl(DFSCredentials dfsCredentials, MutableEncryptio } SwitchableDatasafeServices.Builder switchableDatasafeService = DaggerSwitchableDatasafeServices.builder() - .config(new DefaultDFSConfig(rootAndStorage.getSystemRoot(), universalReadStorePassword)) - .encryption(config.toEncryptionConfig()) - .storage(getStorageService()); + .config(new DefaultDFSConfig(rootAndStorage.getSystemRoot(), universalReadStorePassword)) + .encryption(config.toEncryptionConfig()) + .storage(getStorageService()); if (!pathEncryptionConfig.getWithPathEncryption()) { BaseOverridesRegistry baseOverridesRegistry = new BaseOverridesRegistry(); PathEncryptionImplRuntimeDelegatable.overrideWith(baseOverridesRegistry, args -> - new NoPathEncryptionImpl( - args.getSymmetricPathEncryptionService(), - args.getPrivateKeyService())); + new NoPathEncryptionImpl( + args.getSymmetricPathEncryptionService(), + args.getPrivateKeyService())); switchableDatasafeService.overridesRegistry(baseOverridesRegistry); } @@ -131,7 +130,7 @@ public boolean userExists(UserID userID) { @SneakyThrows public void storeDocument(UserIDAuth userIDAuth, DSDocument dsDocument) { try (OutputStream os = customlyBuiltDatasafeServices.privateService() - .write(WriteRequest.forDefaultPrivate(userIDAuth, dsDocument.getDocumentFQN().getDatasafePath()))) { + .write(WriteRequest.forDefaultPrivate(userIDAuth, dsDocument.getDocumentFQN().getDatasafePath()))) { os.write(dsDocument.getDocumentContent().getValue()); } } @@ -141,7 +140,7 @@ public void storeDocument(UserIDAuth userIDAuth, DSDocument dsDocument) { public DSDocument readDocument(UserIDAuth userIDAuth, DocumentFQN documentFQN) { DocumentContent documentContent; try (InputStream is = customlyBuiltDatasafeServices.privateService() - .read(ReadRequest.forDefaultPrivate(userIDAuth, documentFQN.getDatasafePath()))) { + .read(ReadRequest.forDefaultPrivate(userIDAuth, documentFQN.getDatasafePath()))) { documentContent = new DocumentContent(ByteStreams.toByteArray(is)); } return new DSDocument(documentFQN, documentContent); @@ -151,10 +150,10 @@ public DSDocument readDocument(UserIDAuth userIDAuth, DocumentFQN documentFQN) { @SneakyThrows public void storeDocumentStream(UserIDAuth userIDAuth, DSDocumentStream dsDocumentStream) { try (OutputStream os = customlyBuiltDatasafeServices - .privateService() - .write(WriteRequest.forDefaultPrivate( - userIDAuth, - dsDocumentStream.getDocumentFQN().getDatasafePath()))) { + .privateService() + .write(WriteRequest.forDefaultPrivate( + userIDAuth, + dsDocumentStream.getDocumentFQN().getDatasafePath()))) { ByteStreams.copy(dsDocumentStream.getDocumentStream(), os); } } @@ -162,18 +161,18 @@ public void storeDocumentStream(UserIDAuth userIDAuth, DSDocumentStream dsDocume @Override public OutputStream storeDocumentStream(UserIDAuth userIDAuth, DocumentFQN documentFQN) { return customlyBuiltDatasafeServices - .privateService() - .write(WriteRequest.forDefaultPrivate(userIDAuth, documentFQN.getDatasafePath())); + .privateService() + .write(WriteRequest.forDefaultPrivate(userIDAuth, documentFQN.getDatasafePath())); } @Override @SneakyThrows public DSDocumentStream readDocumentStream(UserIDAuth userIDAuth, DocumentFQN documentFQN) { return new DSDocumentStream( - documentFQN, - customlyBuiltDatasafeServices - .privateService() - .read(ReadRequest.forDefaultPrivate(userIDAuth, documentFQN.getDatasafePath())) + documentFQN, + customlyBuiltDatasafeServices + .privateService() + .read(ReadRequest.forDefaultPrivate(userIDAuth, documentFQN.getDatasafePath())) ); } @@ -201,17 +200,17 @@ public void deleteFolder(UserIDAuth userIDAuth, DocumentDirectoryFQN documentDir @Override public List list(UserIDAuth userIDAuth, DocumentDirectoryFQN documentDirectoryFQN, ListRecursiveFlag recursiveFlag) { List l = customlyBuiltDatasafeServices.privateService().list( - ListRequest.forDefaultPrivate(userIDAuth, documentDirectoryFQN.getDatasafePath())) - .map(it -> new DocumentFQN(it.getResource().asPrivate().decryptedPath().asString())) - .collect(Collectors.toList()); + ListRequest.forDefaultPrivate(userIDAuth, documentDirectoryFQN.getDatasafePath())) + .map(it -> new DocumentFQN(it.getResource().asPrivate().decryptedPath().asString())) + .collect(Collectors.toList()); if (recursiveFlag.equals(ListRecursiveFlag.TRUE)) { return l; } int numberOfSlashesExpected = 1 + CharMatcher.is('/').countIn(documentDirectoryFQN.getDatasafePath()); return l.stream() - .filter(el -> CharMatcher.is('/').countIn(el.getDatasafePath()) == numberOfSlashesExpected) - .collect(Collectors.toList()); + .filter(el -> CharMatcher.is('/').countIn(el.getDatasafePath()) == numberOfSlashesExpected) + .collect(Collectors.toList()); } @Override @@ -222,9 +221,9 @@ public InboxService getInboxService() { @Override public void cleanupDb() { rootAndStorage.getStorageService() - .list(new AbsoluteLocationWithCapability<>( - BasePrivateResource.forPrivate(rootAndStorage.getSystemRoot()), StorageCapability.LIST_RETURNS_DIR) - ).forEach(rootAndStorage.getStorageService()::remove); + .list(new AbsoluteLocationWithCapability<>( + BasePrivateResource.forPrivate(rootAndStorage.getSystemRoot()), StorageCapability.LIST_RETURNS_DIR) + ).forEach(rootAndStorage.getStorageService()::remove); } @@ -249,25 +248,25 @@ private static SystemRootAndStorageService useAmazonS3(AmazonS3DFSCredentials df log.info(lsf.toString()); AmazonS3ClientBuilder amazonS3ClientBuilder = AmazonS3ClientBuilder.standard() - .withCredentials( - new AWSStaticCredentialsProvider( - new BasicAWSCredentials( - amazonS3DFSCredentials.getAccessKey(), - amazonS3DFSCredentials.getSecretKey())) - ); - - boolean useEndpoint = !amazonS3DFSCredentials.getUrl().matches(AMAZON_URL) - && !amazonS3DFSCredentials.getUrl().startsWith(S3_PREFIX); + .withCredentials( + new AWSStaticCredentialsProvider( + new BasicAWSCredentials( + amazonS3DFSCredentials.getAccessKey(), + amazonS3DFSCredentials.getSecretKey())) + ); + + boolean useEndpoint = !amazonS3DFSCredentials.getUrl().matches(AMAZON_URL) && + !amazonS3DFSCredentials.getUrl().startsWith(S3_PREFIX); lsf = new LogStringFrame(); if (useEndpoint) { lsf.add("not real amazon, so use pathStyleAccess"); AwsClientBuilder.EndpointConfiguration endpoint = new AwsClientBuilder.EndpointConfiguration( - amazonS3DFSCredentials.getUrl(), - amazonS3DFSCredentials.getRegion() + amazonS3DFSCredentials.getUrl(), + amazonS3DFSCredentials.getRegion() ); amazonS3ClientBuilder - .withEndpointConfiguration(endpoint) - .enablePathStyleAccess(); + .withEndpointConfiguration(endpoint) + .enablePathStyleAccess(); } else { lsf.add("real amazon, so use bucketStyleAccess"); amazonS3ClientBuilder.withRegion(amazonS3DFSCredentials.getRegion()); @@ -298,13 +297,13 @@ private static SystemRootAndStorageService useAmazonS3(AmazonS3DFSCredentials df amazons3.createBucket(amazonS3DFSCredentials.getContainer()); } StorageService storageService = new S3StorageService( - amazons3, - amazonS3DFSCredentials.getContainer(), - ExecutorServiceUtil - .submitterExecutesOnStarvationExecutingService( - amazonS3DFSCredentials.getThreadPoolSize(), - amazonS3DFSCredentials.getQueueSize() - ) + amazons3, + amazonS3DFSCredentials.getContainer(), + ExecutorServiceUtil + .submitterExecutesOnStarvationExecutingService( + amazonS3DFSCredentials.getThreadPoolSize(), + amazonS3DFSCredentials.getQueueSize() + ) ); URI systemRoot = URI.create(S3_PREFIX + amazonS3DFSCredentials.getRootBucket()); log.info("build DFS to S3 with root " + amazonS3DFSCredentials.getRootBucket() + " and url " + amazonS3DFSCredentials.getUrl()); diff --git a/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/pathencryption/NoPathEncryptionImpl.java b/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/pathencryption/NoPathEncryptionImpl.java index 68ded7dbc..5ffe09a06 100644 --- a/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/pathencryption/NoPathEncryptionImpl.java +++ b/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/main/java/de/adorsys/datasafe/simple/adapter/impl/pathencryption/NoPathEncryptionImpl.java @@ -5,18 +5,17 @@ import de.adorsys.datasafe.encrypiton.api.types.UserIDAuth; import de.adorsys.datasafe.encrypiton.impl.pathencryption.PathEncryptionImpl; import de.adorsys.datasafe.types.api.resource.Uri; -import lombok.extern.slf4j.Slf4j; - -import javax.inject.Inject; import java.util.function.Function; +import javax.inject.Inject; +import lombok.extern.slf4j.Slf4j; @Slf4j public class NoPathEncryptionImpl extends PathEncryptionImpl { @Inject public NoPathEncryptionImpl( - SymmetricPathEncryptionService symmetricPathEncryptionService, - PrivateKeyService privateKeyService) { + SymmetricPathEncryptionService symmetricPathEncryptionService, + PrivateKeyService privateKeyService) { super(symmetricPathEncryptionService, privateKeyService); } diff --git a/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/test/java/de/adorsys/datasafe/simple/adapter/impl/SimpleAdapterFeatureTest.java b/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/test/java/de/adorsys/datasafe/simple/adapter/impl/SimpleAdapterFeatureTest.java index d1d33c51b..5e62d8bcd 100644 --- a/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/test/java/de/adorsys/datasafe/simple/adapter/impl/SimpleAdapterFeatureTest.java +++ b/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/test/java/de/adorsys/datasafe/simple/adapter/impl/SimpleAdapterFeatureTest.java @@ -102,7 +102,7 @@ void testWithoutEncryption() { Assertions.assertEquals(1, absoluteLocationStream.count()); } try (Stream> absoluteLocationStream = simpleDatasafeService.getStorageService().list(rootLocation).filter(el -> el.location().toASCIIString().contains(path))) { - Optional> first =absoluteLocationStream.findFirst(); + Optional> first = absoluteLocationStream.findFirst(); try (InputStream read = simpleDatasafeService.getStorageService().read(first.get())) { StringWriter writer = new StringWriter(); diff --git a/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/test/java/de/adorsys/datasafe/simple/adapter/impl/SimpleDatasafeAdapterIT.java b/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/test/java/de/adorsys/datasafe/simple/adapter/impl/SimpleDatasafeAdapterIT.java index d8aa61c54..d9270b32a 100644 --- a/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/test/java/de/adorsys/datasafe/simple/adapter/impl/SimpleDatasafeAdapterIT.java +++ b/datasafe-simple-adapter/datasafe-simple-adapter-impl/src/test/java/de/adorsys/datasafe/simple/adapter/impl/SimpleDatasafeAdapterIT.java @@ -86,8 +86,7 @@ void justCreateAndDeleteUserForMinioOnly(WithStorageProvider.StorageDescriptor d assertThat(ls).extracting(it -> descriptor.getLocation().relativize(it.location()).asString()) .containsExactlyInAnyOrder( "users/peter/public/pubkeys", - "users/peter/private/keystore" - ); + "users/peter/private/keystore"); } log.info("test create user and delete user with {}", descriptor.getName()); } @@ -106,8 +105,7 @@ void justCreateAndDeleteUser(WithStorageProvider.StorageDescriptor descriptor) { assertThat(ls).extracting(it -> descriptor.getLocation().relativize(it.location()).asString()) .containsExactlyInAnyOrder( "users/peter/public/pubkeys", - "users/peter/private/keystore" - ); + "users/peter/private/keystore"); } log.info("test create user and delete user with {}", descriptor.getName()); } diff --git a/datasafe-simple-adapter/datasafe-simple-adapter-spring/src/main/java/de/adorsys/datasafe/simple/adapter/spring/factory/SpringSimpleDatasafeServiceFactory.java b/datasafe-simple-adapter/datasafe-simple-adapter-spring/src/main/java/de/adorsys/datasafe/simple/adapter/spring/factory/SpringSimpleDatasafeServiceFactory.java index 97ecd5721..8bacb7579 100644 --- a/datasafe-simple-adapter/datasafe-simple-adapter-spring/src/main/java/de/adorsys/datasafe/simple/adapter/spring/factory/SpringSimpleDatasafeServiceFactory.java +++ b/datasafe-simple-adapter/datasafe-simple-adapter-spring/src/main/java/de/adorsys/datasafe/simple/adapter/spring/factory/SpringSimpleDatasafeServiceFactory.java @@ -54,21 +54,21 @@ public SimpleDatasafeService getSimpleDataSafeServiceWithSubdir(String subdirBel if (dfsCredentials instanceof AmazonS3DFSCredentials) { AmazonS3DFSCredentials amazonS3DFSCredentials = (AmazonS3DFSCredentials) dfsCredentials; return new SimpleDatasafeServiceImpl( - amazonS3DFSCredentials.toBuilder().rootBucket( - amazonS3DFSCredentials.getRootBucket() + "/" + subdirBelowRoot - ).build(), - null != encryptionProperties ? encryptionProperties.getEncryption() : new MutableEncryptionConfig(), - new PathEncryptionConfig(null == encryptionProperties ? true : encryptionProperties.getPathEncryption()) + amazonS3DFSCredentials.toBuilder().rootBucket( + amazonS3DFSCredentials.getRootBucket() + "/" + subdirBelowRoot + ).build(), + null != encryptionProperties ? encryptionProperties.getEncryption() : new MutableEncryptionConfig(), + new PathEncryptionConfig(null == encryptionProperties ? true : encryptionProperties.getPathEncryption()) ); } if (dfsCredentials instanceof FilesystemDFSCredentials) { FilesystemDFSCredentials filesystemDFSCredentials = (FilesystemDFSCredentials) dfsCredentials; return new SimpleDatasafeServiceImpl( - filesystemDFSCredentials.toBuilder().root( - filesystemDFSCredentials.getRoot() + "/" + subdirBelowRoot - ).build(), - null != encryptionProperties ? encryptionProperties.getEncryption() : new MutableEncryptionConfig(), - new PathEncryptionConfig(null == encryptionProperties ? true : encryptionProperties.getPathEncryption()) + filesystemDFSCredentials.toBuilder().root( + filesystemDFSCredentials.getRoot() + "/" + subdirBelowRoot + ).build(), + null != encryptionProperties ? encryptionProperties.getEncryption() : new MutableEncryptionConfig(), + new PathEncryptionConfig(null == encryptionProperties ? true : encryptionProperties.getPathEncryption()) ); } throw new SimpleAdapterException("missing switch for DFSCredentials" + dfsCredentials); diff --git a/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/RegexDelegatingStorageTest.java b/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/RegexDelegatingStorageTest.java index be5cd3e4d..a278ca8cd 100644 --- a/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/RegexDelegatingStorageTest.java +++ b/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/RegexDelegatingStorageTest.java @@ -1,4 +1,5 @@ package de.adorsys.datasafe.storage.api; + import de.adorsys.datasafe.types.api.resource.AbsoluteLocation; import de.adorsys.datasafe.types.api.resource.BasePrivateResource; import de.adorsys.datasafe.types.api.resource.WithCallback; @@ -15,7 +16,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; -public class RegexDelegatingStorageTest extends BaseMockitoTest{ +public class RegexDelegatingStorageTest extends BaseMockitoTest { @Mock private StorageService service; @@ -54,9 +55,9 @@ void write() { verify(service).write(any(WithCallback.class)); } @Test - void objectExistsWithNoMatch() { - AbsoluteLocation badlocation = new AbsoluteLocation<>(BasePrivateResource.forPrivate("file://bucket")); - assertThrows(IllegalArgumentException.class, () -> tested.objectExists(badlocation)); + void objectExistsWithNoMatch() { + AbsoluteLocation badlocation = new AbsoluteLocation<>(BasePrivateResource.forPrivate("file://bucket")); + assertThrows(IllegalArgumentException.class, () -> tested.objectExists(badlocation)); } } diff --git a/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/UriBasedAuthStorageServiceTest.java b/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/UriBasedAuthStorageServiceTest.java index 1dade06bd..074f73392 100644 --- a/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/UriBasedAuthStorageServiceTest.java +++ b/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/UriBasedAuthStorageServiceTest.java @@ -86,7 +86,7 @@ void testEndpointExtractor() { assertThat(endpoint).isEqualTo("http://host.com:8080/"); } - @MethodSource("fixture") + @MethodSource("fixture") @ParameterizedTest void objectExists(MappedItem item) { tested.objectExists(item.getUri()); @@ -131,7 +131,7 @@ private static Stream fixture() { return Stream.of( new MappedItem( "http://user:password@host:9999/region/bucket", - new UriBasedAuthStorageService.AccessId( + new UriBasedAuthStorageService.AccessId( "user", "password", "region", @@ -143,7 +143,7 @@ private static Stream fixture() { ), new MappedItem( "http://user:password@host:9999/region/bucket/", - new UriBasedAuthStorageService.AccessId( + new UriBasedAuthStorageService.AccessId( "user", "password", "region", @@ -155,7 +155,7 @@ private static Stream fixture() { ), new MappedItem( "http://user:password@host:9999/region/bucket/path/to", - new UriBasedAuthStorageService.AccessId( + new UriBasedAuthStorageService.AccessId( "user", "password", "region", @@ -167,7 +167,7 @@ private static Stream fixture() { ), new MappedItem( "http://user:password@host:9999/region/bucket/path/to/", - new UriBasedAuthStorageService.AccessId( + new UriBasedAuthStorageService.AccessId( "user", "password", "region", @@ -179,7 +179,7 @@ private static Stream fixture() { ), new MappedItem( "http://user:password@host.com/region/bucket", - new UriBasedAuthStorageService.AccessId( + new UriBasedAuthStorageService.AccessId( "user", "password", "region", @@ -191,7 +191,7 @@ private static Stream fixture() { ), new MappedItem( "http://user:password@host.com/region/bucket/", - new UriBasedAuthStorageService.AccessId( + new UriBasedAuthStorageService.AccessId( "user", "password", "region", diff --git a/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/UserBasedDelegatingStorageTest.java b/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/UserBasedDelegatingStorageTest.java index cabb327eb..308c14f5f 100644 --- a/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/UserBasedDelegatingStorageTest.java +++ b/datasafe-storage/datasafe-storage-api/src/test/java/de/adorsys/datasafe/storage/api/UserBasedDelegatingStorageTest.java @@ -12,7 +12,6 @@ import java.io.OutputStream; import java.util.Optional; - import java.util.List; import java.util.function.Function; @@ -25,9 +24,9 @@ public class UserBasedDelegatingStorageTest extends BaseMockitoTest { @Mock private StorageService storage; @Mock - private Function storageServiceBuilder; + private Function storageServiceBuilder; private UserBasedDelegatingStorage tested; - private static final List AMAZON_BUCKETS = List.of("bucket1","bucket2" ); + private static final List AMAZON_BUCKETS = List.of("bucket1", "bucket2"); private AbsoluteLocation locationUser1 = new AbsoluteLocation<>( BasePrivateResource.forPrivate("s3://datasafe-test1/073047da-dd68-4f70-b9bf-5759d7e30c85/users/user-1/private/files/") @@ -88,7 +87,7 @@ void flushChunkSizeUser3() { } @Test - void listDelegates(){ + void listDelegates() { tested.list(locationUser1); verify(storageServiceBuilder).apply("bucket2"); @@ -96,7 +95,7 @@ void listDelegates(){ } @Test - void readDelegates(){ + void readDelegates() { tested.read(locationUser1); verify(storageServiceBuilder).apply("bucket2"); @@ -104,7 +103,7 @@ void readDelegates(){ } @Test - void removeDelegates(){ + void removeDelegates() { tested.remove(locationUser1); verify(storageServiceBuilder).apply("bucket2"); diff --git a/datasafe-storage/datasafe-storage-impl-db/src/main/java/de/adorsys/datasafe/storage/impl/db/DatabaseStorageService.java b/datasafe-storage/datasafe-storage-impl-db/src/main/java/de/adorsys/datasafe/storage/impl/db/DatabaseStorageService.java index 45df5173e..7a7886d0f 100644 --- a/datasafe-storage/datasafe-storage-impl-db/src/main/java/de/adorsys/datasafe/storage/impl/db/DatabaseStorageService.java +++ b/datasafe-storage/datasafe-storage-impl-db/src/main/java/de/adorsys/datasafe/storage/impl/db/DatabaseStorageService.java @@ -64,8 +64,8 @@ public boolean objectExists(AbsoluteLocation location) { @Override public Stream> list(AbsoluteLocation location) { ParsedLocation parsed = new ParsedLocation(location, allowedTables); - String sql = "SELECT \"key\",`last_modified` FROM " + parsed.getTableName() + " WHERE \"key\" LIKE '" - + parsed.getPathWithUser() + "%'"; + String sql = "SELECT \"key\",`last_modified` FROM " + parsed.getTableName() + " WHERE \"key\" LIKE '" + + parsed.getPathWithUser() + "%'"; List> keys = conn.jdbcTemplate(location).queryForList(sql); return keys.stream().map(it -> new AbsoluteLocation<>( diff --git a/datasafe-storage/datasafe-storage-impl-fs/src/main/java/de/adorsys/datasafe/storage/impl/fs/FileSystemStorageService.java b/datasafe-storage/datasafe-storage-impl-fs/src/main/java/de/adorsys/datasafe/storage/impl/fs/FileSystemStorageService.java index e7b4f93ee..f459f5105 100644 --- a/datasafe-storage/datasafe-storage-impl-fs/src/main/java/de/adorsys/datasafe/storage/impl/fs/FileSystemStorageService.java +++ b/datasafe-storage/datasafe-storage-impl-fs/src/main/java/de/adorsys/datasafe/storage/impl/fs/FileSystemStorageService.java @@ -72,21 +72,21 @@ public Stream> list(AbsoluteLocation path) { private boolean allowableDir(Path it) { String name = it.getFileName().toString(); - return !".".equals(name) - && !"..".equals(name) + return !".".equals(name) && + !"..".equals(name) && // prevents root folder to appear - && !(it.toString() + "/").equals(dir.getRawPath()); + !(it.toString() + "/").equals(dir.getRawPath()); } private boolean shouldReturnDir(AbsoluteLocation path) { - return path instanceof AbsoluteLocationWithCapability - && ((AbsoluteLocationWithCapability) path).getCapability().equals(StorageCapability.LIST_RETURNS_DIR); + return path instanceof AbsoluteLocationWithCapability && + ((AbsoluteLocationWithCapability) path).getCapability().equals(StorageCapability.LIST_RETURNS_DIR); } @SneakyThrows @Override public InputStream read(AbsoluteLocation path) { - log.debug("Read file request: {}",path.location()); + log.debug("Read file request: {}", path.location()); Path filePath = resolve(path.location().getRawPath(), false); return MoreFiles.asByteSource(filePath, StandardOpenOption.READ).openStream(); } diff --git a/datasafe-storage/datasafe-storage-impl-s3/src/test/java/de/adorsys/datasafe/storage/impl/s3/S3SystemStorageServiceIT.java b/datasafe-storage/datasafe-storage-impl-s3/src/test/java/de/adorsys/datasafe/storage/impl/s3/S3SystemStorageServiceIT.java index ee66097af..398bf8735 100644 --- a/datasafe-storage/datasafe-storage-impl-s3/src/test/java/de/adorsys/datasafe/storage/impl/s3/S3SystemStorageServiceIT.java +++ b/datasafe-storage/datasafe-storage-impl-s3/src/test/java/de/adorsys/datasafe/storage/impl/s3/S3SystemStorageServiceIT.java @@ -109,7 +109,7 @@ void testListOutOfStandardListFilesLimit() { assertThat(storageService.list( new AbsoluteLocation<>( BasePrivateResource.forPrivate(new Uri("s3://" + bucketName + "/over_limit"))))) - .hasSize(numberOfFilesOverLimit); + .hasSize(numberOfFilesOverLimit); } @Test diff --git a/datasafe-test-storages/src/test/java/de/adorsys/datasafe/teststorage/WithStorageProvider.java b/datasafe-test-storages/src/test/java/de/adorsys/datasafe/teststorage/WithStorageProvider.java index ba03f52c4..5c50d8c2b 100644 --- a/datasafe-test-storages/src/test/java/de/adorsys/datasafe/teststorage/WithStorageProvider.java +++ b/datasafe-test-storages/src/test/java/de/adorsys/datasafe/teststorage/WithStorageProvider.java @@ -62,8 +62,8 @@ public abstract class WithStorageProvider extends BaseMockitoTest { private static String bucketPath = UUID.randomUUID().toString(); private static final ExecutorService EXECUTOR_SERVICE = "true".equals(readPropOrEnv("USE_EXECUTOR_POOL")) ? - ExecutorServiceUtil.submitterExecutesOnStarvationExecutingService() : - ExecutorServiceUtil.submitterExecutesOnStarvationExecutingService(4, 4); + ExecutorServiceUtil.submitterExecutesOnStarvationExecutingService() : + ExecutorServiceUtil.submitterExecutesOnStarvationExecutingService(4, 4); private static String minioAccessKeyID = "admin"; private static String minioSecretAccessKey = "password"; @@ -75,7 +75,7 @@ public abstract class WithStorageProvider extends BaseMockitoTest { private static String cephAccessKeyID = "admin"; private static String cephSecretAccessKey = "password"; private static String cephRegion = "eu-central-1"; - private static String cephUrl = getDockerUri("http://0.0.0.0");// not localhost! + private static String cephUrl = getDockerUri("http://0.0.0.0"); // not localhost! private static String cephMappedUrl; private static String amazonAccessKeyID = readPropOrEnv("AWS_ACCESS_KEY"); @@ -85,7 +85,7 @@ public abstract class WithStorageProvider extends BaseMockitoTest { private static String amazonMappedUrl; protected static List buckets = - Arrays.asList(readPropOrEnv("AWS_BUCKET", "adorsys-docusafe").split(",")); + Arrays.asList(readPropOrEnv("AWS_BUCKET", "adorsys-docusafe").split(",")); protected static String primaryBucket = buckets.get(0); private static GenericContainer minioContainer; @@ -223,8 +223,8 @@ protected static Stream minioOnly() { protected static StorageDescriptor fs() { return new StorageDescriptor( StorageDescriptorName.FILESYSTEM, - () -> new FileSystemStorageService(new Uri(tempDir.toUri())), - new Uri(tempDir.toUri()), + () -> new FileSystemStorageService(new Uri(tempDir.toUri())), + new Uri(tempDir.toUri()), null, null, null, tempDir.toString() ); @@ -233,11 +233,11 @@ protected static StorageDescriptor fs() { protected static StorageDescriptor minio() { return new StorageDescriptor( StorageDescriptorName.MINIO, - () -> { - minioStorage.get(); - return new S3StorageService(minio, primaryBucket, EXECUTOR_SERVICE); - }, - new Uri("s3://" + primaryBucket + "/" + bucketPath + "/"), + () -> { + minioStorage.get(); + return new S3StorageService(minio, primaryBucket, EXECUTOR_SERVICE); + }, + new Uri("s3://" + primaryBucket + "/" + bucketPath + "/"), minioAccessKeyID, minioSecretAccessKey, minioRegion, @@ -252,11 +252,11 @@ protected static StorageDescriptor cephVersioned() { return new StorageDescriptor( StorageDescriptorName.CEPH, - () -> { - cephStorage.get(); - return new S3StorageService(ceph, primaryBucket, EXECUTOR_SERVICE); - }, - new Uri("s3://" + primaryBucket + "/" + bucketPath + "/"), + () -> { + cephStorage.get(); + return new S3StorageService(ceph, primaryBucket, EXECUTOR_SERVICE); + }, + new Uri("s3://" + primaryBucket + "/" + bucketPath + "/"), cephAccessKeyID, cephSecretAccessKey, cephRegion, @@ -288,11 +288,11 @@ protected static StorageDescriptor s3() { return new StorageDescriptor( StorageDescriptorName.AMAZON, - () -> { - amazonStorage.get(); - return new S3StorageService(amazonS3, primaryBucket, EXECUTOR_SERVICE); - }, - new Uri("s3://" + primaryBucket + "/" + bucketPath + "/"), + () -> { + amazonStorage.get(); + return new S3StorageService(amazonS3, primaryBucket, EXECUTOR_SERVICE); + }, + new Uri("s3://" + primaryBucket + "/" + bucketPath + "/"), amazonAccessKeyID, amazonSecretAccessKey, amazonRegion, @@ -309,11 +309,11 @@ private void removeObjectFromS3(AmazonS3 amazonS3, String bucket, String prefix) } String lambdafinalBucket = bucket; amazonS3.listObjects(bucket, prefix) - .getObjectSummaries() - .forEach(it -> { - log.debug("Remove {}", it.getKey()); - amazonS3.deleteObject(lambdafinalBucket, it.getKey()); - }); + .getObjectSummaries() + .forEach(it -> { + log.debug("Remove {}", it.getKey()); + amazonS3.deleteObject(lambdafinalBucket, it.getKey()); + }); } private static void initS3() { @@ -323,8 +323,8 @@ private static void initS3() { } AmazonS3ClientBuilder amazonS3ClientBuilder = AmazonS3ClientBuilder.standard() - .withCredentials(new AWSStaticCredentialsProvider( - new BasicAWSCredentials(amazonAccessKeyID, amazonSecretAccessKey)) + .withCredentials(new AWSStaticCredentialsProvider( + new BasicAWSCredentials(amazonAccessKeyID, amazonSecretAccessKey)) ); if (buckets.size() > 1) { @@ -372,7 +372,7 @@ private static void startMinio() { ) .withCredentials( new AWSStaticCredentialsProvider( - new BasicAWSCredentials(minioAccessKeyID, minioSecretAccessKey) + new BasicAWSCredentials(minioAccessKeyID, minioSecretAccessKey) ) ) .enablePathStyleAccess() @@ -409,7 +409,7 @@ private static void startCeph() { ) .withCredentials( new AWSStaticCredentialsProvider( - new BasicAWSCredentials(cephAccessKeyID, cephSecretAccessKey) + new BasicAWSCredentials(cephAccessKeyID, cephSecretAccessKey) ) ) .enablePathStyleAccess() @@ -422,7 +422,7 @@ private static void startCeph() { ceph.setBucketVersioningConfiguration( new SetBucketVersioningConfigurationRequest( primaryBucket, - new BucketVersioningConfiguration(BucketVersioningConfiguration.ENABLED) + new BucketVersioningConfiguration(BucketVersioningConfiguration.ENABLED) ) ); } From fe2e4d2bf9797e4ed0d3b9f7ff7fcf8f2eb34c3f Mon Sep 17 00:00:00 2001 From: Calebasah Date: Mon, 30 Sep 2024 14:03:24 +0100 Subject: [PATCH 7/7] Updated CMSEncryptionServiceImpl --- .../encrypiton/impl/cmsencryption/CMSEncryptionServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/CMSEncryptionServiceImpl.java b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/CMSEncryptionServiceImpl.java index 6f9a59e1f..0654ac53e 100644 --- a/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/CMSEncryptionServiceImpl.java +++ b/datasafe-encryption/datasafe-encryption-impl/src/main/java/de/adorsys/datasafe/encrypiton/impl/cmsencryption/CMSEncryptionServiceImpl.java @@ -148,7 +148,7 @@ private OutputStream streamEncrypt(OutputStream dataContentStream, Set